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: def _is_tracked(mac: str, current_devices: ValuesView) -> bool:
"""Check if device is already tracked.""" """Check if device is already tracked."""
for tracked in current_devices: return any(mac in tracked for tracked in current_devices)
if mac in tracked:
return True
return False
def device_filter_out_from_trackers( def device_filter_out_from_trackers(

View File

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

View File

@ -141,8 +141,7 @@ class MqttEvent(MqttEntity, EventEntity):
if ( if (
not payload not payload
or payload is PayloadSentinel.DEFAULT or payload is PayloadSentinel.DEFAULT
or payload == PAYLOAD_NONE or payload in (PAYLOAD_NONE, PAYLOAD_EMPTY_JSON)
or payload == PAYLOAD_EMPTY_JSON
): ):
_LOGGER.debug( _LOGGER.debug(
"Ignoring empty payload '%s' after rendering for topic %s", "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.""" """Return True if at least one specified value is available within entry of list."""
if api.recordings_list is None: if api.recordings_list is None:
return False return False
for rec in api.recordings_list["recordings"]: return any(rec.get(entry) == value for rec in api.recordings_list["recordings"])
if rec.get(entry) == value:
return True
return False
class PhilipsTVBinarySensorEntityRecordingType(PhilipsJsEntity, BinarySensorEntity): class PhilipsTVBinarySensorEntityRecordingType(PhilipsJsEntity, BinarySensorEntity):

View File

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

View File

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

View File

@ -627,8 +627,16 @@ select = [
"S604", # call-with-shell-equals-true "S604", # call-with-shell-equals-true
"S608", # hardcoded-sql-expression "S608", # hardcoded-sql-expression
"S609", # unix-command-wildcard-injection "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 "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 "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 "SIM117", # Merge with-statements that use the same scope
"SIM118", # Use {key} in {dict} instead of {key} in {dict}.keys() "SIM118", # Use {key} in {dict} instead of {key} in {dict}.keys()
"SIM201", # Use {left} != {right} instead of not {left} == {right} "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 module: ast.Module, _type: ast.AsyncFunctionDef | ast.FunctionDef, name: str
) -> bool: ) -> bool:
"""Test if the module defines a function.""" """Test if the module defines a function."""
for item in module.body: return any(type(item) == _type and item.name == name for item in module.body)
if type(item) == _type and item.name == name:
return True
return False
def _has_import(module: ast.Module, name: str) -> bool: 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} data = {ATTR_ENTITY_ID: SELECT_ENTITY_ID}
count = 0 for count, wait_time in enumerate(LitterRobot3.VALID_WAIT_TIMES):
for wait_time in LitterRobot3.VALID_WAIT_TIMES:
count += 1
data[ATTR_OPTION] = wait_time data[ATTR_OPTION] = wait_time
await hass.services.async_call( await hass.services.async_call(
@ -49,7 +47,7 @@ async def test_wait_time_select(
blocking=True, 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: 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: LitterRobot4 = mock_account_with_litterrobot_4.robots[0]
robot.set_panel_brightness = AsyncMock(return_value=True) robot.set_panel_brightness = AsyncMock(return_value=True)
count = 0
for option in select.attributes[ATTR_OPTIONS]: for count, option in enumerate(select.attributes[ATTR_OPTIONS]):
count += 1
data[ATTR_OPTION] = option data[ATTR_OPTION] = option
await hass.services.async_call( await hass.services.async_call(
@ -103,4 +100,4 @@ async def test_panel_brightness_select(
blocking=True, 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} data = {ATTR_ENTITY_ID: entity_id}
count = 0
services = ((SERVICE_TURN_ON, STATE_ON, "1"), (SERVICE_TURN_OFF, STATE_OFF, "0")) services = ((SERVICE_TURN_ON, STATE_ON, "1"), (SERVICE_TURN_OFF, STATE_OFF, "0"))
for service, new_state, new_value in services: for count, (service, new_state, new_value) in enumerate(services):
count += 1
await hass.services.async_call(PLATFORM_DOMAIN, service, data, blocking=True) await hass.services.async_call(PLATFORM_DOMAIN, service, data, blocking=True)
robot._update_data({updated_field: new_value}, partial=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 := hass.states.get(entity_id))
assert state.state == new_state assert state.state == new_state

View File

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

View File

@ -1710,10 +1710,8 @@ async def help_test_publishing_with_custom_encoding(
# setup test entities using discovery # setup test entities using discovery
mqtt_mock = await mqtt_mock_entry() mqtt_mock = await mqtt_mock_entry()
item: int = 0 for item, component_config in enumerate(setup_config):
for component_config in setup_config:
conf = json.dumps(component_config) conf = json.dumps(component_config)
item += 1
async_fire_mqtt_message( async_fire_mqtt_message(
hass, f"homeassistant/{domain}/component_{item}/config", conf 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: async def test_on_off(hass: HomeAssistant, calls) -> None:
"""Test turn on and turn off.""" """Test turn on and turn off."""
await _register_components(hass) await _register_components(hass)
expected_calls = 0
for func, state, action in [ for expected_calls, (func, state, action) in enumerate(
[
(common.async_turn_on, STATE_ON, "turn_on"), (common.async_turn_on, STATE_ON, "turn_on"),
(common.async_turn_off, STATE_OFF, "turn_off"), (common.async_turn_off, STATE_OFF, "turn_off"),
]: ]
):
await func(hass, _TEST_FAN) await func(hass, _TEST_FAN)
assert hass.states.get(_STATE_INPUT_BOOLEAN).state == state assert hass.states.get(_STATE_INPUT_BOOLEAN).state == state
_verify(hass, state, 0, None, None, None) _verify(hass, state, 0, None, None, None)
expected_calls += 1 assert len(calls) == expected_calls + 1
assert len(calls) == expected_calls
assert calls[-1].data["action"] == action assert calls[-1].data["action"] == action
assert calls[-1].data["caller"] == _TEST_FAN 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 cluster_id in all_quirk_ids
assert isinstance(cluster_handler_classes, dict) assert isinstance(cluster_handler_classes, dict)
for quirk_id, cluster_handler in cluster_handler_classes.items(): 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 issubclass(cluster_handler, cluster_handlers.ClusterHandler)
assert quirk_id in all_quirk_ids[cluster_id] 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): if len(list_a) != len(list_b):
return False return False
for item in list_a: return all(item in list_b for item in list_a)
if item not in list_b:
return False
return True
@pytest.fixture @pytest.fixture

View File

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

View File

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