Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Commit

Permalink
Fix isinstance(...) checks, most are false positives.
Browse files Browse the repository at this point in the history
  • Loading branch information
clokep committed Aug 28, 2023
1 parent 68c95b2 commit f9419e0
Show file tree
Hide file tree
Showing 17 changed files with 42 additions and 33 deletions.
8 changes: 4 additions & 4 deletions synapse/config/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,9 +186,9 @@ def parse_size(value: Union[str, int]) -> int:
TypeError, if given something other than an integer or a string
ValueError: if given a string not of the form described above.
"""
if type(value) is int:
if type(value) is int: # noqa: E721
return value
elif type(value) is str:
elif isinstance(value, str):
sizes = {"K": 1024, "M": 1024 * 1024}
size = 1
suffix = value[-1]
Expand Down Expand Up @@ -218,9 +218,9 @@ def parse_duration(value: Union[str, int]) -> int:
TypeError, if given something other than an integer or a string
ValueError: if given a string not of the form described above.
"""
if type(value) is int:
if type(value) is int: # noqa: E721
return value
elif type(value) is str:
elif isinstance(value, str):
second = 1000
minute = 60 * second
hour = 60 * minute
Expand Down
2 changes: 1 addition & 1 deletion synapse/config/appservice.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class AppServiceConfig(Config):
def read_config(self, config: JsonDict, **kwargs: Any) -> None:
self.app_service_config_files = config.get("app_service_config_files", [])
if not isinstance(self.app_service_config_files, list) or not all(
type(x) is str for x in self.app_service_config_files
isinstance(x, str) for x in self.app_service_config_files
):
raise ConfigError(
"Expected '%s' to be a list of AS config files:"
Expand Down
4 changes: 2 additions & 2 deletions synapse/event_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -846,11 +846,11 @@ def _check_power_levels(
"kick",
"invite",
}:
if type(v) is not int:
if type(v) is not int: # noqa: E721
raise SynapseError(400, f"{v!r} must be an integer.")
if k in {"events", "notifications", "users"}:
if not isinstance(v, collections.abc.Mapping) or not all(
type(v) is int for v in v.values()
type(v) is int for v in v.values() # noqa: E721
):
raise SynapseError(
400,
Expand Down
4 changes: 2 additions & 2 deletions synapse/events/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -702,7 +702,7 @@ def _copy_power_level_value_as_integer(
:raises TypeError: if `old_value` is neither an integer nor a base-10 string
representation of an integer.
"""
if type(old_value) is int:
if type(old_value) is int: # noqa: E721
power_levels[key] = old_value
return

Expand Down Expand Up @@ -730,7 +730,7 @@ def validate_canonicaljson(value: Any) -> None:
* Floats
* NaN, Infinity, -Infinity
"""
if type(value) is int:
if type(value) is int: # noqa: E721
if value < CANONICALJSON_MIN_INT or CANONICALJSON_MAX_INT < value:
raise SynapseError(400, "JSON integer out of range", Codes.BAD_JSON)

Expand Down
4 changes: 2 additions & 2 deletions synapse/events/validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,15 +151,15 @@ def _validate_retention(self, event: EventBase) -> None:
max_lifetime = event.content.get("max_lifetime")

if min_lifetime is not None:
if type(min_lifetime) is not int:
if type(min_lifetime) is not int: # noqa: E721
raise SynapseError(
code=400,
msg="'min_lifetime' must be an integer",
errcode=Codes.BAD_JSON,
)

if max_lifetime is not None:
if type(max_lifetime) is not int:
if type(max_lifetime) is not int: # noqa: E721
raise SynapseError(
code=400,
msg="'max_lifetime' must be an integer",
Expand Down
2 changes: 1 addition & 1 deletion synapse/federation/federation_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ def event_from_pdu_json(pdu_json: JsonDict, room_version: RoomVersion) -> EventB
_strip_unsigned_values(pdu_json)

depth = pdu_json["depth"]
if type(depth) is not int:
if type(depth) is not int: # noqa: E721
raise SynapseError(400, "Depth %r not an intger" % (depth,), Codes.BAD_JSON)

if depth < 0:
Expand Down
2 changes: 1 addition & 1 deletion synapse/federation/federation_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1891,7 +1891,7 @@ def from_json_dict(cls, d: JsonDict) -> "TimestampToEventResponse":
)

origin_server_ts = d.get("origin_server_ts")
if type(origin_server_ts) is not int:
if type(origin_server_ts) is not int: # noqa: E721
raise ValueError(
"Invalid response: 'origin_server_ts' must be a int but received %r"
% origin_server_ts
Expand Down
2 changes: 1 addition & 1 deletion synapse/handlers/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ def maybe_schedule_expiry(self, event: EventBase) -> None:
"""

expiry_ts = event.content.get(EventContentFields.SELF_DESTRUCT_AFTER)
if type(expiry_ts) is not int or event.is_state():
if type(expiry_ts) is not int or event.is_state(): # noqa: E721
return

# _schedule_expiry_for_event won't actually schedule anything if there's already
Expand Down
2 changes: 1 addition & 1 deletion synapse/http/matrixfederationclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ def _validate(v: Any) -> bool:
return (
isinstance(v, list)
and len(v) == 2
and type(v[0]) == int
and type(v[0]) == int # noqa: E721
and isinstance(v[1], dict)
)

Expand Down
2 changes: 1 addition & 1 deletion synapse/media/oembed.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ def parse_oembed_response(self, url: str, raw_body: bytes) -> OEmbedResult:
calc_description_and_urls(open_graph_response, oembed["html"])
for size in ("width", "height"):
val = oembed.get(size)
if type(val) is int:
if type(val) is int: # noqa: E721
open_graph_response[f"og:video:{size}"] = val

elif oembed_type == "link":
Expand Down
2 changes: 1 addition & 1 deletion synapse/media/thumbnailer.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def __init__(self, input_path: str):
image_exif = self.image._getexif() # type: ignore
if image_exif is not None:
image_orientation = image_exif.get(EXIF_ORIENTATION_TAG)
assert type(image_orientation) is int
assert type(image_orientation) is int # noqa: E721
self.transpose_method = EXIF_TRANSPOSE_MAPPINGS.get(image_orientation)
except Exception as e:
# A lot of parsing errors can happen when parsing EXIF
Expand Down
6 changes: 4 additions & 2 deletions synapse/push/bulk_push_rule_evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ async def _action_for_event_by_user(
keys = list(notification_levels.keys())
for key in keys:
level = notification_levels.get(key, SENTINEL)
if level is not SENTINEL and type(level) is not int:
if level is not SENTINEL and type(level) is not int: # noqa: E721
try:
notification_levels[key] = int(level)
except (TypeError, ValueError):
Expand Down Expand Up @@ -472,7 +472,9 @@ async def _action_for_event_by_user(


def _is_simple_value(value: Any) -> bool:
return isinstance(value, (bool, str)) or type(value) is int or value is None
return (
isinstance(value, (bool, str)) or type(value) is int or value is None # noqa: E721
)


def _flatten_dict(
Expand Down
2 changes: 1 addition & 1 deletion synapse/rest/admin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ async def on_POST(
logger.info("[purge] purging up to token %s (event_id %s)", token, event_id)
elif "purge_up_to_ts" in body:
ts = body["purge_up_to_ts"]
if type(ts) is not int:
if type(ts) is not int: # noqa: E721
raise SynapseError(
HTTPStatus.BAD_REQUEST,
"purge_up_to_ts must be an int",
Expand Down
19 changes: 12 additions & 7 deletions synapse/rest/admin/registration_tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ async def on_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
else:
# Get length of token to generate (default is 16)
length = body.get("length", 16)
if type(length) is not int:
if type(length) is not int: # noqa: E721
raise SynapseError(
HTTPStatus.BAD_REQUEST,
"length must be an integer",
Expand All @@ -163,7 +163,8 @@ async def on_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]:

uses_allowed = body.get("uses_allowed", None)
if not (
uses_allowed is None or (type(uses_allowed) is int and uses_allowed >= 0)
uses_allowed is None
or (type(uses_allowed) is int and uses_allowed >= 0) # noqa: E721
):
raise SynapseError(
HTTPStatus.BAD_REQUEST,
Expand All @@ -172,13 +173,15 @@ async def on_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
)

expiry_time = body.get("expiry_time", None)
if type(expiry_time) not in (int, type(None)):
if expiry_time is not None and type(expiry_time) is not int: # noqa: E721
raise SynapseError(
HTTPStatus.BAD_REQUEST,
"expiry_time must be an integer or null",
Codes.INVALID_PARAM,
)
if type(expiry_time) is int and expiry_time < self.clock.time_msec():
if (
type(expiry_time) is int and expiry_time < self.clock.time_msec() # noqa: E721
):
raise SynapseError(
HTTPStatus.BAD_REQUEST,
"expiry_time must not be in the past",
Expand Down Expand Up @@ -283,7 +286,7 @@ async def on_PUT(self, request: SynapseRequest, token: str) -> Tuple[int, JsonDi
uses_allowed = body["uses_allowed"]
if not (
uses_allowed is None
or (type(uses_allowed) is int and uses_allowed >= 0)
or (type(uses_allowed) is int and uses_allowed >= 0) # noqa: E721
):
raise SynapseError(
HTTPStatus.BAD_REQUEST,
Expand All @@ -294,13 +297,15 @@ async def on_PUT(self, request: SynapseRequest, token: str) -> Tuple[int, JsonDi

if "expiry_time" in body:
expiry_time = body["expiry_time"]
if type(expiry_time) not in (int, type(None)):
if expiry_time is not None and type(expiry_time) is not int: # noqa: E721
raise SynapseError(
HTTPStatus.BAD_REQUEST,
"expiry_time must be an integer or null",
Codes.INVALID_PARAM,
)
if type(expiry_time) is int and expiry_time < self.clock.time_msec():
if (
type(expiry_time) is int and expiry_time < self.clock.time_msec() # noqa: E721
):
raise SynapseError(
HTTPStatus.BAD_REQUEST,
"expiry_time must not be in the past",
Expand Down
6 changes: 4 additions & 2 deletions synapse/rest/admin/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -1172,14 +1172,16 @@ async def on_POST(
messages_per_second = body.get("messages_per_second", 0)
burst_count = body.get("burst_count", 0)

if type(messages_per_second) is not int or messages_per_second < 0:
if (
type(messages_per_second) is not int or messages_per_second < 0 # noqa: E721
):
raise SynapseError(
HTTPStatus.BAD_REQUEST,
"%r parameter must be a positive int" % (messages_per_second,),
errcode=Codes.INVALID_PARAM,
)

if type(burst_count) is not int or burst_count < 0:
if type(burst_count) is not int or burst_count < 0: # noqa: E721
raise SynapseError(
HTTPStatus.BAD_REQUEST,
"%r parameter must be a positive int" % (burst_count,),
Expand Down
2 changes: 1 addition & 1 deletion synapse/rest/client/report_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ async def on_POST(
"Param 'reason' must be a string",
Codes.BAD_JSON,
)
if type(body.get("score", 0)) is not int:
if type(body.get("score", 0)) is not int: # noqa: E721
raise SynapseError(
HTTPStatus.BAD_REQUEST,
"Param 'score' must be an integer",
Expand Down
6 changes: 3 additions & 3 deletions synapse/storage/databases/main/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -1671,7 +1671,7 @@ def _update_metadata_tables_txn(
if self._ephemeral_messages_enabled:
# If there's an expiry timestamp on the event, store it.
expiry_ts = event.content.get(EventContentFields.SELF_DESTRUCT_AFTER)
if type(expiry_ts) is int and not event.is_state():
if type(expiry_ts) is int and not event.is_state(): # noqa: E721
self._insert_event_expiry_txn(txn, event.event_id, expiry_ts)

# Insert into the room_memberships table.
Expand Down Expand Up @@ -2039,10 +2039,10 @@ def _store_retention_policy_for_room_txn(
):
if (
"min_lifetime" in event.content
and type(event.content["min_lifetime"]) is not int
and type(event.content["min_lifetime"]) is not int # noqa: E721
) or (
"max_lifetime" in event.content
and type(event.content["max_lifetime"]) is not int
and type(event.content["max_lifetime"]) is not int # noqa: E721
):
# Ignore the event if one of the value isn't an integer.
return
Expand Down

0 comments on commit f9419e0

Please sign in to comment.