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.

request: Improve validator type so mypy can check it against REQ.

Anders Kaseorg7e9db327b335
diff --git a/zerver/lib/actions.py b/zerver/lib/actions.py
index 0b021c19fa4..cc6aba628cb 100644
--- a/zerver/lib/actions.py
+++ b/zerver/lib/actions.py
@@ -2350,10 +2350,11 @@ def check_message(sender: UserProfile, client: Client, addressee: Addressee,
except Exception:
raise JsonableError(_('Widgets: API programmer sent invalid JSON content'))
- error_msg = check_widget_content(widget_content)
- if error_msg:
+ try:
+ check_widget_content(widget_content)
+ except ValidationError as error:
raise JsonableError(_('Widgets: {error_msg}').format(
- error_msg=error_msg,
+ error_msg=error.message,
))
return {'message': message, 'stream': stream, 'local_id': local_id,
diff --git a/zerver/lib/external_accounts.py b/zerver/lib/external_accounts.py
index 81a07728956..a7a55dbeab3 100644
--- a/zerver/lib/external_accounts.py
+++ b/zerver/lib/external_accounts.py
@@ -1,8 +1,7 @@
"""
This module stores data for "External Account" custom profile field.
"""
-from typing import Optional
-
+from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from zerver.lib.types import ProfileFieldData
@@ -35,21 +34,19 @@ DEFAULT_EXTERNAL_ACCOUNTS = {
},
}
-def validate_external_account_field_data(field_data: ProfileFieldData) -> Optional[str]:
+def validate_external_account_field_data(field_data: ProfileFieldData) -> ProfileFieldData:
field_validator = check_dict_only(
[('subtype', check_required_string)],
[('url_pattern', check_external_account_url_pattern)],
)
- error = field_validator('field_data', field_data)
- if error:
- return error
+ field_validator('field_data', field_data)
field_subtype = field_data.get('subtype')
if field_subtype not in DEFAULT_EXTERNAL_ACCOUNTS.keys():
if field_subtype == "custom":
if 'url_pattern' not in field_data.keys():
- return _("Custom external account must define url pattern")
+ raise ValidationError(_("Custom external account must define url pattern"))
else:
- return _("Invalid external account type")
+ raise ValidationError(_("Invalid external account type"))
- return None
+ return field_data
diff --git a/zerver/lib/integrations.py b/zerver/lib/integrations.py
index 6dc18df0cd9..a4d69e03e8b 100644
--- a/zerver/lib/integrations.py
+++ b/zerver/lib/integrations.py
@@ -56,7 +56,7 @@ class Integration:
logo: Optional[str]=None, secondary_line_text: Optional[str]=None,
display_name: Optional[str]=None, doc: Optional[str]=None,
stream_name: Optional[str]=None, legacy: bool=False,
- config_options: Sequence[Tuple[str, str, Validator]]=[]) -> None:
+ config_options: Sequence[Tuple[str, str, Validator[object]]]=[]) -> None:
self.name = name
self.client_name = client_name
self.secondary_line_text = secondary_line_text
@@ -158,7 +158,7 @@ class WebhookIntegration(Integration):
function: Optional[str]=None, url: Optional[str]=None,
display_name: Optional[str]=None, doc: Optional[str]=None,
stream_name: Optional[str]=None, legacy: bool=False,
- config_options: Sequence[Tuple[str, str, Validator]]=[]) -> None:
+ config_options: Sequence[Tuple[str, str, Validator[object]]]=[]) -> None:
if client_name is None:
client_name = self.DEFAULT_CLIENT_NAME.format(name=name.title())
super().__init__(
diff --git a/zerver/lib/request.py b/zerver/lib/request.py
index dcbe00d6cb0..d8247ba5f16 100644
--- a/zerver/lib/request.py
+++ b/zerver/lib/request.py
@@ -16,6 +16,7 @@ from typing import (
)
import ujson
+from django.core.exceptions import ValidationError
from django.http import HttpRequest, HttpResponse
from django.utils.translation import ugettext as _
from typing_extensions import Literal
@@ -76,8 +77,8 @@ class _REQ(Generic[ResultT]):
*,
converter: Optional[Callable[[str], ResultT]] = None,
default: Union[_NotSpecified, ResultT, None] = NotSpecified,
- validator: Optional[Validator] = None,
- str_validator: Optional[Validator] = None,
+ validator: Optional[Validator[ResultT]] = None,
+ str_validator: Optional[Validator[ResultT]] = None,
argument_type: Optional[str] = None,
intentionally_undocumented: bool=False,
documentation_pending: bool=False,
@@ -157,7 +158,7 @@ def REQ(
whence: Optional[str] = ...,
*,
default: ResultT = ...,
- validator: Validator,
+ validator: Validator[ResultT],
intentionally_undocumented: bool = ...,
documentation_pending: bool = ...,
aliases: Sequence[str] = ...,
@@ -171,7 +172,7 @@ def REQ(
whence: Optional[str] = ...,
*,
default: str = ...,
- str_validator: Optional[Validator] = ...,
+ str_validator: Optional[Validator[str]] = ...,
intentionally_undocumented: bool = ...,
documentation_pending: bool = ...,
aliases: Sequence[str] = ...,
@@ -185,7 +186,7 @@ def REQ(
whence: Optional[str] = ...,
*,
default: None,
- str_validator: Optional[Validator] = ...,
+ str_validator: Optional[Validator[str]] = ...,
intentionally_undocumented: bool = ...,
documentation_pending: bool = ...,
aliases: Sequence[str] = ...,
@@ -199,7 +200,6 @@ def REQ(
whence: Optional[str] = ...,
*,
default: ResultT = ...,
- str_validator: Optional[Validator] = ...,
argument_type: Literal["body"],
intentionally_undocumented: bool = ...,
documentation_pending: bool = ...,
@@ -214,8 +214,8 @@ def REQ(
*,
converter: Optional[Callable[[str], ResultT]] = None,
default: Union[_REQ._NotSpecified, ResultT] = _REQ.NotSpecified,
- validator: Optional[Validator] = None,
- str_validator: Optional[Validator] = None,
+ validator: Optional[Validator[ResultT]] = None,
+ str_validator: Optional[Validator[ResultT]] = None,
argument_type: Optional[str] = None,
intentionally_undocumented: bool=False,
documentation_pending: bool=False,
@@ -350,15 +350,17 @@ def has_request_variables(view_func: ViewFuncT) -> ViewFuncT:
except Exception:
raise JsonableError(_('Argument "{}" is not valid JSON.').format(post_var_name))
- error = param.validator(post_var_name, val)
- if error:
- raise JsonableError(error)
+ try:
+ val = param.validator(post_var_name, val)
+ except ValidationError as error:
+ raise JsonableError(error.message)
# str_validators is like validator, but for direct strings (no JSON parsing).
if param.str_validator is not None and not default_assigned:
- error = param.str_validator(post_var_name, val)
- if error:
- raise JsonableError(error)
+ try:
+ val = param.str_validator(post_var_name, val)
+ except ValidationError as error:
+ raise JsonableError(error.message)
kwargs[func_var_name] = val
diff --git a/zerver/lib/types.py b/zerver/lib/types.py
index fb013088020..bbc38efa703 100644
--- a/zerver/lib/types.py
+++ b/zerver/lib/types.py
@@ -7,9 +7,10 @@ ViewFuncT = TypeVar('ViewFuncT', bound=Callable[..., HttpResponse])
# See zerver/lib/validator.py for more details of Validators,
# including many examples
-Validator = Callable[[str, object], Optional[str]]
-ExtendedValidator = Callable[[str, str, object], Optional[str]]
-RealmUserValidator = Callable[[int, List[int], bool], Optional[str]]
+ResultT = TypeVar("ResultT")
+Validator = Callable[[str, object], ResultT]
+ExtendedValidator = Callable[[str, str, object], str]
+RealmUserValidator = Callable[[int, List[int], bool], List[int]]
class ProfileDataElementBase(TypedDict):
id: int
@@ -25,7 +26,7 @@ class ProfileDataElement(ProfileDataElementBase):
ProfileData = List[ProfileDataElement]
-FieldElement = Tuple[int, str, Validator, Callable[[Any], Any], str]
+FieldElement = Tuple[int, str, Validator[Union[int, str, List[int]]], Callable[[Any], Any], str]
ExtendedFieldElement = Tuple[int, str, ExtendedValidator, Callable[[Any], Any], str]
UserFieldElement = Tuple[int, str, RealmUserValidator, Callable[[Any], Any], str]
diff --git a/zerver/lib/users.py b/zerver/lib/users.py
index 181b635dd24..9c5285f2c74 100644
--- a/zerver/lib/users.py
+++ b/zerver/lib/users.py
@@ -4,6 +4,7 @@ from collections import defaultdict
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union, cast
from django.conf import settings
+from django.core.exceptions import ValidationError
from django.db.models.query import QuerySet
from django.forms.models import model_to_dict
from django.utils.translation import ugettext as _
@@ -253,25 +254,24 @@ def get_all_api_keys(user_profile: UserProfile) -> List[str]:
return [user_profile.api_key]
def validate_user_custom_profile_field(realm_id: int, field: CustomProfileField,
- value: Union[int, str, List[int]]) -> Optional[str]:
+ value: Union[int, str, List[int]]) -> Union[int, str, List[int]]:
validators = CustomProfileField.FIELD_VALIDATORS
field_type = field.field_type
var_name = f'{field.name}'
if field_type in validators:
validator = validators[field_type]
- result = validator(var_name, value)
+ return validator(var_name, value)
elif field_type == CustomProfileField.CHOICE:
choice_field_validator = CustomProfileField.CHOICE_FIELD_VALIDATORS[field_type]
field_data = field.field_data
# Put an assertion so that mypy doesn't complain.
assert field_data is not None
- result = choice_field_validator(var_name, field_data, value)
+ return choice_field_validator(var_name, field_data, value)
elif field_type == CustomProfileField.USER:
user_field_validator = CustomProfileField.USER_FIELD_VALIDATORS[field_type]
- result = user_field_validator(realm_id, cast(List[int], value), False)
+ return user_field_validator(realm_id, cast(List[int], value), False)
else:
raise AssertionError("Invalid field type")
- return result
def validate_user_custom_profile_data(realm_id: int,
profile_data: List[Dict[str, Union[int, str, List[int]]]]) -> None:
@@ -283,9 +283,10 @@ def validate_user_custom_profile_data(realm_id: int,
except CustomProfileField.DoesNotExist:
raise JsonableError(_('Field id {id} not found.').format(id=field_id))
- result = validate_user_custom_profile_field(realm_id, field, item['value'])
- if result is not None:
- raise JsonableError(result)
+ try:
+ validate_user_custom_profile_field(realm_id, field, item['value'])
+ except ValidationError as error:
+ raise JsonableError(error.message)
def compute_show_invites_and_add_streams(user_profile: Optional[UserProfile]) -> Tuple[bool, bool]:
if user_profile is None:
diff --git a/zerver/lib/validator.py b/zerver/lib/validator.py
index 5048fe70276..924ebae4dba 100644
--- a/zerver/lib/validator.py
+++ b/zerver/lib/validator.py
@@ -3,9 +3,10 @@ This module sets up a scheme for validating that arbitrary Python
objects are correctly typed. It is totally decoupled from Django,
composable, easily wrapped, and easily extended.
-A validator takes two parameters--var_name and val--and returns an
+A validator takes two parameters--var_name and val--and raises an
error if val is not the correct type. The var_name parameter is used
-to format error messages. Validators return None when there are no errors.
+to format error messages. Validators return the validated value when
+there are no errors.
Example primitive validators are check_string, check_int, and check_bool.
@@ -20,14 +21,28 @@ for arbitrarily complex validators. See ValidatorTestCase for example usage.
A simple example of composition is this:
- check_list(check_string)('my_list', ['a', 'b', 'c']) is None
+ check_list(check_string)('my_list', ['a', 'b', 'c'])
To extend this concept, it's simply a matter of writing your own validator
for any particular type of object.
+
'''
import re
from datetime import datetime
-from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, TypeVar, Union, cast
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ Iterable,
+ List,
+ Optional,
+ Set,
+ Tuple,
+ TypeVar,
+ Union,
+ cast,
+ overload,
+)
import ujson
from django.conf import settings
@@ -35,7 +50,7 @@ from django.core.exceptions import ValidationError
from django.core.validators import URLValidator, validate_email
from django.utils.translation import ugettext as _
-from zerver.lib.request import JsonableError
+from zerver.lib.request import JsonableError, ResultT
from zerver.lib.types import ProfileFieldData, Validator
FuncT = Callable[..., Any]
@@ -56,131 +71,128 @@ def set_type_structure(type_structure: TypeStructure) -> Callable[[FuncT], Any]:
return _set_type_structure
@set_type_structure("str")
-def check_string(var_name: str, val: object) -> Optional[str]:
+def check_string(var_name: str, val: object) -> str:
if not isinstance(val, str):
- return _('{var_name} is not a string').format(var_name=var_name)
- return None
+ raise ValidationError(_('{var_name} is not a string').format(var_name=var_name))
+ return val
@set_type_structure("str")
-def check_required_string(var_name: str, val: object) -> Optional[str]:
- error = check_string(var_name, val)
- if error:
- return error
-
- val = cast(str, val)
- if not val.strip():
- return _("{item} cannot be blank.").format(item=var_name)
+def check_required_string(var_name: str, val: object) -> str:
+ s = check_string(var_name, val)
+ if not s.strip():
+ raise ValidationError(_("{item} cannot be blank.").format(item=var_name))
+ return s
- return None
-
-def check_string_in(possible_values: Union[Set[str], List[str]]) -> Validator:
+def check_string_in(possible_values: Union[Set[str], List[str]]) -> Validator[str]:
@set_type_structure("str")
- def validator(var_name: str, val: object) -> Optional[str]:
- not_str = check_string(var_name, val)
- if not_str is not None:
- return not_str
- if val not in possible_values:
- return _("Invalid {var_name}").format(var_name=var_name)
- return None
+ def validator(var_name: str, val: object) -> str:
+ s = check_string(var_name, val)
+ if s not in possible_values:
+ raise ValidationError(_("Invalid {var_name}").format(var_name=var_name))
+ return s
return validator
@set_type_structure("str")
-def check_short_string(var_name: str, val: object) -> Optional[str]:
+def check_short_string(var_name: str, val: object) -> str:
return check_capped_string(50)(var_name, val)
-def check_capped_string(max_length: int) -> Validator:
+def check_capped_string(max_length: int) -> Validator[str]:
@set_type_structure("str")
- def validator(var_name: str, val: object) -> Optional[str]:
- if not isinstance(val, str):
- return _('{var_name} is not a string').format(var_name=var_name)
- if len(val) > max_length:
- return _("{var_name} is too long (limit: {max_length} characters)").format(
- var_name=var_name, max_length=max_length)
- return None
+ def validator(var_name: str, val: object) -> str:
+ s = check_string(var_name, val)
+ if len(s) > max_length:
+ raise ValidationError(_("{var_name} is too long (limit: {max_length} characters)").format(
+ var_name=var_name, max_length=max_length,
+ ))
+ return s
return validator
-def check_string_fixed_length(length: int) -> Validator:
+def check_string_fixed_length(length: int) -> Validator[str]:
@set_type_structure("str")
def validator(var_name: str, val: object) -> Optional[str]:
- if not isinstance(val, str):
- return _('{var_name} is not a string').format(var_name=var_name)
- if len(val) != length:
- return _("{var_name} has incorrect length {length}; should be {target_length}").format(
- var_name=var_name, target_length=length, length=len(val))
- return None
+ s = check_string(var_name, val)
+ if len(s) != length:
+ raise ValidationError(_("{var_name} has incorrect length {length}; should be {target_length}").format(
+ var_name=var_name, target_length=length, length=len(s),
+ ))
+ return s
+
return validator
@set_type_structure("str")
-def check_long_string(var_name: str, val: object) -> Optional[str]:
+def check_long_string(var_name: str, val: object) -> str:
return check_capped_string(500)(var_name, val)
@set_type_structure("date")
-def check_date(var_name: str, val: object) -> Optional[str]:
+def check_date(var_name: str, val: object) -> str:
if not isinstance(val, str):
- return _('{var_name} is not a string').format(var_name=var_name)
+ raise ValidationError(_('{var_name} is not a string').format(var_name=var_name))
try:
datetime.strptime(val, '%Y-%m-%d')
except ValueError:
- return _('{var_name} is not a date').format(var_name=var_name)
- return None
+ raise ValidationError(_('{var_name} is not a date').format(var_name=var_name))
+ return val
@set_type_structure("int")
-def check_int(var_name: str, val: object) -> Optional[str]:
+def check_int(var_name: str, val: object) -> int:
if not isinstance(val, int):
- return _('{var_name} is not an integer').format(var_name=var_name)
- return None
+ raise ValidationError(_('{var_name} is not an integer').format(var_name=var_name))
+ return val
-def check_int_in(possible_values: List[int]) -> Validator:
+def check_int_in(possible_values: List[int]) -> Validator[int]:
@set_type_structure("int")
- def validator(var_name: str, val: object) -> Optional[str]:
- not_int = check_int(var_name, val)
- if not_int is not None:
- return not_int
- if val not in possible_values:
- return _("Invalid {var_name}").format(var_name=var_name)
- return None
+ def validator(var_name: str, val: object) -> int:
+ n = check_int(var_name, val)
+ if n not in possible_values:
+ raise ValidationError(_("Invalid {var_name}").format(var_name=var_name))
+ return n
return validator
@set_type_structure("float")
-def check_float(var_name: str, val: object) -> Optional[str]:
+def check_float(var_name: str, val: object) -> float:
if not isinstance(val, float):
- return _('{var_name} is not a float').format(var_name=var_name)
- return None
+ raise ValidationError(_('{var_name} is not a float').format(var_name=var_name))
+ return val
@set_type_structure("bool")
-def check_bool(var_name: str, val: object) -> Optional[str]:
+def check_bool(var_name: str, val: object) -> bool:
if not isinstance(val, bool):
- return _('{var_name} is not a boolean').format(var_name=var_name)
- return None
+ raise ValidationError(_('{var_name} is not a boolean').format(var_name=var_name))
+ return val
@set_type_structure("str")
-def check_color(var_name: str, val: object) -> Optional[str]:
- if not isinstance(val, str):
- return _('{var_name} is not a string').format(var_name=var_name)
+def check_color(var_name: str, val: object) -> str:
+ s = check_string(var_name, val)
valid_color_pattern = re.compile(r'^#([a-fA-F0-9]{3,6})$')
- matched_results = valid_color_pattern.match(val)
+ matched_results = valid_color_pattern.match(s)
if not matched_results:
- return _('{var_name} is not a valid hex color code').format(var_name=var_name)
- return None
+ raise ValidationError(_('{var_name} is not a valid hex color code').format(var_name=var_name))
+ return s
-def check_none_or(sub_validator: Validator) -> Validator:
+def check_none_or(sub_validator: Validator[ResultT]) -> Validator[ResultT]:
if USING_TYPE_STRUCTURE:
type_structure = 'none_or_' + sub_validator.type_structure # type: ignore[attr-defined] # monkey-patching
else:
type_structure = None
@set_type_structure(type_structure)
- def f(var_name: str, val: object) -> Optional[str]:
+ def f(var_name: str, val: object) -> Optional[ResultT]:
if val is None:
- return None
+ return val
else:
return sub_validator(var_name, val)
return f
-def check_list(sub_validator: Optional[Validator], length: Optional[int]=None) -> Validator:
+@overload
+def check_list(sub_validator: None, length: Optional[int]=None) -> Validator[List[object]]:
+ ...
+@overload
+def check_list(sub_validator: Validator[ResultT], length: Optional[int]=None) -> Validator[List[ResultT]]:
+ ...
+def check_list(sub_validator: Optional[Validator[ResultT]]=None, length: Optional[int]=None) -> Validator[List[ResultT]]:
if USING_TYPE_STRUCTURE:
if sub_validator:
type_structure = [sub_validator.type_structure] # type: ignore[attr-defined] # monkey-patching
@@ -190,63 +202,74 @@ def check_list(sub_validator: Optional[Validator], length: Optional[int]=None) -
type_structure = None # type: ignore[assignment] # monkey-patching
@set_type_structure(type_structure)
- def f(var_name: str, val: object) -> Optional[str]:
+ def f(var_name: str, val: object) -> List[ResultT]:
if not isinstance(val, list):
- return _('{var_name} is not a list').format(var_name=var_name)
+ raise ValidationError(_('{var_name} is not a list').format(var_name=var_name))
if length is not None and length != len(val):
- return (_('{container} should have exactly {length} items').format(
+ raise ValidationError(_('{container} should have exactly {length} items').format(
container=var_name, length=length,
))
if sub_validator:
for i, item in enumerate(val):
vname = f'{var_name}[{i}]'
- error = sub_validator(vname, item)
- if error:
- return error
+ valid_item = sub_validator(vname, item)
+ assert item is valid_item # To justify the unchecked cast below
- return None
+ return cast(List[ResultT], val)
return f
-def check_dict(required_keys: Iterable[Tuple[str, Validator]]=[],
- optional_keys: Iterable[Tuple[str, Validator]]=[],
- value_validator: Optional[Validator]=None,
- _allow_only_listed_keys: bool=False) -> Validator:
+@overload
+def check_dict(required_keys: Iterable[Tuple[str, Validator[object]]]=[],
+ optional_keys: Iterable[Tuple[str, Validator[object]]]=[],
+ *,
+ _allow_only_listed_keys: bool=False) -> Validator[Dict[str, object]]:
+ ...
+@overload
+def check_dict(required_keys: Iterable[Tuple[str, Validator[ResultT]]]=[],
+ optional_keys: Iterable[Tuple[str, Validator[ResultT]]]=[],
+ *,
+ value_validator: Validator[ResultT],
+ _allow_only_listed_keys: bool=False) -> Validator[Dict[str, ResultT]]:
+ ...
+def check_dict(required_keys: Iterable[Tuple[str, Validator[ResultT]]]=[],
+ optional_keys: Iterable[Tuple[str, Validator[ResultT]]]=[],
+ *,
+ value_validator: Optional[Validator[ResultT]]=None,
+ _allow_only_listed_keys: bool=False) -> Validator[Dict[str, ResultT]]:
type_structure: Dict[str, Any] = {}
@set_type_structure(type_structure)
- def f(var_name: str, val: object) -> Optional[str]:
+ def f(var_name: str, val: object) -> Dict[str, ResultT]:
if not isinstance(val, dict):
- return _('{var_name} is not a dict').format(var_name=var_name)
+ raise ValidationError(_('{var_name} is not a dict').format(var_name=var_name))
+
+ for k in val:
+ check_string(f'{var_name} key', k)
for k, sub_validator in required_keys:
if k not in val:
- return (_('{key_name} key is missing from {var_name}').format(
+ raise ValidationError(_('{key_name} key is missing from {var_name}').format(
key_name=k, var_name=var_name,
))
vname = f'{var_name}["{k}"]'
- error = sub_validator(vname, val[k])
- if error:
- return error
+ sub_validator(vname, val[k])
if USING_TYPE_STRUCTURE:
type_structure[k] = sub_validator.type_structure # type: ignore[attr-defined] # monkey-patching
for k, sub_validator in optional_keys:
if k in val:
vname = f'{var_name}["{k}"]'
- error = sub_validator(vname, val[k])
- if error:
- return error
+ sub_validator(vname, val[k])
if USING_TYPE_STRUCTURE:
type_structure[k] = sub_validator.type_structure # type: ignore[attr-defined] # monkey-patching
if value_validator:
for key in val:
vname = f'{var_name} contains a value that'
- error = value_validator(vname, val[key])
- if error:
- return error
+ valid_value = value_validator(vname, val[key])
+ assert val[key] is valid_value # To justify the unchecked cast below
if USING_TYPE_STRUCTURE:
type_structure['any'] = value_validator.type_structure # type: ignore[attr-defined] # monkey-patching
@@ -255,17 +278,20 @@ def check_dict(required_keys: Iterable[Tuple[str, Validator]]=[],
optional_keys_set = {x[0] for x in optional_keys}
delta_keys = set(val.keys()) - required_keys_set - optional_keys_set
if len(delta_keys) != 0:
- return _("Unexpected arguments: {}").format(", ".join(list(delta_keys)))
+ raise ValidationError(_("Unexpected arguments: {}").format(", ".join(list(delta_keys))))
- return None
+ return cast(Dict[str, ResultT], val)
return f
-def check_dict_only(required_keys: Iterable[Tuple[str, Validator]],
- optional_keys: Iterable[Tuple[str, Validator]]=[]) -> Validator:
- return check_dict(required_keys, optional_keys, _allow_only_listed_keys=True)
+def check_dict_only(required_keys: Iterable[Tuple[str, Validator[ResultT]]],
+ optional_keys: Iterable[Tuple[str, Validator[ResultT]]]=[]) -> Validator[Dict[str, ResultT]]:
+ return cast(
+ Validator[Dict[str, ResultT]],
+ check_dict(required_keys, optional_keys, _allow_only_listed_keys=True),
+ )
-def check_union(allowed_type_funcs: Iterable[Validator]) -> Validator:
+def check_union(allowed_type_funcs: Iterable[Validator[ResultT]]) -> Validator[ResultT]:
"""
Use this validator if an argument is of a variable type (e.g. processing
properties that might be strings or booleans).
@@ -280,21 +306,23 @@ def check_union(allowed_type_funcs: Iterable[Validator]) -> Validator:
type_structure = None # type: ignore[assignment] # monkey-patching
@set_type_structure(type_structure)
- def enumerated_type_check(var_name: str, val: object) -> Optional[str]:
+ def enumerated_type_check(var_name: str, val: object) -> ResultT:
for func in allowed_type_funcs:
- if not func(var_name, val):
- return None
- return _('{var_name} is not an allowed_type').format(var_name=var_name)
+ try:
+ return func(var_name, val)
+ except ValidationError:
+ pass
+ raise ValidationError(_('{var_name} is not an allowed_type').format(var_name=var_name))
return enumerated_type_check
-def equals(expected_val: object) -> Validator:
+def equals(expected_val: ResultT) -> Validator[ResultT]:
@set_type_structure(f'equals("{str(expected_val)}")')
- def f(var_name: str, val: object) -> Optional[str]:
+ def f(var_name: str, val: object) -> ResultT:
if val != expected_val:
- return (_('{variable} != {expected_value} ({value} is wrong)').format(
+ raise ValidationError(_('{variable} != {expected_value} ({value} is wrong)').format(
variable=var_name, expected_value=expected_val, value=val,
))
- return None
+ return cast(ResultT, val)
return f
@set_type_structure('str')
@@ -305,36 +333,29 @@ def validate_login_email(email: str) -> None:
raise JsonableError(str(err.message))
@set_type_structure('str')
-def check_url(var_name: str, val: object) -> Optional[str]:
+def check_url(var_name: str, val: object) -> str:
# First, ensure val is a string
- string_msg = check_string(var_name, val)
- if string_msg is not None:
- return string_msg
+ s = check_string(var_name, val)
# Now, validate as URL
validate = URLValidator()
try:
- validate(val)
- return None
+ validate(s)
+ return s
except ValidationError:
- return _('{var_name} is not a URL').format(var_name=var_name)
+ raise ValidationError(_('{var_name} is not a URL').format(var_name=var_name))
@set_type_structure('str')
-def check_external_account_url_pattern(var_name: str, val: object) -> Optional[str]:
- error = check_string(var_name, val)
- if error:
- return error
- val = cast(str, val)
-
- if val.count('%(username)s') != 1:
- return _('Malformed URL pattern.')
- url_val = val.replace('%(username)s', 'username')
-
- error = check_url(var_name, url_val)
- if error:
- return error
- return None
-
-def validate_choice_field_data(field_data: ProfileFieldData) -> Optional[str]:
+def check_external_account_url_pattern(var_name: str, val: object) -> str:
+ s = check_string(var_name, val)
+
+ if s.count('%(username)s') != 1:
+ raise ValidationError(_('Malformed URL pattern.'))
+ url_val = s.replace('%(username)s', 'username')
+
+ check_url(var_name, url_val)
+ return s
+
+def validate_choice_field_data(field_data: ProfileFieldData) -> Dict[str, Dict[str, str]]:
"""
This function is used to validate the data sent to the server while
creating/editing choices of the choice field in Organization settings.
@@ -346,45 +367,45 @@ def validate_choice_field_data(field_data: ProfileFieldData) -> Optional[str]:
for key, value in field_data.items():
if not key.strip():
- return _("'{item}' cannot be blank.").format(item='value')
+ raise ValidationError(_("'{item}' cannot be blank.").format(item='value'))
- error = validator('field_data', value)
- if error:
- return error
+ valid_value = validator('field_data', value)
+ assert value is valid_value # To justify the unchecked cast below
- return None
+ return cast(Dict[str, Dict[str, str]], field_data)
-def validate_choice_field(var_name: str, field_data: str, value: object) -> Optional[str]:
+def validate_choice_field(var_name: str, field_data: str, value: object) -> str:
"""
This function is used to validate the value selected by the user against a
choice field. This is not used to validate admin data.
"""
+ s = check_string(var_name, value)
field_data_dict = ujson.loads(field_data)
- if value not in field_data_dict:
+ if s not in field_data_dict:
msg = _("'{value}' is not a valid choice for '{field_name}'.")
- return msg.format(value=value, field_name=var_name)
- return None
+ raise ValidationError(msg.format(value=value, field_name=var_name))
+ return s
-def check_widget_content(widget_content: object) -> Optional[str]:
+def check_widget_content(widget_content: object) -> Dict[str, Any]:
if not isinstance(widget_content, dict):
- return 'widget_content is not a dict'
+ raise ValidationError('widget_content is not a dict')
if 'widget_type' not in widget_content:
- return 'widget_type is not in widget_content'
+ raise ValidationError('widget_type is not in widget_content')
if 'extra_data' not in widget_content:
- return 'extra_data is not in widget_content'
+ raise ValidationError('extra_data is not in widget_content')
widget_type = widget_content['widget_type']
extra_data = widget_content['extra_data']
if not isinstance(extra_data, dict):
- return 'extra_data is not a dict'
+ raise ValidationError('extra_data is not a dict')
if widget_type == 'zform':
if 'type' not in extra_data:
- return 'zform is missing type field'
+ raise ValidationError('zform is missing type field')
if extra_data['type'] == 'choices':
check_choices = check_list(
@@ -400,15 +421,13 @@ def check_widget_content(widget_content: object) -> Optional[str]:
('choices', check_choices),
])
- msg = checker('extra_data', extra_data)
- if msg:
- return msg
+ checker('extra_data', extra_data)
- return None
+ return widget_content
- return 'unknown zform type: ' + extra_data['type']
+ raise ValidationError('unknown zform type: ' + extra_data['type'])
- return 'unknown widget type: ' + widget_type
+ raise ValidationError('unknown widget type: ' + widget_type)
# Converter functions for use with has_request_variables
@@ -433,18 +452,18 @@ def to_positive_or_allowed_int(allowed_integer: int) -> Callable[[str], int]:
return convertor
@set_type_structure('any(List[int], str)]')
-def check_string_or_int_list(var_name: str, val: object) -> Optional[str]:
+def check_string_or_int_list(var_name: str, val: object) -> Union[str, List[int]]:
if isinstance(val, str):
- return None
+ return val
if not isinstance(val, list):
- return _('{var_name} is not a string or an integer list').format(var_name=var_name)
+ raise ValidationError(_('{var_name} is not a string or an integer list').format(var_name=var_name))
return check_list(check_int)(var_name, val)
@set_type_structure('any(int, str)')
-def check_string_or_int(var_name: str, val: object) -> Optional[str]:
+def check_string_or_int(var_name: str, val: object) -> Union[str, int]:
if isinstance(val, str) or isinstance(val, int):
- return None
+ return val
- return _('{var_name} is not a string or integer').format(var_name=var_name)
+ raise ValidationError(_('{var_name} is not a string or integer').format(var_name=var_name))
diff --git a/zerver/models.py b/zerver/models.py
index 0969d882dc9..0020967f0ff 100644
--- a/zerver/models.py
+++ b/zerver/models.py
@@ -2738,10 +2738,8 @@ class UserHotspot(models.Model):
unique_together = ("user", "hotspot")
def check_valid_user_ids(realm_id: int, user_ids: List[int],
- allow_deactivated: bool=False) -> Optional[str]:
- error = check_list(check_int)("User IDs", user_ids)
- if error:
- return error
+ allow_deactivated: bool=False) -> List[int]:
+ check_list(check_int)("User IDs", user_ids)
realm = Realm.objects.get(id=realm_id)
for user_id in user_ids:
# TODO: Structurally, we should be doing a bulk fetch query to
@@ -2751,16 +2749,16 @@ def check_valid_user_ids(realm_id: int, user_ids: List[int],
try:
user_profile = get_user_profile_by_id_in_realm(user_id, realm)
except UserProfile.DoesNotExist:
- return _('Invalid user ID: %d') % (user_id)
+ raise ValidationError(_('Invalid user ID: %d') % (user_id))
if not allow_deactivated:
if not user_profile.is_active:
- return _('User with ID %d is deactivated') % (user_id)
+ raise ValidationError(_('User with ID %d is deactivated') % (user_id))
if (user_profile.is_bot):
- return _('User with ID %d is a bot') % (user_id)
+ raise ValidationError(_('User with ID %d is a bot') % (user_id))
- return None
+ return user_ids
class CustomProfileField(models.Model):
"""Defines a form field for the per-realm custom profile fields feature.
@@ -2812,7 +2810,7 @@ class CustomProfileField(models.Model):
ALL_FIELD_TYPES = [*FIELD_TYPE_DATA, *CHOICE_FIELD_TYPE_DATA, *USER_FIELD_TYPE_DATA]
- FIELD_VALIDATORS: Dict[int, Validator] = {item[0]: item[2] for item in FIELD_TYPE_DATA}
+ FIELD_VALIDATORS: Dict[int, Validator[Union[int, str, List[int]]]] = {item[0]: item[2] for item in FIELD_TYPE_DATA}
FIELD_CONVERTERS: Dict[int, Callable[[Any], Any]] = {item[0]: item[3] for item in ALL_FIELD_TYPES}
FIELD_TYPE_CHOICES: List[Tuple[int, str]] = [(item[0], item[1]) for item in ALL_FIELD_TYPES]
FIELD_TYPE_CHOICES_DICT: Dict[str, Dict[str, Union[str, int]]] = {
diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.py
index 0172c1c9e7d..fce4bc01288 100644
--- a/zerver/tests/test_auth_backends.py
+++ b/zerver/tests/test_auth_backends.py
@@ -3187,12 +3187,8 @@ class ExternalMethodDictsTests(ZulipTestCase):
{'saml:test_idp', 'saml:test_idp2'})
class FetchAuthBackends(ZulipTestCase):
- def assert_on_error(self, error: Optional[str]) -> None:
- if error:
- raise AssertionError(error)
-
def test_get_server_settings(self) -> None:
- def check_result(result: HttpResponse, extra_fields: Sequence[Tuple[str, Validator]] = []) -> None:
+ def check_result(result: HttpResponse, extra_fields: Sequence[Tuple[str, Validator[object]]] = []) -> None:
authentication_methods_list = [
('password', check_bool),
]
@@ -3215,7 +3211,7 @@ class FetchAuthBackends(ZulipTestCase):
('result', check_string),
*extra_fields,
])
- self.assert_on_error(checker("data", result.json()))
+ checker("data", result.json())
result = self.client_get("/api/v1/server_settings", subdomain="", HTTP_USER_AGENT="")
check_result(result)
diff --git a/zerver/tests/test_decorators.py b/zerver/tests/test_decorators.py
index 221a55dcea4..ae2edb9cf25 100644
--- a/zerver/tests/test_decorators.py
+++ b/zerver/tests/test_decorators.py
@@ -2,11 +2,12 @@ import base64
import os
import re
from collections import defaultdict
-from typing import Any, Dict, Iterable, List, Optional, Tuple
+from typing import Any, Dict, Iterable, List, Tuple
from unittest import mock
import ujson
from django.conf import settings
+from django.core.exceptions import ValidationError
from django.http import HttpRequest, HttpResponse
from django.test import TestCase
@@ -723,71 +724,85 @@ class RateLimitTestCase(TestCase):
class ValidatorTestCase(TestCase):
def test_check_string(self) -> None:
x: Any = "hello"
- self.assertEqual(check_string('x', x), None)
+ check_string('x', x)
x = 4
- self.assertEqual(check_string('x', x), 'x is not a string')
+ with self.assertRaisesRegex(ValidationError, r'x is not a string'):
+ check_string('x', x)
def test_check_string_fixed_length(self) -> None:
x: Any = "hello"
- self.assertEqual(check_string_fixed_length(5)('x', x), None)
+ check_string_fixed_length(5)('x', x)
x = 4
- self.assertEqual(check_string_fixed_length(5)('x', x), 'x is not a string')
+ with self.assertRaisesRegex(ValidationError, r'x is not a string'):
+ check_string_fixed_length(5)('x', x)
x = "helloz"
- self.assertEqual(check_string_fixed_length(5)('x', x), 'x has incorrect length 6; should be 5')
+ with self.assertRaisesRegex(ValidationError, r'x has incorrect length 6; should be 5'):
+ check_string_fixed_length(5)('x', x)
x = "hi"
- self.assertEqual(check_string_fixed_length(5)('x', x), 'x has incorrect length 2; should be 5')
+ with self.assertRaisesRegex(ValidationError, r'x has incorrect length 2; should be 5'):
+ check_string_fixed_length(5)('x', x)
def test_check_capped_string(self) -> None:
x: Any = "hello"
- self.assertEqual(check_capped_string(5)('x', x), None)
+ check_capped_string(5)('x', x)
x = 4
- self.assertEqual(check_capped_string(5)('x', x), 'x is not a string')
+ with self.assertRaisesRegex(ValidationError, r'x is not a string'):
+ check_capped_string(5)('x', x)
x = "helloz"
- self.assertEqual(check_capped_string(5)('x', x), 'x is too long (limit: 5 characters)')
+ with self.assertRaisesRegex(ValidationError, r'x is too long \(limit: 5 characters\)'):
+ check_capped_string(5)('x', x)
x = "hi"
- self.assertEqual(check_capped_string(5)('x', x), None)
+ check_capped_string(5)('x', x)
def test_check_string_in(self) -> None:
- self.assertEqual(check_string_in(['valid', 'othervalid'])('Test', "valid"), None)
- self.assertEqual(check_string_in(['valid', 'othervalid'])('Test', 15), 'Test is not a string')
- self.assertEqual(check_string_in(['valid', 'othervalid'])('Test', "othervalid"), None)
- self.assertEqual(check_string_in(['valid', 'othervalid'])('Test', "invalid"), 'Invalid Test')
+ check_string_in(['valid', 'othervalid'])('Test', "valid")
+ with self.assertRaisesRegex(ValidationError, r'Test is not a string'):
+ check_string_in(['valid', 'othervalid'])('Test', 15)
+ check_string_in(['valid', 'othervalid'])('Test', "othervalid")
+ with self.assertRaisesRegex(ValidationError, r'Invalid Test'):
+ check_string_in(['valid', 'othervalid'])('Test', "invalid")
def test_check_int_in(self) -> None:
- self.assertEqual(check_int_in([1])("Test", 1), None)
- self.assertEqual(check_int_in([1])("Test", 2), "Invalid Test")
- self.assertEqual(check_int_in([1])("Test", "t"), "Test is not an integer")
+ check_int_in([1])("Test", 1)
+ with self.assertRaisesRegex(ValidationError, r"Invalid Test"):
+ check_int_in([1])("Test", 2)
+ with self.assertRaisesRegex(ValidationError, r"Test is not an integer"):
+ check_int_in([1])("Test", "t")
def test_check_short_string(self) -> None:
x: Any = "hello"
- self.assertEqual(check_short_string('x', x), None)
+ check_short_string('x', x)
x = 'x' * 201
- self.assertEqual(check_short_string('x', x), "x is too long (limit: 50 characters)")
+ with self.assertRaisesRegex(ValidationError, r"x is too long \(limit: 50 characters\)"):
+ check_short_string('x', x)
x = 4
- self.assertEqual(check_short_string('x', x), 'x is not a string')
+ with self.assertRaisesRegex(ValidationError, r'x is not a string'):
+ check_short_string('x', x)
def test_check_bool(self) -> None:
x: Any = True
- self.assertEqual(check_bool('x', x), None)
+ check_bool('x', x)
x = 4
- self.assertEqual(check_bool('x', x), 'x is not a boolean')
+ with self.assertRaisesRegex(ValidationError, r'x is not a boolean'):
+ check_bool('x', x)
def test_check_int(self) -> None:
x: Any = 5
- self.assertEqual(check_int('x', x), None)
+ check_int('x', x)
x = [{}]
- self.assertEqual(check_int('x', x), 'x is not an integer')
+ with self.assertRaisesRegex(ValidationError, r'x is not an integer'):
+ check_int('x', x)
def test_to_non_negative_int(self) -> None:
self.assertEqual(to_non_negative_int('5'), 5)
@@ -808,13 +823,15 @@ class ValidatorTestCase(TestCase):
def test_check_float(self) -> None:
x: Any = 5.5
- self.assertEqual(check_float('x', x), None)
+ check_float('x', x)
x = 5
- self.assertEqual(check_float('x', x), 'x is not a float')
+ with self.assertRaisesRegex(ValidationError, r'x is not a float'):
+ check_float('x', x)
x = [{}]
- self.assertEqual(check_float('x', x), 'x is not a float')
+ with self.assertRaisesRegex(ValidationError, r'x is not a float'):
+ check_float('x', x)
def test_check_color(self) -> None:
x = ['#000099', '#80ffaa', '#80FFAA', '#abcd12', '#ffff00', '#ff0', '#f00'] # valid
@@ -822,35 +839,34 @@ class ValidatorTestCase(TestCase):
z = 5 # invalid
for hex_color in x:
- error = check_color('color', hex_color)
- self.assertEqual(error, None)
+ check_color('color', hex_color)
for hex_color in y:
- error = check_color('color', hex_color)
- self.assertEqual(error, 'color is not a valid hex color code')
+ with self.assertRaisesRegex(ValidationError, r'color is not a valid hex color code'):
+ check_color('color', hex_color)
- error = check_color('color', z)
- self.assertEqual(error, 'color is not a string')
+ with self.assertRaisesRegex(ValidationError, r'color is not a string'):
+ check_color('color', z)
def test_check_list(self) -> None:
x: Any = 999
- error = check_list(check_string)('x', x)
- self.assertEqual(error, 'x is not a list')
+ with self.assertRaisesRegex(ValidationError, r'x is not a list'):
+ check_list(check_string)('x', x)
x = ["hello", 5]
- error = check_list(check_string)('x', x)
- self.assertEqual(error, 'x[1] is not a string')
+ with self.assertRaisesRegex(ValidationError, r'x\[1\] is not a string'):
+ check_list(check_string)('x', x)
x = [["yo"], ["hello", "goodbye", 5]]
- error = check_list(check_list(check_string))('x', x)
- self.assertEqual(error, 'x[1][2] is not a string')
+ with self.assertRaisesRegex(ValidationError, r'x\[1\]\[2\] is not a string'):
+ check_list(check_list(check_string))('x', x)
x = ["hello", "goodbye", "hello again"]
- error = check_list(check_string, length=2)('x', x)
- self.assertEqual(error, 'x should have exactly 2 items')
+ with self.assertRaisesRegex(ValidationError, r'x should have exactly 2 items'):
+ check_list(check_string, length=2)('x', x)
def test_check_dict(self) -> None:
- keys: List[Tuple[str, Validator]] = [
+ keys: List[Tuple[str, Validator[object]]] = [
('names', check_list(check_string)),
('city', check_string),
]
@@ -859,58 +875,55 @@ class ValidatorTestCase(TestCase):
'names': ['alice', 'bob'],
'city': 'Boston',
}
- error = check_dict(keys)('x', x)
- self.assertEqual(error, None)
+ check_dict(keys)('x', x)
x = 999
- error = check_dict(keys)('x', x)
- self.assertEqual(error, 'x is not a dict')
+ with self.assertRaisesRegex(ValidationError, r'x is not a dict'):
+ check_dict(keys)('x', x)
x = {}
- error = check_dict(keys)('x', x)
- self.assertEqual(error, 'names key is missing from x')
+ with self.assertRaisesRegex(ValidationError, r'names key is missing from x'):
+ check_dict(keys)('x', x)
x = {
'names': ['alice', 'bob', {}],
}
- error = check_dict(keys)('x', x)
- self.assertEqual(error, 'x["names"][2] is not a string')
+ with self.assertRaisesRegex(ValidationError, r'x\["names"\]\[2\] is not a string'):
+ check_dict(keys)('x', x)
x = {
'names': ['alice', 'bob'],
'city': 5,
}
- error = check_dict(keys)('x', x)
- self.assertEqual(error, 'x["city"] is not a string')
+ with self.assertRaisesRegex(ValidationError, r'x\["city"\] is not a string'):
+ check_dict(keys)('x', x)
x = {
'names': ['alice', 'bob'],
'city': 'Boston',
}
- error = check_dict(value_validator=check_string)('x', x)
- self.assertEqual(error, 'x contains a value that is not a string')
+ with self.assertRaisesRegex(ValidationError, r'x contains a value that is not a string'):
+ check_dict(value_validator=check_string)('x', x)
x = {
'city': 'Boston',
}
- error = check_dict(value_validator=check_string)('x', x)
- self.assertEqual(error, None)
+ check_dict(value_validator=check_string)('x', x)
# test dict_only
x = {
'names': ['alice', 'bob'],
'city': 'Boston',
}
- error = check_dict_only(keys)('x', x)
- self.assertEqual(error, None)
+ check_dict_only(keys)('x', x)
x = {
'names': ['alice', 'bob'],
'city': 'Boston',
'state': 'Massachusetts',
}
- error = check_dict_only(keys)('x', x)
- self.assertEqual(error, 'Unexpected arguments: state')
+ with self.assertRaisesRegex(ValidationError, r'Unexpected arguments: state'):
+ check_dict_only(keys)('x', x)
# Test optional keys
optional_keys = [
@@ -924,100 +937,107 @@ class ValidatorTestCase(TestCase):
'food': ['Lobster Spaghetti'],
}
- error = check_dict(keys)('x', x)
- self.assertEqual(error, None) # since _allow_only_listed_keys is False
+ check_dict(keys)('x', x) # since _allow_only_listed_keys is False
- error = check_dict_only(keys)('x', x)
- self.assertEqual(error, 'Unexpected arguments: food')
+ with self.assertRaisesRegex(ValidationError, r'Unexpected arguments: food'):
+ check_dict_only(keys)('x', x)
- error = check_dict_only(keys, optional_keys)('x', x)
- self.assertEqual(error, None)
+ check_dict_only(keys, optional_keys)('x', x)
x = {
'names': ['alice', 'bob'],
'city': 'Boston',
'food': 'Lobster Spaghetti',
}
- error = check_dict_only(keys, optional_keys)('x', x)
- self.assertEqual(error, 'x["food"] is not a list')
+ with self.assertRaisesRegex(ValidationError, r'x\["food"\] is not a list'):
+ check_dict_only(keys, optional_keys)('x', x)
def test_encapsulation(self) -> None:
# There might be situations where we want deep
# validation, but the error message should be customized.
# This is an example.
- def check_person(val: Any) -> Optional[str]:
- error = check_dict([
- ('name', check_string),
- ('age', check_int),
- ])('_', val)
- if error:
- return 'This is not a valid person'
- return None
+ def check_person(val: object) -> Dict[str, object]:
+ try:
+ return check_dict([
+ ('name', check_string),
+ ('age', check_int),
+ ])('_', val)
+ except ValidationError:
+ raise ValidationError('This is not a valid person')
person = {'name': 'King Lear', 'age': 42}
- self.assertEqual(check_person(person), None)
+ check_person(person)
nonperson = 'misconfigured data'
- self.assertEqual(check_person(nonperson), 'This is not a valid person')
+ with self.assertRaisesRegex(ValidationError, r'This is not a valid person'):
+ check_person(nonperson)
def test_check_union(self) -> None:
x: Any = 5
- self.assertEqual(check_union([check_string, check_int])('x', x), None)
+ check_union([check_string, check_int])('x', x)
x = 'x'
- self.assertEqual(check_union([check_string, check_int])('x', x), None)
+ check_union([check_string, check_int])('x', x)
x = [{}]
- self.assertEqual(check_union([check_string, check_int])('x', x), 'x is not an allowed_type')
+ with self.assertRaisesRegex(ValidationError, r'x is not an allowed_type'):
+ check_union([check_string, check_int])('x', x)
def test_equals(self) -> None:
x: Any = 5
- self.assertEqual(equals(5)('x', x), None)
- self.assertEqual(equals(6)('x', x), 'x != 6 (5 is wrong)')
+ equals(5)('x', x)
+ with self.assertRaisesRegex(ValidationError, r'x != 6 \(5 is wrong\)'):
+ equals(6)('x', x)
def test_check_none_or(self) -> None:
x: Any = 5
- self.assertEqual(check_none_or(check_int)('x', x), None)
+ check_none_or(check_int)('x', x)
x = None
- self.assertEqual(check_none_or(check_int)('x', x), None)
+ check_none_or(check_int)('x', x)
x = 'x'
- self.assertEqual(check_none_or(check_int)('x', x), 'x is not an integer')
+ with self.assertRaisesRegex(ValidationError, r'x is not an integer'):
+ check_none_or(check_int)('x', x)
def test_check_url(self) -> None:
url: Any = "http://127.0.0.1:5002/"
- self.assertEqual(check_url('url', url), None)
+ check_url('url', url)
url = "http://zulip-bots.example.com/"
- self.assertEqual(check_url('url', url), None)
+ check_url('url', url)
url = "http://127.0.0"
- self.assertEqual(check_url('url', url), 'url is not a URL')
+ with self.assertRaisesRegex(ValidationError, r'url is not a URL'):
+ check_url('url', url)
url = 99.3
- self.assertEqual(check_url('url', url), 'url is not a string')
+ with self.assertRaisesRegex(ValidationError, r'url is not a string'):
+ check_url('url', url)
def test_check_string_or_int_list(self) -> None:
x: Any = "string"
- self.assertEqual(check_string_or_int_list('x', x), None)
+ check_string_or_int_list('x', x)
x = [1, 2, 4]
- self.assertEqual(check_string_or_int_list('x', x), None)
+ check_string_or_int_list('x', x)
x = None
- self.assertEqual(check_string_or_int_list('x', x), 'x is not a string or an integer list')
+ with self.assertRaisesRegex(ValidationError, r'x is not a string or an integer list'):
+ check_string_or_int_list('x', x)
x = [1, 2, '3']
- self.assertEqual(check_string_or_int_list('x', x), 'x[2] is not an integer')
+ with self.assertRaisesRegex(ValidationError, r'x\[2\] is not an integer'):
+ check_string_or_int_list('x', x)
def test_check_string_or_int(self) -> None:
x: Any = "string"
- self.assertEqual(check_string_or_int('x', x), None)
+ check_string_or_int('x', x)
x = 1
- self.assertEqual(check_string_or_int('x', x), None)
+ check_string_or_int('x', x)
x = None
- self.assertEqual(check_string_or_int('x', x), 'x is not a string or integer')
+ with self.assertRaisesRegex(ValidationError, r'x is not a string or integer'):
+ check_string_or_int('x', x)
class DeactivatedRealmTest(ZulipTestCase):
diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.py
index 1eb76974c86..6242765a888 100644
--- a/zerver/tests/test_events.py
+++ b/zerver/tests/test_events.py
@@ -491,7 +491,7 @@ class EventsRegisterTest(ZulipTestCase):
def create_bot(self, email: str, **extras: Any) -> Optional[UserProfile]:
return self.create_test_bot(email, self.user_profile, **extras)
- def realm_bot_schema(self, field_name: str, check: Validator) -> Validator:
+ def realm_bot_schema(self, field_name: str, check: Validator[object]) -> Validator[Dict[str, object]]:
return self.check_events_dict([
('type', equals('realm_bot')),
('op', equals('update')),
@@ -576,10 +576,6 @@ class EventsRegisterTest(ZulipTestCase):
self.match_states(hybrid_state, normal_state, events)
return events
- def assert_on_error(self, error: Optional[str]) -> None:
- if error:
- raise AssertionError(error)
-
def match_states(self, state1: Dict[str, Any], state2: Dict[str, Any],
events: List[Dict[str, Any]]) -> None:
def normalize(state: Dict[str, Any]) -> None:
@@ -633,7 +629,7 @@ class EventsRegisterTest(ZulipTestCase):
sys.stdout.flush()
raise AssertionError('Mismatching states')
- def check_events_dict(self, required_keys: List[Tuple[str, Validator]]) -> Validator:
+ def check_events_dict(self, required_keys: List[Tuple[str, Validator[object]]]) -> Validator[Dict[str, object]]:
required_keys.append(('id', check_int))
# Raise AssertionError if `required_keys` contains duplicate items.
keys = [key[0] for key in required_keys]
@@ -683,7 +679,7 @@ class EventsRegisterTest(ZulipTestCase):
)
def test_stream_send_message_events(self) -> None:
- def get_checker(check_gravatar: Validator) -> Validator:
+ def get_checker(check_gravatar: Validator[Optional[str]]) -> Validator[Dict[str, object]]:
schema_checker = self.check_events_dict([
('type', equals('message')),
('flags', check_list(None)),
@@ -717,16 +713,14 @@ class EventsRegisterTest(ZulipTestCase):
client_gravatar=False,
)
schema_checker = get_checker(check_gravatar=check_string)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
events = self.do_test(
lambda: self.send_stream_message(self.example_user("hamlet"), "Verona", "hello"),
client_gravatar=True,
)
schema_checker = get_checker(check_gravatar=equals(None))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
# Verify message editing
schema_checker = self.check_events_dict([
@@ -776,8 +770,7 @@ class EventsRegisterTest(ZulipTestCase):
mentioned_user_ids, mention_data),
state_change_expected=True,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
# Verify do_update_embedded_data
schema_checker = self.check_events_dict([
@@ -795,8 +788,7 @@ class EventsRegisterTest(ZulipTestCase):
"embed_content", "<p>embed_content</p>"),
state_change_expected=False,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_update_message_flags(self) -> None:
# Test message flag update events
@@ -818,8 +810,7 @@ class EventsRegisterTest(ZulipTestCase):
lambda: do_update_message_flags(user_profile, get_client("website"), 'add', 'starred', [message]),
state_change_expected=True,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
schema_checker = self.check_events_dict([
('all', check_bool),
('type', equals('update_message_flags')),
@@ -831,8 +822,7 @@ class EventsRegisterTest(ZulipTestCase):
lambda: do_update_message_flags(user_profile, get_client("website"), 'remove', 'starred', [message]),
state_change_expected=True,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_update_read_flag_removes_unread_msg_ids(self) -> None:
@@ -886,8 +876,7 @@ class EventsRegisterTest(ZulipTestCase):
self.user_profile, message, "tada"),
state_change_expected=False,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_remove_reaction_legacy(self) -> None:
schema_checker = self.check_events_dict([
@@ -913,8 +902,7 @@ class EventsRegisterTest(ZulipTestCase):
self.user_profile, message, "tada"),
state_change_expected=False,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_add_reaction(self) -> None:
schema_checker = self.check_events_dict([
@@ -939,8 +927,7 @@ class EventsRegisterTest(ZulipTestCase):
self.user_profile, message, "tada", "1f389", "unicode_emoji"),
state_change_expected=False,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_add_submessage(self) -> None:
schema_checker = self.check_events_dict([
@@ -968,8 +955,7 @@ class EventsRegisterTest(ZulipTestCase):
),
state_change_expected=False,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_remove_reaction(self) -> None:
schema_checker = self.check_events_dict([
@@ -995,8 +981,7 @@ class EventsRegisterTest(ZulipTestCase):
self.user_profile, message, "1f389", "unicode_emoji"),
state_change_expected=False,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_invite_user_event(self) -> None:
schema_checker = self.check_events_dict([
@@ -1011,8 +996,7 @@ class EventsRegisterTest(ZulipTestCase):
lambda: do_invite_users(self.user_profile, ["[email protected]"], streams, False),
state_change_expected=False,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_create_multiuse_invite_event(self) -> None:
schema_checker = self.check_events_dict([
@@ -1028,8 +1012,7 @@ class EventsRegisterTest(ZulipTestCase):
lambda: do_create_multiuse_invite_link(self.user_profile, PreregistrationUser.INVITE_AS['MEMBER'], streams),
state_change_expected=False,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_revoke_user_invite_event(self) -> None:
schema_checker = self.check_events_dict([
@@ -1046,8 +1029,7 @@ class EventsRegisterTest(ZulipTestCase):
lambda: do_revoke_user_invite(prereg_users[0]),
state_change_expected=False,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_revoke_multiuse_invite_event(self) -> None:
schema_checker = self.check_events_dict([
@@ -1065,8 +1047,7 @@ class EventsRegisterTest(ZulipTestCase):
lambda: do_revoke_multi_use_invite(multiuse_object),
state_change_expected=False,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_invitation_accept_invite_event(self) -> None:
reset_emails_in_zulip_realm()
@@ -1090,8 +1071,7 @@ class EventsRegisterTest(ZulipTestCase):
num_events=5,
)
- error = schema_checker('events[4]', events[4])
- self.assert_on_error(error)
+ schema_checker('events[4]', events[4])
def test_typing_events(self) -> None:
schema_checker = self.check_events_dict([
@@ -1111,8 +1091,7 @@ class EventsRegisterTest(ZulipTestCase):
self.user_profile, [self.example_user("cordelia").id], "start"),
state_change_expected=False,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_custom_profile_fields_events(self) -> None:
schema_checker = self.check_events_dict([
@@ -1133,8 +1112,7 @@ class EventsRegisterTest(ZulipTestCase):
self.user_profile.realm, 'add'),
state_change_expected=False,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
realm = self.user_profile.realm
field = realm.customprofilefield_set.get(realm=realm, name='Biography')
@@ -1147,8 +1125,7 @@ class EventsRegisterTest(ZulipTestCase):
self.user_profile.realm, 'add'),
state_change_expected=False,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_custom_profile_field_data_events(self) -> None:
schema_checker_basic = self.check_events_dict([
@@ -1183,8 +1160,7 @@ class EventsRegisterTest(ZulipTestCase):
"value": "New value",
}
events = self.do_test(lambda: do_update_user_custom_profile_data_if_changed(self.user_profile, [field]))
- error = schema_checker_with_rendered_value('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker_with_rendered_value('events[0]', events[0])
# Test we pass correct stringify value in custom-user-field data event
field_id = self.user_profile.realm.customprofilefield_set.get(
@@ -1194,8 +1170,7 @@ class EventsRegisterTest(ZulipTestCase):
"value": [self.example_user("ZOE").id],
}
events = self.do_test(lambda: do_update_user_custom_profile_data_if_changed(self.user_profile, [field]))
- error = schema_checker_basic('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker_basic('events[0]', events[0])
def test_presence_events(self) -> None:
fields = [
@@ -1219,16 +1194,14 @@ class EventsRegisterTest(ZulipTestCase):
timezone_now(), UserPresence.ACTIVE),
slim_presence=False)
schema_checker = self.check_events_dict(fields + [email_field])
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
events = self.do_test(lambda: do_update_user_presence(
self.example_user('cordelia'), get_client("website"),
timezone_now(), UserPresence.ACTIVE),
slim_presence=True)
schema_checker = self.check_events_dict(fields)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_presence_events_multiple_clients(self) -> None:
schema_checker_android = self.check_events_dict([
@@ -1252,8 +1225,7 @@ class EventsRegisterTest(ZulipTestCase):
self.user_profile, get_client("website"), timezone_now(), UserPresence.ACTIVE))
events = self.do_test(lambda: do_update_user_presence(
self.user_profile, get_client("ZulipAndroid/1.0"), timezone_now(), UserPresence.IDLE))
- error = schema_checker_android('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker_android('events[0]', events[0])
def test_pointer_events(self) -> None:
schema_checker = self.check_events_dict([
@@ -1261,8 +1233,7 @@ class EventsRegisterTest(ZulipTestCase):
('pointer', check_int),
])
events = self.do_test(lambda: do_update_pointer(self.user_profile, get_client("website"), 1500))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_register_events(self) -> None:
realm_user_add_checker = self.check_events_dict([
@@ -1287,8 +1258,7 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(lambda: self.register("[email protected]", "test1"))
self.assert_length(events, 1)
- error = realm_user_add_checker('events[0]', events[0])
- self.assert_on_error(error)
+ realm_user_add_checker('events[0]', events[0])
new_user_profile = get_user_by_delivery_email("[email protected]", self.user_profile.realm)
self.assertEqual(new_user_profile.delivery_email, "[email protected]")
@@ -1318,8 +1288,7 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(lambda: self.register("[email protected]", "test1"))
self.assert_length(events, 1)
- error = realm_user_add_checker('events[0]', events[0])
- self.assert_on_error(error)
+ realm_user_add_checker('events[0]', events[0])
new_user_profile = get_user_by_delivery_email("[email protected]", self.user_profile.realm)
self.assertEqual(new_user_profile.email, f"user{new_user_profile.id}@zulip.testserver")
@@ -1330,12 +1299,10 @@ class EventsRegisterTest(ZulipTestCase):
])
events = self.do_test(lambda: do_add_alert_words(self.user_profile, ["alert_word"]))
- error = alert_words_checker('events[0]', events[0])
- self.assert_on_error(error)
+ alert_words_checker('events[0]', events[0])
events = self.do_test(lambda: do_remove_alert_words(self.user_profile, ["alert_word"]))
- error = alert_words_checker('events[0]', events[0])
- self.assert_on_error(error)
+ alert_words_checker('events[0]', events[0])
def test_away_events(self) -> None:
checker = self.check_events_dict([
@@ -1350,15 +1317,13 @@ class EventsRegisterTest(ZulipTestCase):
away=True,
status_text='out to lunch',
client_id=client.id))
- error = checker('events[0]', events[0])
- self.assert_on_error(error)
+ checker('events[0]', events[0])
events = self.do_test(lambda: do_update_user_status(user_profile=self.user_profile,
away=False,
status_text='',
client_id=client.id))
- error = checker('events[0]', events[0])
- self.assert_on_error(error)
+ checker('events[0]', events[0])
def test_user_group_events(self) -> None:
user_group_add_checker = self.check_events_dict([
@@ -1375,8 +1340,7 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(lambda: check_add_user_group(self.user_profile.realm,
'backend', [othello],
'Backend team'))
- error = user_group_add_checker('events[0]', events[0])
- self.assert_on_error(error)
+ user_group_add_checker('events[0]', events[0])
# Test name update
user_group_update_checker = self.check_events_dict([
@@ -1389,8 +1353,7 @@ class EventsRegisterTest(ZulipTestCase):
])
backend = UserGroup.objects.get(name='backend')
events = self.do_test(lambda: do_update_user_group_name(backend, 'backendteam'))
- error = user_group_update_checker('events[0]', events[0])
- self.assert_on_error(error)
+ user_group_update_checker('events[0]', events[0])
# Test description update
user_group_update_checker = self.check_events_dict([
@@ -1403,8 +1366,7 @@ class EventsRegisterTest(ZulipTestCase):
])
description = "Backend team to deal with backend code."
events = self.do_test(lambda: do_update_user_group_description(backend, description))
- error = user_group_update_checker('events[0]', events[0])
- self.assert_on_error(error)
+ user_group_update_checker('events[0]', events[0])
# Test add members
user_group_add_member_checker = self.check_events_dict([
@@ -1415,8 +1377,7 @@ class EventsRegisterTest(ZulipTestCase):
])
hamlet = self.example_user('hamlet')
events = self.do_test(lambda: bulk_add_members_to_user_group(backend, [hamlet]))
- error = user_group_add_member_checker('events[0]', events[0])
- self.assert_on_error(error)
+ user_group_add_member_checker('events[0]', events[0])
# Test remove members
user_group_remove_member_checker = self.check_events_dict([
@@ -1427,8 +1388,7 @@ class EventsRegisterTest(ZulipTestCase):
])
hamlet = self.example_user('hamlet')
events = self.do_test(lambda: remove_members_from_user_group(backend, [hamlet]))
- error = user_group_remove_member_checker('events[0]', events[0])
- self.assert_on_error(error)
+ user_group_remove_member_checker('events[0]', events[0])
# Test delete event
user_group_remove_checker = self.check_events_dict([
@@ -1437,8 +1397,7 @@ class EventsRegisterTest(ZulipTestCase):
('group_id', check_int),
])
events = self.do_test(lambda: check_delete_user_group(backend.id, othello))
- error = user_group_remove_checker('events[0]', events[0])
- self.assert_on_error(error)
+ user_group_remove_checker('events[0]', events[0])
def test_default_stream_groups_events(self) -> None:
default_stream_groups_checker = self.check_events_dict([
@@ -1468,34 +1427,28 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(lambda: do_create_default_stream_group(
self.user_profile.realm, "group1", "This is group1", streams))
- error = default_stream_groups_checker('events[0]', events[0])
- self.assert_on_error(error)
+ default_stream_groups_checker('events[0]', events[0])
group = lookup_default_stream_groups(["group1"], self.user_profile.realm)[0]
venice_stream = get_stream("Venice", self.user_profile.realm)
events = self.do_test(lambda: do_add_streams_to_default_stream_group(self.user_profile.realm,
group, [venice_stream]))
- error = default_stream_groups_checker('events[0]', events[0])
- self.assert_on_error(error)
+ default_stream_groups_checker('events[0]', events[0])
events = self.do_test(lambda: do_remove_streams_from_default_stream_group(self.user_profile.realm,
group, [venice_stream]))
- error = default_stream_groups_checker('events[0]', events[0])
- self.assert_on_error(error)
+ default_stream_groups_checker('events[0]', events[0])
events = self.do_test(lambda: do_change_default_stream_group_description(self.user_profile.realm,
group, "New description"))
- error = default_stream_groups_checker('events[0]', events[0])
- self.assert_on_error(error)
+ default_stream_groups_checker('events[0]', events[0])
events = self.do_test(lambda: do_change_default_stream_group_name(self.user_profile.realm,
group, "New Group Name"))
- error = default_stream_groups_checker('events[0]', events[0])
- self.assert_on_error(error)
+ default_stream_groups_checker('events[0]', events[0])
events = self.do_test(lambda: do_remove_default_stream_group(self.user_profile.realm, group))
- error = default_stream_groups_checker('events[0]', events[0])
- self.assert_on_error(error)
+ default_stream_groups_checker('events[0]', events[0])
def test_default_stream_group_events_guest(self) -> None:
streams = []
@@ -1515,7 +1468,7 @@ class EventsRegisterTest(ZulipTestCase):
def test_default_streams_events(self) -> None:
default_streams_checker = self.check_events_dict([
('type', equals('default_streams')),
- ('default_streams', check_list(check_dict_only([
+ ('default_streams', check_list(check_dict([
('description', check_string),
('invite_only', check_bool),
('name', check_string),
@@ -1525,10 +1478,9 @@ class EventsRegisterTest(ZulipTestCase):
stream = get_stream("Scotland", self.user_profile.realm)
events = self.do_test(lambda: do_add_default_stream(stream))
- error = default_streams_checker('events[0]', events[0])
+ default_streams_checker('events[0]', events[0])
events = self.do_test(lambda: do_remove_default_stream(stream))
- error = default_streams_checker('events[0]', events[0])
- self.assert_on_error(error)
+ default_streams_checker('events[0]', events[0])
def test_default_streams_events_guest(self) -> None:
do_change_user_role(self.user_profile, UserProfile.ROLE_GUEST)
@@ -1547,13 +1499,11 @@ class EventsRegisterTest(ZulipTestCase):
recipient = stream.recipient
events = self.do_test(lambda: do_mute_topic(
self.user_profile, stream, recipient, "topic"))
- error = muted_topics_checker('events[0]', events[0])
- self.assert_on_error(error)
+ muted_topics_checker('events[0]', events[0])
events = self.do_test(lambda: do_unmute_topic(
self.user_profile, stream, "topic"))
- error = muted_topics_checker('events[0]', events[0])
- self.assert_on_error(error)
+ muted_topics_checker('events[0]', events[0])
def test_change_avatar_fields(self) -> None:
schema_checker = self.check_events_dict([
@@ -1570,8 +1520,7 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(
lambda: do_change_avatar_fields(self.user_profile, UserProfile.AVATAR_FROM_USER),
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
schema_checker = self.check_events_dict([
('type', equals('realm_user')),
@@ -1587,8 +1536,7 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(
lambda: do_change_avatar_fields(self.user_profile, UserProfile.AVATAR_FROM_GRAVATAR),
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_change_full_name(self) -> None:
schema_checker = self.check_events_dict([
@@ -1600,8 +1548,7 @@ class EventsRegisterTest(ZulipTestCase):
])),
])
events = self.do_test(lambda: do_change_full_name(self.user_profile, 'Sir Hamlet', self.user_profile))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_change_user_delivery_email_email_address_visibilty_admins(self) -> None:
schema_checker = self.check_events_dict([
@@ -1631,10 +1578,8 @@ class EventsRegisterTest(ZulipTestCase):
self.user_profile.refresh_from_db()
action = lambda: do_change_user_delivery_email(self.user_profile, '[email protected]')
events = self.do_test(action, num_events=2, client_gravatar=False)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
- error = avatar_schema_checker('events[1]', events[1])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
+ avatar_schema_checker('events[1]', events[1])
def do_set_realm_property_test(self, name: str) -> None:
bool_tests: List[bool] = [True, False, True]
@@ -1687,8 +1632,7 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(
lambda: do_set_realm_property(self.user_profile.realm, name, val),
state_change_expected=state_change_expected)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
@slow("Actually runs several full-stack fetching tests")
def test_change_realm_property(self) -> None:
@@ -1732,8 +1676,7 @@ class EventsRegisterTest(ZulipTestCase):
self.user_profile.realm,
auth_method_dict))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_change_pin_stream(self) -> None:
schema_checker = self.check_events_dict([
@@ -1750,8 +1693,7 @@ class EventsRegisterTest(ZulipTestCase):
do_change_subscription_property(self.user_profile, sub, stream, "pin_to_top", False)
for pinned in (True, False):
events = self.do_test(lambda: do_change_subscription_property(self.user_profile, sub, stream, "pin_to_top", pinned))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_change_stream_notification_settings(self) -> None:
for setting_name in ['email_notifications']:
@@ -1772,14 +1714,12 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(lambda: do_change_subscription_property(self.user_profile, sub, stream,
setting_name, value),
notification_settings_null=True)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
for value in (True, False):
events = self.do_test(lambda: do_change_subscription_property(self.user_profile, sub, stream,
setting_name, value))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
@slow("Runs a matrix of 6 queries to the /home view")
def test_change_realm_message_edit_settings(self) -> None:
@@ -1802,8 +1742,7 @@ class EventsRegisterTest(ZulipTestCase):
allow_message_editing,
message_content_edit_limit_seconds,
False))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_change_realm_notifications_stream(self) -> None:
schema_checker = self.check_events_dict([
@@ -1820,8 +1759,7 @@ class EventsRegisterTest(ZulipTestCase):
lambda: do_set_realm_notifications_stream(self.user_profile.realm,
notifications_stream,
notifications_stream_id))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_change_realm_signup_notifications_stream(self) -> None:
schema_checker = self.check_events_dict([
@@ -1838,8 +1776,7 @@ class EventsRegisterTest(ZulipTestCase):
lambda: do_set_realm_signup_notifications_stream(self.user_profile.realm,
signup_notifications_stream,
signup_notifications_stream_id))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_change_is_admin(self) -> None:
reset_emails_in_zulip_realm()
@@ -1861,8 +1798,7 @@ class EventsRegisterTest(ZulipTestCase):
do_change_user_role(self.user_profile, UserProfile.ROLE_MEMBER)
for role in [UserProfile.ROLE_REALM_ADMINISTRATOR, UserProfile.ROLE_MEMBER]:
events = self.do_test(lambda: do_change_user_role(self.user_profile, role))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_change_is_owner(self) -> None:
reset_emails_in_zulip_realm()
@@ -1884,8 +1820,7 @@ class EventsRegisterTest(ZulipTestCase):
do_change_user_role(self.user_profile, UserProfile.ROLE_MEMBER)
for role in [UserProfile.ROLE_REALM_OWNER, UserProfile.ROLE_MEMBER]:
events = self.do_test(lambda: do_change_user_role(self.user_profile, role))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_change_is_guest(self) -> None:
reset_emails_in_zulip_realm()
@@ -1907,8 +1842,7 @@ class EventsRegisterTest(ZulipTestCase):
do_change_user_role(self.user_profile, UserProfile.ROLE_MEMBER)
for role in [UserProfile.ROLE_GUEST, UserProfile.ROLE_MEMBER]:
events = self.do_test(lambda: do_change_user_role(self.user_profile, role))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def do_set_user_display_settings_test(self, setting_name: str) -> None:
"""Test updating each setting in UserProfile.property_types dict."""
@@ -1960,21 +1894,21 @@ class EventsRegisterTest(ZulipTestCase):
('setting', validator),
])
if setting_name == "default_language":
- error = language_schema_checker('events[0]', events[0])
+ language_schema_checker('events[0]', events[0])
else:
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
timezone_schema_checker = self.check_events_dict([
('type', equals('realm_user')),
('op', equals('update')),
('person', check_dict_only([
+ ('email', check_string),
('user_id', check_int),
('timezone', check_string),
])),
])
if setting_name == "timezone":
- error = timezone_schema_checker('events[1]', events[1])
+ timezone_schema_checker('events[1]', events[1])
@slow("Actually runs several full-stack fetching tests")
def test_set_user_display_settings(self) -> None:
@@ -1999,8 +1933,7 @@ class EventsRegisterTest(ZulipTestCase):
for setting_value in [True, False]:
events = self.do_test(lambda: do_change_notification_settings(
self.user_profile, notification_setting, setting_value, log=False))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
# Also test with notification_settings_null=True
events = self.do_test(
@@ -2008,8 +1941,7 @@ class EventsRegisterTest(ZulipTestCase):
self.user_profile, notification_setting, setting_value, log=False),
notification_settings_null=True,
state_change_expected=False)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_change_notification_sound(self) -> None:
notification_setting = "notification_sound"
@@ -2022,8 +1954,7 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(lambda: do_change_notification_settings(
self.user_profile, notification_setting, 'ding', log=False))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_change_desktop_icon_count_display(self) -> None:
notification_setting = "desktop_icon_count_display"
@@ -2036,8 +1967,7 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(lambda: do_change_notification_settings(
self.user_profile, notification_setting, 2, log=False))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
schema_checker = self.check_events_dict([
('type', equals('update_global_notifications')),
@@ -2048,8 +1978,7 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(lambda: do_change_notification_settings(
self.user_profile, notification_setting, 1, log=False))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_realm_update_plan_type(self) -> None:
realm = self.user_profile.realm
@@ -2068,8 +1997,7 @@ class EventsRegisterTest(ZulipTestCase):
])),
])
events = self.do_test(lambda: do_change_plan_type(realm, Realm.LIMITED))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
state_data = fetch_initial_state_data(self.user_profile, None, "", False, False)
self.assertEqual(state_data['realm_plan_type'], Realm.LIMITED)
@@ -2087,12 +2015,10 @@ class EventsRegisterTest(ZulipTestCase):
"my_emoji",
author,
img_file))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
events = self.do_test(lambda: do_remove_realm_emoji(self.user_profile.realm, "my_emoji"))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_realm_filter_events(self) -> None:
schema_checker = self.check_events_dict([
@@ -2101,12 +2027,10 @@ class EventsRegisterTest(ZulipTestCase):
])
events = self.do_test(lambda: do_add_realm_filter(self.user_profile.realm, "#(?P<id>[123])",
"https://realm.com/my_realm_filter/%(id)s"))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
events = self.do_test(lambda: do_remove_realm_filter(self.user_profile.realm, "#(?P<id>[123])"))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_realm_domain_events(self) -> None:
schema_checker = self.check_events_dict([
@@ -2119,8 +2043,7 @@ class EventsRegisterTest(ZulipTestCase):
])
events = self.do_test(lambda: do_add_realm_domain(
self.user_profile.realm, 'zulip.org', False))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
schema_checker = self.check_events_dict([
('type', equals('realm_domains')),
@@ -2133,8 +2056,7 @@ class EventsRegisterTest(ZulipTestCase):
test_domain = RealmDomain.objects.get(realm=self.user_profile.realm,
domain='zulip.org')
events = self.do_test(lambda: do_change_realm_domain(test_domain, True))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
schema_checker = self.check_events_dict([
('type', equals('realm_domains')),
@@ -2142,12 +2064,11 @@ class EventsRegisterTest(ZulipTestCase):
('domain', equals('zulip.org')),
])
events = self.do_test(lambda: do_remove_realm_domain(test_domain))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_create_bot(self) -> None:
- def get_bot_created_checker(bot_type: str) -> Validator:
+ def get_bot_created_checker(bot_type: str) -> Validator[object]:
if bot_type == "GENERIC_BOT":
check_services = check_list(sub_validator=None, length=0)
elif bot_type == "OUTGOING_WEBHOOK_BOT":
@@ -2181,8 +2102,7 @@ class EventsRegisterTest(ZulipTestCase):
])
action = lambda: self.create_bot('test')
events = self.do_test(action, num_events=2)
- error = get_bot_created_checker(bot_type="GENERIC_BOT")('events[1]', events[1])
- self.assert_on_error(error)
+ get_bot_created_checker(bot_type="GENERIC_BOT")('events[1]', events[1])
action = lambda: self.create_bot('test_outgoing_webhook',
full_name='Outgoing Webhook Bot',
@@ -2192,8 +2112,7 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(action, num_events=2)
# The third event is the second call of notify_created_bot, which contains additional
# data for services (in contrast to the first call).
- error = get_bot_created_checker(bot_type="OUTGOING_WEBHOOK_BOT")('events[1]', events[1])
- self.assert_on_error(error)
+ get_bot_created_checker(bot_type="OUTGOING_WEBHOOK_BOT")('events[1]', events[1])
action = lambda: self.create_bot('test_embedded',
full_name='Embedded Bot',
@@ -2201,30 +2120,26 @@ class EventsRegisterTest(ZulipTestCase):
config_data=ujson.dumps({'foo': 'bar'}),
bot_type=UserProfile.EMBEDDED_BOT)
events = self.do_test(action, num_events=2)
- error = get_bot_created_checker(bot_type="EMBEDDED_BOT")('events[1]', events[1])
- self.assert_on_error(error)
+ get_bot_created_checker(bot_type="EMBEDDED_BOT")('events[1]', events[1])
def test_change_bot_full_name(self) -> None:
bot = self.create_bot('test')
action = lambda: do_change_full_name(bot, 'New Bot Name', self.user_profile)
events = self.do_test(action, num_events=2)
- error = self.realm_bot_schema('full_name', check_string)('events[1]', events[1])
- self.assert_on_error(error)
+ self.realm_bot_schema('full_name', check_string)('events[1]', events[1])
def test_regenerate_bot_api_key(self) -> None:
bot = self.create_bot('test')
action = lambda: do_regenerate_api_key(bot, self.user_profile)
events = self.do_test(action)
- error = self.realm_bot_schema('api_key', check_string)('events[0]', events[0])
- self.assert_on_error(error)
+ self.realm_bot_schema('api_key', check_string)('events[0]', events[0])
def test_change_bot_avatar_source(self) -> None:
bot = self.create_bot('test')
action = lambda: do_change_avatar_fields(bot, bot.AVATAR_FROM_USER)
events = self.do_test(action, num_events=2)
- error = self.realm_bot_schema('avatar_url', check_string)('events[0]', events[0])
+ self.realm_bot_schema('avatar_url', check_string)('events[0]', events[0])
self.assertEqual(events[1]['type'], 'realm_user')
- self.assert_on_error(error)
def test_change_realm_icon_source(self) -> None:
action = lambda: do_change_icon_source(self.user_profile.realm, Realm.ICON_UPLOADED)
@@ -2238,8 +2153,7 @@ class EventsRegisterTest(ZulipTestCase):
('icon_source', check_string),
])),
])
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_change_realm_day_mode_logo_source(self) -> None:
action = lambda: do_change_logo_source(self.user_profile.realm, Realm.LOGO_UPLOADED, False)
@@ -2253,8 +2167,7 @@ class EventsRegisterTest(ZulipTestCase):
('logo_source', check_string),
])),
])
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_change_realm_night_mode_logo_source(self) -> None:
action = lambda: do_change_logo_source(self.user_profile.realm, Realm.LOGO_UPLOADED, True)
@@ -2268,15 +2181,13 @@ class EventsRegisterTest(ZulipTestCase):
('night_logo_source', check_string),
])),
])
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_change_bot_default_all_public_streams(self) -> None:
bot = self.create_bot('test')
action = lambda: do_change_default_all_public_streams(bot, True)
events = self.do_test(action)
- error = self.realm_bot_schema('default_all_public_streams', check_bool)('events[0]', events[0])
- self.assert_on_error(error)
+ self.realm_bot_schema('default_all_public_streams', check_bool)('events[0]', events[0])
def test_change_bot_default_sending_stream(self) -> None:
bot = self.create_bot('test')
@@ -2284,13 +2195,11 @@ class EventsRegisterTest(ZulipTestCase):
action = lambda: do_change_default_sending_stream(bot, stream)
events = self.do_test(action)
- error = self.realm_bot_schema('default_sending_stream', check_string)('events[0]', events[0])
- self.assert_on_error(error)
+ self.realm_bot_schema('default_sending_stream', check_string)('events[0]', events[0])
action = lambda: do_change_default_sending_stream(bot, None)
events = self.do_test(action)
- error = self.realm_bot_schema('default_sending_stream', equals(None))('events[0]', events[0])
- self.assert_on_error(error)
+ self.realm_bot_schema('default_sending_stream', equals(None))('events[0]', events[0])
def test_change_bot_default_events_register_stream(self) -> None:
bot = self.create_bot('test')
@@ -2298,13 +2207,11 @@ class EventsRegisterTest(ZulipTestCase):
action = lambda: do_change_default_events_register_stream(bot, stream)
events = self.do_test(action)
- error = self.realm_bot_schema('default_events_register_stream', check_string)('events[0]', events[0])
- self.assert_on_error(error)
+ self.realm_bot_schema('default_events_register_stream', check_string)('events[0]', events[0])
action = lambda: do_change_default_events_register_stream(bot, None)
events = self.do_test(action)
- error = self.realm_bot_schema('default_events_register_stream', equals(None))('events[0]', events[0])
- self.assert_on_error(error)
+ self.realm_bot_schema('default_events_register_stream', equals(None))('events[0]', events[0])
def test_change_bot_owner(self) -> None:
change_bot_owner_checker_user = self.check_events_dict([
@@ -2329,10 +2236,8 @@ class EventsRegisterTest(ZulipTestCase):
bot = self.create_bot('test')
action = lambda: do_change_bot_owner(bot, owner, self.user_profile)
events = self.do_test(action, num_events=2)
- error = change_bot_owner_checker_bot('events[0]', events[0])
- self.assert_on_error(error)
- error = change_bot_owner_checker_user('events[1]', events[1])
- self.assert_on_error(error)
+ change_bot_owner_checker_bot('events[0]', events[0])
+ change_bot_owner_checker_user('events[1]', events[1])
change_bot_owner_checker_bot = self.check_events_dict([
('type', equals('realm_bot')),
@@ -2346,10 +2251,8 @@ class EventsRegisterTest(ZulipTestCase):
bot = self.create_bot('test1', full_name='Test1 Testerson')
action = lambda: do_change_bot_owner(bot, owner, self.user_profile)
events = self.do_test(action, num_events=2)
- error = change_bot_owner_checker_bot('events[0]', events[0])
- self.assert_on_error(error)
- error = change_bot_owner_checker_user('events[1]', events[1])
- self.assert_on_error(error)
+ change_bot_owner_checker_bot('events[0]', events[0])
+ change_bot_owner_checker_user('events[1]', events[1])
check_services = check_list(sub_validator=None, length=0)
change_bot_owner_checker_bot = self.check_events_dict([
@@ -2375,10 +2278,8 @@ class EventsRegisterTest(ZulipTestCase):
bot = self.create_test_bot('test2', previous_owner, full_name='Test2 Testerson')
action = lambda: do_change_bot_owner(bot, self.user_profile, previous_owner)
events = self.do_test(action, num_events=2)
- error = change_bot_owner_checker_bot('events[0]', events[0])
- self.assert_on_error(error)
- error = change_bot_owner_checker_user('events[1]', events[1])
- self.assert_on_error(error)
+ change_bot_owner_checker_bot('events[0]', events[0])
+ change_bot_owner_checker_user('events[1]', events[1])
def test_do_update_outgoing_webhook_service(self) -> None:
update_outgoing_webhook_service_checker = self.check_events_dict([
@@ -2402,8 +2303,7 @@ class EventsRegisterTest(ZulipTestCase):
)
action = lambda: do_update_outgoing_webhook_service(bot, 2, 'http://hostname.domain2.com')
events = self.do_test(action)
- error = update_outgoing_webhook_service_checker('events[0]', events[0])
- self.assert_on_error(error)
+ update_outgoing_webhook_service_checker('events[0]', events[0])
def test_do_deactivate_user(self) -> None:
bot_deactivate_checker = self.check_events_dict([
@@ -2417,8 +2317,7 @@ class EventsRegisterTest(ZulipTestCase):
bot = self.create_bot('test')
action = lambda: do_deactivate_user(bot)
events = self.do_test(action, num_events=2)
- error = bot_deactivate_checker('events[1]', events[1])
- self.assert_on_error(error)
+ bot_deactivate_checker('events[1]', events[1])
def test_do_reactivate_user(self) -> None:
bot_reactivate_checker = self.check_events_dict([
@@ -2446,8 +2345,7 @@ class EventsRegisterTest(ZulipTestCase):
do_deactivate_user(bot)
action = lambda: do_reactivate_user(bot)
events = self.do_test(action, num_events=2)
- error = bot_reactivate_checker('events[1]', events[1])
- self.assert_on_error(error)
+ bot_reactivate_checker('events[1]', events[1])
def test_do_mark_hotspot_as_read(self) -> None:
self.user_profile.tutorial_status = UserProfile.TUTORIAL_WAITING
@@ -2463,8 +2361,7 @@ class EventsRegisterTest(ZulipTestCase):
]))),
])
events = self.do_test(lambda: do_mark_hotspot_as_read(self.user_profile, 'intro_reply'))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_rename_stream(self) -> None:
stream = self.make_stream('old_name')
@@ -2482,8 +2379,7 @@ class EventsRegisterTest(ZulipTestCase):
('stream_id', check_int),
('name', equals('old_name')),
])
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
schema_checker = self.check_events_dict([
('type', equals('stream')),
('op', equals('update')),
@@ -2492,8 +2388,7 @@ class EventsRegisterTest(ZulipTestCase):
('name', equals('old_name')),
('stream_id', check_int),
])
- error = schema_checker('events[1]', events[1])
- self.assert_on_error(error)
+ schema_checker('events[1]', events[1])
schema_checker = check_dict([
('flags', check_list(check_string)),
('type', equals('message')),
@@ -2521,8 +2416,7 @@ class EventsRegisterTest(ZulipTestCase):
])),
('id', check_int),
])
- error = schema_checker('events[2]', events[2])
- self.assert_on_error(error)
+ schema_checker('events[2]', events[2])
def test_deactivate_stream_neversubscribed(self) -> None:
stream = self.make_stream('old_name')
@@ -2535,8 +2429,7 @@ class EventsRegisterTest(ZulipTestCase):
('op', equals('delete')),
('streams', check_list(check_dict([]))),
])
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_subscribe_other_user_never_subscribed(self) -> None:
action = lambda: self.subscribe(self.example_user("othello"), "test_stream")
@@ -2547,8 +2440,7 @@ class EventsRegisterTest(ZulipTestCase):
('user_id', check_int),
('stream_id', check_int),
])
- error = peer_add_schema_checker('events[1]', events[1])
- self.assert_on_error(error)
+ peer_add_schema_checker('events[1]', events[1])
@slow("Actually several tests combined together")
def test_subscribe_events(self) -> None:
@@ -2591,7 +2483,7 @@ class EventsRegisterTest(ZulipTestCase):
stream_create_schema_checker = self.check_events_dict([
('type', equals('stream')),
('op', equals('create')),
- ('streams', check_list(check_dict_only([
+ ('streams', check_list(check_dict([
('name', check_string),
('stream_id', check_int),
('invite_only', check_bool),
@@ -2665,8 +2557,7 @@ class EventsRegisterTest(ZulipTestCase):
action: Callable[[], object] = lambda: self.subscribe(self.example_user("hamlet"), "test_stream")
events = self.do_test(action, event_types=["subscription", "realm_user"],
include_subscribers=include_subscribers)
- error = add_schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ add_schema_checker('events[0]', events[0])
# Add another user to that totally new stream
action = lambda: self.subscribe(self.example_user("othello"), "test_stream")
@@ -2674,8 +2565,7 @@ class EventsRegisterTest(ZulipTestCase):
include_subscribers=include_subscribers,
state_change_expected=include_subscribers,
)
- error = peer_add_schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ peer_add_schema_checker('events[0]', events[0])
stream = get_stream("test_stream", self.user_profile.realm)
@@ -2688,8 +2578,7 @@ class EventsRegisterTest(ZulipTestCase):
include_subscribers=include_subscribers,
state_change_expected=include_subscribers,
)
- error = peer_remove_schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ peer_remove_schema_checker('events[0]', events[0])
# Now remove the second user, to test the 'vacate' event flow
action = lambda: bulk_remove_subscriptions(
@@ -2699,42 +2588,36 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(action,
include_subscribers=include_subscribers,
num_events=3)
- error = remove_schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ remove_schema_checker('events[0]', events[0])
# Now resubscribe a user, to make sure that works on a vacated stream
action = lambda: self.subscribe(self.example_user("hamlet"), "test_stream")
events = self.do_test(action,
include_subscribers=include_subscribers,
num_events=2)
- error = add_schema_checker('events[1]', events[1])
- self.assert_on_error(error)
+ add_schema_checker('events[1]', events[1])
action = lambda: do_change_stream_description(stream, 'new description')
events = self.do_test(action,
include_subscribers=include_subscribers)
- error = stream_update_schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ stream_update_schema_checker('events[0]', events[0])
# Update stream privacy
action = lambda: do_change_stream_invite_only(stream, True, history_public_to_subscribers=True)
events = self.do_test(action,
include_subscribers=include_subscribers)
- error = stream_update_invite_only_schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ stream_update_invite_only_schema_checker('events[0]', events[0])
# Update stream stream_post_policy property
action = lambda: do_change_stream_post_policy(stream, Stream.STREAM_POST_POLICY_ADMINS)
events = self.do_test(action,
include_subscribers=include_subscribers, num_events=2)
- error = stream_update_stream_post_policy_schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ stream_update_stream_post_policy_schema_checker('events[0]', events[0])
action = lambda: do_change_stream_message_retention_days(stream, -1)
events = self.do_test(action,
include_subscribers=include_subscribers, num_events=1)
- error = stream_update_message_retention_days_schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ stream_update_message_retention_days_schema_checker('events[0]', events[0])
# Subscribe to a totally new invite-only stream, so it's just Hamlet on it
stream = self.make_stream("private", self.user_profile.realm, invite_only=True)
@@ -2742,9 +2625,8 @@ class EventsRegisterTest(ZulipTestCase):
action = lambda: bulk_add_subscriptions([stream], [user_profile])
events = self.do_test(action, include_subscribers=include_subscribers,
num_events=2)
- error = stream_create_schema_checker('events[0]', events[0])
- error = add_schema_checker('events[1]', events[1])
- self.assert_on_error(error)
+ stream_create_schema_checker('events[0]', events[0])
+ add_schema_checker('events[1]', events[1])
def test_do_delete_message_stream(self) -> None:
schema_checker = self.check_events_dict([
@@ -2765,8 +2647,7 @@ class EventsRegisterTest(ZulipTestCase):
lambda: do_delete_messages(self.user_profile.realm, messages),
state_change_expected=True,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_do_delete_message_stream_legacy(self) -> None:
"""
@@ -2792,8 +2673,7 @@ class EventsRegisterTest(ZulipTestCase):
state_change_expected=True, bulk_message_deletion=False,
num_events=2
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_do_delete_message_personal(self) -> None:
schema_checker = self.check_events_dict([
@@ -2813,8 +2693,7 @@ class EventsRegisterTest(ZulipTestCase):
lambda: do_delete_messages(self.user_profile.realm, [message]),
state_change_expected=True,
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_do_delete_message_personal_legacy(self) -> None:
schema_checker = self.check_events_dict([
@@ -2834,8 +2713,7 @@ class EventsRegisterTest(ZulipTestCase):
lambda: do_delete_messages(self.user_profile.realm, [message]),
state_change_expected=True, bulk_message_deletion=False
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_do_delete_message_no_max_id(self) -> None:
user_profile = self.example_user('aaron')
@@ -2887,8 +2765,7 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(
lambda: do_upload(),
num_events=1, state_change_expected=False)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
# Verify that the DB has the attachment marked as unclaimed
entry = Attachment.objects.get(file_name='zulip.txt')
@@ -2918,8 +2795,7 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(
lambda: self.send_stream_message(self.example_user("hamlet"), "Denmark", body, "test"),
num_events=2)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
# Now remove the attachment
schema_checker = self.check_events_dict([
@@ -2934,8 +2810,7 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(
lambda: self.client_delete(f"/json/attachments/{entry.id}"),
num_events=1, state_change_expected=False)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
def test_notify_realm_export(self) -> None:
pending_schema_checker = self.check_events_dict([
@@ -2975,12 +2850,10 @@ class EventsRegisterTest(ZulipTestCase):
state_change_expected=True, num_events=3)
# We first notify when an export is initiated,
- error = pending_schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ pending_schema_checker('events[0]', events[0])
# The second event is then a message from notification-bot.
- error = schema_checker('events[2]', events[2])
- self.assert_on_error(error)
+ schema_checker('events[2]', events[2])
# Now we check the deletion of the export.
deletion_schema_checker = self.check_events_dict([
@@ -3001,8 +2874,7 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(
lambda: self.client_delete(f'/json/export/realm/{audit_log_entry.id}'),
state_change_expected=False, num_events=1)
- error = deletion_schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ deletion_schema_checker('events[0]', events[0])
def test_notify_realm_export_on_failure(self) -> None:
pending_schema_checker = self.check_events_dict([
@@ -3041,11 +2913,9 @@ class EventsRegisterTest(ZulipTestCase):
lambda: self.client_post('/json/export/realm'),
state_change_expected=False, num_events=2)
- error = pending_schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ pending_schema_checker('events[0]', events[0])
- error = failed_schema_checker('events[1]', events[1])
- self.assert_on_error(error)
+ failed_schema_checker('events[1]', events[1])
def test_has_zoom_token(self) -> None:
schema_checker = self.check_events_dict([
@@ -3055,16 +2925,14 @@ class EventsRegisterTest(ZulipTestCase):
events = self.do_test(
lambda: do_set_zoom_token(self.user_profile, {'access_token': 'token'}),
)
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
schema_checker = self.check_events_dict([
('type', equals('has_zoom_token')),
('value', equals(False)),
])
events = self.do_test(lambda: do_set_zoom_token(self.user_profile, None))
- error = schema_checker('events[0]', events[0])
- self.assert_on_error(error)
+ schema_checker('events[0]', events[0])
class FetchInitialStateDataTest(ZulipTestCase):
# Non-admin users don't have access to all bots
diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.py
index c33d28aa3be..f2d2f6ec8b3 100644
--- a/zerver/tests/test_users.py
+++ b/zerver/tests/test_users.py
@@ -5,6 +5,7 @@ from unittest import mock
import ujson
from django.conf import settings
+from django.core.exceptions import ValidationError
from django.test import override_settings
from zerver.lib.actions import (
@@ -876,36 +877,36 @@ class UserProfileTest(ZulipTestCase):
# Invalid user ID
invalid_uid: Any = 1000
- self.assertEqual(check_valid_user_ids(realm.id, invalid_uid),
- "User IDs is not a list")
- self.assertEqual(check_valid_user_ids(realm.id, [invalid_uid]),
- f"Invalid user ID: {invalid_uid}")
+ with self.assertRaisesRegex(ValidationError, r"User IDs is not a list"):
+ check_valid_user_ids(realm.id, invalid_uid)
+ with self.assertRaisesRegex(ValidationError, rf"Invalid user ID: {invalid_uid}"):
+ check_valid_user_ids(realm.id, [invalid_uid])
invalid_uid = "abc"
- self.assertEqual(check_valid_user_ids(realm.id, [invalid_uid]),
- "User IDs[0] is not an integer")
+ with self.assertRaisesRegex(ValidationError, r"User IDs\[0\] is not an integer"):
+ check_valid_user_ids(realm.id, [invalid_uid])
+
invalid_uid = str(othello.id)
- self.assertEqual(check_valid_user_ids(realm.id, [invalid_uid]),
- "User IDs[0] is not an integer")
+ with self.assertRaisesRegex(ValidationError, r"User IDs\[0\] is not an integer"):
+ check_valid_user_ids(realm.id, [invalid_uid])
# User is in different realm
- self.assertEqual(check_valid_user_ids(get_realm("zephyr").id, [hamlet.id]),
- f"Invalid user ID: {hamlet.id}")
+ with self.assertRaisesRegex(ValidationError, rf"Invalid user ID: {hamlet.id}"):
+ check_valid_user_ids(get_realm("zephyr").id, [hamlet.id])
# User is not active
hamlet.is_active = False
hamlet.save()
- self.assertEqual(check_valid_user_ids(realm.id, [hamlet.id]),
- f"User with ID {hamlet.id} is deactivated")
- self.assertEqual(check_valid_user_ids(realm.id, [hamlet.id], allow_deactivated=True),
- None)
+ with self.assertRaisesRegex(ValidationError, rf"User with ID {hamlet.id} is deactivated"):
+ check_valid_user_ids(realm.id, [hamlet.id])
+ check_valid_user_ids(realm.id, [hamlet.id], allow_deactivated=True)
# User is a bot
- self.assertEqual(check_valid_user_ids(realm.id, [bot.id]),
- f"User with ID {bot.id} is a bot")
+ with self.assertRaisesRegex(ValidationError, rf"User with ID {bot.id} is a bot"):
+ check_valid_user_ids(realm.id, [bot.id])
# Successfully get non-bot, active user belong to your realm
- self.assertEqual(check_valid_user_ids(realm.id, [othello.id]), None)
+ check_valid_user_ids(realm.id, [othello.id])
def test_cache_invalidation(self) -> None:
hamlet = self.example_user('hamlet')
diff --git a/zerver/tests/test_widgets.py b/zerver/tests/test_widgets.py
index d362930c302..9f3579c0b4c 100644
--- a/zerver/tests/test_widgets.py
+++ b/zerver/tests/test_widgets.py
@@ -1,6 +1,8 @@
+import re
from typing import Any, Dict
import ujson
+from django.core.exceptions import ValidationError
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.validator import check_widget_content
@@ -11,7 +13,8 @@ from zerver.models import SubMessage
class WidgetContentTestCase(ZulipTestCase):
def test_validation(self) -> None:
def assert_error(obj: object, msg: str) -> None:
- self.assertEqual(check_widget_content(obj), msg)
+ with self.assertRaisesRegex(ValidationError, re.escape(msg)):
+ check_widget_content(obj)
assert_error(5,
'widget_content is not a dict')
@@ -57,7 +60,7 @@ class WidgetContentTestCase(ZulipTestCase):
dict(short_name='a', long_name='foo', reply='bar'),
]
- self.assertEqual(check_widget_content(obj), None)
+ check_widget_content(obj)
def test_message_error_handling(self) -> None:
sender = self.example_user('cordelia')
diff --git a/zerver/views/custom_profile_fields.py b/zerver/views/custom_profile_fields.py
index 883dd96ef6e..57ac632debc 100644
--- a/zerver/views/custom_profile_fields.py
+++ b/zerver/views/custom_profile_fields.py
@@ -1,6 +1,7 @@
from typing import Dict, List, Union
import ujson
+from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.http import HttpRequest, HttpResponse
from django.utils.translation import ugettext as _
@@ -44,27 +45,24 @@ def validate_field_name_and_hint(name: str, hint: str) -> None:
if not name.strip():
raise JsonableError(_("Label cannot be blank."))
- error = hint_validator('hint', hint)
- if error:
- raise JsonableError(error)
-
- error = name_validator('name', name)
- if error:
- raise JsonableError(error)
+ try:
+ hint_validator('hint', hint)
+ name_validator('name', name)
+ except ValidationError as error:
+ raise JsonableError(error.message)
def validate_custom_field_data(field_type: int,
field_data: ProfileFieldData) -> None:
- error = None
- if field_type == CustomProfileField.CHOICE:
- # Choice type field must have at least have one choice
- if len(field_data) < 1:
- raise JsonableError(_("Field must have at least one choice."))
- error = validate_choice_field_data(field_data)
- elif field_type == CustomProfileField.EXTERNAL_ACCOUNT:
- error = validate_external_account_field_data(field_data)
-
- if error:
- raise JsonableError(error)
+ try:
+ if field_type == CustomProfileField.CHOICE:
+ # Choice type field must have at least have one choice
+ if len(field_data) < 1:
+ raise JsonableError(_("Field must have at least one choice."))
+ validate_choice_field_data(field_data)
+ elif field_type == CustomProfileField.EXTERNAL_ACCOUNT:
+ validate_external_account_field_data(field_data)
+ except ValidationError as error:
+ raise JsonableError(error.message)
def is_default_external_field(field_type: int, field_data: ProfileFieldData) -> bool:
if field_type != CustomProfileField.EXTERNAL_ACCOUNT:
diff --git a/zerver/views/messages.py b/zerver/views/messages.py
index 7e8ac962da6..fd61dab71db 100644
--- a/zerver/views/messages.py
+++ b/zerver/views/messages.py
@@ -608,9 +608,10 @@ def narrow_parameter(json: str) -> OptionalNarrowListT:
('operand', operand_validator),
])
- error = validator('elem', elem)
- if error:
- raise JsonableError(error)
+ try:
+ validator('elem', elem)
+ except ValidationError as error:
+ raise JsonableError(error.message)
# whitelist the fields we care about for now
return dict(
diff --git a/zerver/views/streams.py b/zerver/views/streams.py
index 5b0e8010270..9ff2a92e424 100644
--- a/zerver/views/streams.py
+++ b/zerver/views/streams.py
@@ -15,6 +15,7 @@ from typing import (
import ujson
from django.conf import settings
+from django.core.exceptions import ValidationError
from django.db import transaction
from django.http import HttpRequest, HttpResponse
from django.utils.translation import ugettext as _
@@ -710,9 +711,10 @@ def update_subscription_properties_backend(
if sub is None:
return json_error(_("Not subscribed to stream id {}").format(stream_id))
- property_conversion = property_converters[property](property, value)
- if property_conversion:
- return json_error(property_conversion)
+ try:
+ value = property_converters[property](property, value)
+ except ValidationError as error:
+ return json_error(error.message)
do_change_subscription_property(user_profile, sub, stream,
property, value)
diff --git a/zproject/backends.py b/zproject/backends.py
index a5034ba1087..44443009002 100644
--- a/zproject/backends.py
+++ b/zproject/backends.py
@@ -628,9 +628,10 @@ class ZulipLDAPAuthBackendBase(ZulipAuthMixin, LDAPBackend):
raise ZulipLDAPException(f'Custom profile field with name {var_name} not found.')
if existing_values.get(var_name) == value:
continue
- result = validate_user_custom_profile_field(user_profile.realm.id, field, value)
- if result is not None:
- raise ZulipLDAPException(f'Invalid data for {var_name} field: {result}')
+ try:
+ validate_user_custom_profile_field(user_profile.realm.id, field, value)
+ except ValidationError as error:
+ raise ZulipLDAPException(f'Invalid data for {var_name} field: {error.message}')
profile_data.append({
'id': field.id,
'value': value,