Skip to content

armgit / zulip

Public Imported from GitHub
0

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

validator: Fix type errors hidden by bad Any use in set_type_structure.

Anders Kaseorg07fa63e0c871
diff --git a/zerver/lib/validator.py b/zerver/lib/validator.py
index fa89a9ceb50..848031b8dee 100644
--- a/zerver/lib/validator.py
+++ b/zerver/lib/validator.py
@@ -53,7 +53,7 @@ from django.utils.translation import ugettext as _
from zerver.lib.request import JsonableError, ResultT
from zerver.lib.types import ProfileFieldData, Validator
-FuncT = Callable[..., Any]
+FuncT = TypeVar("FuncT", bound=Callable[..., object])
TypeStructure = TypeVar("TypeStructure")
USING_TYPE_STRUCTURE = settings.LOG_API_EVENT_TYPES
@@ -63,7 +63,7 @@ USING_TYPE_STRUCTURE = settings.LOG_API_EVENT_TYPES
#
# Ultimately, it should be possible to do this with mypy rather than a
# parallel system.
-def set_type_structure(type_structure: TypeStructure) -> Callable[[FuncT], Any]:
+def set_type_structure(type_structure: TypeStructure) -> Callable[[FuncT], FuncT]:
def _set_type_structure(func: FuncT) -> FuncT:
if USING_TYPE_STRUCTURE:
func.type_structure = type_structure # type: ignore[attr-defined] # monkey-patching
@@ -111,7 +111,7 @@ def check_capped_string(max_length: int) -> Validator[str]:
def check_string_fixed_length(length: int) -> Validator[str]:
@set_type_structure("str")
- def validator(var_name: str, val: object) -> Optional[str]:
+ def validator(var_name: str, val: object) -> str:
s = check_string(var_name, val)
if len(s) != length:
raise ValidationError(_("{var_name} has incorrect length {length}; should be {target_length}").format(
@@ -172,7 +172,7 @@ def check_color(var_name: str, val: object) -> str:
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[ResultT]) -> Validator[ResultT]:
+def check_none_or(sub_validator: Validator[ResultT]) -> Validator[Optional[ResultT]]:
if USING_TYPE_STRUCTURE:
type_structure = 'none_or_' + sub_validator.type_structure # type: ignore[attr-defined] # monkey-patching
else:
diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.py
index d9a2756a221..c721d9f0e28 100644
--- a/zerver/tests/test_events.py
+++ b/zerver/tests/test_events.py
@@ -1605,7 +1605,7 @@ class EventsRegisterTest(ZulipTestCase):
vals = test_values.get(name)
property_type = Realm.property_types[name]
if property_type is bool:
- validator = check_bool
+ validator: Validator[object] = check_bool
vals = bool_tests
elif property_type is str:
validator = check_string
@@ -1857,7 +1857,7 @@ class EventsRegisterTest(ZulipTestCase):
property_type = UserProfile.property_types[setting_name]
if property_type is bool:
- validator = check_bool
+ validator: Validator[object] = check_bool
elif property_type is str:
validator = check_string
elif property_type is int:
diff --git a/zerver/views/message_fetch.py b/zerver/views/message_fetch.py
index e4352400240..257e1ebadc5 100644
--- a/zerver/views/message_fetch.py
+++ b/zerver/views/message_fetch.py
@@ -41,6 +41,7 @@ from zerver.lib.streams import (
)
from zerver.lib.topic import DB_TOPIC_NAME, MATCH_TOPIC, topic_column_sa, topic_match_sa
from zerver.lib.topic_mutes import exclude_topic_mutes
+from zerver.lib.types import Validator
from zerver.lib.utils import statsd
from zerver.lib.validator import (
check_bool,
@@ -545,7 +546,7 @@ def narrow_parameter(json: str) -> OptionalNarrowListT:
operator = elem.get('operator', '')
if operator in operators_supporting_id:
- operand_validator = check_string_or_int
+ operand_validator: Validator[object] = check_string_or_int
elif operator in operators_supporting_ids:
operand_validator = check_string_or_int_list
elif operator in operators_non_empty_operand:
diff --git a/zerver/views/streams.py b/zerver/views/streams.py
index 9ff2a92e424..8671cedfc95 100644
--- a/zerver/views/streams.py
+++ b/zerver/views/streams.py
@@ -65,6 +65,7 @@ from zerver.lib.streams import (
list_to_streams,
)
from zerver.lib.topic import get_topic_history_for_stream, messages_for_topic
+from zerver.lib.types import Validator
from zerver.lib.validator import (
check_bool,
check_capped_string,
@@ -335,12 +336,15 @@ def compose_views(
json_dict.update(ujson.loads(response.content))
return json_success(json_dict)
+check_principals: Validator[Union[List[str], List[int]]] = check_union(
+ [check_list(check_string), check_list(check_int)],
+)
+
@has_request_variables
def remove_subscriptions_backend(
request: HttpRequest, user_profile: UserProfile,
streams_raw: Iterable[str]=REQ("subscriptions", validator=check_list(check_string)),
- principals: Optional[Union[List[str], List[int]]]=REQ(validator=check_union([
- check_list(check_string), check_list(check_int)]), default=None),
+ principals: Optional[Union[List[str], List[int]]]=REQ(validator=check_principals, default=None),
) -> HttpResponse:
removing_someone_else = check_if_removing_someone_else(user_profile, principals)
@@ -391,6 +395,9 @@ def you_were_just_subscribed_message(acting_user: UserProfile,
message += f"* #**{stream_name}**\n"
return message
+RETENTION_DEFAULT: Union[str, int] = "realm_default"
+EMPTY_PRINCIPALS: Union[Sequence[str], Sequence[int]] = []
+
@require_non_guest_user
@has_request_variables
def add_subscriptions_backend(
@@ -407,10 +414,11 @@ def add_subscriptions_backend(
Stream.STREAM_POST_POLICY_TYPES), default=Stream.STREAM_POST_POLICY_EVERYONE),
history_public_to_subscribers: Optional[bool]=REQ(validator=check_bool, default=None),
message_retention_days: Union[str, int]=REQ(validator=check_string_or_int,
- default="realm_default"),
+ default=RETENTION_DEFAULT),
announce: bool=REQ(validator=check_bool, default=False),
- principals: Union[Sequence[str], Sequence[int]]=REQ(validator=check_union([
- check_list(check_string), check_list(check_int)]), default=[]),
+ principals: Union[Sequence[str], Sequence[int]]=REQ(
+ validator=check_principals, default=EMPTY_PRINCIPALS,
+ ),
authorization_errors_fatal: bool=REQ(validator=check_bool, default=True),
) -> HttpResponse:
stream_dicts = []
diff --git a/zerver/views/users.py b/zerver/views/users.py
index 535b7ec4586..c07fbefc14f 100644
--- a/zerver/views/users.py
+++ b/zerver/views/users.py
@@ -34,6 +34,7 @@ from zerver.lib.integrations import EMBEDDED_BOTS
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_error, json_success
from zerver.lib.streams import access_stream_by_id, access_stream_by_name, subscribed_to_stream
+from zerver.lib.types import Validator
from zerver.lib.upload import upload_avatar_image
from zerver.lib.url_encoding import add_query_arg_to_redirect_url
from zerver.lib.users import (
@@ -122,6 +123,15 @@ def reactivate_user_backend(request: HttpRequest, user_profile: UserProfile,
do_reactivate_user(target, acting_user=user_profile)
return json_success()
+check_profile_data: Validator[List[Dict[str, Optional[Union[int, str, List[int]]]]]] = check_list(
+ check_dict(
+ [('id', check_int)],
+ value_validator=check_none_or(check_union([
+ check_int, check_string, check_list(check_int),
+ ])),
+ ),
+)
+
@has_request_variables
def update_user_backend(
request: HttpRequest, user_profile: UserProfile, user_id: int,
@@ -130,15 +140,7 @@ def update_user_backend(
UserProfile.ROLE_TYPES,
)),
profile_data: Optional[List[Dict[str, Optional[Union[int, str, List[int]]]]]] = REQ(
- default=None,
- validator=check_list(
- check_dict(
- [('id', check_int)],
- value_validator=check_none_or(check_union([
- check_int, check_string, check_list(check_int),
- ])),
- ),
- ),
+ default=None, validator=check_profile_data,
),
) -> HttpResponse:
target = access_user_by_id(user_profile, user_id, allow_deactivated=True, allow_bots=True)