From 524a1a75877ee86f58209368d2dd5bc71c650143 Mon Sep 17 00:00:00 2001 From: springstan <46536646+springstan@users.noreply.github.com> Date: Sun, 23 Feb 2020 22:38:05 +0100 Subject: [PATCH] Use f-strings in integrations starting with "A" (#32110) * Use f-strings in integrations starting with A * Use f-strings in tests for integrations starting with A * Fix pylint by renaming variable * Fix nested for loop in f-string for aprs device_tracker * Break long lines into multiple short lines * Break long lines into multiple short lines v2 --- homeassistant/components/abode/__init__.py | 12 +--- .../components/abode/binary_sensor.py | 4 +- homeassistant/components/abode/camera.py | 4 +- homeassistant/components/abode/const.py | 3 - homeassistant/components/abode/sensor.py | 4 +- homeassistant/components/airvisual/sensor.py | 2 +- .../components/aladdin_connect/cover.py | 4 +- homeassistant/components/alert/__init__.py | 3 +- homeassistant/components/alexa/handlers.py | 14 ++-- .../components/ambient_station/__init__.py | 7 +- .../components/ambient_station/const.py | 2 - .../components/amcrest/binary_sensor.py | 2 +- homeassistant/components/amcrest/camera.py | 4 +- homeassistant/components/amcrest/helpers.py | 2 +- homeassistant/components/amcrest/sensor.py | 18 +++-- .../components/anel_pwrctrl/switch.py | 4 +- homeassistant/components/api/__init__.py | 3 +- homeassistant/components/apple_tv/__init__.py | 13 ++-- .../components/aprs/device_tracker.py | 2 +- homeassistant/components/aqualogic/sensor.py | 2 +- homeassistant/components/aqualogic/switch.py | 2 +- .../components/arcam_fmj/__init__.py | 6 +- homeassistant/components/arest/sensor.py | 5 +- homeassistant/components/arest/switch.py | 2 +- homeassistant/components/arlo/__init__.py | 4 +- homeassistant/components/arlo/camera.py | 5 +- homeassistant/components/arlo/sensor.py | 13 ++-- .../components/aruba/device_tracker.py | 4 +- homeassistant/components/arwn/sensor.py | 2 +- .../components/asterisk_cdr/mailbox.py | 6 +- homeassistant/components/august/__init__.py | 7 +- .../components/august/binary_sensor.py | 21 ++---- .../components/aurora_abb_powerone/sensor.py | 1 - .../components/automatic/device_tracker.py | 3 +- .../components/automation/__init__.py | 10 +-- homeassistant/components/automation/config.py | 2 +- .../components/axis/binary_sensor.py | 4 +- homeassistant/components/axis/camera.py | 28 ++++---- homeassistant/components/axis/switch.py | 4 +- .../components/azure_event_hub/__init__.py | 5 +- tests/components/adguard/test_config_flow.py | 24 +++---- .../test_device_trigger.py | 35 +++++----- tests/components/alert/test_init.py | 2 +- .../components/alexa/test_flash_briefings.py | 2 +- tests/components/api/test_init.py | 67 +++++++------------ tests/components/auth/test_init.py | 4 +- tests/components/auth/test_init_link_user.py | 8 +-- tests/components/auth/test_login_flow.py | 6 +- 48 files changed, 162 insertions(+), 229 deletions(-) diff --git a/homeassistant/components/abode/__init__.py b/homeassistant/components/abode/__init__.py index a5f3e6116a4..4ce9a4faca0 100644 --- a/homeassistant/components/abode/__init__.py +++ b/homeassistant/components/abode/__init__.py @@ -24,13 +24,7 @@ from homeassistant.helpers import config_validation as cv from homeassistant.helpers.dispatcher import dispatcher_send from homeassistant.helpers.entity import Entity -from .const import ( - ATTRIBUTION, - DEFAULT_CACHEDB, - DOMAIN, - SIGNAL_CAPTURE_IMAGE, - SIGNAL_TRIGGER_QUICK_ACTION, -) +from .const import ATTRIBUTION, DEFAULT_CACHEDB, DOMAIN _LOGGER = logging.getLogger(__name__) @@ -193,7 +187,7 @@ def setup_hass_services(hass): ] for entity_id in target_entities: - signal = SIGNAL_CAPTURE_IMAGE.format(entity_id) + signal = f"abode_camera_capture_{entity_id}" dispatcher_send(hass, signal) def trigger_quick_action(call): @@ -207,7 +201,7 @@ def setup_hass_services(hass): ] for entity_id in target_entities: - signal = SIGNAL_TRIGGER_QUICK_ACTION.format(entity_id) + signal = f"abode_trigger_quick_action_{entity_id}" dispatcher_send(hass, signal) hass.services.register( diff --git a/homeassistant/components/abode/binary_sensor.py b/homeassistant/components/abode/binary_sensor.py index c27357ca076..7d4474437e9 100644 --- a/homeassistant/components/abode/binary_sensor.py +++ b/homeassistant/components/abode/binary_sensor.py @@ -8,7 +8,7 @@ from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.helpers.dispatcher import async_dispatcher_connect from . import AbodeAutomation, AbodeDevice -from .const import DOMAIN, SIGNAL_TRIGGER_QUICK_ACTION +from .const import DOMAIN _LOGGER = logging.getLogger(__name__) @@ -60,7 +60,7 @@ class AbodeQuickActionBinarySensor(AbodeAutomation, BinarySensorDevice): async def async_added_to_hass(self): """Subscribe Abode events.""" await super().async_added_to_hass() - signal = SIGNAL_TRIGGER_QUICK_ACTION.format(self.entity_id) + signal = f"abode_trigger_quick_action_{self.entity_id}" async_dispatcher_connect(self.hass, signal, self.trigger) def trigger(self): diff --git a/homeassistant/components/abode/camera.py b/homeassistant/components/abode/camera.py index 1742a0a5d6c..edf29c4a198 100644 --- a/homeassistant/components/abode/camera.py +++ b/homeassistant/components/abode/camera.py @@ -11,7 +11,7 @@ from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util import Throttle from . import AbodeDevice -from .const import DOMAIN, SIGNAL_CAPTURE_IMAGE +from .const import DOMAIN MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=90) @@ -50,7 +50,7 @@ class AbodeCamera(AbodeDevice, Camera): self._capture_callback, ) - signal = SIGNAL_CAPTURE_IMAGE.format(self.entity_id) + signal = f"abode_camera_capture_{self.entity_id}" async_dispatcher_connect(self.hass, signal, self.capture) def capture(self): diff --git a/homeassistant/components/abode/const.py b/homeassistant/components/abode/const.py index 267eb04f72e..092843ba212 100644 --- a/homeassistant/components/abode/const.py +++ b/homeassistant/components/abode/const.py @@ -3,6 +3,3 @@ DOMAIN = "abode" ATTRIBUTION = "Data provided by goabode.com" DEFAULT_CACHEDB = "abodepy_cache.pickle" - -SIGNAL_CAPTURE_IMAGE = "abode_camera_capture_{}" -SIGNAL_TRIGGER_QUICK_ACTION = "abode_trigger_quick_action_{}" diff --git a/homeassistant/components/abode/sensor.py b/homeassistant/components/abode/sensor.py index dc622cb1a38..afa5e372222 100644 --- a/homeassistant/components/abode/sensor.py +++ b/homeassistant/components/abode/sensor.py @@ -44,9 +44,7 @@ class AbodeSensor(AbodeDevice): """Initialize a sensor for an Abode device.""" super().__init__(data, device) self._sensor_type = sensor_type - self._name = "{0} {1}".format( - self._device.name, SENSOR_TYPES[self._sensor_type][0] - ) + self._name = f"{self._device.name} {SENSOR_TYPES[self._sensor_type][0]}" self._device_class = SENSOR_TYPES[self._sensor_type][1] @property diff --git a/homeassistant/components/airvisual/sensor.py b/homeassistant/components/airvisual/sensor.py index 3b177c4ce67..1c0109c0d68 100644 --- a/homeassistant/components/airvisual/sensor.py +++ b/homeassistant/components/airvisual/sensor.py @@ -185,7 +185,7 @@ class AirVisualSensor(Entity): @property def name(self): """Return the name.""" - return "{0} {1}".format(SENSOR_LOCALES[self._locale], self._name) + return f"{SENSOR_LOCALES[self._locale]} {self._name}" @property def state(self): diff --git a/homeassistant/components/aladdin_connect/cover.py b/homeassistant/components/aladdin_connect/cover.py index 4cfcd5403dd..351703c5cb3 100644 --- a/homeassistant/components/aladdin_connect/cover.py +++ b/homeassistant/components/aladdin_connect/cover.py @@ -53,9 +53,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): except (TypeError, KeyError, NameError, ValueError) as ex: _LOGGER.error("%s", ex) hass.components.persistent_notification.create( - "Error: {}
" - "You will need to restart hass after fixing." - "".format(ex), + "Error: {ex}
You will need to restart hass after fixing.", title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID, ) diff --git a/homeassistant/components/alert/__init__.py b/homeassistant/components/alert/__init__.py index 3a473b17f17..9aa3c62e76c 100644 --- a/homeassistant/components/alert/__init__.py +++ b/homeassistant/components/alert/__init__.py @@ -31,7 +31,6 @@ from homeassistant.util.dt import now _LOGGER = logging.getLogger(__name__) DOMAIN = "alert" -ENTITY_ID_FORMAT = DOMAIN + ".{}" CONF_CAN_ACK = "can_acknowledge" CONF_NOTIFIERS = "notifiers" @@ -200,7 +199,7 @@ class Alert(ToggleEntity): self._ack = False self._cancel = None self._send_done_message = False - self.entity_id = ENTITY_ID_FORMAT.format(entity_id) + self.entity_id = f"{DOMAIN}.{entity_id}" event.async_track_state_change( hass, watched_entity_id, self.watched_entity_change diff --git a/homeassistant/components/alexa/handlers.py b/homeassistant/components/alexa/handlers.py index 03c5acd42fa..b771a8fc50c 100644 --- a/homeassistant/components/alexa/handlers.py +++ b/homeassistant/components/alexa/handlers.py @@ -478,8 +478,8 @@ async def async_api_select_input(hass, config, directive, context): media_input = source break else: - msg = "failed to map input {} to a media source on {}".format( - media_input, entity.entity_id + msg = ( + f"failed to map input {media_input} to a media source on {entity.entity_id}" ) raise AlexaInvalidValueError(msg) @@ -1225,7 +1225,7 @@ async def async_api_adjust_range(hass, config, directive, context): service = SERVICE_SET_COVER_POSITION current = entity.attributes.get(cover.ATTR_POSITION) if not current: - msg = "Unable to determine {} current position".format(entity.entity_id) + msg = f"Unable to determine {entity.entity_id} current position" raise AlexaInvalidValueError(msg) position = response_value = min(100, max(0, range_delta + current)) if position == 100: @@ -1241,9 +1241,7 @@ async def async_api_adjust_range(hass, config, directive, context): service = SERVICE_SET_COVER_TILT_POSITION current = entity.attributes.get(cover.ATTR_TILT_POSITION) if not current: - msg = "Unable to determine {} current tilt position".format( - entity.entity_id - ) + msg = f"Unable to determine {entity.entity_id} current tilt position" raise AlexaInvalidValueError(msg) tilt_position = response_value = min(100, max(0, range_delta + current)) if tilt_position == 100: @@ -1439,9 +1437,7 @@ async def async_api_set_eq_mode(hass, config, directive, context): if sound_mode_list and mode.lower() in sound_mode_list: data[media_player.const.ATTR_SOUND_MODE] = mode.lower() else: - msg = "failed to map sound mode {} to a mode on {}".format( - mode, entity.entity_id - ) + msg = f"failed to map sound mode {mode} to a mode on {entity.entity_id}" raise AlexaInvalidValueError(msg) await hass.services.async_call( diff --git a/homeassistant/components/ambient_station/__init__.py b/homeassistant/components/ambient_station/__init__.py index 0bbb7a760fe..9e8ff4b9f8d 100644 --- a/homeassistant/components/ambient_station/__init__.py +++ b/homeassistant/components/ambient_station/__init__.py @@ -30,7 +30,6 @@ from .const import ( CONF_APP_KEY, DATA_CLIENT, DOMAIN, - TOPIC_UPDATE, TYPE_BINARY_SENSOR, TYPE_SENSOR, ) @@ -378,7 +377,9 @@ class AmbientStation: if data != self.stations[mac_address][ATTR_LAST_DATA]: _LOGGER.debug("New data received: %s", data) self.stations[mac_address][ATTR_LAST_DATA] = data - async_dispatcher_send(self._hass, TOPIC_UPDATE.format(mac_address)) + async_dispatcher_send( + self._hass, f"ambient_station_data_update_{mac_address}" + ) _LOGGER.debug("Resetting watchdog") self._watchdog_listener() @@ -518,7 +519,7 @@ class AmbientWeatherEntity(Entity): self.async_schedule_update_ha_state(True) self._async_unsub_dispatcher_connect = async_dispatcher_connect( - self.hass, TOPIC_UPDATE.format(self._mac_address), update + self.hass, f"ambient_station_data_update_{self._mac_address}", update ) async def async_will_remove_from_hass(self): diff --git a/homeassistant/components/ambient_station/const.py b/homeassistant/components/ambient_station/const.py index 4f94e1cfe88..3b1990ae837 100644 --- a/homeassistant/components/ambient_station/const.py +++ b/homeassistant/components/ambient_station/const.py @@ -8,7 +8,5 @@ CONF_APP_KEY = "app_key" DATA_CLIENT = "data_client" -TOPIC_UPDATE = "ambient_station_data_update_{0}" - TYPE_BINARY_SENSOR = "binary_sensor" TYPE_SENSOR = "sensor" diff --git a/homeassistant/components/amcrest/binary_sensor.py b/homeassistant/components/amcrest/binary_sensor.py index a99901f54a3..809b448876c 100644 --- a/homeassistant/components/amcrest/binary_sensor.py +++ b/homeassistant/components/amcrest/binary_sensor.py @@ -54,7 +54,7 @@ class AmcrestBinarySensor(BinarySensorDevice): def __init__(self, name, device, sensor_type): """Initialize entity.""" - self._name = "{} {}".format(name, BINARY_SENSORS[sensor_type][0]) + self._name = f"{name} {BINARY_SENSORS[sensor_type][0]}" self._signal_name = name self._api = device.api self._sensor_type = sensor_type diff --git a/homeassistant/components/amcrest/camera.py b/homeassistant/components/amcrest/camera.py index 0e64d4fefc9..f9515256403 100644 --- a/homeassistant/components/amcrest/camera.py +++ b/homeassistant/components/amcrest/camera.py @@ -491,9 +491,7 @@ class AmcrestCam(Camera): """Enable or disable indicator light.""" try: self._api.command( - "configManager.cgi?action=setConfig&LightGlobal[0].Enable={}".format( - str(enable).lower() - ) + f"configManager.cgi?action=setConfig&LightGlobal[0].Enable={str(enable).lower()}" ) except AmcrestError as error: log_update_error( diff --git a/homeassistant/components/amcrest/helpers.py b/homeassistant/components/amcrest/helpers.py index a40d6ace50a..57d1a73c97e 100644 --- a/homeassistant/components/amcrest/helpers.py +++ b/homeassistant/components/amcrest/helpers.py @@ -6,7 +6,7 @@ def service_signal(service, ident=None): """Encode service and identifier into signal.""" signal = f"{DOMAIN}_{service}" if ident: - signal += "_{}".format(ident.replace(".", "_")) + signal += f"_{ident.replace('.', '_')}" return signal diff --git a/homeassistant/components/amcrest/sensor.py b/homeassistant/components/amcrest/sensor.py index 04436cd95ab..bcff1775879 100644 --- a/homeassistant/components/amcrest/sensor.py +++ b/homeassistant/components/amcrest/sensor.py @@ -45,7 +45,7 @@ class AmcrestSensor(Entity): def __init__(self, name, device, sensor_type): """Initialize a sensor for Amcrest camera.""" - self._name = "{} {}".format(name, SENSORS[sensor_type][0]) + self._name = f"{name} {SENSORS[sensor_type][0]}" self._signal_name = name self._api = device.api self._sensor_type = sensor_type @@ -98,15 +98,21 @@ class AmcrestSensor(Entity): elif self._sensor_type == SENSOR_SDCARD: storage = self._api.storage_all try: - self._attrs["Total"] = "{:.2f} {}".format(*storage["total"]) + self._attrs[ + "Total" + ] = f"{storage['total'][0]:.2f} {storage['total'][1]}" except ValueError: - self._attrs["Total"] = "{} {}".format(*storage["total"]) + self._attrs[ + "Total" + ] = f"{storage['total'][0]} {storage['total'][1]}" try: - self._attrs["Used"] = "{:.2f} {}".format(*storage["used"]) + self._attrs[ + "Used" + ] = f"{storage['used'][0]:.2f} {storage['used'][1]}" except ValueError: - self._attrs["Used"] = "{} {}".format(*storage["used"]) + self._attrs["Used"] = f"{storage['used'][0]} {storage['used'][1]}" try: - self._state = "{:.2f}".format(storage["used_percent"]) + self._state = f"{storage['used_percent']:.2f}" except ValueError: self._state = storage["used_percent"] except AmcrestError as error: diff --git a/homeassistant/components/anel_pwrctrl/switch.py b/homeassistant/components/anel_pwrctrl/switch.py index 3c181d7d04b..19a0cc7c6ad 100644 --- a/homeassistant/components/anel_pwrctrl/switch.py +++ b/homeassistant/components/anel_pwrctrl/switch.py @@ -75,9 +75,7 @@ class PwrCtrlSwitch(SwitchDevice): @property def unique_id(self): """Return the unique ID of the device.""" - return "{device}-{switch_idx}".format( - device=self._port.device.host, switch_idx=self._port.get_index() - ) + return f"{self._port.device.host}-{self._port.get_index()}" @property def name(self): diff --git a/homeassistant/components/api/__init__.py b/homeassistant/components/api/__init__.py index b9638d44d2b..e11bc5e61f9 100644 --- a/homeassistant/components/api/__init__.py +++ b/homeassistant/components/api/__init__.py @@ -26,7 +26,6 @@ from homeassistant.const import ( URL_API_EVENTS, URL_API_SERVICES, URL_API_STATES, - URL_API_STATES_ENTITY, URL_API_STREAM, URL_API_TEMPLATE, __version__, @@ -254,7 +253,7 @@ class APIEntityStateView(HomeAssistantView): status_code = HTTP_CREATED if is_new_state else 200 resp = self.json(hass.states.get(entity_id), status_code) - resp.headers.add("Location", URL_API_STATES_ENTITY.format(entity_id)) + resp.headers.add("Location", f"/api/states/{entity_id}") return resp diff --git a/homeassistant/components/apple_tv/__init__.py b/homeassistant/components/apple_tv/__init__.py index e11b246fd5e..52e02cfaf72 100644 --- a/homeassistant/components/apple_tv/__init__.py +++ b/homeassistant/components/apple_tv/__init__.py @@ -88,16 +88,15 @@ def request_configuration(hass, config, atv, credentials): try: await atv.airplay.finish_authentication(pin) hass.components.persistent_notification.async_create( - "Authentication succeeded!

Add the following " - "to credentials: in your apple_tv configuration:

" - "{0}".format(credentials), + f"Authentication succeeded!

" + f"Add the following to credentials: " + f"in your apple_tv configuration:

{credentials}", title=NOTIFICATION_AUTH_TITLE, notification_id=NOTIFICATION_AUTH_ID, ) except DeviceAuthenticationError as ex: hass.components.persistent_notification.async_create( - "Authentication failed! Did you enter correct PIN?

" - "Details: {0}".format(ex), + f"Authentication failed! Did you enter correct PIN?

Details: {ex}", title=NOTIFICATION_AUTH_TITLE, notification_id=NOTIFICATION_AUTH_ID, ) @@ -124,9 +123,7 @@ async def scan_apple_tvs(hass): if login_id is None: login_id = "Home Sharing disabled" devices.append( - "Name: {0}
Host: {1}
Login ID: {2}".format( - atv.name, atv.address, login_id - ) + f"Name: {atv.name}
Host: {atv.address}
Login ID: {login_id}" ) if not devices: diff --git a/homeassistant/components/aprs/device_tracker.py b/homeassistant/components/aprs/device_tracker.py index 6258b470ebb..fb29a0ac8c7 100644 --- a/homeassistant/components/aprs/device_tracker.py +++ b/homeassistant/components/aprs/device_tracker.py @@ -57,7 +57,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( def make_filter(callsigns: list) -> str: """Make a server-side filter from a list of callsigns.""" - return " ".join("b/{0}".format(cs.upper()) for cs in callsigns) + return " ".join(f"b/{sign.upper()}" for sign in callsigns) def gps_accuracy(gps, posambiguity: int) -> int: diff --git a/homeassistant/components/aqualogic/sensor.py b/homeassistant/components/aqualogic/sensor.py index 1cc06fc446f..7fff009baa5 100644 --- a/homeassistant/components/aqualogic/sensor.py +++ b/homeassistant/components/aqualogic/sensor.py @@ -70,7 +70,7 @@ class AquaLogicSensor(Entity): @property def name(self): """Return the name of the sensor.""" - return "AquaLogic {}".format(SENSOR_TYPES[self._type][0]) + return f"AquaLogic {SENSOR_TYPES[self._type][0]}" @property def unit_of_measurement(self): diff --git a/homeassistant/components/aqualogic/switch.py b/homeassistant/components/aqualogic/switch.py index 74f1a9d9f9a..6950929ee80 100644 --- a/homeassistant/components/aqualogic/switch.py +++ b/homeassistant/components/aqualogic/switch.py @@ -70,7 +70,7 @@ class AquaLogicSwitch(SwitchDevice): @property def name(self): """Return the name of the switch.""" - return "AquaLogic {}".format(SWITCH_TYPES[self._type]) + return f"AquaLogic {SWITCH_TYPES[self._type]}" @property def should_poll(self): diff --git a/homeassistant/components/arcam_fmj/__init__.py b/homeassistant/components/arcam_fmj/__init__.py index d818414753f..59bcd08a641 100644 --- a/homeassistant/components/arcam_fmj/__init__.py +++ b/homeassistant/components/arcam_fmj/__init__.py @@ -44,9 +44,9 @@ def _optional_zone(value): def _zone_name_validator(config): for zone, zone_config in config[CONF_ZONE].items(): if CONF_NAME not in zone_config: - zone_config[CONF_NAME] = "{} ({}:{}) - {}".format( - DEFAULT_NAME, config[CONF_HOST], config[CONF_PORT], zone - ) + zone_config[ + CONF_NAME + ] = f"{DEFAULT_NAME} ({config[CONF_HOST]}:{config[CONF_PORT]}) - {zone}" return config diff --git a/homeassistant/components/arest/sensor.py b/homeassistant/components/arest/sensor.py index 2533ce3619e..1bb34a11693 100644 --- a/homeassistant/components/arest/sensor.py +++ b/homeassistant/components/arest/sensor.py @@ -140,7 +140,7 @@ class ArestSensor(Entity): """Initialize the sensor.""" self.arest = arest self._resource = resource - self._name = "{} {}".format(location.title(), name.title()) + self._name = f"{location.title()} {name.title()}" self._variable = variable self._pin = pin self._state = None @@ -204,8 +204,7 @@ class ArestData: try: if str(self._pin[0]) == "A": response = requests.get( - "{}/analog/{}".format(self._resource, self._pin[1:]), - timeout=10, + f"{self._resource,}/analog/{self._pin[1:]}", timeout=10 ) self.data = {"value": response.json()["return_value"]} except TypeError: diff --git a/homeassistant/components/arest/switch.py b/homeassistant/components/arest/switch.py index ccc2c5d8bf5..d3a51391627 100644 --- a/homeassistant/components/arest/switch.py +++ b/homeassistant/components/arest/switch.py @@ -86,7 +86,7 @@ class ArestSwitchBase(SwitchDevice): def __init__(self, resource, location, name): """Initialize the switch.""" self._resource = resource - self._name = "{} {}".format(location.title(), name.title()) + self._name = f"{location.title()} {name.title()}" self._state = None self._available = True diff --git a/homeassistant/components/arlo/__init__.py b/homeassistant/components/arlo/__init__.py index df24bdd1a92..40d75d557bb 100644 --- a/homeassistant/components/arlo/__init__.py +++ b/homeassistant/components/arlo/__init__.py @@ -67,9 +67,7 @@ def setup(hass, config): except (ConnectTimeout, HTTPError) as ex: _LOGGER.error("Unable to connect to Netgear Arlo: %s", str(ex)) hass.components.persistent_notification.create( - "Error: {}
" - "You will need to restart hass after fixing." - "".format(ex), + f"Error: {ex}
You will need to restart hass after fixing.", title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID, ) diff --git a/homeassistant/components/arlo/camera.py b/homeassistant/components/arlo/camera.py index 958c383765a..f52c22fced2 100644 --- a/homeassistant/components/arlo/camera.py +++ b/homeassistant/components/arlo/camera.py @@ -81,8 +81,9 @@ class ArloCam(Camera): video = self._camera.last_video if not video: - error_msg = "Video not found for {0}. Is it older than {1} days?".format( - self.name, self._camera.min_days_vdo_cache + error_msg = ( + f"Video not found for {self.name}. " + f"Is it older than {self._camera.min_days_vdo_cache} days?" ) _LOGGER.error(error_msg) return diff --git a/homeassistant/components/arlo/sensor.py b/homeassistant/components/arlo/sensor.py index aadd5a48d37..959fe9916df 100644 --- a/homeassistant/components/arlo/sensor.py +++ b/homeassistant/components/arlo/sensor.py @@ -57,7 +57,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): if sensor_type in ("temperature", "humidity", "air_quality"): continue - name = "{0} {1}".format(SENSOR_TYPES[sensor_type][0], camera.name) + name = f"{SENSOR_TYPES[sensor_type][0]} {camera.name}" sensors.append(ArloSensor(name, camera, sensor_type)) for base_station in arlo.base_stations: @@ -65,9 +65,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): sensor_type in ("temperature", "humidity", "air_quality") and base_station.model_id == "ABC1000" ): - name = "{0} {1}".format( - SENSOR_TYPES[sensor_type][0], base_station.name - ) + name = f"{SENSOR_TYPES[sensor_type][0]} {base_station.name}" sensors.append(ArloSensor(name, base_station, sensor_type)) add_entities(sensors, True) @@ -83,7 +81,7 @@ class ArloSensor(Entity): self._data = device self._sensor_type = sensor_type self._state = None - self._icon = "mdi:{}".format(SENSOR_TYPES.get(self._sensor_type)[2]) + self._icon = f"mdi:{SENSOR_TYPES.get(self._sensor_type)[2]}" @property def name(self): @@ -141,8 +139,9 @@ class ArloSensor(Entity): video = self._data.last_video self._state = video.created_at_pretty("%m-%d-%Y %H:%M:%S") except (AttributeError, IndexError): - error_msg = "Video not found for {0}. Older than {1} days?".format( - self.name, self._data.min_days_vdo_cache + error_msg = ( + f"Video not found for {self.name}. " + f"Older than {self._data.min_days_vdo_cache} days?" ) _LOGGER.debug(error_msg) self._state = None diff --git a/homeassistant/components/aruba/device_tracker.py b/homeassistant/components/aruba/device_tracker.py index 485c731ff6a..355bcad3aaf 100644 --- a/homeassistant/components/aruba/device_tracker.py +++ b/homeassistant/components/aruba/device_tracker.py @@ -84,8 +84,8 @@ class ArubaDeviceScanner(DeviceScanner): def get_aruba_data(self): """Retrieve data from Aruba Access Point and return parsed result.""" - connect = "ssh {}@{}" - ssh = pexpect.spawn(connect.format(self.username, self.host)) + connect = f"ssh {self.username}@{self.host}" + ssh = pexpect.spawn(connect) query = ssh.expect( [ "password:", diff --git a/homeassistant/components/arwn/sensor.py b/homeassistant/components/arwn/sensor.py index 685e5d90f53..014c46fd73c 100644 --- a/homeassistant/components/arwn/sensor.py +++ b/homeassistant/components/arwn/sensor.py @@ -50,7 +50,7 @@ def discover_sensors(topic, payload): def _slug(name): - return "sensor.arwn_{}".format(slugify(name)) + return f"sensor.arwn_{slugify(name)}" async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): diff --git a/homeassistant/components/asterisk_cdr/mailbox.py b/homeassistant/components/asterisk_cdr/mailbox.py index 0bae6ebf3ad..12587e531d7 100644 --- a/homeassistant/components/asterisk_cdr/mailbox.py +++ b/homeassistant/components/asterisk_cdr/mailbox.py @@ -49,8 +49,10 @@ class AsteriskCDR(Mailbox): "duration": entry["duration"], } sha = hashlib.sha256(str(entry).encode("utf-8")).hexdigest() - msg = "Destination: {}\nApplication: {}\n Context: {}".format( - entry["dest"], entry["application"], entry["context"] + msg = ( + f"Destination: {entry['dest']}\n" + f"Application: {entry['application']}\n " + f"Context: {entry['context']}" ) cdr.append({"info": info, "sha": sha, "text": msg}) self.cdr = cdr diff --git a/homeassistant/components/august/__init__.py b/homeassistant/components/august/__init__.py index 7c7108943fb..f49cae7b107 100644 --- a/homeassistant/components/august/__init__.py +++ b/homeassistant/components/august/__init__.py @@ -102,8 +102,7 @@ def request_configuration(hass, config, api, authenticator, token_refresh_lock): _CONFIGURING[DOMAIN] = configurator.request_config( NOTIFICATION_TITLE, august_configuration_callback, - description="Please check your {} ({}) and enter the verification " - "code below".format(login_method, username), + description=f"Please check your {login_method} ({username}) and enter the verification code below", submit_caption="Verify", fields=[ {"id": "verification_code", "name": "Verification code", "type": "string"} @@ -121,9 +120,7 @@ def setup_august(hass, config, api, authenticator, token_refresh_lock): _LOGGER.error("Unable to connect to August service: %s", str(ex)) hass.components.persistent_notification.create( - "Error: {}
" - "You will need to restart hass after fixing." - "".format(ex), + "Error: {ex}
You will need to restart hass after fixing.", title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID, ) diff --git a/homeassistant/components/august/binary_sensor.py b/homeassistant/components/august/binary_sensor.py index 935642585fd..41bf820319c 100644 --- a/homeassistant/components/august/binary_sensor.py +++ b/homeassistant/components/august/binary_sensor.py @@ -70,14 +70,10 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info= for door in data.locks: if not data.lock_has_doorsense(door.device_id): - _LOGGER.debug( - "Not adding sensor class door for lock %s ", door.device_name, - ) + _LOGGER.debug("Not adding sensor class door for lock %s ", door.device_name) continue - _LOGGER.debug( - "Adding sensor class door for %s", door.device_name, - ) + _LOGGER.debug("Adding sensor class door for %s", door.device_name) devices.append(AugustDoorBinarySensor(data, "door_open", door)) for doorbell in data.doorbells: @@ -121,7 +117,7 @@ class AugustDoorBinarySensor(BinarySensorDevice): @property def name(self): """Return the name of the binary sensor.""" - return "{} Open".format(self._door.device_name) + return f"{self._door.device_name} Open" async def async_update(self): """Get the latest state of the sensor and update activity.""" @@ -175,10 +171,7 @@ class AugustDoorbellBinarySensor(BinarySensorDevice): @property def name(self): """Return the name of the binary sensor.""" - return "{} {}".format( - self._doorbell.device_name, - SENSOR_TYPES_DOORBELL[self._sensor_type][SENSOR_NAME], - ) + return f"{self._doorbell.device_name} {SENSOR_TYPES_DOORBELL[self._sensor_type][SENSOR_NAME]}" async def async_update(self): """Get the latest state of the sensor.""" @@ -194,7 +187,7 @@ class AugustDoorbellBinarySensor(BinarySensorDevice): @property def unique_id(self) -> str: """Get the unique id of the doorbell sensor.""" - return "{:s}_{:s}".format( - self._doorbell.device_id, - SENSOR_TYPES_DOORBELL[self._sensor_type][SENSOR_NAME].lower(), + return ( + f"{self._doorbell.device_id}_" + f"{SENSOR_TYPES_DOORBELL[self._sensor_type][SENSOR_NAME].lower()}" ) diff --git a/homeassistant/components/aurora_abb_powerone/sensor.py b/homeassistant/components/aurora_abb_powerone/sensor.py index a2645e5d7cb..69a513dd8fb 100644 --- a/homeassistant/components/aurora_abb_powerone/sensor.py +++ b/homeassistant/components/aurora_abb_powerone/sensor.py @@ -96,7 +96,6 @@ class AuroraABBSolarPVMonitorSensor(Entity): if "No response after" in str(error): _LOGGER.debug("No response from inverter (could be dark)") else: - # print("Exception!!: {}".format(str(e))) raise error self._state = None finally: diff --git a/homeassistant/components/automatic/device_tracker.py b/homeassistant/components/automatic/device_tracker.py index 3c9e33cdc84..0fc747ffaa9 100644 --- a/homeassistant/components/automatic/device_tracker.py +++ b/homeassistant/components/automatic/device_tracker.py @@ -28,7 +28,6 @@ from homeassistant.helpers.event import async_track_time_interval _LOGGER = logging.getLogger(__name__) ATTR_FUEL_LEVEL = "fuel_level" -AUTOMATIC_CONFIG_FILE = ".automatic/session-{}.json" CONF_CLIENT_ID = "client_id" CONF_CURRENT_LOCATION = "current_location" @@ -95,7 +94,7 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None): request_kwargs={"timeout": DEFAULT_TIMEOUT}, ) - filename = AUTOMATIC_CONFIG_FILE.format(config[CONF_CLIENT_ID]) + filename = f".automatic/session-{config[CONF_CLIENT_ID]}.json" refresh_token = yield from hass.async_add_job( _get_refresh_token_from_file, hass, filename ) diff --git a/homeassistant/components/automation/__init__.py b/homeassistant/components/automation/__init__.py index 1a73de885c0..b1d6c24d303 100644 --- a/homeassistant/components/automation/__init__.py +++ b/homeassistant/components/automation/__init__.py @@ -72,9 +72,7 @@ AutomationActionType = Callable[[HomeAssistant, TemplateVarsType], Awaitable[Non def _platform_validator(config): """Validate it is a valid platform.""" try: - platform = importlib.import_module( - ".{}".format(config[CONF_PLATFORM]), __name__ - ) + platform = importlib.import_module(f".{config[CONF_PLATFORM]}", __name__) except ImportError: raise vol.Invalid("Invalid platform specified") from None @@ -221,7 +219,7 @@ async def async_setup(hass, config): await _async_process_config(hass, conf, component) async_register_admin_service( - hass, DOMAIN, SERVICE_RELOAD, reload_service_handler, schema=vol.Schema({}), + hass, DOMAIN, SERVICE_RELOAD, reload_service_handler, schema=vol.Schema({}) ) return True @@ -456,9 +454,7 @@ class AutomationEntity(ToggleEntity, RestoreEntity): info = {"name": self._name} for conf in self._trigger_config: - platform = importlib.import_module( - ".{}".format(conf[CONF_PLATFORM]), __name__ - ) + platform = importlib.import_module(f".{conf[CONF_PLATFORM]}", __name__) remove = await platform.async_attach_trigger( self.hass, conf, self.async_trigger, info diff --git a/homeassistant/components/automation/config.py b/homeassistant/components/automation/config.py index d11472a2128..d29a561f378 100644 --- a/homeassistant/components/automation/config.py +++ b/homeassistant/components/automation/config.py @@ -26,7 +26,7 @@ async def async_validate_config_item(hass, config, full_config=None): triggers = [] for trigger in config[CONF_TRIGGER]: trigger_platform = importlib.import_module( - "..{}".format(trigger[CONF_PLATFORM]), __name__ + f"..{trigger[CONF_PLATFORM]}", __name__ ) if hasattr(trigger_platform, "async_validate_trigger_config"): trigger = await trigger_platform.async_validate_trigger_config( diff --git a/homeassistant/components/axis/binary_sensor.py b/homeassistant/components/axis/binary_sensor.py index b3593179ffc..d7551abebc1 100644 --- a/homeassistant/components/axis/binary_sensor.py +++ b/homeassistant/components/axis/binary_sensor.py @@ -79,8 +79,8 @@ class AxisBinarySensor(AxisEventBase, BinarySensorDevice): and self.event.id and self.device.api.vapix.ports[self.event.id].name ): - return "{} {}".format( - self.device.name, self.device.api.vapix.ports[self.event.id].name + return ( + f"{self.device.name} {self.device.api.vapix.ports[self.event.id].name}" ) return super().name diff --git a/homeassistant/components/axis/camera.py b/homeassistant/components/axis/camera.py index 51d6b6805cc..3cf84ce2288 100644 --- a/homeassistant/components/axis/camera.py +++ b/homeassistant/components/axis/camera.py @@ -21,10 +21,6 @@ from homeassistant.helpers.dispatcher import async_dispatcher_connect from .axis_base import AxisEntityBase from .const import DOMAIN as AXIS_DOMAIN -AXIS_IMAGE = "http://{}:{}/axis-cgi/jpg/image.cgi" -AXIS_VIDEO = "http://{}:{}/axis-cgi/mjpg/video.cgi" -AXIS_STREAM = "rtsp://{}:{}@{}/axis-media/media.amp?videocodec=h264" - async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Axis camera video stream.""" @@ -36,11 +32,13 @@ async def async_setup_entry(hass, config_entry, async_add_entities): CONF_NAME: config_entry.data[CONF_NAME], CONF_USERNAME: config_entry.data[CONF_USERNAME], CONF_PASSWORD: config_entry.data[CONF_PASSWORD], - CONF_MJPEG_URL: AXIS_VIDEO.format( - config_entry.data[CONF_HOST], config_entry.data[CONF_PORT], + CONF_MJPEG_URL: ( + f"http://{config_entry.data[CONF_HOST]}" + f":{config_entry.data[CONF_PORT]}/axis-cgi/mjpg/video.cgi" ), - CONF_STILL_IMAGE_URL: AXIS_IMAGE.format( - config_entry.data[CONF_HOST], config_entry.data[CONF_PORT], + CONF_STILL_IMAGE_URL: ( + f"http://{config_entry.data[CONF_HOST]}" + f":{config_entry.data[CONF_PORT]}/axis-cgi/jpg/image.cgi" ), CONF_AUTHENTICATION: HTTP_DIGEST_AUTHENTICATION, } @@ -72,17 +70,19 @@ class AxisCamera(AxisEntityBase, MjpegCamera): async def stream_source(self): """Return the stream source.""" - return AXIS_STREAM.format( - self.device.config_entry.data[CONF_USERNAME], - self.device.config_entry.data[CONF_PASSWORD], - self.device.host, + return ( + f"rtsp://{self.device.config_entry.data[CONF_USERNAME]}ยด" + f":{self.device.config_entry.data[CONF_PASSWORD]}" + f"@{self.device.host}/axis-media/media.amp?videocodec=h264" ) def _new_address(self): """Set new device address for video stream.""" port = self.device.config_entry.data[CONF_PORT] - self._mjpeg_url = AXIS_VIDEO.format(self.device.host, port) - self._still_image_url = AXIS_IMAGE.format(self.device.host, port) + self._mjpeg_url = (f"http://{self.device.host}:{port}/axis-cgi/mjpg/video.cgi",) + self._still_image_url = ( + f"http://{self.device.host}:{port}/axis-cgi/jpg/image.cgi" + ) @property def unique_id(self): diff --git a/homeassistant/components/axis/switch.py b/homeassistant/components/axis/switch.py index a83460bc529..ed822543a00 100644 --- a/homeassistant/components/axis/switch.py +++ b/homeassistant/components/axis/switch.py @@ -53,8 +53,8 @@ class AxisSwitch(AxisEventBase, SwitchDevice): def name(self): """Return the name of the event.""" if self.event.id and self.device.api.vapix.ports[self.event.id].name: - return "{} {}".format( - self.device.name, self.device.api.vapix.ports[self.event.id].name + return ( + f"{self.device.name} {self.device.api.vapix.ports[self.event.id].name}" ) return super().name diff --git a/homeassistant/components/azure_event_hub/__init__.py b/homeassistant/components/azure_event_hub/__init__.py index 7e141cd8060..cc59790b646 100644 --- a/homeassistant/components/azure_event_hub/__init__.py +++ b/homeassistant/components/azure_event_hub/__init__.py @@ -47,8 +47,9 @@ async def async_setup(hass: HomeAssistant, yaml_config: Dict[str, Any]): """Activate Azure EH component.""" config = yaml_config[DOMAIN] - event_hub_address = "amqps://{}.servicebus.windows.net/{}".format( - config[CONF_EVENT_HUB_NAMESPACE], config[CONF_EVENT_HUB_INSTANCE_NAME] + event_hub_address = ( + f"amqps://{config[CONF_EVENT_HUB_NAMESPACE]}" + f".servicebus.windows.net/{config[CONF_EVENT_HUB_INSTANCE_NAME]}" ) entities_filter = config[CONF_FILTER] diff --git a/tests/components/adguard/test_config_flow.py b/tests/components/adguard/test_config_flow.py index 903314ab1b7..a0d575deac0 100644 --- a/tests/components/adguard/test_config_flow.py +++ b/tests/components/adguard/test_config_flow.py @@ -40,11 +40,9 @@ async def test_show_authenticate_form(hass): async def test_connection_error(hass, aioclient_mock): """Test we show user form on AdGuard Home connection error.""" aioclient_mock.get( - "{}://{}:{}/control/status".format( - "https" if FIXTURE_USER_INPUT[CONF_SSL] else "http", - FIXTURE_USER_INPUT[CONF_HOST], - FIXTURE_USER_INPUT[CONF_PORT], - ), + f"{'https' if FIXTURE_USER_INPUT[CONF_SSL] else 'http'}" + f"://{FIXTURE_USER_INPUT[CONF_HOST]}" + f":{FIXTURE_USER_INPUT[CONF_PORT]}/control/status", exc=aiohttp.ClientError, ) @@ -60,11 +58,9 @@ async def test_connection_error(hass, aioclient_mock): async def test_full_flow_implementation(hass, aioclient_mock): """Test registering an integration and finishing flow works.""" aioclient_mock.get( - "{}://{}:{}/control/status".format( - "https" if FIXTURE_USER_INPUT[CONF_SSL] else "http", - FIXTURE_USER_INPUT[CONF_HOST], - FIXTURE_USER_INPUT[CONF_PORT], - ), + f"{'https' if FIXTURE_USER_INPUT[CONF_SSL] else 'http'}" + f"://{FIXTURE_USER_INPUT[CONF_HOST]}" + f":{FIXTURE_USER_INPUT[CONF_PORT]}/control/status", json={"version": "v0.99.0"}, headers={"Content-Type": "application/json"}, ) @@ -244,11 +240,9 @@ async def test_hassio_connection_error(hass, aioclient_mock): async def test_outdated_adguard_version(hass, aioclient_mock): """Test we show abort when connecting with unsupported AdGuard version.""" aioclient_mock.get( - "{}://{}:{}/control/status".format( - "https" if FIXTURE_USER_INPUT[CONF_SSL] else "http", - FIXTURE_USER_INPUT[CONF_HOST], - FIXTURE_USER_INPUT[CONF_PORT], - ), + f"{'https' if FIXTURE_USER_INPUT[CONF_SSL] else 'http'}" + f"://{FIXTURE_USER_INPUT[CONF_HOST]}" + f":{FIXTURE_USER_INPUT[CONF_PORT]}/control/status", json={"version": "v0.98.0"}, headers={"Content-Type": "application/json"}, ) diff --git a/tests/components/alarm_control_panel/test_device_trigger.py b/tests/components/alarm_control_panel/test_device_trigger.py index ec14cefc291..9b890aa4d25 100644 --- a/tests/components/alarm_control_panel/test_device_trigger.py +++ b/tests/components/alarm_control_panel/test_device_trigger.py @@ -207,20 +207,18 @@ async def test_if_fires_on_state_change(hass, calls): hass.states.async_set("alarm_control_panel.entity", STATE_ALARM_TRIGGERED) await hass.async_block_till_done() assert len(calls) == 1 - assert calls[0].data[ - "some" - ] == "triggered - device - {} - pending - triggered - None".format( - "alarm_control_panel.entity" + assert ( + calls[0].data["some"] + == "triggered - device - alarm_control_panel.entity - pending - triggered - None" ) # Fake that the entity is disarmed. hass.states.async_set("alarm_control_panel.entity", STATE_ALARM_DISARMED) await hass.async_block_till_done() assert len(calls) == 2 - assert calls[1].data[ - "some" - ] == "disarmed - device - {} - triggered - disarmed - None".format( - "alarm_control_panel.entity" + assert ( + calls[1].data["some"] + == "disarmed - device - alarm_control_panel.entity - triggered - disarmed - None" ) # Fake that the entity is armed home. @@ -228,10 +226,9 @@ async def test_if_fires_on_state_change(hass, calls): hass.states.async_set("alarm_control_panel.entity", STATE_ALARM_ARMED_HOME) await hass.async_block_till_done() assert len(calls) == 3 - assert calls[2].data[ - "some" - ] == "armed_home - device - {} - pending - armed_home - None".format( - "alarm_control_panel.entity" + assert ( + calls[2].data["some"] + == "armed_home - device - alarm_control_panel.entity - pending - armed_home - None" ) # Fake that the entity is armed away. @@ -239,10 +236,9 @@ async def test_if_fires_on_state_change(hass, calls): hass.states.async_set("alarm_control_panel.entity", STATE_ALARM_ARMED_AWAY) await hass.async_block_till_done() assert len(calls) == 4 - assert calls[3].data[ - "some" - ] == "armed_away - device - {} - pending - armed_away - None".format( - "alarm_control_panel.entity" + assert ( + calls[3].data["some"] + == "armed_away - device - alarm_control_panel.entity - pending - armed_away - None" ) # Fake that the entity is armed night. @@ -250,8 +246,7 @@ async def test_if_fires_on_state_change(hass, calls): hass.states.async_set("alarm_control_panel.entity", STATE_ALARM_ARMED_NIGHT) await hass.async_block_till_done() assert len(calls) == 5 - assert calls[4].data[ - "some" - ] == "armed_night - device - {} - pending - armed_night - None".format( - "alarm_control_panel.entity" + assert ( + calls[4].data["some"] + == "armed_night - device - alarm_control_panel.entity - pending - armed_night - None" ) diff --git a/tests/components/alert/test_init.py b/tests/components/alert/test_init.py index 55a3112c32f..d4de97f3b46 100644 --- a/tests/components/alert/test_init.py +++ b/tests/components/alert/test_init.py @@ -60,7 +60,7 @@ TEST_NOACK = [ None, None, ] -ENTITY_ID = alert.ENTITY_ID_FORMAT.format(NAME) +ENTITY_ID = f"{alert.DOMAIN}.{NAME}" def turn_on(hass, entity_id): diff --git a/tests/components/alexa/test_flash_briefings.py b/tests/components/alexa/test_flash_briefings.py index d3fe28d227d..d459ee2cc32 100644 --- a/tests/components/alexa/test_flash_briefings.py +++ b/tests/components/alexa/test_flash_briefings.py @@ -63,7 +63,7 @@ def alexa_client(loop, hass, hass_client): def _flash_briefing_req(client, briefing_id): - return client.get("/api/alexa/flash_briefings/{}".format(briefing_id)) + return client.get(f"/api/alexa/flash_briefings/{briefing_id}") async def test_flash_briefing_invalid_id(alexa_client): diff --git a/tests/components/api/test_init.py b/tests/components/api/test_init.py index 01c8b27bfcc..4417f3d4f91 100644 --- a/tests/components/api/test_init.py +++ b/tests/components/api/test_init.py @@ -36,7 +36,7 @@ async def test_api_list_state_entities(hass, mock_api_client): async def test_api_get_state(hass, mock_api_client): """Test if the debug interface allows us to get a state.""" hass.states.async_set("hello.world", "nice", {"attr": 1}) - resp = await mock_api_client.get(const.URL_API_STATES_ENTITY.format("hello.world")) + resp = await mock_api_client.get("/api/states/hello.world") assert resp.status == 200 json = await resp.json() @@ -51,9 +51,7 @@ async def test_api_get_state(hass, mock_api_client): async def test_api_get_non_existing_state(hass, mock_api_client): """Test if the debug interface allows us to get a state.""" - resp = await mock_api_client.get( - const.URL_API_STATES_ENTITY.format("does_not_exist") - ) + resp = await mock_api_client.get("/api/states/does_not_exist") assert resp.status == 404 @@ -62,8 +60,7 @@ async def test_api_state_change(hass, mock_api_client): hass.states.async_set("test.test", "not_to_be_set") await mock_api_client.post( - const.URL_API_STATES_ENTITY.format("test.test"), - json={"state": "debug_state_change2"}, + "/api/states/test.test", json={"state": "debug_state_change2"} ) assert hass.states.get("test.test").state == "debug_state_change2" @@ -75,8 +72,7 @@ async def test_api_state_change_of_non_existing_entity(hass, mock_api_client): new_state = "debug_state_change" resp = await mock_api_client.post( - const.URL_API_STATES_ENTITY.format("test_entity.that_does_not_exist"), - json={"state": new_state}, + "/api/states/test_entity.that_does_not_exist", json={"state": new_state} ) assert resp.status == 201 @@ -88,7 +84,7 @@ async def test_api_state_change_of_non_existing_entity(hass, mock_api_client): async def test_api_state_change_with_bad_data(hass, mock_api_client): """Test if API sends appropriate error if we omit state.""" resp = await mock_api_client.post( - const.URL_API_STATES_ENTITY.format("test_entity.that_does_not_exist"), json={} + "/api/states/test_entity.that_does_not_exist", json={} ) assert resp.status == 400 @@ -98,15 +94,13 @@ async def test_api_state_change_with_bad_data(hass, mock_api_client): async def test_api_state_change_to_zero_value(hass, mock_api_client): """Test if changing a state to a zero value is possible.""" resp = await mock_api_client.post( - const.URL_API_STATES_ENTITY.format("test_entity.with_zero_state"), - json={"state": 0}, + "/api/states/test_entity.with_zero_state", json={"state": 0} ) assert resp.status == 201 resp = await mock_api_client.post( - const.URL_API_STATES_ENTITY.format("test_entity.with_zero_state"), - json={"state": 0.0}, + "/api/states/test_entity.with_zero_state", json={"state": 0.0} ) assert resp.status == 200 @@ -126,15 +120,12 @@ async def test_api_state_change_push(hass, mock_api_client): hass.bus.async_listen(const.EVENT_STATE_CHANGED, event_listener) - await mock_api_client.post( - const.URL_API_STATES_ENTITY.format("test.test"), json={"state": "not_to_be_set"} - ) + await mock_api_client.post("/api/states/test.test", json={"state": "not_to_be_set"}) await hass.async_block_till_done() assert len(events) == 0 await mock_api_client.post( - const.URL_API_STATES_ENTITY.format("test.test"), - json={"state": "not_to_be_set", "force_update": True}, + "/api/states/test.test", json={"state": "not_to_be_set", "force_update": True} ) await hass.async_block_till_done() assert len(events) == 1 @@ -152,7 +143,7 @@ async def test_api_fire_event_with_no_data(hass, mock_api_client): hass.bus.async_listen_once("test.event_no_data", listener) - await mock_api_client.post(const.URL_API_EVENTS_EVENT.format("test.event_no_data")) + await mock_api_client.post("/api/events/test.event_no_data") await hass.async_block_till_done() assert len(test_value) == 1 @@ -174,9 +165,7 @@ async def test_api_fire_event_with_data(hass, mock_api_client): hass.bus.async_listen_once("test_event_with_data", listener) - await mock_api_client.post( - const.URL_API_EVENTS_EVENT.format("test_event_with_data"), json={"test": 1} - ) + await mock_api_client.post("/api/events/test_event_with_data", json={"test": 1}) await hass.async_block_till_done() @@ -196,8 +185,7 @@ async def test_api_fire_event_with_invalid_json(hass, mock_api_client): hass.bus.async_listen_once("test_event_bad_data", listener) resp = await mock_api_client.post( - const.URL_API_EVENTS_EVENT.format("test_event_bad_data"), - data=json.dumps("not an object"), + "/api/events/test_event_bad_data", data=json.dumps("not an object") ) await hass.async_block_till_done() @@ -207,8 +195,7 @@ async def test_api_fire_event_with_invalid_json(hass, mock_api_client): # Try now with valid but unusable JSON resp = await mock_api_client.post( - const.URL_API_EVENTS_EVENT.format("test_event_bad_data"), - data=json.dumps([1, 2, 3]), + "/api/events/test_event_bad_data", data=json.dumps([1, 2, 3]) ) await hass.async_block_till_done() @@ -272,9 +259,7 @@ async def test_api_call_service_no_data(hass, mock_api_client): hass.services.async_register("test_domain", "test_service", listener) - await mock_api_client.post( - const.URL_API_SERVICES_SERVICE.format("test_domain", "test_service") - ) + await mock_api_client.post("/api/services/test_domain/test_service") await hass.async_block_till_done() assert len(test_value) == 1 @@ -295,8 +280,7 @@ async def test_api_call_service_with_data(hass, mock_api_client): hass.services.async_register("test_domain", "test_service", listener) await mock_api_client.post( - const.URL_API_SERVICES_SERVICE.format("test_domain", "test_service"), - json={"test": 1}, + "/api/services/test_domain/test_service", json={"test": 1} ) await hass.async_block_till_done() @@ -348,7 +332,7 @@ async def test_stream_with_restricted(hass, mock_api_client): listen_count = _listen_count(hass) resp = await mock_api_client.get( - "{}?restrict=test_event1,test_event3".format(const.URL_API_STREAM) + f"{const.URL_API_STREAM}?restrict=test_event1,test_event3" ) assert resp.status == 200 assert listen_count + 1 == _listen_count(hass) @@ -403,7 +387,7 @@ async def test_api_error_log(hass, aiohttp_client, hass_access_token, hass_admin ) as mock_file: resp = await client.get( const.URL_API_ERROR_LOG, - headers={"Authorization": "Bearer {}".format(hass_access_token)}, + headers={"Authorization": f"Bearer {hass_access_token}"}, ) assert len(mock_file.mock_calls) == 1 @@ -415,7 +399,7 @@ async def test_api_error_log(hass, aiohttp_client, hass_access_token, hass_admin hass_admin_user.groups = [] resp = await client.get( const.URL_API_ERROR_LOG, - headers={"Authorization": "Bearer {}".format(hass_access_token)}, + headers={"Authorization": f"Bearer {hass_access_token}"}, ) assert resp.status == 401 @@ -432,8 +416,8 @@ async def test_api_fire_event_context(hass, mock_api_client, hass_access_token): hass.bus.async_listen("test.event", listener) await mock_api_client.post( - const.URL_API_EVENTS_EVENT.format("test.event"), - headers={"authorization": "Bearer {}".format(hass_access_token)}, + "/api/events/test.event", + headers={"authorization": f"Bearer {hass_access_token}"}, ) await hass.async_block_till_done() @@ -449,7 +433,7 @@ async def test_api_call_service_context(hass, mock_api_client, hass_access_token await mock_api_client.post( "/api/services/test_domain/test_service", - headers={"authorization": "Bearer {}".format(hass_access_token)}, + headers={"authorization": f"Bearer {hass_access_token}"}, ) await hass.async_block_till_done() @@ -464,7 +448,7 @@ async def test_api_set_state_context(hass, mock_api_client, hass_access_token): await mock_api_client.post( "/api/states/light.kitchen", json={"state": "on"}, - headers={"authorization": "Bearer {}".format(hass_access_token)}, + headers={"authorization": f"Bearer {hass_access_token}"}, ) refresh_token = await hass.auth.async_validate_access_token(hass_access_token) @@ -542,9 +526,7 @@ async def test_rendering_template_legacy_user( async def test_api_call_service_not_found(hass, mock_api_client): """Test if the API fails 400 if unknown service.""" - resp = await mock_api_client.post( - const.URL_API_SERVICES_SERVICE.format("test_domain", "test_service") - ) + resp = await mock_api_client.post("/api/services/test_domain/test_service") assert resp.status == 400 @@ -562,7 +544,6 @@ async def test_api_call_service_bad_data(hass, mock_api_client): ) resp = await mock_api_client.post( - const.URL_API_SERVICES_SERVICE.format("test_domain", "test_service"), - json={"hello": 5}, + "/api/services/test_domain/test_service", json={"hello": 5} ) assert resp.status == 400 diff --git a/tests/components/auth/test_init.py b/tests/components/auth/test_init.py index 96d497c3dae..2c9a39c6fb6 100644 --- a/tests/components/auth/test_init.py +++ b/tests/components/auth/test_init.py @@ -28,7 +28,7 @@ async def test_login_new_user_and_trying_refresh_token(hass, aiohttp_client): step = await resp.json() resp = await client.post( - "/auth/login_flow/{}".format(step["flow_id"]), + f"/auth/login_flow/{step['flow_id']}", json={"client_id": CLIENT_ID, "username": "test-user", "password": "test-pass"}, ) @@ -71,7 +71,7 @@ async def test_login_new_user_and_trying_refresh_token(hass, aiohttp_client): assert resp.status == 401 resp = await client.get( - "/api/", headers={"authorization": "Bearer {}".format(tokens["access_token"])} + "/api/", headers={"authorization": f"Bearer {tokens['access_token']}"} ) assert resp.status == 200 diff --git a/tests/components/auth/test_init_link_user.py b/tests/components/auth/test_init_link_user.py index 2aa6b0d9f8d..3f0e9bce063 100644 --- a/tests/components/auth/test_init_link_user.py +++ b/tests/components/auth/test_init_link_user.py @@ -42,7 +42,7 @@ async def async_get_code(hass, aiohttp_client): step = await resp.json() resp = await client.post( - "/auth/login_flow/{}".format(step["flow_id"]), + f"/auth/login_flow/{step['flow_id']}", json={"client_id": CLIENT_ID, "username": "2nd-user", "password": "2nd-pass"}, ) @@ -67,7 +67,7 @@ async def test_link_user(hass, aiohttp_client): resp = await client.post( "/auth/link_user", json={"client_id": CLIENT_ID, "code": code}, - headers={"authorization": "Bearer {}".format(info["access_token"])}, + headers={"authorization": f"Bearer {info['access_token']}"}, ) assert resp.status == 200 @@ -84,7 +84,7 @@ async def test_link_user_invalid_client_id(hass, aiohttp_client): resp = await client.post( "/auth/link_user", json={"client_id": "invalid", "code": code}, - headers={"authorization": "Bearer {}".format(info["access_token"])}, + headers={"authorization": f"Bearer {info['access_token']}"}, ) assert resp.status == 400 @@ -100,7 +100,7 @@ async def test_link_user_invalid_code(hass, aiohttp_client): resp = await client.post( "/auth/link_user", json={"client_id": CLIENT_ID, "code": "invalid"}, - headers={"authorization": "Bearer {}".format(info["access_token"])}, + headers={"authorization": f"Bearer {info['access_token']}"}, ) assert resp.status == 400 diff --git a/tests/components/auth/test_login_flow.py b/tests/components/auth/test_login_flow.py index d7bb5448938..e6e5281d601 100644 --- a/tests/components/auth/test_login_flow.py +++ b/tests/components/auth/test_login_flow.py @@ -54,7 +54,7 @@ async def test_invalid_username_password(hass, aiohttp_client): # Incorrect username resp = await client.post( - "/auth/login_flow/{}".format(step["flow_id"]), + f"/auth/login_flow/{step['flow_id']}", json={ "client_id": CLIENT_ID, "username": "wrong-user", @@ -70,7 +70,7 @@ async def test_invalid_username_password(hass, aiohttp_client): # Incorrect password resp = await client.post( - "/auth/login_flow/{}".format(step["flow_id"]), + f"/auth/login_flow/{step['flow_id']}", json={ "client_id": CLIENT_ID, "username": "test-user", @@ -105,7 +105,7 @@ async def test_login_exist_user(hass, aiohttp_client): step = await resp.json() resp = await client.post( - "/auth/login_flow/{}".format(step["flow_id"]), + f"/auth/login_flow/{step['flow_id']}", json={"client_id": CLIENT_ID, "username": "test-user", "password": "test-pass"}, )