From 9864f2ef8be676dc4aa8ed03e63594199895a60a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Tue, 13 Jul 2021 01:12:55 +0300 Subject: [PATCH] String formatting cleanups (#52937) --- homeassistant/components/buienradar/util.py | 2 +- homeassistant/components/cisco_ios/device_tracker.py | 2 +- homeassistant/components/etherscan/sensor.py | 2 +- homeassistant/components/google_travel_time/helpers.py | 2 +- homeassistant/components/mailbox/__init__.py | 3 +-- homeassistant/components/mobile_app/webhook.py | 2 +- homeassistant/components/mochad/switch.py | 2 +- homeassistant/components/nest/legacy/sensor.py | 4 ++-- homeassistant/components/netio/switch.py | 8 ++++---- homeassistant/components/octoprint/__init__.py | 4 ++-- homeassistant/components/openhardwaremonitor/sensor.py | 2 +- homeassistant/components/rss_feed_template/__init__.py | 2 +- homeassistant/components/smtp/notify.py | 2 +- homeassistant/components/statsd/__init__.py | 2 +- homeassistant/components/xiaomi_aqara/light.py | 2 +- homeassistant/util/async_.py | 2 +- homeassistant/util/ruamel_yaml.py | 2 +- tests/auth/test_init.py | 2 +- tests/components/foobot/test_sensor.py | 2 +- tests/components/hyperion/test_light.py | 2 +- tests/components/mailbox/test_init.py | 10 +++++----- tests/components/statsd/test_init.py | 6 ++---- 22 files changed, 32 insertions(+), 35 deletions(-) diff --git a/homeassistant/components/buienradar/util.py b/homeassistant/components/buienradar/util.py index 83c511713d0..8934a7a6833 100644 --- a/homeassistant/components/buienradar/util.py +++ b/homeassistant/components/buienradar/util.py @@ -99,7 +99,7 @@ class BrData: return result except (asyncio.TimeoutError, aiohttp.ClientError) as err: - result[MESSAGE] = "%s" % err + result[MESSAGE] = str(err) return result finally: if resp is not None: diff --git a/homeassistant/components/cisco_ios/device_tracker.py b/homeassistant/components/cisco_ios/device_tracker.py index b9eadec7d18..b30e9dae1f3 100644 --- a/homeassistant/components/cisco_ios/device_tracker.py +++ b/homeassistant/components/cisco_ios/device_tracker.py @@ -118,7 +118,7 @@ class CiscoDeviceScanner(DeviceScanner): router_hostname = initial_line[len(initial_line) - 1] router_hostname += "#" # Set the discovered hostname as prompt - regex_expression = ("(?i)^%s" % router_hostname).encode() + regex_expression = f"(?i)^{router_hostname}".encode() cisco_ssh.PROMPT = re.compile(regex_expression, re.MULTILINE) # Allow full arp table to print at once cisco_ssh.sendline("terminal length 0") diff --git a/homeassistant/components/etherscan/sensor.py b/homeassistant/components/etherscan/sensor.py index 1fa2edbf2e8..1b10cc39fe1 100644 --- a/homeassistant/components/etherscan/sensor.py +++ b/homeassistant/components/etherscan/sensor.py @@ -34,7 +34,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): if token: token = token.upper() if not name: - name = "%s Balance" % token + name = f"{token} Balance" if not name: name = "ETH Balance" diff --git a/homeassistant/components/google_travel_time/helpers.py b/homeassistant/components/google_travel_time/helpers.py index 425d21ee181..cf5f6e8b0af 100644 --- a/homeassistant/components/google_travel_time/helpers.py +++ b/homeassistant/components/google_travel_time/helpers.py @@ -41,7 +41,7 @@ def get_location_from_entity(hass, logger, entity_id): return get_location_from_attributes(entity) # Check if device is in a zone - zone_entity = hass.states.get("zone.%s" % entity.state) + zone_entity = hass.states.get(f"zone.{entity.state}") if location.has_location(zone_entity): logger.debug( "%s is in %s, getting zone location", entity_id, zone_entity.entity_id diff --git a/homeassistant/components/mailbox/__init__.py b/homeassistant/components/mailbox/__init__.py index 5d05596fb23..307bd54195f 100644 --- a/homeassistant/components/mailbox/__init__.py +++ b/homeassistant/components/mailbox/__init__.py @@ -254,8 +254,7 @@ class MailboxMediaView(MailboxView): try: stream = await mailbox.async_get_media(msgid) except StreamError as err: - error_msg = "Error getting media: %s" % (err) - _LOGGER.error(error_msg) + _LOGGER.error("Error getting media: %s", err) return web.Response(status=HTTP_INTERNAL_SERVER_ERROR) if stream: return web.Response(body=stream, content_type=mailbox.media_type) diff --git a/homeassistant/components/mobile_app/webhook.py b/homeassistant/components/mobile_app/webhook.py index 64f10d5616a..99bb153f3ee 100644 --- a/homeassistant/components/mobile_app/webhook.py +++ b/homeassistant/components/mobile_app/webhook.py @@ -268,7 +268,7 @@ async def webhook_stream_camera(hass, config_entry, data): status=HTTP_BAD_REQUEST, ) - resp = {"mjpeg_path": "/api/camera_proxy_stream/%s" % (camera.entity_id)} + resp = {"mjpeg_path": f"/api/camera_proxy_stream/{camera.entity_id}"} if camera.attributes[ATTR_SUPPORTED_FEATURES] & CAMERA_SUPPORT_STREAM: try: diff --git a/homeassistant/components/mochad/switch.py b/homeassistant/components/mochad/switch.py index e7f1bee99f6..d23d46c8392 100644 --- a/homeassistant/components/mochad/switch.py +++ b/homeassistant/components/mochad/switch.py @@ -44,7 +44,7 @@ class MochadSwitch(SwitchEntity): self._controller = ctrl self._address = dev[CONF_ADDRESS] - self._name = dev.get(CONF_NAME, "x10_switch_dev_%s" % self._address) + self._name = dev.get(CONF_NAME, f"x10_switch_dev_{self._address}") self._comm_type = dev.get(CONF_COMM_TYPE, "pl") self.switch = device.Device(ctrl, self._address, comm_type=self._comm_type) # Init with false to avoid locking HA for long on CM19A (goes from rf diff --git a/homeassistant/components/nest/legacy/sensor.py b/homeassistant/components/nest/legacy/sensor.py index 53d9c824466..54df3921bbd 100644 --- a/homeassistant/components/nest/legacy/sensor.py +++ b/homeassistant/components/nest/legacy/sensor.py @@ -93,9 +93,9 @@ async def async_setup_legacy_entry(hass, entry, async_add_entities): if variable in _SENSOR_TYPES_DEPRECATED: if variable in DEPRECATED_WEATHER_VARS: wstr = ( - "Nest no longer provides weather data like %s. See " + f"Nest no longer provides weather data like {variable}. See " "https://www.home-assistant.io/integrations/#weather " - "for a list of other weather integrations to use." % variable + "for a list of other weather integrations to use." ) else: wstr = ( diff --git a/homeassistant/components/netio/switch.py b/homeassistant/components/netio/switch.py index a254d06fc06..c39b1598c89 100644 --- a/homeassistant/components/netio/switch.py +++ b/homeassistant/components/netio/switch.py @@ -97,12 +97,12 @@ class NetioApiView(HomeAssistantView): for i in range(1, 5): out = "output%d" % i - states.append(data.get("%s_state" % out) == STATE_ON) - consumptions.append(float(data.get("%s_consumption" % out, 0))) + states.append(data.get(f"{out}_state") == STATE_ON) + consumptions.append(float(data.get(f"{out}_consumption", 0))) cumulated_consumptions.append( - float(data.get("%s_cumulatedConsumption" % out, 0)) / 1000 + float(data.get(f"{out}_cumulatedConsumption", 0)) / 1000 ) - start_dates.append(data.get("%s_consumptionStart" % out, "")) + start_dates.append(data.get(f"{out}_consumptionStart", "")) _LOGGER.debug( "%s: %s, %s, %s since %s", diff --git a/homeassistant/components/octoprint/__init__.py b/homeassistant/components/octoprint/__init__.py index 918f0258f78..396a18318f2 100644 --- a/homeassistant/components/octoprint/__init__.py +++ b/homeassistant/components/octoprint/__init__.py @@ -241,7 +241,7 @@ class OctoPrintAPI: return response.json() except requests.ConnectionError as exc_con: - log_string = "Failed to connect to Octoprint server. Error: %s" % exc_con + log_string = f"Failed to connect to Octoprint server. Error: {exc_con}" if not self.available_error_logged: _LOGGER.error(log_string) @@ -254,7 +254,7 @@ class OctoPrintAPI: except requests.HTTPError as ex_http: status_code = ex_http.response.status_code - log_string = "Failed to update OctoPrint status. Error: %s" % ex_http + log_string = f"Failed to update OctoPrint status. Error: {ex_http}" # Only log the first failure if endpoint == "job": log_string = f"Endpoint: job {log_string}" diff --git a/homeassistant/components/openhardwaremonitor/sensor.py b/homeassistant/components/openhardwaremonitor/sensor.py index 70d0d36176c..8d14074892d 100644 --- a/homeassistant/components/openhardwaremonitor/sensor.py +++ b/homeassistant/components/openhardwaremonitor/sensor.py @@ -109,7 +109,7 @@ class OpenHardwareMonitorDevice(SensorEntity): self.attributes = _attributes return array = array[path_number][OHM_CHILDREN] - _attributes.update({"level_%s" % path_index: values[OHM_NAME]}) + _attributes.update({f"level_{path_index}": values[OHM_NAME]}) class OpenHardwareMonitorData: diff --git a/homeassistant/components/rss_feed_template/__init__.py b/homeassistant/components/rss_feed_template/__init__.py index c9871c8f6b5..4ea9c27b82e 100644 --- a/homeassistant/components/rss_feed_template/__init__.py +++ b/homeassistant/components/rss_feed_template/__init__.py @@ -40,7 +40,7 @@ CONFIG_SCHEMA = vol.Schema( def setup(hass, config): """Set up the RSS feed template component.""" for (feeduri, feedconfig) in config[DOMAIN].items(): - url = "/api/rss_template/%s" % feeduri + url = f"/api/rss_template/{feeduri}" requires_auth = feedconfig.get("requires_api_password") diff --git a/homeassistant/components/smtp/notify.py b/homeassistant/components/smtp/notify.py index 29f0eb777ba..0586a5838fc 100644 --- a/homeassistant/components/smtp/notify.py +++ b/homeassistant/components/smtp/notify.py @@ -241,7 +241,7 @@ def _attach_file(atch_name, content_id): atch_name, ) attachment = MIMEApplication(file_bytes, Name=atch_name) - attachment["Content-Disposition"] = "attachment; " 'filename="%s"' % atch_name + attachment["Content-Disposition"] = f'attachment; filename="{atch_name}"' attachment.add_header("Content-ID", f"<{content_id}>") return attachment diff --git a/homeassistant/components/statsd/__init__.py b/homeassistant/components/statsd/__init__.py index 7ca3068f003..b4657838683 100644 --- a/homeassistant/components/statsd/__init__.py +++ b/homeassistant/components/statsd/__init__.py @@ -74,7 +74,7 @@ def setup(hass, config): if show_attribute_flag is True: if isinstance(_state, (float, int)): - statsd_client.gauge("%s.state" % state.entity_id, _state, sample_rate) + statsd_client.gauge(f"{state.entity_id}.state", _state, sample_rate) # Send attribute values for key, value in states.items(): diff --git a/homeassistant/components/xiaomi_aqara/light.py b/homeassistant/components/xiaomi_aqara/light.py index 494c9af920e..30f72a7ba59 100644 --- a/homeassistant/components/xiaomi_aqara/light.py +++ b/homeassistant/components/xiaomi_aqara/light.py @@ -58,7 +58,7 @@ class XiaomiGatewayLight(XiaomiDevice, LightEntity): self._state = False return True - rgbhexstr = "%x" % value + rgbhexstr = f"{value:x}" if len(rgbhexstr) > 8: _LOGGER.error( "Light RGB data error." diff --git a/homeassistant/util/async_.py b/homeassistant/util/async_.py index a467d544174..86308b48f7a 100644 --- a/homeassistant/util/async_.py +++ b/homeassistant/util/async_.py @@ -30,7 +30,7 @@ def fire_coroutine_threadsafe(coro: Coroutine, loop: AbstractEventLoop) -> None: raise RuntimeError("Cannot be called from within the event loop") if not coroutines.iscoroutine(coro): - raise TypeError("A coroutine object is required: %s" % coro) + raise TypeError(f"A coroutine object is required: {coro}") def callback() -> None: """Handle the firing of a coroutine.""" diff --git a/homeassistant/util/ruamel_yaml.py b/homeassistant/util/ruamel_yaml.py index b9f69b15578..8d813eaa5a4 100644 --- a/homeassistant/util/ruamel_yaml.py +++ b/homeassistant/util/ruamel_yaml.py @@ -47,7 +47,7 @@ def _include_yaml( """ if constructor.name is None: raise HomeAssistantError( - "YAML include error: filename not set for %s" % node.value + f"YAML include error: filename not set for {node.value}" ) fname = os.path.join(os.path.dirname(constructor.name), node.value) return load_yaml(fname, False) diff --git a/tests/auth/test_init.py b/tests/auth/test_init.py index 0128c9794f3..4a763a6e995 100644 --- a/tests/auth/test_init.py +++ b/tests/auth/test_init.py @@ -335,7 +335,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, "Unknown client_id: %s" % r_token.client_id + assert False, f"Unknown client_id: {r_token.client_id}" async def test_cannot_retrieve_expired_access_token(hass): diff --git a/tests/components/foobot/test_sensor.py b/tests/components/foobot/test_sensor.py index f817b38c98b..f3bf961fdc8 100644 --- a/tests/components/foobot/test_sensor.py +++ b/tests/components/foobot/test_sensor.py @@ -51,7 +51,7 @@ async def test_default_setup(hass, aioclient_mock): } for name, value in metrics.items(): - state = hass.states.get("sensor.foobot_happybot_%s" % name) + state = hass.states.get(f"sensor.foobot_happybot_{name}") assert state.state == value[0] assert state.attributes.get("unit_of_measurement") == value[1] diff --git a/tests/components/hyperion/test_light.py b/tests/components/hyperion/test_light.py index 829a76f22d3..5d57d3be70d 100644 --- a/tests/components/hyperion/test_light.py +++ b/tests/components/hyperion/test_light.py @@ -1384,7 +1384,7 @@ async def test_deprecated_effect_names(caplog, hass: HomeAssistant) -> None: {ATTR_ENTITY_ID: TEST_ENTITY_ID_1, ATTR_EFFECT: component}, blocking=True, ) - assert "Use of Hyperion effect '%s' is deprecated" % component in caplog.text + assert f"Use of Hyperion effect '{component}' is deprecated" in caplog.text # Simulate a state callback from Hyperion. client.visible_priority = { diff --git a/tests/components/mailbox/test_init.py b/tests/components/mailbox/test_init.py index 75ecc8d9db3..8f75085f9ee 100644 --- a/tests/components/mailbox/test_init.py +++ b/tests/components/mailbox/test_init.py @@ -43,7 +43,7 @@ async def test_get_media_from_mailbox(mock_http_client): msgtxt = "Message 1. Lorem ipsum dolor sit amet, consectetur adipiscing elit. " msgsha = sha1(msgtxt.encode("utf-8")).hexdigest() - url = "/api/mailbox/media/DemoMailbox/%s" % (msgsha) + url = f"/api/mailbox/media/DemoMailbox/{msgsha}" req = await mock_http_client.get(url) assert req.status == 200 data = await req.read() @@ -58,7 +58,7 @@ async def test_delete_from_mailbox(mock_http_client): msgsha2 = sha1(msgtxt2.encode("utf-8")).hexdigest() for msg in [msgsha1, msgsha2]: - url = "/api/mailbox/delete/DemoMailbox/%s" % (msg) + url = f"/api/mailbox/delete/DemoMailbox/{msg}" req = await mock_http_client.delete(url) assert req.status == 200 @@ -80,7 +80,7 @@ async def test_get_messages_from_invalid_mailbox(mock_http_client): async def test_get_media_from_invalid_mailbox(mock_http_client): """Get messages from mailbox.""" msgsha = "0000000000000000000000000000000000000000" - url = "/api/mailbox/media/mailbox.invalid_mailbox/%s" % (msgsha) + url = f"/api/mailbox/media/mailbox.invalid_mailbox/{msgsha}" req = await mock_http_client.get(url) assert req.status == HTTP_NOT_FOUND @@ -89,7 +89,7 @@ async def test_get_media_from_invalid_mailbox(mock_http_client): async def test_get_media_from_invalid_msgid(mock_http_client): """Get messages from mailbox.""" msgsha = "0000000000000000000000000000000000000000" - url = "/api/mailbox/media/DemoMailbox/%s" % (msgsha) + url = f"/api/mailbox/media/DemoMailbox/{msgsha}" req = await mock_http_client.get(url) assert req.status == HTTP_INTERNAL_SERVER_ERROR @@ -98,7 +98,7 @@ async def test_get_media_from_invalid_msgid(mock_http_client): async def test_delete_from_invalid_mailbox(mock_http_client): """Get audio from mailbox.""" msgsha = "0000000000000000000000000000000000000000" - url = "/api/mailbox/delete/mailbox.invalid_mailbox/%s" % (msgsha) + url = f"/api/mailbox/delete/mailbox.invalid_mailbox/{msgsha}" req = await mock_http_client.delete(url) assert req.status == HTTP_NOT_FOUND diff --git a/tests/components/statsd/test_init.py b/tests/components/statsd/test_init.py index a0e5fd51669..62808491c2d 100644 --- a/tests/components/statsd/test_init.py +++ b/tests/components/statsd/test_init.py @@ -110,10 +110,8 @@ async def test_event_listener_attr_details(hass, mock_client): handler_method(MagicMock(data={"new_state": state})) mock_client.gauge.assert_has_calls( [ - mock.call("%s.state" % state.entity_id, out, statsd.DEFAULT_RATE), - mock.call( - "%s.attribute_key" % state.entity_id, 3.2, statsd.DEFAULT_RATE - ), + mock.call(f"{state.entity_id}.state", out, statsd.DEFAULT_RATE), + mock.call(f"{state.entity_id}.attribute_key", 3.2, statsd.DEFAULT_RATE), ] )