Enable Ruff PT015 (#86775)

This commit is contained in:
Franck Nijhof 2023-01-27 11:10:29 +01:00 committed by GitHub
parent 49148421cb
commit 57cf11f067
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 43 additions and 36 deletions

View File

@ -247,8 +247,6 @@ select = [
"E", # pycodestyle "E", # pycodestyle
"F", # pyflakes/autoflake "F", # pyflakes/autoflake
"PGH004", # Use specific rule codes when using noqa "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 "SIM105", # Use contextlib.suppress({exception}) instead of try-except-pass
"T20", # flake8-print "T20", # flake8-print
"UP", # pyupgrade "UP", # pyupgrade

View File

@ -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_at is None
assert r_token.last_used_ip is None assert r_token.last_used_ip is None
else: 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): async def test_cannot_retrieve_expired_access_token(hass):

View File

@ -2,6 +2,8 @@
from unittest.mock import Mock from unittest.mock import Mock
from uuid import uuid4 from uuid import uuid4
import pytest
from homeassistant.components.alexa import config, smart_home, smart_home_http 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.components.alexa.const import CONF_ENDPOINT, CONF_FILTER, CONF_LOCALE
from homeassistant.core import Context, callback from homeassistant.core import Context, callback
@ -216,7 +218,7 @@ class ReportedProperties:
"""Assert a property does not exist.""" """Assert a property does not exist."""
for prop in self.properties: for prop in self.properties:
if prop["namespace"] == namespace and prop["name"] == name: 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): def assert_equal(self, namespace, name, value):
"""Assert a property is equal to a given value.""" """Assert a property is equal to a given value."""
@ -225,4 +227,4 @@ class ReportedProperties:
assert prop["value"] == value assert prop["value"] == value
return prop return prop
assert False, f"property {namespace}:{name} not in {self.properties!r}" pytest.fail(f"property {namespace}:{name} not in {self.properties!r}")

View File

@ -2,6 +2,7 @@
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
import aprslib import aprslib
import pytest
import homeassistant.components.aprs.device_tracker as device_tracker import homeassistant.components.aprs.device_tracker as device_tracker
@ -57,7 +58,7 @@ def test_gps_accuracy_invalid_int():
try: try:
device_tracker.gps_accuracy(TEST_COORDS_NULL_ISLAND, level) device_tracker.gps_accuracy(TEST_COORDS_NULL_ISLAND, level)
assert False, "No exception." pytest.fail("No exception.")
except ValueError: except ValueError:
pass pass
@ -68,7 +69,7 @@ def test_gps_accuracy_invalid_string():
try: try:
device_tracker.gps_accuracy(TEST_COORDS_NULL_ISLAND, level) device_tracker.gps_accuracy(TEST_COORDS_NULL_ISLAND, level)
assert False, "No exception." pytest.fail("No exception.")
except ValueError: except ValueError:
pass pass
@ -79,7 +80,7 @@ def test_gps_accuracy_invalid_float():
try: try:
device_tracker.gps_accuracy(TEST_COORDS_NULL_ISLAND, level) device_tracker.gps_accuracy(TEST_COORDS_NULL_ISLAND, level)
assert False, "No exception." pytest.fail("No exception.")
except ValueError: except ValueError:
pass pass

View File

@ -5,6 +5,8 @@ from datetime import timedelta
import pathlib import pathlib
from unittest.mock import patch from unittest.mock import patch
import pytest
from homeassistant.components import automation from homeassistant.components import automation
from homeassistant.components.blueprint import models from homeassistant.components.blueprint import models
from homeassistant.core import callback from homeassistant.core import callback
@ -24,7 +26,7 @@ def patch_blueprint(blueprint_path: str, data_path):
@callback @callback
def mock_load_blueprint(self, path): def mock_load_blueprint(self, path):
if path != blueprint_path: if path != blueprint_path:
assert False, f"Unexpected blueprint {path}" pytest.fail(f"Unexpected blueprint {path}")
return orig_load(self, path) return orig_load(self, path)
return models.Blueprint( return models.Blueprint(

View File

@ -59,7 +59,7 @@ def test_blueprint_schema(blueprint):
schemas.BLUEPRINT_SCHEMA(blueprint) schemas.BLUEPRINT_SCHEMA(blueprint)
except vol.Invalid: except vol.Invalid:
_LOGGER.exception("%s", blueprint) _LOGGER.exception("%s", blueprint)
assert False, "Expected schema to be valid" pytest.fail("Expected schema to be valid")
@pytest.mark.parametrize( @pytest.mark.parametrize(

View File

@ -291,7 +291,7 @@ async def test_setup_api_push_api_data_default(hass, aioclient_mock, hass_storag
if token.token == refresh_token: if token.token == refresh_token:
break break
else: 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): async def test_setup_adds_admin_group_to_user(hass, aioclient_mock, hass_storage):

View File

@ -330,7 +330,7 @@ async def test_require_admin(hass, hass_read_only_user):
context=ha.Context(user_id=hass_read_only_user.id), context=ha.Context(user_id=hass_read_only_user.id),
blocking=True, blocking=True,
) )
assert False, f"Should have raises for {service}" pytest.fail(f"Should have raises for {service}")
with pytest.raises(Unauthorized): with pytest.raises(Unauthorized):
await hass.services.async_call( await hass.services.async_call(

View File

@ -1,4 +1,6 @@
"""Tests for the humidifier intents.""" """Tests for the humidifier intents."""
import pytest
from homeassistant.components.humidifier import ( from homeassistant.components.humidifier import (
ATTR_AVAILABLE_MODES, ATTR_AVAILABLE_MODES,
ATTR_HUMIDITY, ATTR_HUMIDITY,
@ -178,7 +180,7 @@ async def test_intent_set_mode_tests_feature(hass):
intent.INTENT_MODE, intent.INTENT_MODE,
{"name": {"value": "Bedroom humidifier"}, "mode": {"value": "away"}}, {"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: except IntentHandleError as err:
assert str(err) == "Entity bedroom humidifier does not support modes" 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, intent.INTENT_MODE,
{"name": {"value": "Bedroom humidifier"}, "mode": {"value": "eco"}}, {"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: except IntentHandleError as err:
assert str(err) == "Entity bedroom humidifier does not support eco mode" assert str(err) == "Entity bedroom humidifier does not support eco mode"

View File

@ -34,7 +34,7 @@ async def matter_client_fixture() -> AsyncGenerator[MagicMock, None]:
init_ready.set() init_ready.set()
listen_block = asyncio.Event() listen_block = asyncio.Event()
await listen_block.wait() await listen_block.wait()
assert False, "Listen was not cancelled!" pytest.fail("Listen was not cancelled!")
client.connect = AsyncMock(side_effect=connect) client.connect = AsyncMock(side_effect=connect)
client.start_listening = AsyncMock(side_effect=listen) client.start_listening = AsyncMock(side_effect=listen)

View File

@ -148,7 +148,7 @@ def mock_process_uploaded_file(tmp_path):
keyfile.write(b"## mock key file ##") keyfile.write(b"## mock key file ##")
return tmp_path / "client.key" return tmp_path / "client.key"
else: else:
assert False pytest.fail(f"Unexpected file_id: {file_id}")
with patch( with patch(
"homeassistant.components.mqtt.config_flow.process_uploaded_file", "homeassistant.components.mqtt.config_flow.process_uploaded_file",

View File

@ -5,6 +5,8 @@ import contextlib
import pathlib import pathlib
from unittest.mock import patch from unittest.mock import patch
import pytest
from homeassistant.components import script from homeassistant.components import script
from homeassistant.components.blueprint.models import Blueprint, DomainBlueprints from homeassistant.components.blueprint.models import Blueprint, DomainBlueprints
from homeassistant.core import Context, HomeAssistant, callback from homeassistant.core import Context, HomeAssistant, callback
@ -25,7 +27,7 @@ def patch_blueprint(blueprint_path: str, data_path: str) -> Iterator[None]:
@callback @callback
def mock_load_blueprint(self, path: str) -> Blueprint: def mock_load_blueprint(self, path: str) -> Blueprint:
if path != blueprint_path: if path != blueprint_path:
assert False, f"Unexpected blueprint {path}" pytest.fail(f"Unexpected blueprint {path}")
return orig_load(self, path) return orig_load(self, path)
return Blueprint( return Blueprint(

View File

@ -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 print(fil.relative_to(tmp_path)) # noqa: T201
# To show the log. # To show the log.
assert False pytest.fail("Test failed, see log for details")
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)

View File

@ -210,27 +210,21 @@ async def test_data_manager_webhook_subscription(
api.notify_subscribe.assert_any_call( api.notify_subscribe.assert_any_call(
data_manager.webhook_config.url, NotifyAppli.SLEEP data_manager.webhook_config.url, NotifyAppli.SLEEP
) )
try:
with pytest.raises(AssertionError):
api.notify_subscribe.assert_any_call( api.notify_subscribe.assert_any_call(
data_manager.webhook_config.url, NotifyAppli.USER data_manager.webhook_config.url, NotifyAppli.USER
) )
assert False
except AssertionError: with pytest.raises(AssertionError):
pass
try:
api.notify_subscribe.assert_any_call( api.notify_subscribe.assert_any_call(
data_manager.webhook_config.url, NotifyAppli.BED_IN data_manager.webhook_config.url, NotifyAppli.BED_IN
) )
assert False
except AssertionError: with pytest.raises(AssertionError):
pass
try:
api.notify_subscribe.assert_any_call( api.notify_subscribe.assert_any_call(
data_manager.webhook_config.url, NotifyAppli.BED_OUT data_manager.webhook_config.url, NotifyAppli.BED_OUT
) )
assert False
except AssertionError:
pass
# Test unsubscribing. # Test unsubscribing.
await data_manager.async_unsubscribe_webhook() await data_manager.async_unsubscribe_webhook()

View File

@ -36,7 +36,7 @@ def config_schema_assert_fail(withings_config) -> None:
"""Assert a schema config will fail.""" """Assert a schema config will fail."""
try: try:
config_schema_validate(withings_config) 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: except vol.error.MultipleInvalid:
assert True assert True

View File

@ -614,7 +614,7 @@ def mock_client_fixture(
driver_ready.set() driver_ready.set()
listen_block = asyncio.Event() listen_block = asyncio.Event()
await listen_block.wait() await listen_block.wait()
assert False, "Listen wasn't canceled!" pytest.fail("Listen wasn't canceled!")
async def disconnect(): async def disconnect():
client.connected = False client.connected = False

View File

@ -4404,7 +4404,7 @@ async def test_validate_action_config(hass):
hass, validated_config[action_type] hass, validated_config[action_type]
) )
except vol.Invalid as err: 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 # Verify non-static actions have validated
for action_type, paths_to_templates in expected_templates.items(): for action_type, paths_to_templates in expected_templates.items():

8
tests/ruff.toml Normal file
View File

@ -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()
]

View File

@ -146,9 +146,7 @@ class AiohttpClientMocker:
raise response.exc raise response.exc
return response return response
assert False, "No mock registered for {} {} {}".format( raise AssertionError(f"No mock registered for {method.upper()} {url} {params}")
method.upper(), url, params
)
class AiohttpClientMockResponse: class AiohttpClientMockResponse: