Enable more SIM ruff rules (#113015)

* SIM101 SIM103

* SIM107 SIM109

* SIM110

* SIM112 SIM113

* SIM115

* SIM116

* Fix

* Fix

* Fix
This commit is contained in:
Joost Lekkerkerker 2024-03-11 04:20:37 +01:00 committed by GitHub
parent e96ef4613c
commit cddce0ce0d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 41 additions and 70 deletions

View File

@ -64,10 +64,7 @@ _LOGGER = logging.getLogger(__name__)
def _is_tracked(mac: str, current_devices: ValuesView) -> bool:
"""Check if device is already tracked."""
for tracked in current_devices:
if mac in tracked:
return True
return False
return any(mac in tracked for tracked in current_devices)
def device_filter_out_from_trackers(

View File

@ -305,11 +305,7 @@ class HomematicipHeatingGroup(HomematicipGenericEntity, ClimateEntity):
@property
def _has_switch(self) -> bool:
"""Return, if a switch is in the hmip heating group."""
for device in self._device.devices:
if isinstance(device, Switch):
return True
return False
return any(isinstance(device, Switch) for device in self._device.devices)
@property
def _has_radiator_thermostat(self) -> bool:

View File

@ -141,8 +141,7 @@ class MqttEvent(MqttEntity, EventEntity):
if (
not payload
or payload is PayloadSentinel.DEFAULT
or payload == PAYLOAD_NONE
or payload == PAYLOAD_EMPTY_JSON
or payload in (PAYLOAD_NONE, PAYLOAD_EMPTY_JSON)
):
_LOGGER.debug(
"Ignoring empty payload '%s' after rendering for topic %s",

View File

@ -64,10 +64,7 @@ def _check_for_recording_entry(api: PhilipsTV, entry: str, value: str) -> bool:
"""Return True if at least one specified value is available within entry of list."""
if api.recordings_list is None:
return False
for rec in api.recordings_list["recordings"]:
if rec.get(entry) == value:
return True
return False
return any(rec.get(entry) == value for rec in api.recordings_list["recordings"])
class PhilipsTVBinarySensorEntityRecordingType(PhilipsJsEntity, BinarySensorEntity):

View File

@ -197,11 +197,7 @@ def _has_name(
if (entity is None) or (not entity.aliases):
return False
for alias in entity.aliases:
if name == alias.casefold():
return True
return False
return any(name == alias.casefold() for alias in entity.aliases)
def _find_area(

View File

@ -3050,10 +3050,7 @@ def _get_named_annotation(
def _has_valid_annotations(
annotations: list[nodes.NodeNG | None],
) -> bool:
for annotation in annotations:
if annotation is not None:
return True
return False
return any(annotation is not None for annotation in annotations)
def _get_module_platform(module_name: str) -> str | None:

View File

@ -627,8 +627,16 @@ select = [
"S604", # call-with-shell-equals-true
"S608", # hardcoded-sql-expression
"S609", # unix-command-wildcard-injection
"SIM101", # Multiple isinstance calls for {name}, merge into a single call
"SIM103", # Return the condition {condition} directly
"SIM105", # Use contextlib.suppress({exception}) instead of try-except-pass
"SIM107", # Don't use return in try-except and finally
"SIM109", # Use {replacement} instead of multiple equality comparisons
"SIM110", # Use {replacement} instead of for loop
"SIM112", # Use capitalized environment variable {expected} instead of {actual}
"SIM113", # Use enumerate() for index variable {index} in for loop
"SIM114", # Combine if branches using logical or operator
"SIM116", # Use a dictionary instead of consecutive if statements
"SIM117", # Merge with-statements that use the same scope
"SIM118", # Use {key} in {dict} instead of {key} in {dict}.keys()
"SIM201", # Use {left} != {right} instead of not {left} == {right}

View File

@ -33,10 +33,7 @@ def _has_function(
module: ast.Module, _type: ast.AsyncFunctionDef | ast.FunctionDef, name: str
) -> bool:
"""Test if the module defines a function."""
for item in module.body:
if type(item) == _type and item.name == name:
return True
return False
return any(type(item) == _type and item.name == name for item in module.body)
def _has_import(module: ast.Module, name: str) -> bool:

View File

@ -37,9 +37,7 @@ async def test_wait_time_select(
data = {ATTR_ENTITY_ID: SELECT_ENTITY_ID}
count = 0
for wait_time in LitterRobot3.VALID_WAIT_TIMES:
count += 1
for count, wait_time in enumerate(LitterRobot3.VALID_WAIT_TIMES):
data[ATTR_OPTION] = wait_time
await hass.services.async_call(
@ -49,7 +47,7 @@ async def test_wait_time_select(
blocking=True,
)
assert mock_account.robots[0].set_wait_time.call_count == count
assert mock_account.robots[0].set_wait_time.call_count == count + 1
async def test_invalid_wait_time_select(hass: HomeAssistant, mock_account) -> None:
@ -91,9 +89,8 @@ async def test_panel_brightness_select(
robot: LitterRobot4 = mock_account_with_litterrobot_4.robots[0]
robot.set_panel_brightness = AsyncMock(return_value=True)
count = 0
for option in select.attributes[ATTR_OPTIONS]:
count += 1
for count, option in enumerate(select.attributes[ATTR_OPTIONS]):
data[ATTR_OPTION] = option
await hass.services.async_call(
@ -103,4 +100,4 @@ async def test_panel_brightness_select(
blocking=True,
)
assert robot.set_panel_brightness.call_count == count
assert robot.set_panel_brightness.call_count == count + 1

View File

@ -58,13 +58,11 @@ async def test_on_off_commands(
data = {ATTR_ENTITY_ID: entity_id}
count = 0
services = ((SERVICE_TURN_ON, STATE_ON, "1"), (SERVICE_TURN_OFF, STATE_OFF, "0"))
for service, new_state, new_value in services:
count += 1
for count, (service, new_state, new_value) in enumerate(services):
await hass.services.async_call(PLATFORM_DOMAIN, service, data, blocking=True)
robot._update_data({updated_field: new_value}, partial=True)
assert getattr(robot, robot_command).call_count == count
assert getattr(robot, robot_command).call_count == count + 1
assert (state := hass.states.get(entity_id))
assert state.state == new_state

View File

@ -233,14 +233,13 @@ async def test_cookiefile_detection(
if not os.path.exists(cookies_dir):
os.makedirs(cookies_dir)
f = open(cookies_file, "w+", encoding="utf-8")
f.write(
"""# Netscape HTTP Cookie File
with open(cookies_file, "w+", encoding="utf-8") as f:
f.write(
"""# Netscape HTTP Cookie File
.youtube.com TRUE / TRUE 1701708706 GPS 1
"""
)
f.close()
.youtube.com TRUE / TRUE 1701708706 GPS 1
"""
)
await hass.services.async_call(
DOMAIN,

View File

@ -1710,10 +1710,8 @@ async def help_test_publishing_with_custom_encoding(
# setup test entities using discovery
mqtt_mock = await mqtt_mock_entry()
item: int = 0
for component_config in setup_config:
for item, component_config in enumerate(setup_config):
conf = json.dumps(component_config)
item += 1
async_fire_mqtt_message(
hass, f"homeassistant/{domain}/component_{item}/config", conf
)

View File

@ -404,17 +404,17 @@ async def test_invalid_availability_template_keeps_component_available(
async def test_on_off(hass: HomeAssistant, calls) -> None:
"""Test turn on and turn off."""
await _register_components(hass)
expected_calls = 0
for func, state, action in [
(common.async_turn_on, STATE_ON, "turn_on"),
(common.async_turn_off, STATE_OFF, "turn_off"),
]:
for expected_calls, (func, state, action) in enumerate(
[
(common.async_turn_on, STATE_ON, "turn_on"),
(common.async_turn_off, STATE_OFF, "turn_off"),
]
):
await func(hass, _TEST_FAN)
assert hass.states.get(_STATE_INPUT_BOOLEAN).state == state
_verify(hass, state, 0, None, None, None)
expected_calls += 1
assert len(calls) == expected_calls
assert len(calls) == expected_calls + 1
assert calls[-1].data["action"] == action
assert calls[-1].data["caller"] == _TEST_FAN

View File

@ -380,7 +380,7 @@ def test_cluster_handler_registry() -> None:
assert cluster_id in all_quirk_ids
assert isinstance(cluster_handler_classes, dict)
for quirk_id, cluster_handler in cluster_handler_classes.items():
assert isinstance(quirk_id, NoneType) or isinstance(quirk_id, str)
assert isinstance(quirk_id, (NoneType, str))
assert issubclass(cluster_handler, cluster_handlers.ClusterHandler)
assert quirk_id in all_quirk_ids[cluster_id]

View File

@ -72,10 +72,7 @@ def _same_lists(list_a, list_b):
if len(list_a) != len(list_b):
return False
for item in list_a:
if item not in list_b:
return False
return True
return all(item in list_b for item in list_a)
@pytest.fixture

View File

@ -70,10 +70,7 @@ IGNORE_SUFFIXES = [
def contains_ignored_suffix(unique_id: str) -> bool:
"""Return true if the unique_id ends with an ignored suffix."""
for suffix in IGNORE_SUFFIXES:
if suffix.lower() in unique_id.lower():
return True
return False
return any(suffix.lower() in unique_id.lower() for suffix in IGNORE_SUFFIXES)
@patch(

View File

@ -43,11 +43,9 @@ BAD_CORE_CONFIG = "homeassistant:\n unit_system: bad\n\n\n"
def log_ha_config(conf):
"""Log the returned config."""
cnt = 0
_LOGGER.debug("CONFIG - %s lines - %s errors", len(conf), len(conf.errors))
for key, val in conf.items():
_LOGGER.debug("#%s - %s: %s", cnt, key, val)
cnt += 1
for cnt, (key, val) in enumerate(conf.items()):
_LOGGER.debug("#%s - %s: %s", cnt + 1, key, val)
for cnt, err in enumerate(conf.errors):
_LOGGER.debug("error[%s] = %s", cnt, err)