Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
custom_profile: Convert to typed_endpoint.
Kenneth Rodrigues387fba715633
diff --git a/zerver/lib/types.py b/zerver/lib/types.pyindex 4ab61b820f8..b68bf7bcdf9 100644--- a/zerver/lib/types.py+++ b/zerver/lib/types.py@@ -1,9 +1,9 @@from dataclasses import dataclass, fieldfrom datetime import datetime-from typing import Any, Callable, Dict, List, Optional, Tuple, TypedDict, TypeVar, Union+from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Unionfrom django_stubs_ext import StrPromise-from typing_extensions import NotRequired, TypeAlias+from typing_extensions import NotRequired, TypeAlias, TypedDict# See zerver/lib/validator.py for more details of Validators,# including many examplesdiff --git a/zerver/tests/test_custom_profile_data.py b/zerver/tests/test_custom_profile_data.pyindex 92cf70f71f6..405d5c2e850 100644--- a/zerver/tests/test_custom_profile_data.py+++ b/zerver/tests/test_custom_profile_data.py@@ -39,7 +39,7 @@ class CreateCustomProfileFieldTest(CustomProfileFieldTestCase):realm = get_realm("zulip")data: Dict[str, Any] = {"name": "Phone", "field_type": "text id"}result = self.client_post("/json/realm/profile_fields", info=data)- self.assert_json_error(result, 'Argument "field_type" is not valid JSON.')+ self.assert_json_error(result, "field_type is not valid JSON")data["name"] = ""data["field_type"] = 100@@ -106,7 +106,7 @@ class CreateCustomProfileFieldTest(CustomProfileFieldTestCase):data["field_data"] = "invalid"result = self.client_post("/json/realm/profile_fields", info=data)- error_msg = 'Argument "field_data" is not valid JSON.'+ error_msg = "field_data is not valid JSON"self.assert_json_error(result, error_msg)data["field_data"] = orjson.dumps(@@ -116,7 +116,7 @@ class CreateCustomProfileFieldTest(CustomProfileFieldTestCase):}).decode()result = self.client_post("/json/realm/profile_fields", info=data)- self.assert_json_error(result, "field_data contains a value that is not an allowed_type")+ self.assert_json_error(result, 'field_data["python"]["dict[str,str]"] is not a dict')data["field_data"] = orjson.dumps({@@ -152,7 +152,7 @@ class CreateCustomProfileFieldTest(CustomProfileFieldTestCase):}).decode()result = self.client_post("/json/realm/profile_fields", info=data)- self.assert_json_error(result, "field_data contains a value that is not an allowed_type")+ self.assert_json_error(result, 'field_data["0"]["dict[str,str]"]["order"] is not a string')data["field_data"] = orjson.dumps({}).decode()result = self.client_post("/json/realm/profile_fields", info=data)@@ -247,7 +247,7 @@ class CreateCustomProfileFieldTest(CustomProfileFieldTestCase):data["field_data"] = "invalid"result = self.client_post("/json/realm/profile_fields", info=data)- self.assert_json_error(result, 'Argument "field_data" is not valid JSON.')+ self.assert_json_error(result, "field_data is not valid JSON")data["field_data"] = orjson.dumps({}).decode()result = self.client_post("/json/realm/profile_fields", info=data)@@ -307,7 +307,7 @@ class CreateCustomProfileFieldTest(CustomProfileFieldTestCase):}).decode()result = self.client_post("/json/realm/profile_fields", info=data)- self.assert_json_error(result, "field_data contains a value that is not an allowed_type")+ self.assert_json_error(result, 'field_data["url_pattern"]["dict[str,str]"] is not a dict')data["field_data"] = orjson.dumps({@@ -493,7 +493,7 @@ class UpdateCustomProfileFieldTest(CustomProfileFieldTestCase):"required": "invalid value",},)- msg = 'Argument "required" is not valid JSON.'+ msg = "required is not valid JSON"self.assert_json_error(result, msg)result = self.client_patch(@@ -555,7 +555,7 @@ class UpdateCustomProfileFieldTest(CustomProfileFieldTestCase):"display_in_profile_summary": "invalid value",},)- msg = 'Argument "display_in_profile_summary" is not valid JSON.'+ msg = "display_in_profile_summary is not valid JSON"self.assert_json_error(result, msg)result = self.client_patch(@@ -613,7 +613,7 @@ class UpdateCustomProfileFieldTest(CustomProfileFieldTestCase):f"/json/realm/profile_fields/{field.id}",info={"field_data": "invalid"},)- self.assert_json_error(result, 'Argument "field_data" is not valid JSON.')+ self.assert_json_error(result, "field_data is not valid JSON")field_data = orjson.dumps({diff --git a/zerver/views/custom_profile_fields.py b/zerver/views/custom_profile_fields.pyindex 498f6482969..605f4d1d1f2 100644--- a/zerver/views/custom_profile_fields.py+++ b/zerver/views/custom_profile_fields.py@@ -1,10 +1,11 @@-from typing import List, Optional, cast+from typing import Annotated, List, Optionalimport orjsonfrom django.core.exceptions import ValidationErrorfrom django.db import IntegrityErrorfrom django.http import HttpRequest, HttpResponsefrom django.utils.translation import gettext as _+from pydantic import Json, StringConstraintsfrom zerver.actions.custom_profile_fields import (check_remove_custom_profile_field_value,@@ -18,21 +19,11 @@ from zerver.actions.custom_profile_fields import (from zerver.decorator import human_users_only, require_realm_adminfrom zerver.lib.exceptions import JsonableErrorfrom zerver.lib.external_accounts import validate_external_account_field_data-from zerver.lib.request import REQ, has_request_variablesfrom zerver.lib.response import json_success-from zerver.lib.types import ProfileDataElementUpdateDict, ProfileFieldData, Validator+from zerver.lib.typed_endpoint import PathOnly, typed_endpoint+from zerver.lib.types import ProfileDataElementUpdateDict, ProfileFieldDatafrom zerver.lib.users import validate_user_custom_profile_data-from zerver.lib.validator import (- check_bool,- check_capped_string,- check_dict,- check_dict_only,- check_int,- check_list,- check_string,- check_union,- validate_select_field_data,-)+from zerver.lib.validator import check_capped_string, validate_select_field_datafrom zerver.models import CustomProfileField, Realm, UserProfilefrom zerver.models.custom_profile_fields import custom_profile_fields_for_realm@@ -147,11 +138,6 @@ def validate_custom_profile_field_update()-check_profile_field_data: Validator[ProfileFieldData] = check_dict(- value_validator=check_union([check_dict(value_validator=check_string), check_string])-)--def update_only_display_in_profile_summary(existing_field: CustomProfileField,requested_field_data: Optional[ProfileFieldData] = None,@@ -180,17 +166,20 @@ def display_in_profile_summary_limit_reached(@require_realm_admin-@has_request_variables+@typed_endpointdef create_realm_custom_profile_field(request: HttpRequest,user_profile: UserProfile,- name: str = REQ(default="", converter=lambda var_name, x: x.strip()),- hint: str = REQ(default=""),- field_data: ProfileFieldData = REQ(default={}, json_validator=check_profile_field_data),- field_type: int = REQ(json_validator=check_int),- display_in_profile_summary: bool = REQ(default=False, json_validator=check_bool),- required: bool = REQ(default=False, json_validator=check_bool),+ *,+ name: Annotated[str, StringConstraints(strip_whitespace=True)] = "",+ hint: str = "",+ field_data: Optional[Json[ProfileFieldData]] = None,+ field_type: Json[int],+ display_in_profile_summary: Json[bool] = False,+ required: Json[bool] = False,) -> HttpResponse:+ if field_data is None:+ field_data = {}if display_in_profile_summary and display_in_profile_summary_limit_reached(user_profile.realm):raise JsonableError(_("Only 2 custom profile fields can be displayed in the profile summary.")@@ -237,18 +226,17 @@ def delete_realm_custom_profile_field(@require_realm_admin-@has_request_variables+@typed_endpointdef update_realm_custom_profile_field(request: HttpRequest,user_profile: UserProfile,- field_id: int,- name: Optional[str] = REQ(default=None, converter=lambda var_name, x: x.strip()),- hint: Optional[str] = REQ(default=None),- field_data: Optional[ProfileFieldData] = REQ(- default=None, json_validator=check_profile_field_data- ),- required: Optional[bool] = REQ(default=None, json_validator=check_bool),- display_in_profile_summary: Optional[bool] = REQ(default=None, json_validator=check_bool),+ *,+ field_id: PathOnly[int],+ name: Optional[Annotated[str, StringConstraints(strip_whitespace=True)]] = None,+ hint: Optional[str] = None,+ field_data: Optional[Json[ProfileFieldData]] = None,+ required: Optional[Json[bool]] = None,+ display_in_profile_summary: Optional[Json[bool]] = None,) -> HttpResponse:realm = user_profile.realmtry:@@ -295,49 +283,37 @@ def update_realm_custom_profile_field(@require_realm_admin-@has_request_variables+@typed_endpointdef reorder_realm_custom_profile_fields(request: HttpRequest,user_profile: UserProfile,- order: List[int] = REQ(json_validator=check_list(check_int)),+ *,+ order: Json[List[int]],) -> HttpResponse:try_reorder_realm_custom_profile_fields(user_profile.realm, order)return json_success(request)@human_users_only-@has_request_variables+@typed_endpointdef remove_user_custom_profile_data(request: HttpRequest,user_profile: UserProfile,- data: List[int] = REQ(json_validator=check_list(check_int)),+ *,+ data: Json[List[int]],) -> HttpResponse:for field_id in data:check_remove_custom_profile_field_value(user_profile, field_id)return json_success(request)-check_profile_data_element_update_dict = cast(- Validator[ProfileDataElementUpdateDict],- check_dict_only(- [- ("id", check_int),- ("value", check_union([check_string, check_list(check_int)])),- ]- ),-)--@human_users_only-@has_request_variables+@typed_endpointdef update_user_custom_profile_data(request: HttpRequest,user_profile: UserProfile,- data: List[ProfileDataElementUpdateDict] = REQ(- json_validator=check_list(- check_profile_data_element_update_dict,- )- ),+ *,+ data: Json[List[ProfileDataElementUpdateDict]],) -> HttpResponse:validate_user_custom_profile_data(user_profile.realm.id, data)do_update_user_custom_profile_data_if_changed(user_profile, data)