python: Reformat with Black, except quotes.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg
2021-02-11 23:19:30 -08:00
committed by Tim Abbott
parent 5028c081cb
commit 11741543da
817 changed files with 44952 additions and 24860 deletions

View File

@@ -45,12 +45,14 @@ def check_string(var_name: str, val: object) -> str:
raise ValidationError(_('{var_name} is not a string').format(var_name=var_name))
return val
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
def check_string_in(possible_values: Union[Set[str], List[str]]) -> Validator[str]:
def validator(var_name: str, val: object) -> str:
s = check_string(var_name, val)
@@ -60,34 +62,46 @@ def check_string_in(possible_values: Union[Set[str], List[str]]) -> Validator[st
return validator
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[str]:
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,
))
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[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(
var_name=var_name, target_length=length, length=len(s),
))
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
def check_long_string(var_name: str, val: object) -> str:
return check_capped_string(500)(var_name, val)
def check_date(var_name: str, val: object) -> str:
if not isinstance(val, str):
raise ValidationError(_('{var_name} is not a string').format(var_name=var_name))
@@ -98,11 +112,13 @@ def check_date(var_name: str, val: object) -> str:
raise ValidationError(_('{var_name} is not a date').format(var_name=var_name))
return val
def check_int(var_name: str, val: object) -> int:
if not isinstance(val, int):
raise ValidationError(_('{var_name} is not an integer').format(var_name=var_name))
return val
def check_int_in(possible_values: List[int]) -> Validator[int]:
def validator(var_name: str, val: object) -> int:
n = check_int(var_name, val)
@@ -112,41 +128,54 @@ def check_int_in(possible_values: List[int]) -> Validator[int]:
return validator
def check_float(var_name: str, val: object) -> float:
if not isinstance(val, float):
raise ValidationError(_('{var_name} is not a float').format(var_name=var_name))
return val
def check_bool(var_name: str, val: object) -> bool:
if not isinstance(val, bool):
raise ValidationError(_('{var_name} is not a boolean').format(var_name=var_name))
return val
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(s)
if not matched_results:
raise ValidationError(_('{var_name} is not a valid hex color code').format(var_name=var_name))
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[Optional[ResultT]]:
def f(var_name: str, val: object) -> Optional[ResultT]:
if val is None:
return val
else:
return sub_validator(var_name, val)
return f
def check_list(sub_validator: Validator[ResultT], length: Optional[int]=None) -> Validator[List[ResultT]]:
def check_list(
sub_validator: Validator[ResultT], length: Optional[int] = None
) -> Validator[List[ResultT]]:
def f(var_name: str, val: object) -> List[ResultT]:
if not isinstance(val, list):
raise ValidationError(_('{var_name} is not a list').format(var_name=var_name))
if length is not None and length != len(val):
raise ValidationError(_('{container} should have exactly {length} items').format(
container=var_name, length=length,
))
raise ValidationError(
_('{container} should have exactly {length} items').format(
container=var_name,
length=length,
)
)
for i, item in enumerate(val):
vname = f'{var_name}[{i}]'
@@ -154,8 +183,10 @@ def check_list(sub_validator: Validator[ResultT], length: Optional[int]=None) ->
assert item is valid_item # To justify the unchecked cast below
return cast(List[ResultT], val)
return f
def check_tuple(sub_validators: List[Validator[ResultT]]) -> Validator[Tuple[Any, ...]]:
def f(var_name: str, val: object) -> Tuple[Any, ...]:
if not isinstance(val, tuple):
@@ -163,36 +194,51 @@ def check_tuple(sub_validators: List[Validator[ResultT]]) -> Validator[Tuple[Any
desired_len = len(sub_validators)
if desired_len != len(val):
raise ValidationError(_('{var_name} should have exactly {desired_len} items').format(
var_name=var_name, desired_len=desired_len,
))
raise ValidationError(
_('{var_name} should have exactly {desired_len} items').format(
var_name=var_name,
desired_len=desired_len,
)
)
for i, sub_validator in enumerate(sub_validators):
vname = f'{var_name}[{i}]'
sub_validator(vname, val[i])
return val
return f
# https://zulip.readthedocs.io/en/latest/testing/mypy.html#using-overload-to-accurately-describe-variations
@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]]:
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: 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]]:
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]]:
def f(var_name: str, val: object) -> Dict[str, ResultT]:
if not isinstance(val, dict):
raise ValidationError(_('{var_name} is not a dict').format(var_name=var_name))
@@ -202,9 +248,12 @@ def check_dict(required_keys: Iterable[Tuple[str, Validator[ResultT]]]=[],
for k, sub_validator in required_keys:
if k not in val:
raise ValidationError(_('{key_name} key is missing from {var_name}').format(
key_name=k, var_name=var_name,
))
raise ValidationError(
_('{key_name} key is missing from {var_name}').format(
key_name=k,
var_name=var_name,
)
)
vname = f'{var_name}["{k}"]'
sub_validator(vname, val[k])
@@ -224,19 +273,25 @@ def check_dict(required_keys: Iterable[Tuple[str, Validator[ResultT]]]=[],
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:
raise ValidationError(_("Unexpected arguments: {}").format(", ".join(list(delta_keys))))
raise ValidationError(
_("Unexpected arguments: {}").format(", ".join(list(delta_keys)))
)
return cast(Dict[str, ResultT], val)
return f
def check_dict_only(required_keys: Iterable[Tuple[str, Validator[ResultT]]],
optional_keys: Iterable[Tuple[str, Validator[ResultT]]]=[]) -> Validator[Dict[str, ResultT]]:
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[ResultT]]) -> Validator[ResultT]:
"""
Use this validator if an argument is of a variable type (e.g. processing
@@ -253,23 +308,32 @@ def check_union(allowed_type_funcs: Iterable[Validator[ResultT]]) -> Validator[R
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: ResultT) -> Validator[ResultT]:
def f(var_name: str, val: object) -> ResultT:
if val != expected_val:
raise ValidationError(_('{variable} != {expected_value} ({value} is wrong)').format(
variable=var_name, expected_value=expected_val, value=val,
))
raise ValidationError(
_('{variable} != {expected_value} ({value} is wrong)').format(
variable=var_name,
expected_value=expected_val,
value=val,
)
)
return cast(ResultT, val)
return f
def validate_login_email(email: str) -> None:
try:
validate_email(email)
except ValidationError as err:
raise JsonableError(str(err.message))
def check_url(var_name: str, val: object) -> str:
# First, ensure val is a string
s = check_string(var_name, val)
@@ -281,6 +345,7 @@ def check_url(var_name: str, val: object) -> str:
except ValidationError:
raise ValidationError(_('{var_name} is not a URL').format(var_name=var_name))
def check_external_account_url_pattern(var_name: str, val: object) -> str:
s = check_string(var_name, val)
@@ -291,15 +356,18 @@ def check_external_account_url_pattern(var_name: str, val: object) -> str:
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.
"""
validator = check_dict_only([
('text', check_required_string),
('order', check_required_string),
])
validator = check_dict_only(
[
('text', check_required_string),
('order', check_required_string),
]
)
for key, value in field_data.items():
if not key.strip():
@@ -310,6 +378,7 @@ def validate_choice_field_data(field_data: ProfileFieldData) -> Dict[str, Dict[s
return cast(Dict[str, Dict[str, str]], field_data)
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
@@ -322,6 +391,7 @@ def validate_choice_field(var_name: str, field_data: str, value: object) -> str:
raise ValidationError(msg.format(value=value, field_name=var_name))
return s
def check_widget_content(widget_content: object) -> Dict[str, Any]:
if not isinstance(widget_content, dict):
raise ValidationError('widget_content is not a dict')
@@ -345,20 +415,24 @@ def check_widget_content(widget_content: object) -> Dict[str, Any]:
if extra_data['type'] == 'choices':
check_choices = check_list(
check_dict([
('short_name', check_string),
('long_name', check_string),
('reply', check_string),
]),
check_dict(
[
('short_name', check_string),
('long_name', check_string),
('reply', check_string),
]
),
)
# We re-check "type" here just to avoid it looking
# like we have extraneous keys.
checker = check_dict([
('type', equals('choices')),
('heading', check_string),
('choices', check_choices),
])
checker = check_dict(
[
('type', equals('choices')),
('heading', check_string),
('choices', check_choices),
]
)
checker('extra_data', extra_data)
@@ -370,7 +444,7 @@ def check_widget_content(widget_content: object) -> Dict[str, Any]:
# Converter functions for use with has_request_variables
def to_non_negative_int(s: str, max_int_size: int=2**32-1) -> int:
def to_non_negative_int(s: str, max_int_size: int = 2 ** 32 - 1) -> int:
x = int(s)
if x < 0:
raise ValueError("argument is negative")
@@ -378,6 +452,7 @@ def to_non_negative_int(s: str, max_int_size: int=2**32-1) -> int:
raise ValueError(f'{x} is too large (max {max_int_size})')
return x
def to_positive_or_allowed_int(allowed_integer: int) -> Callable[[str], int]:
def converter(s: str) -> int:
x = int(s)
@@ -386,17 +461,22 @@ def to_positive_or_allowed_int(allowed_integer: int) -> Callable[[str], int]:
if x == 0:
raise ValueError("argument is 0")
return to_non_negative_int(s)
return converter
def check_string_or_int_list(var_name: str, val: object) -> Union[str, List[int]]:
if isinstance(val, str):
return val
if not isinstance(val, list):
raise ValidationError(_('{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)
def check_string_or_int(var_name: str, val: object) -> Union[str, int]:
if isinstance(val, (str, int)):
return val