From 57cf11f06743185aef9e4ad5b561fa0ba750d616 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 27 Jan 2023 11:10:29 +0100 Subject: [PATCH] Enable Ruff PT015 (#86775) --- pyproject.toml | 2 -- tests/auth/test_init.py | 2 +- tests/components/alexa/test_common.py | 6 ++++-- tests/components/aprs/test_device_tracker.py | 7 ++++--- tests/components/automation/test_blueprint.py | 4 +++- tests/components/blueprint/test_schemas.py | 2 +- tests/components/hassio/test_init.py | 2 +- tests/components/homeassistant/test_init.py | 2 +- tests/components/humidifier/test_intent.py | 6 ++++-- tests/components/matter/conftest.py | 2 +- tests/components/mqtt/test_config_flow.py | 2 +- tests/components/script/test_blueprint.py | 4 +++- tests/components/tts/conftest.py | 2 +- tests/components/withings/test_common.py | 18 ++++++------------ tests/components/withings/test_init.py | 2 +- tests/components/zwave_js/conftest.py | 2 +- tests/helpers/test_script.py | 2 +- tests/ruff.toml | 8 ++++++++ tests/test_util/aiohttp.py | 4 +--- 19 files changed, 43 insertions(+), 36 deletions(-) create mode 100644 tests/ruff.toml diff --git a/pyproject.toml b/pyproject.toml index b45c3d75f27..4ecc444e897 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -247,8 +247,6 @@ select = [ "E", # pycodestyle "F", # pyflakes/autoflake "PGH004", # Use specific rule codes when using noqa - "PT001", # Use @pytest.fixture without parentheses - "PT013", # Found incorrect pytest import, use simple import pytest instead "SIM105", # Use contextlib.suppress({exception}) instead of try-except-pass "T20", # flake8-print "UP", # pyupgrade diff --git a/tests/auth/test_init.py b/tests/auth/test_init.py index f8ba8108f59..ceb497fddf5 100644 --- a/tests/auth/test_init.py +++ b/tests/auth/test_init.py @@ -352,7 +352,7 @@ async def test_saving_loading(hass, hass_storage): assert r_token.last_used_at is None assert r_token.last_used_ip is None else: - assert False, f"Unknown client_id: {r_token.client_id}" + pytest.fail(f"Unknown client_id: {r_token.client_id}") async def test_cannot_retrieve_expired_access_token(hass): diff --git a/tests/components/alexa/test_common.py b/tests/components/alexa/test_common.py index da17ce253c3..53a836f97f3 100644 --- a/tests/components/alexa/test_common.py +++ b/tests/components/alexa/test_common.py @@ -2,6 +2,8 @@ from unittest.mock import Mock from uuid import uuid4 +import pytest + from homeassistant.components.alexa import config, smart_home, smart_home_http from homeassistant.components.alexa.const import CONF_ENDPOINT, CONF_FILTER, CONF_LOCALE from homeassistant.core import Context, callback @@ -216,7 +218,7 @@ class ReportedProperties: """Assert a property does not exist.""" for prop in self.properties: if prop["namespace"] == namespace and prop["name"] == name: - assert False, "Property %s:%s exists" + pytest.fail(f"Property {namespace}:{name} exists") def assert_equal(self, namespace, name, value): """Assert a property is equal to a given value.""" @@ -225,4 +227,4 @@ class ReportedProperties: assert prop["value"] == value return prop - assert False, f"property {namespace}:{name} not in {self.properties!r}" + pytest.fail(f"property {namespace}:{name} not in {self.properties!r}") diff --git a/tests/components/aprs/test_device_tracker.py b/tests/components/aprs/test_device_tracker.py index 6301b3d7d9b..b1b21ff8949 100644 --- a/tests/components/aprs/test_device_tracker.py +++ b/tests/components/aprs/test_device_tracker.py @@ -2,6 +2,7 @@ from unittest.mock import Mock, patch import aprslib +import pytest import homeassistant.components.aprs.device_tracker as device_tracker @@ -57,7 +58,7 @@ def test_gps_accuracy_invalid_int(): try: device_tracker.gps_accuracy(TEST_COORDS_NULL_ISLAND, level) - assert False, "No exception." + pytest.fail("No exception.") except ValueError: pass @@ -68,7 +69,7 @@ def test_gps_accuracy_invalid_string(): try: device_tracker.gps_accuracy(TEST_COORDS_NULL_ISLAND, level) - assert False, "No exception." + pytest.fail("No exception.") except ValueError: pass @@ -79,7 +80,7 @@ def test_gps_accuracy_invalid_float(): try: device_tracker.gps_accuracy(TEST_COORDS_NULL_ISLAND, level) - assert False, "No exception." + pytest.fail("No exception.") except ValueError: pass diff --git a/tests/components/automation/test_blueprint.py b/tests/components/automation/test_blueprint.py index e035c238383..b4563e0d841 100644 --- a/tests/components/automation/test_blueprint.py +++ b/tests/components/automation/test_blueprint.py @@ -5,6 +5,8 @@ from datetime import timedelta import pathlib from unittest.mock import patch +import pytest + from homeassistant.components import automation from homeassistant.components.blueprint import models from homeassistant.core import callback @@ -24,7 +26,7 @@ def patch_blueprint(blueprint_path: str, data_path): @callback def mock_load_blueprint(self, path): if path != blueprint_path: - assert False, f"Unexpected blueprint {path}" + pytest.fail(f"Unexpected blueprint {path}") return orig_load(self, path) return models.Blueprint( diff --git a/tests/components/blueprint/test_schemas.py b/tests/components/blueprint/test_schemas.py index 7c91c1e4117..106a9a60b58 100644 --- a/tests/components/blueprint/test_schemas.py +++ b/tests/components/blueprint/test_schemas.py @@ -59,7 +59,7 @@ def test_blueprint_schema(blueprint): schemas.BLUEPRINT_SCHEMA(blueprint) except vol.Invalid: _LOGGER.exception("%s", blueprint) - assert False, "Expected schema to be valid" + pytest.fail("Expected schema to be valid") @pytest.mark.parametrize( diff --git a/tests/components/hassio/test_init.py b/tests/components/hassio/test_init.py index 5f6b8c49f87..cc64e0d1875 100644 --- a/tests/components/hassio/test_init.py +++ b/tests/components/hassio/test_init.py @@ -291,7 +291,7 @@ async def test_setup_api_push_api_data_default(hass, aioclient_mock, hass_storag if token.token == refresh_token: break else: - assert False, "refresh token not found" + pytest.fail("refresh token not found") async def test_setup_adds_admin_group_to_user(hass, aioclient_mock, hass_storage): diff --git a/tests/components/homeassistant/test_init.py b/tests/components/homeassistant/test_init.py index a405a7a5672..91e154f11c2 100644 --- a/tests/components/homeassistant/test_init.py +++ b/tests/components/homeassistant/test_init.py @@ -330,7 +330,7 @@ async def test_require_admin(hass, hass_read_only_user): context=ha.Context(user_id=hass_read_only_user.id), blocking=True, ) - assert False, f"Should have raises for {service}" + pytest.fail(f"Should have raises for {service}") with pytest.raises(Unauthorized): await hass.services.async_call( diff --git a/tests/components/humidifier/test_intent.py b/tests/components/humidifier/test_intent.py index ed207231bc6..37cc20a06c9 100644 --- a/tests/components/humidifier/test_intent.py +++ b/tests/components/humidifier/test_intent.py @@ -1,4 +1,6 @@ """Tests for the humidifier intents.""" +import pytest + from homeassistant.components.humidifier import ( ATTR_AVAILABLE_MODES, ATTR_HUMIDITY, @@ -178,7 +180,7 @@ async def test_intent_set_mode_tests_feature(hass): intent.INTENT_MODE, {"name": {"value": "Bedroom humidifier"}, "mode": {"value": "away"}}, ) - assert False, "handling intent should have raised" + pytest.fail("handling intent should have raised") except IntentHandleError as err: assert str(err) == "Entity bedroom humidifier does not support modes" @@ -207,7 +209,7 @@ async def test_intent_set_unknown_mode(hass): intent.INTENT_MODE, {"name": {"value": "Bedroom humidifier"}, "mode": {"value": "eco"}}, ) - assert False, "handling intent should have raised" + pytest.fail("handling intent should have raised") except IntentHandleError as err: assert str(err) == "Entity bedroom humidifier does not support eco mode" diff --git a/tests/components/matter/conftest.py b/tests/components/matter/conftest.py index ad66bb7f6a9..7305c69e43b 100644 --- a/tests/components/matter/conftest.py +++ b/tests/components/matter/conftest.py @@ -34,7 +34,7 @@ async def matter_client_fixture() -> AsyncGenerator[MagicMock, None]: init_ready.set() listen_block = asyncio.Event() await listen_block.wait() - assert False, "Listen was not cancelled!" + pytest.fail("Listen was not cancelled!") client.connect = AsyncMock(side_effect=connect) client.start_listening = AsyncMock(side_effect=listen) diff --git a/tests/components/mqtt/test_config_flow.py b/tests/components/mqtt/test_config_flow.py index 5cccb341218..173b1731cab 100644 --- a/tests/components/mqtt/test_config_flow.py +++ b/tests/components/mqtt/test_config_flow.py @@ -148,7 +148,7 @@ def mock_process_uploaded_file(tmp_path): keyfile.write(b"## mock key file ##") return tmp_path / "client.key" else: - assert False + pytest.fail(f"Unexpected file_id: {file_id}") with patch( "homeassistant.components.mqtt.config_flow.process_uploaded_file", diff --git a/tests/components/script/test_blueprint.py b/tests/components/script/test_blueprint.py index 10e73a80939..48bdd294420 100644 --- a/tests/components/script/test_blueprint.py +++ b/tests/components/script/test_blueprint.py @@ -5,6 +5,8 @@ import contextlib import pathlib from unittest.mock import patch +import pytest + from homeassistant.components import script from homeassistant.components.blueprint.models import Blueprint, DomainBlueprints from homeassistant.core import Context, HomeAssistant, callback @@ -25,7 +27,7 @@ def patch_blueprint(blueprint_path: str, data_path: str) -> Iterator[None]: @callback def mock_load_blueprint(self, path: str) -> Blueprint: if path != blueprint_path: - assert False, f"Unexpected blueprint {path}" + pytest.fail(f"Unexpected blueprint {path}") return orig_load(self, path) return Blueprint( diff --git a/tests/components/tts/conftest.py b/tests/components/tts/conftest.py index a8b9b4cf5ce..c251bdcb8bf 100644 --- a/tests/components/tts/conftest.py +++ b/tests/components/tts/conftest.py @@ -60,7 +60,7 @@ def empty_cache_dir(tmp_path, mock_init_cache_dir, mock_get_cache_files, request print(fil.relative_to(tmp_path)) # noqa: T201 # To show the log. - assert False + pytest.fail("Test failed, see log for details") @pytest.fixture(autouse=True) diff --git a/tests/components/withings/test_common.py b/tests/components/withings/test_common.py index 8a0bf88f6e9..02c4825a26a 100644 --- a/tests/components/withings/test_common.py +++ b/tests/components/withings/test_common.py @@ -210,27 +210,21 @@ async def test_data_manager_webhook_subscription( api.notify_subscribe.assert_any_call( data_manager.webhook_config.url, NotifyAppli.SLEEP ) - try: + + with pytest.raises(AssertionError): api.notify_subscribe.assert_any_call( data_manager.webhook_config.url, NotifyAppli.USER ) - assert False - except AssertionError: - pass - try: + + with pytest.raises(AssertionError): api.notify_subscribe.assert_any_call( data_manager.webhook_config.url, NotifyAppli.BED_IN ) - assert False - except AssertionError: - pass - try: + + with pytest.raises(AssertionError): api.notify_subscribe.assert_any_call( data_manager.webhook_config.url, NotifyAppli.BED_OUT ) - assert False - except AssertionError: - pass # Test unsubscribing. await data_manager.async_unsubscribe_webhook() diff --git a/tests/components/withings/test_init.py b/tests/components/withings/test_init.py index 70c4d177e59..7f9dc68cf0c 100644 --- a/tests/components/withings/test_init.py +++ b/tests/components/withings/test_init.py @@ -36,7 +36,7 @@ def config_schema_assert_fail(withings_config) -> None: """Assert a schema config will fail.""" try: config_schema_validate(withings_config) - assert False, "This line should not have run." + pytest.fail("This line should not have run.") except vol.error.MultipleInvalid: assert True diff --git a/tests/components/zwave_js/conftest.py b/tests/components/zwave_js/conftest.py index a863118a0be..1f332f04fd4 100644 --- a/tests/components/zwave_js/conftest.py +++ b/tests/components/zwave_js/conftest.py @@ -614,7 +614,7 @@ def mock_client_fixture( driver_ready.set() listen_block = asyncio.Event() await listen_block.wait() - assert False, "Listen wasn't canceled!" + pytest.fail("Listen wasn't canceled!") async def disconnect(): client.connected = False diff --git a/tests/helpers/test_script.py b/tests/helpers/test_script.py index 3f8bf7c9eef..6b25f741927 100644 --- a/tests/helpers/test_script.py +++ b/tests/helpers/test_script.py @@ -4404,7 +4404,7 @@ async def test_validate_action_config(hass): hass, validated_config[action_type] ) except vol.Invalid as err: - assert False, f"{action_type} config invalid: {err}" + pytest.fail(f"{action_type} config invalid: {err}") # Verify non-static actions have validated for action_type, paths_to_templates in expected_templates.items(): diff --git a/tests/ruff.toml b/tests/ruff.toml new file mode 100644 index 00000000000..767e0a30a61 --- /dev/null +++ b/tests/ruff.toml @@ -0,0 +1,8 @@ +# This extend our general Ruff rules specifically for tests +extend = "../pyproject.toml" + +extend-select = [ + "PT001", # Use @pytest.fixture without parentheses + "PT013", # Found incorrect pytest import, use simple import pytest instead + "PT015", # Assertion always fails, replace with pytest.fail() +] \ No newline at end of file diff --git a/tests/test_util/aiohttp.py b/tests/test_util/aiohttp.py index bd77ca2b5b9..b8a6dc5ad96 100644 --- a/tests/test_util/aiohttp.py +++ b/tests/test_util/aiohttp.py @@ -146,9 +146,7 @@ class AiohttpClientMocker: raise response.exc return response - assert False, "No mock registered for {} {} {}".format( - method.upper(), url, params - ) + raise AssertionError(f"No mock registered for {method.upper()} {url} {params}") class AiohttpClientMockResponse: