Skip to content

Commit

Permalink
Add first batch of Ruff PT rules (home-assistant#113665)
Browse files Browse the repository at this point in the history
* Add first batch of Ruff PT rules

* fix weather test

* Fix pilight test

* Update test_intent.py

* Update pilight test_init.py

* Update test_init.py
  • Loading branch information
autinerd authored Mar 18, 2024
1 parent 8f33bad commit 727581e
Show file tree
Hide file tree
Showing 19 changed files with 60 additions and 102 deletions.
4 changes: 2 additions & 2 deletions homeassistant/components/recorder/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -645,7 +645,7 @@ def wrapper(instance: _RecorderT, *args: _P.args, **kwargs: _P.kwargs) -> bool:
return job(instance, *args, **kwargs)
except OperationalError as err:
if _is_retryable_error(instance, err):
assert isinstance(err.orig, BaseException)
assert isinstance(err.orig, BaseException) # noqa: PT017
_LOGGER.info(
"%s; %s not completed, retrying", err.orig.args[1], description
)
Expand Down Expand Up @@ -691,7 +691,7 @@ def wrapper(instance: _RecorderT, *args: _P.args, **kwargs: _P.kwargs) -> None:
instance, err
):
raise
assert isinstance(err.orig, BaseException)
assert isinstance(err.orig, BaseException) # noqa: PT017
_LOGGER.info(
"%s; %s failed, retrying", err.orig.args[1], description
)
Expand Down
10 changes: 10 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,7 @@ select = [
"PGH004", # Use specific rule codes when using noqa
"PIE", # flake8-pie
"PL", # pylint
"PT", # flake8-pytest-style
"RSE", # flake8-raise
"RUF005", # Consider iterable unpacking instead of concatenation
"RUF006", # Store a reference to the return value of asyncio.create_task
Expand Down Expand Up @@ -679,6 +680,15 @@ ignore = [

# Disabled because ruff does not understand type of __all__ generated by a function
"PLE0605",

# temporarily disabled
"PT004",
"PT007",
"PT011",
"PT018",
"PT012",
"PT023",
"PT019"
]

[tool.ruff.lint.flake8-import-conventions.extend-aliases]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ async def test_get_actions(


@pytest.mark.parametrize(
"hidden_by,entity_category",
("hidden_by", "entity_category"),
(
(er.RegistryEntryHider.INTEGRATION, None),
(er.RegistryEntryHider.USER, None),
Expand Down
2 changes: 1 addition & 1 deletion script/version_bump.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def bump_version(version, bump_type):
to_change["dev"] = ("dev", dt_util.utcnow().strftime("%Y%m%d"))

else:
assert False, f"Unsupported type: {bump_type}"
raise ValueError(f"Unsupported type: {bump_type}")

temp = Version("0")
temp._version = version._version._replace(**to_change)
Expand Down
2 changes: 1 addition & 1 deletion tests/components/blackbird/test_media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ async def setup_blackbird(hass, mock_blackbird):
"""Set up blackbird."""
with mock.patch(
"homeassistant.components.blackbird.media_player.get_blackbird",
new=lambda *a: mock_blackbird,
return_value=mock_blackbird,
):
await hass.async_add_executor_job(
setup_platform,
Expand Down
1 change: 0 additions & 1 deletion tests/components/dsmr/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@
("5B", "1234_Max_current_per_phase", "1234_belgium_max_current_per_phase"),
("5L", "1234_Energy_Consumption_(total)", "1234_electricity_imported_total"),
("5L", "1234_Energy_Production_(total)", "1234_electricity_exported_total"),
("5L", "1234_Energy_Production_(total)", "1234_electricity_exported_total"),
("5", "1234_Gas_Consumption", "1234_hourly_gas_meter_reading"),
("5B", "1234_Gas_Consumption", "1234_belgium_5min_gas_meter_reading"),
("2.2", "1234_Gas_Consumption", "1234_gas_meter_reading"),
Expand Down
14 changes: 4 additions & 10 deletions tests/components/humidifier/test_intent.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,17 +175,14 @@ async def test_intent_set_mode_tests_feature(hass: HomeAssistant) -> None:
mode_calls = async_mock_service(hass, DOMAIN, SERVICE_SET_MODE)
await intent.async_setup_intents(hass)

try:
with pytest.raises(IntentHandleError) as excinfo:
await async_handle(
hass,
"test",
intent.INTENT_MODE,
{"name": {"value": "Bedroom humidifier"}, "mode": {"value": "away"}},
)
pytest.fail("handling intent should have raised")
except IntentHandleError as err:
assert str(err) == "Entity bedroom humidifier does not support modes"

assert str(excinfo.value) == "Entity bedroom humidifier does not support modes"
assert len(mode_calls) == 0


Expand All @@ -207,15 +204,12 @@ async def test_intent_set_unknown_mode(
mode_calls = async_mock_service(hass, DOMAIN, SERVICE_SET_MODE)
await intent.async_setup_intents(hass)

try:
with pytest.raises(IntentHandleError) as excinfo:
await async_handle(
hass,
"test",
intent.INTENT_MODE,
{"name": {"value": "Bedroom humidifier"}, "mode": {"value": "eco"}},
)
pytest.fail("handling intent should have raised")
except IntentHandleError as err:
assert str(err) == "Entity bedroom humidifier does not support eco mode"

assert str(excinfo.value) == "Entity bedroom humidifier does not support eco mode"
assert len(mode_calls) == 0
27 changes: 0 additions & 27 deletions tests/components/modbus/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,11 +329,6 @@ async def test_ok_struct_validator(do_config) -> None:
CONF_VIRTUAL_COUNT: 2,
CONF_DATA_TYPE: DataType.INT32,
},
{
CONF_NAME: TEST_ENTITY_NAME,
CONF_DATA_TYPE: DataType.INT16,
CONF_SWAP: CONF_SWAP_WORD,
},
{
CONF_NAME: TEST_ENTITY_NAME,
CONF_DATA_TYPE: DataType.INT16,
Expand Down Expand Up @@ -981,28 +976,6 @@ async def test_no_duplicate_names(hass: HomeAssistant, do_config) -> None:
}
],
},
{
CONF_TYPE: TCP,
CONF_HOST: TEST_MODBUS_HOST,
CONF_PORT: TEST_PORT_TCP,
CONF_SENSORS: [
{
CONF_NAME: "dummy",
CONF_ADDRESS: 9999,
}
],
},
{
CONF_TYPE: TCP,
CONF_HOST: TEST_MODBUS_HOST,
CONF_PORT: TEST_PORT_TCP,
CONF_SENSORS: [
{
CONF_NAME: "dummy",
CONF_ADDRESS: 9999,
}
],
},
{
CONF_TYPE: TCP,
CONF_HOST: TEST_MODBUS_HOST,
Expand Down
9 changes: 0 additions & 9 deletions tests/components/modbus/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,15 +116,6 @@
}
]
},
{
CONF_SENSORS: [
{
CONF_NAME: TEST_ENTITY_NAME,
CONF_ADDRESS: 51,
CONF_DATA_TYPE: DataType.INT16,
}
]
},
{
CONF_SENSORS: [
{
Expand Down
6 changes: 3 additions & 3 deletions tests/components/pilight/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import socket
from unittest.mock import patch

import pytest
from voluptuous import MultipleInvalid

from homeassistant.components import pilight
Expand Down Expand Up @@ -104,16 +105,15 @@ async def test_send_code_no_protocol(hass: HomeAssistant) -> None:
assert await async_setup_component(hass, pilight.DOMAIN, {pilight.DOMAIN: {}})

# Call without protocol info, should raise an error
try:
with pytest.raises(MultipleInvalid) as excinfo:
await hass.services.async_call(
pilight.DOMAIN,
pilight.SERVICE_NAME,
service_data={"noprotocol": "test", "value": 42},
blocking=True,
)
await hass.async_block_till_done()
except MultipleInvalid as error:
assert "required key not provided @ data['protocol']" in str(error)
assert "required key not provided @ data['protocol']" in str(excinfo.value)


@patch("homeassistant.components.pilight._LOGGER.error")
Expand Down
7 changes: 4 additions & 3 deletions tests/components/risco/test_alarm_control_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -512,7 +512,8 @@ async def _check_local_state(


@pytest.fixture
def _mock_partition_handler():
def mock_partition_handler():
"""Create a mock for add_partition_handler."""
with patch(
"homeassistant.components.risco.RiscoLocal.add_partition_handler"
) as mock:
Expand All @@ -523,11 +524,11 @@ def _mock_partition_handler():
async def test_local_states(
hass: HomeAssistant,
two_part_local_alarm,
_mock_partition_handler,
mock_partition_handler,
setup_risco_local,
) -> None:
"""Test the various alarm states."""
callback = _mock_partition_handler.call_args.args[0]
callback = mock_partition_handler.call_args.args[0]

assert callback is not None

Expand Down
15 changes: 8 additions & 7 deletions tests/components/risco/test_binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,16 +134,17 @@ async def _check_local_state(


@pytest.fixture
def _mock_zone_handler():
def mock_zone_handler():
"""Create a mock for add_zone_handler."""
with patch("homeassistant.components.risco.RiscoLocal.add_zone_handler") as mock:
yield mock


async def test_local_states(
hass: HomeAssistant, two_zone_local, _mock_zone_handler, setup_risco_local
hass: HomeAssistant, two_zone_local, mock_zone_handler, setup_risco_local
) -> None:
"""Test the various zone states."""
callback = _mock_zone_handler.call_args.args[0]
callback = mock_zone_handler.call_args.args[0]

assert callback is not None

Expand All @@ -162,10 +163,10 @@ async def test_local_states(


async def test_alarmed_local_states(
hass: HomeAssistant, two_zone_local, _mock_zone_handler, setup_risco_local
hass: HomeAssistant, two_zone_local, mock_zone_handler, setup_risco_local
) -> None:
"""Test the various zone alarmed states."""
callback = _mock_zone_handler.call_args.args[0]
callback = mock_zone_handler.call_args.args[0]

assert callback is not None

Expand All @@ -184,10 +185,10 @@ async def test_alarmed_local_states(


async def test_armed_local_states(
hass: HomeAssistant, two_zone_local, _mock_zone_handler, setup_risco_local
hass: HomeAssistant, two_zone_local, mock_zone_handler, setup_risco_local
) -> None:
"""Test the various zone armed states."""
callback = _mock_zone_handler.call_args.args[0]
callback = mock_zone_handler.call_args.args[0]

assert callback is not None

Expand Down
7 changes: 4 additions & 3 deletions tests/components/risco/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,8 @@ def _set_utc_time_zone(hass):


@pytest.fixture
def _save_mock():
def save_mock():
"""Create a mock for async_save."""
with patch(
"homeassistant.components.risco.Store.async_save",
) as save_mock:
Expand All @@ -175,15 +176,15 @@ async def test_cloud_setup(
hass: HomeAssistant,
two_zone_cloud,
_set_utc_time_zone,
_save_mock,
save_mock,
setup_risco_cloud,
) -> None:
"""Test entity setup."""
registry = er.async_get(hass)
for id in ENTITY_IDS.values():
assert registry.async_is_registered(id)

_save_mock.assert_awaited_once_with({LAST_EVENT_TIMESTAMP_KEY: TEST_EVENTS[0].time})
save_mock.assert_awaited_once_with({LAST_EVENT_TIMESTAMP_KEY: TEST_EVENTS[0].time})
for category, entity_id in ENTITY_IDS.items():
_check_state(hass, category, entity_id)

Expand Down
7 changes: 4 additions & 3 deletions tests/components/risco/test_switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,16 +124,17 @@ async def _check_local_state(hass, zones, bypassed, entity_id, zone_id, callback


@pytest.fixture
def _mock_zone_handler():
def mock_zone_handler():
"""Create a mock for add_zone_handler."""
with patch("homeassistant.components.risco.RiscoLocal.add_zone_handler") as mock:
yield mock


async def test_local_states(
hass: HomeAssistant, two_zone_local, _mock_zone_handler, setup_risco_local
hass: HomeAssistant, two_zone_local, mock_zone_handler, setup_risco_local
) -> None:
"""Test the various alarm states."""
callback = _mock_zone_handler.call_args.args[0]
callback = mock_zone_handler.call_args.args[0]

assert callback is not None

Expand Down
23 changes: 12 additions & 11 deletions tests/components/rympro/test_config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@


@pytest.fixture
def _config_entry(hass):
def config_entry(hass: HomeAssistant) -> MockConfigEntry:
"""Create a mock config entry."""
config_entry = MockConfigEntry(
domain=DOMAIN,
data=TEST_DATA,
Expand Down Expand Up @@ -122,7 +123,7 @@ async def test_login_error(hass: HomeAssistant, exception, error) -> None:
assert len(mock_setup_entry.mock_calls) == 1


async def test_form_already_exists(hass: HomeAssistant, _config_entry) -> None:
async def test_form_already_exists(hass: HomeAssistant, config_entry) -> None:
"""Test that a flow with an existing account aborts."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
Expand All @@ -148,16 +149,16 @@ async def test_form_already_exists(hass: HomeAssistant, _config_entry) -> None:
assert result2["reason"] == "already_configured"


async def test_form_reauth(hass: HomeAssistant, _config_entry) -> None:
async def test_form_reauth(hass: HomeAssistant, config_entry) -> None:
"""Test reauthentication."""

result = await hass.config_entries.flow.async_init(
DOMAIN,
context={
"source": config_entries.SOURCE_REAUTH,
"entry_id": _config_entry.entry_id,
"entry_id": config_entry.entry_id,
},
data=_config_entry.data,
data=config_entry.data,
)
assert result["type"] == "form"
assert result["errors"] is None
Expand All @@ -183,20 +184,20 @@ async def test_form_reauth(hass: HomeAssistant, _config_entry) -> None:

assert result2["type"] == "abort"
assert result2["reason"] == "reauth_successful"
assert _config_entry.data[CONF_PASSWORD] == "new_password"
assert config_entry.data[CONF_PASSWORD] == "new_password"
assert len(mock_setup_entry.mock_calls) == 1


async def test_form_reauth_with_new_account(hass: HomeAssistant, _config_entry) -> None:
async def test_form_reauth_with_new_account(hass: HomeAssistant, config_entry) -> None:
"""Test reauthentication with new account."""

result = await hass.config_entries.flow.async_init(
DOMAIN,
context={
"source": config_entries.SOURCE_REAUTH,
"entry_id": _config_entry.entry_id,
"entry_id": config_entry.entry_id,
},
data=_config_entry.data,
data=config_entry.data,
)
assert result["type"] == "form"
assert result["errors"] is None
Expand All @@ -222,6 +223,6 @@ async def test_form_reauth_with_new_account(hass: HomeAssistant, _config_entry)

assert result2["type"] == "abort"
assert result2["reason"] == "reauth_successful"
assert _config_entry.data[CONF_UNIQUE_ID] == "new-account-number"
assert _config_entry.unique_id == "new-account-number"
assert config_entry.data[CONF_UNIQUE_ID] == "new-account-number"
assert config_entry.unique_id == "new-account-number"
assert len(mock_setup_entry.mock_calls) == 1
Loading

0 comments on commit 727581e

Please sign in to comment.