From eae21be5b9766fbefbaa0b71a7745e6e4b77e3c5 Mon Sep 17 00:00:00 2001 From: springstan <46536646+springstan@users.noreply.github.com> Date: Tue, 7 Apr 2020 23:14:28 +0200 Subject: [PATCH] Improve string formatting v6 (#33698) --- homeassistant/components/evohome/__init__.py | 4 ++-- .../components/google_travel_time/sensor.py | 2 +- homeassistant/components/nest/config_flow.py | 2 +- homeassistant/components/nest/sensor.py | 2 +- .../components/nissan_leaf/binary_sensor.py | 4 ++-- homeassistant/components/nissan_leaf/switch.py | 2 +- .../components/nmap_tracker/device_tracker.py | 2 +- homeassistant/components/nmbs/sensor.py | 4 ++-- homeassistant/components/no_ip/__init__.py | 2 +- homeassistant/components/notion/__init__.py | 6 ++---- homeassistant/components/nut/sensor.py | 2 +- homeassistant/components/octoprint/__init__.py | 5 +++-- homeassistant/components/octoprint/sensor.py | 2 +- homeassistant/components/onvif/camera.py | 2 +- .../openalpr_cloud/image_processing.py | 2 +- .../openalpr_local/image_processing.py | 2 +- .../components/opencv/image_processing.py | 6 ++---- homeassistant/components/opengarage/cover.py | 5 +++-- .../components/openhardwaremonitor/sensor.py | 5 +++-- homeassistant/components/openuv/__init__.py | 6 +++--- homeassistant/components/openuv/config_flow.py | 12 +++++------- homeassistant/util/__init__.py | 2 +- tests/components/august/mocks.py | 9 +++------ tests/components/automation/test_litejet.py | 2 +- tests/components/emulated_hue/test_hue_api.py | 2 +- tests/components/group/test_init.py | 2 +- tests/components/hddtemp/test_sensor.py | 8 ++++---- tests/components/influxdb/test_init.py | 2 +- tests/components/litejet/test_light.py | 2 +- tests/components/litejet/test_scene.py | 2 +- tests/components/litejet/test_switch.py | 2 +- .../manual_mqtt/test_alarm_control_panel.py | 8 ++++---- tests/components/plant/test_init.py | 18 +++++++++--------- tests/components/proximity/test_init.py | 6 +++--- tests/components/rflink/test_sensor.py | 4 ++-- .../smartthings/test_binary_sensor.py | 4 ++-- tests/components/smartthings/test_sensor.py | 2 +- tests/components/tts/conftest.py | 2 +- tests/components/wunderground/test_sensor.py | 2 +- tests/components/xiaomi/test_device_tracker.py | 2 +- tests/components/yessssms/test_notify.py | 4 ++-- tests/util/test_json.py | 2 +- tests/util/test_ruamel_yaml.py | 2 +- 43 files changed, 81 insertions(+), 87 deletions(-) diff --git a/homeassistant/components/evohome/__init__.py b/homeassistant/components/evohome/__init__.py index f56c92d6572..e4d2cf00e71 100644 --- a/homeassistant/components/evohome/__init__.py +++ b/homeassistant/components/evohome/__init__.py @@ -86,7 +86,7 @@ SET_ZONE_OVERRIDE_SCHEMA = vol.Schema( vol.Coerce(float), vol.Range(min=4.0, max=35.0) ), vol.Optional(ATTR_DURATION_UNTIL): vol.All( - cv.time_period, vol.Range(min=timedelta(days=0), max=timedelta(days=1)), + cv.time_period, vol.Range(min=timedelta(days=0), max=timedelta(days=1)) ), } ) @@ -121,7 +121,7 @@ def convert_dict(dictionary: Dict[str, Any]) -> Dict[str, Any]: """Convert a string to snake_case.""" string = re.sub(r"[\-\.\s]", "_", str(key)) return (string[0]).lower() + re.sub( - r"[A-Z]", lambda matched: "_" + matched.group(0).lower(), string[1:] + r"[A-Z]", lambda matched: f"_{matched.group(0).lower()}", string[1:] ) return { diff --git a/homeassistant/components/google_travel_time/sensor.py b/homeassistant/components/google_travel_time/sensor.py index 5e99b42b115..098c6d2d59c 100644 --- a/homeassistant/components/google_travel_time/sensor.py +++ b/homeassistant/components/google_travel_time/sensor.py @@ -321,7 +321,7 @@ class GoogleTravelTimeSensor(Entity): def _get_location_from_attributes(entity): """Get the lat/long string from an entities attributes.""" attr = entity.attributes - return "{},{}".format(attr.get(ATTR_LATITUDE), attr.get(ATTR_LONGITUDE)) + return f"{attr.get(ATTR_LATITUDE)},{attr.get(ATTR_LONGITUDE)}" def _resolve_zone(self, friendly_name): entities = self._hass.states.all() diff --git a/homeassistant/components/nest/config_flow.py b/homeassistant/components/nest/config_flow.py index b8fa2ad93f5..8f7a0909f33 100644 --- a/homeassistant/components/nest/config_flow.py +++ b/homeassistant/components/nest/config_flow.py @@ -100,7 +100,7 @@ class NestFlowHandler(config_entries.ConfigFlow): with async_timeout.timeout(10): tokens = await flow["convert_code"](user_input["code"]) return self._entry_from_tokens( - "Nest (via {})".format(flow["name"]), flow, tokens + f"Nest (via {flow['name']})", flow, tokens ) except asyncio.TimeoutError: diff --git a/homeassistant/components/nest/sensor.py b/homeassistant/components/nest/sensor.py index 082b5b19b5f..f7e727e0e2d 100644 --- a/homeassistant/components/nest/sensor.py +++ b/homeassistant/components/nest/sensor.py @@ -203,6 +203,6 @@ class NestTempSensor(NestSensorDevice): if isinstance(temp, tuple): low, high = temp - self._state = "{}-{}".format(int(low), int(high)) + self._state = f"{int(low)}-{int(high)}" else: self._state = round(temp, 1) diff --git a/homeassistant/components/nissan_leaf/binary_sensor.py b/homeassistant/components/nissan_leaf/binary_sensor.py index 1ee450df87d..786d495cc9b 100644 --- a/homeassistant/components/nissan_leaf/binary_sensor.py +++ b/homeassistant/components/nissan_leaf/binary_sensor.py @@ -28,7 +28,7 @@ class LeafPluggedInSensor(LeafEntity, BinarySensorDevice): @property def name(self): """Sensor name.""" - return "{} {}".format(self.car.leaf.nickname, "Plug Status") + return f"{self.car.leaf.nickname} Plug Status" @property def is_on(self): @@ -49,7 +49,7 @@ class LeafChargingSensor(LeafEntity, BinarySensorDevice): @property def name(self): """Sensor name.""" - return "{} {}".format(self.car.leaf.nickname, "Charging Status") + return f"{self.car.leaf.nickname} Charging Status" @property def is_on(self): diff --git a/homeassistant/components/nissan_leaf/switch.py b/homeassistant/components/nissan_leaf/switch.py index e15d595d65b..d95d3e4ed39 100644 --- a/homeassistant/components/nissan_leaf/switch.py +++ b/homeassistant/components/nissan_leaf/switch.py @@ -27,7 +27,7 @@ class LeafClimateSwitch(LeafEntity, ToggleEntity): @property def name(self): """Switch name.""" - return "{} {}".format(self.car.leaf.nickname, "Climate Control") + return f"{self.car.leaf.nickname} Climate Control" def log_registration(self): """Log registration.""" diff --git a/homeassistant/components/nmap_tracker/device_tracker.py b/homeassistant/components/nmap_tracker/device_tracker.py index d41e80f17a2..0a8c177b08c 100644 --- a/homeassistant/components/nmap_tracker/device_tracker.py +++ b/homeassistant/components/nmap_tracker/device_tracker.py @@ -109,7 +109,7 @@ class NmapDeviceScanner(DeviceScanner): last_results = [] exclude_hosts = self.exclude if exclude_hosts: - options += " --exclude {}".format(",".join(exclude_hosts)) + options += f" --exclude {','.join(exclude_hosts)}" try: result = scanner.scan(hosts=" ".join(self.hosts), arguments=options) diff --git a/homeassistant/components/nmbs/sensor.py b/homeassistant/components/nmbs/sensor.py index 23b8bbea46b..bdf4658434c 100644 --- a/homeassistant/components/nmbs/sensor.py +++ b/homeassistant/components/nmbs/sensor.py @@ -159,8 +159,8 @@ class NMBSLiveBoard(Entity): next_departure = liveboard["departures"]["departure"][0] self._attrs = next_departure - self._state = "Track {} - {}".format( - next_departure["platform"], next_departure["station"] + self._state = ( + f"Track {next_departure['platform']} - {next_departure['station']}" ) diff --git a/homeassistant/components/no_ip/__init__.py b/homeassistant/components/no_ip/__init__.py index 12d0fb08ad3..9efaac79562 100644 --- a/homeassistant/components/no_ip/__init__.py +++ b/homeassistant/components/no_ip/__init__.py @@ -83,7 +83,7 @@ async def _update_no_ip(hass, session, domain, auth_str, timeout): params = {"hostname": domain} headers = { - AUTHORIZATION: "Basic {}".format(auth_str.decode("utf-8")), + AUTHORIZATION: f"Basic {auth_str.decode('utf-8')}", USER_AGENT: HA_USER_AGENT, } diff --git a/homeassistant/components/notion/__init__.py b/homeassistant/components/notion/__init__.py index b06ba768765..a1c54d96299 100644 --- a/homeassistant/components/notion/__init__.py +++ b/homeassistant/components/notion/__init__.py @@ -254,9 +254,7 @@ class NotionEntity(Entity): @property def name(self): """Return the name of the sensor.""" - return "{}: {}".format( - self._notion.sensors[self._sensor_id]["name"], self._name - ) + return f"{self._notion.sensors[self._sensor_id]['name']}: {self._name}" @property def should_poll(self): @@ -267,7 +265,7 @@ class NotionEntity(Entity): def unique_id(self): """Return a unique, unchanging string that represents this sensor.""" task = self._notion.tasks[self._task_id] - return "{}_{}".format(self._sensor_id, task["task_type"]) + return f"{self._sensor_id}_{task['task_type']}" async def _update_bridge_id(self): """Update the entity's bridge ID if it has changed. diff --git a/homeassistant/components/nut/sensor.py b/homeassistant/components/nut/sensor.py index a611c8d4268..f6e809d5280 100644 --- a/homeassistant/components/nut/sensor.py +++ b/homeassistant/components/nut/sensor.py @@ -122,7 +122,7 @@ class NUTSensor(Entity): self._firmware = firmware self._model = model self._device_name = name - self._name = "{} {}".format(name, SENSOR_TYPES[sensor_type][0]) + self._name = f"{name} {SENSOR_TYPES[sensor_type][0]}" self._unit = SENSOR_TYPES[sensor_type][1] self._state = None self._unique_id = unique_id diff --git a/homeassistant/components/octoprint/__init__.py b/homeassistant/components/octoprint/__init__.py index dba7e656aff..9e8f1dff6c6 100644 --- a/homeassistant/components/octoprint/__init__.py +++ b/homeassistant/components/octoprint/__init__.py @@ -145,8 +145,9 @@ def setup(hass, config): for printer in config[DOMAIN]: name = printer[CONF_NAME] ssl = "s" if printer[CONF_SSL] else "" - base_url = "http{}://{}:{}{}api/".format( - ssl, printer[CONF_HOST], printer[CONF_PORT], printer[CONF_PATH] + base_url = ( + f"http{ssl}://{printer[CONF_HOST]}:{printer[CONF_PORT]}" + f"{printer[CONF_PATH]}api/" ) api_key = printer[CONF_API_KEY] number_of_tools = printer[CONF_NUMBER_OF_TOOLS] diff --git a/homeassistant/components/octoprint/sensor.py b/homeassistant/components/octoprint/sensor.py index 83b247c39cb..9c488564ea9 100644 --- a/homeassistant/components/octoprint/sensor.py +++ b/homeassistant/components/octoprint/sensor.py @@ -91,7 +91,7 @@ class OctoPrintSensor(Entity): if tool is None: self._name = f"{sensor_name} {condition}" else: - self._name = "{} {} {} {}".format(sensor_name, condition, tool, "temp") + self._name = f"{sensor_name} {condition} {tool} temp" self.sensor_type = sensor_type self.api = api self._state = None diff --git a/homeassistant/components/onvif/camera.py b/homeassistant/components/onvif/camera.py index 0c6a3bffa1b..d623f1d879b 100644 --- a/homeassistant/components/onvif/camera.py +++ b/homeassistant/components/onvif/camera.py @@ -183,7 +183,7 @@ class ONVIFHassCamera(Camera): self._port, self._username, self._password, - "{}/wsdl/".format(os.path.dirname(onvif.__file__)), + f"{os.path.dirname(onvif.__file__)}/wsdl/", transport=transport, ) diff --git a/homeassistant/components/openalpr_cloud/image_processing.py b/homeassistant/components/openalpr_cloud/image_processing.py index 13d8cf75e7c..41a631937d7 100644 --- a/homeassistant/components/openalpr_cloud/image_processing.py +++ b/homeassistant/components/openalpr_cloud/image_processing.py @@ -86,7 +86,7 @@ class OpenAlprCloudEntity(ImageProcessingAlprEntity): if name: self._name = name else: - self._name = "OpenAlpr {}".format(split_entity_id(camera_entity)[1]) + self._name = f"OpenAlpr {split_entity_id(camera_entity)[1]}" @property def confidence(self): diff --git a/homeassistant/components/openalpr_local/image_processing.py b/homeassistant/components/openalpr_local/image_processing.py index b2e90ad5597..c7c96b05872 100644 --- a/homeassistant/components/openalpr_local/image_processing.py +++ b/homeassistant/components/openalpr_local/image_processing.py @@ -161,7 +161,7 @@ class OpenAlprLocalEntity(ImageProcessingAlprEntity): if name: self._name = name else: - self._name = "OpenAlpr {}".format(split_entity_id(camera_entity)[1]) + self._name = f"OpenAlpr {split_entity_id(camera_entity)[1]}" @property def confidence(self): diff --git a/homeassistant/components/opencv/image_processing.py b/homeassistant/components/opencv/image_processing.py index c2cd62237d7..f35d063de50 100644 --- a/homeassistant/components/opencv/image_processing.py +++ b/homeassistant/components/opencv/image_processing.py @@ -75,9 +75,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( def _create_processor_from_config(hass, camera_entity, config): """Create an OpenCV processor from configuration.""" classifier_config = config.get(CONF_CLASSIFIER) - name = "{} {}".format( - config[CONF_NAME], split_entity_id(camera_entity)[1].replace("_", " ") - ) + name = f"{config[CONF_NAME]} {split_entity_id(camera_entity)[1].replace('_', ' ')}" processor = OpenCVImageProcessor(hass, camera_entity, name, classifier_config) @@ -132,7 +130,7 @@ class OpenCVImageProcessor(ImageProcessingEntity): if name: self._name = name else: - self._name = "OpenCV {}".format(split_entity_id(camera_entity)[1]) + self._name = f"OpenCV {split_entity_id(camera_entity)[1]}" self._classifiers = classifiers self._matches = {} self._total_matches = 0 diff --git a/homeassistant/components/opengarage/cover.py b/homeassistant/components/opengarage/cover.py index 26a69fa11af..0bb9d7a7c5b 100644 --- a/homeassistant/components/opengarage/cover.py +++ b/homeassistant/components/opengarage/cover.py @@ -79,8 +79,9 @@ class OpenGarageCover(CoverDevice): def __init__(self, args): """Initialize the cover.""" - self.opengarage_url = "{}://{}:{}".format( - "https" if args[CONF_SSL] else "http", args[CONF_HOST], args[CONF_PORT] + self.opengarage_url = ( + f"http{'s' if args[CONF_SSL] else ''}://" + f"{args[CONF_HOST]}:{args[CONF_PORT]}" ) self._name = args[CONF_NAME] self._device_key = args[CONF_DEVICE_KEY] diff --git a/homeassistant/components/openhardwaremonitor/sensor.py b/homeassistant/components/openhardwaremonitor/sensor.py index 0729943a770..c0c71405ab3 100644 --- a/homeassistant/components/openhardwaremonitor/sensor.py +++ b/homeassistant/components/openhardwaremonitor/sensor.py @@ -125,8 +125,9 @@ class OpenHardwareMonitorData: def refresh(self): """Download and parse JSON from OHM.""" - data_url = "http://{}:{}/data.json".format( - self._config.get(CONF_HOST), self._config.get(CONF_PORT) + data_url = ( + f"http://{self._config.get(CONF_HOST)}:" + f"{self._config.get(CONF_PORT)}/data.json" ) try: diff --git a/homeassistant/components/openuv/__init__.py b/homeassistant/components/openuv/__init__.py index ee8e5f0b8ee..e6a302975a5 100644 --- a/homeassistant/components/openuv/__init__.py +++ b/homeassistant/components/openuv/__init__.py @@ -82,9 +82,9 @@ async def async_setup(hass, config): conf = config[DOMAIN] - identifier = "{}, {}".format( - conf.get(CONF_LATITUDE, hass.config.latitude), - conf.get(CONF_LONGITUDE, hass.config.longitude), + identifier = ( + f"{conf.get(CONF_LATITUDE, hass.config.latitude)}, " + f"{conf.get(CONF_LONGITUDE, hass.config.longitude)}" ) if identifier in configured_instances(hass): return True diff --git a/homeassistant/components/openuv/config_flow.py b/homeassistant/components/openuv/config_flow.py index aa6e58d6036..821c9624c58 100644 --- a/homeassistant/components/openuv/config_flow.py +++ b/homeassistant/components/openuv/config_flow.py @@ -20,10 +20,8 @@ from .const import DOMAIN def configured_instances(hass): """Return a set of configured OpenUV instances.""" return { - "{}, {}".format( - entry.data.get(CONF_LATITUDE, hass.config.latitude), - entry.data.get(CONF_LONGITUDE, hass.config.longitude), - ) + f"{entry.data.get(CONF_LATITUDE, hass.config.latitude)}, " + f"{entry.data.get(CONF_LONGITUDE, hass.config.longitude)}" for entry in hass.config_entries.async_entries(DOMAIN) } @@ -60,9 +58,9 @@ class OpenUvFlowHandler(config_entries.ConfigFlow): if not user_input: return await self._show_form() - identifier = "{}, {}".format( - user_input.get(CONF_LATITUDE, self.hass.config.latitude), - user_input.get(CONF_LONGITUDE, self.hass.config.longitude), + identifier = ( + f"{user_input.get(CONF_LATITUDE, self.hass.config.latitude)}, " + f"{user_input.get(CONF_LONGITUDE, self.hass.config.longitude)}" ) if identifier in configured_instances(self.hass): return await self._show_form({CONF_LATITUDE: "identifier_exists"}) diff --git a/homeassistant/util/__init__.py b/homeassistant/util/__init__.py index d80f9775449..ee423a33b52 100644 --- a/homeassistant/util/__init__.py +++ b/homeassistant/util/__init__.py @@ -53,7 +53,7 @@ def repr_helper(inp: Any) -> str: """Help creating a more readable string representation of objects.""" if isinstance(inp, (dict, MappingProxyType)): return ", ".join( - repr_helper(key) + "=" + repr_helper(item) for key, item in inp.items() + f"{repr_helper(key)}={repr_helper(item)}" for key, item in inp.items() ) if isinstance(inp, datetime): return as_local(inp).isoformat() diff --git a/tests/components/august/mocks.py b/tests/components/august/mocks.py index 651a17ac80f..62249e0fb1e 100644 --- a/tests/components/august/mocks.py +++ b/tests/components/august/mocks.py @@ -64,10 +64,7 @@ async def _create_august_with_devices( if api_call_side_effects is None: api_call_side_effects = {} - device_data = { - "doorbells": [], - "locks": [], - } + device_data = {"doorbells": [], "locks": []} for device in devices: if isinstance(device, LockDetail): device_data["locks"].append( @@ -212,7 +209,7 @@ def _mock_august_doorbell_data(deviceid="mockdeviceid1", houseid="mockhouseid1") return { "_id": deviceid, "DeviceID": deviceid, - "name": deviceid + " Name", + "name": f"{deviceid} Name", "HouseID": houseid, "UserType": "owner", "serialNumber": "mockserial", @@ -232,7 +229,7 @@ def _mock_august_lock_data(lockid="mocklockid1", houseid="mockhouseid1"): return { "_id": lockid, "LockID": lockid, - "LockName": lockid + " Name", + "LockName": f"{lockid} Name", "HouseID": houseid, "UserType": "owner", "SerialNumber": "mockserial", diff --git a/tests/components/automation/test_litejet.py b/tests/components/automation/test_litejet.py index 710b16d1b48..c001f417982 100644 --- a/tests/components/automation/test_litejet.py +++ b/tests/components/automation/test_litejet.py @@ -28,7 +28,7 @@ def calls(hass): def get_switch_name(number): """Get a mock switch name.""" - return "Mock Switch #" + str(number) + return f"Mock Switch #{number}" @pytest.fixture diff --git a/tests/components/emulated_hue/test_hue_api.py b/tests/components/emulated_hue/test_hue_api.py index c47940e98cd..e9925132b00 100644 --- a/tests/components/emulated_hue/test_hue_api.py +++ b/tests/components/emulated_hue/test_hue_api.py @@ -289,7 +289,7 @@ async def test_reachable_for_state(hass_hue, hue_client, state, is_reachable): async def test_discover_full_state(hue_client): """Test the discovery of full state.""" - result = await hue_client.get("/api/" + HUE_API_USERNAME) + result = await hue_client.get(f"/api/{HUE_API_USERNAME}") assert result.status == 200 assert "application/json" in result.headers["content-type"] diff --git a/tests/components/group/test_init.py b/tests/components/group/test_init.py index 9cc75ff39aa..467bd1ede95 100644 --- a/tests/components/group/test_init.py +++ b/tests/components/group/test_init.py @@ -285,7 +285,7 @@ class TestComponentsGroup(unittest.TestCase): group_conf = OrderedDict() group_conf["second_group"] = { - "entities": "light.Bowl, " + test_group.entity_id, + "entities": f"light.Bowl, {test_group.entity_id}", "icon": "mdi:work", } group_conf["test_group"] = "hello.world,sensor.happy" diff --git a/tests/components/hddtemp/test_sensor.py b/tests/components/hddtemp/test_sensor.py index c5b0c2bb562..1b6150fbc3f 100644 --- a/tests/components/hddtemp/test_sensor.py +++ b/tests/components/hddtemp/test_sensor.py @@ -110,7 +110,7 @@ class TestHDDTempSensor(unittest.TestCase): ) assert ( state.attributes.get("friendly_name") - == "HD Temperature " + reference["device"] + == f"HD Temperature {reference['device']}" ) @patch("telnetlib.Telnet", new=TelnetMock) @@ -123,7 +123,7 @@ class TestHDDTempSensor(unittest.TestCase): reference = self.reference[state.attributes.get("device")] - assert state.attributes.get("friendly_name") == "FooBar " + reference["device"] + assert state.attributes.get("friendly_name") == f"FooBar {reference['device']}" @patch("telnetlib.Telnet", new=TelnetMock) def test_hddtemp_one_disk(self): @@ -143,7 +143,7 @@ class TestHDDTempSensor(unittest.TestCase): ) assert ( state.attributes.get("friendly_name") - == "HD Temperature " + reference["device"] + == f"HD Temperature {reference['device']}" ) @patch("telnetlib.Telnet", new=TelnetMock) @@ -179,7 +179,7 @@ class TestHDDTempSensor(unittest.TestCase): ) assert ( state.attributes.get("friendly_name") - == "HD Temperature " + reference["device"] + == f"HD Temperature {reference['device']}" ) @patch("telnetlib.Telnet", new=TelnetMock) diff --git a/tests/components/influxdb/test_init.py b/tests/components/influxdb/test_init.py index 958bcc9d975..bdfd41eae83 100644 --- a/tests/components/influxdb/test_init.py +++ b/tests/components/influxdb/test_init.py @@ -666,7 +666,7 @@ class TestInfluxDB(unittest.TestCase): state = mock.MagicMock( state=1, domain=comp["domain"], - entity_id=comp["domain"] + "." + comp["id"], + entity_id=f"{comp['domain']}.{comp['id']}", object_id=comp["id"], attributes={}, ) diff --git a/tests/components/litejet/test_light.py b/tests/components/litejet/test_light.py index 304487ca502..e08bd5c27ac 100644 --- a/tests/components/litejet/test_light.py +++ b/tests/components/litejet/test_light.py @@ -31,7 +31,7 @@ class TestLiteJetLight(unittest.TestCase): self.load_deactivated_callbacks = {} def get_load_name(number): - return "Mock Load #" + str(number) + return f"Mock Load #{number}" def on_load_activated(number, callback): self.load_activated_callbacks[number] = callback diff --git a/tests/components/litejet/test_scene.py b/tests/components/litejet/test_scene.py index 48f5559799e..c2297af6d3f 100644 --- a/tests/components/litejet/test_scene.py +++ b/tests/components/litejet/test_scene.py @@ -27,7 +27,7 @@ class TestLiteJetScene(unittest.TestCase): self.hass.start() def get_scene_name(number): - return "Mock Scene #" + str(number) + return f"Mock Scene #{number}" self.mock_lj = mock_pylitejet.return_value self.mock_lj.loads.return_value = range(0) diff --git a/tests/components/litejet/test_switch.py b/tests/components/litejet/test_switch.py index 1244d8d9a25..2f897045c92 100644 --- a/tests/components/litejet/test_switch.py +++ b/tests/components/litejet/test_switch.py @@ -31,7 +31,7 @@ class TestLiteJetSwitch(unittest.TestCase): self.switch_released_callbacks = {} def get_switch_name(number): - return "Mock Switch #" + str(number) + return f"Mock Switch #{number}" def on_switch_pressed(number, callback): self.switch_pressed_callbacks[number] = callback diff --git a/tests/components/manual_mqtt/test_alarm_control_panel.py b/tests/components/manual_mqtt/test_alarm_control_panel.py index 9567391e273..1ac6bca91c4 100644 --- a/tests/components/manual_mqtt/test_alarm_control_panel.py +++ b/tests/components/manual_mqtt/test_alarm_control_panel.py @@ -189,7 +189,7 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): assert STATE_ALARM_DISARMED == self.hass.states.get(entity_id).state - common.alarm_arm_home(self.hass, CODE + "2") + common.alarm_arm_home(self.hass, f"{CODE}2") self.hass.block_till_done() assert STATE_ALARM_DISARMED == self.hass.states.get(entity_id).state @@ -342,7 +342,7 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): assert STATE_ALARM_DISARMED == self.hass.states.get(entity_id).state - common.alarm_arm_away(self.hass, CODE + "2") + common.alarm_arm_away(self.hass, f"{CODE}2") self.hass.block_till_done() assert STATE_ALARM_DISARMED == self.hass.states.get(entity_id).state @@ -473,7 +473,7 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): assert STATE_ALARM_DISARMED == self.hass.states.get(entity_id).state - common.alarm_arm_night(self.hass, CODE + "2") + common.alarm_arm_night(self.hass, f"{CODE}2") self.hass.block_till_done() assert STATE_ALARM_DISARMED == self.hass.states.get(entity_id).state @@ -942,7 +942,7 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): "platform": "manual_mqtt", "name": "test", "pending_time": 5, - "code": CODE + "2", + "code": f"{CODE}2", "disarm_after_trigger": False, "command_topic": "alarm/command", "state_topic": "alarm/state", diff --git a/tests/components/plant/test_init.py b/tests/components/plant/test_init.py index 280ad9a0efe..5250fb0fa70 100644 --- a/tests/components/plant/test_init.py +++ b/tests/components/plant/test_init.py @@ -99,7 +99,7 @@ class TestPlant(unittest.TestCase): self.hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}} ) self.hass.block_till_done() - state = self.hass.states.get("plant." + plant_name) + state = self.hass.states.get(f"plant.{plant_name}") assert 5 == state.attributes[plant.READING_MOISTURE] def test_update_states(self): @@ -113,7 +113,7 @@ class TestPlant(unittest.TestCase): ) self.hass.states.set(MOISTURE_ENTITY, 5, {ATTR_UNIT_OF_MEASUREMENT: "us/cm"}) self.hass.block_till_done() - state = self.hass.states.get("plant." + plant_name) + state = self.hass.states.get(f"plant.{plant_name}") assert STATE_PROBLEM == state.state assert 5 == state.attributes[plant.READING_MOISTURE] @@ -130,7 +130,7 @@ class TestPlant(unittest.TestCase): MOISTURE_ENTITY, STATE_UNAVAILABLE, {ATTR_UNIT_OF_MEASUREMENT: "us/cm"} ) self.hass.block_till_done() - state = self.hass.states.get("plant." + plant_name) + state = self.hass.states.get(f"plant.{plant_name}") assert state.state == STATE_PROBLEM assert state.attributes[plant.READING_MOISTURE] == STATE_UNAVAILABLE @@ -145,14 +145,14 @@ class TestPlant(unittest.TestCase): ) self.hass.states.set(MOISTURE_ENTITY, 42, {ATTR_UNIT_OF_MEASUREMENT: "us/cm"}) self.hass.block_till_done() - state = self.hass.states.get("plant." + plant_name) + state = self.hass.states.get(f"plant.{plant_name}") assert state.state == STATE_OK assert state.attributes[plant.READING_MOISTURE] == 42 self.hass.states.set( MOISTURE_ENTITY, STATE_UNAVAILABLE, {ATTR_UNIT_OF_MEASUREMENT: "us/cm"} ) self.hass.block_till_done() - state = self.hass.states.get("plant." + plant_name) + state = self.hass.states.get(f"plant.{plant_name}") assert state.state == STATE_PROBLEM assert state.attributes[plant.READING_MOISTURE] == STATE_UNAVAILABLE @@ -184,7 +184,7 @@ class TestPlant(unittest.TestCase): ) self.hass.block_till_done() - state = self.hass.states.get("plant." + plant_name) + state = self.hass.states.get(f"plant.{plant_name}") assert STATE_UNKNOWN == state.state max_brightness = state.attributes.get(plant.ATTR_MAX_BRIGHTNESS_HISTORY) assert 30 == max_brightness @@ -197,17 +197,17 @@ class TestPlant(unittest.TestCase): ) self.hass.states.set(BRIGHTNESS_ENTITY, 100, {ATTR_UNIT_OF_MEASUREMENT: "lux"}) self.hass.block_till_done() - state = self.hass.states.get("plant." + plant_name) + state = self.hass.states.get(f"plant.{plant_name}") assert STATE_PROBLEM == state.state self.hass.states.set(BRIGHTNESS_ENTITY, 600, {ATTR_UNIT_OF_MEASUREMENT: "lux"}) self.hass.block_till_done() - state = self.hass.states.get("plant." + plant_name) + state = self.hass.states.get(f"plant.{plant_name}") assert STATE_OK == state.state self.hass.states.set(BRIGHTNESS_ENTITY, 100, {ATTR_UNIT_OF_MEASUREMENT: "lux"}) self.hass.block_till_done() - state = self.hass.states.get("plant." + plant_name) + state = self.hass.states.get(f"plant.{plant_name}") assert STATE_OK == state.state diff --git a/tests/components/proximity/test_init.py b/tests/components/proximity/test_init.py index 826a73bece2..d3b6f9274e5 100644 --- a/tests/components/proximity/test_init.py +++ b/tests/components/proximity/test_init.py @@ -48,14 +48,14 @@ class TestProximity(unittest.TestCase): proximities = ["home", "work"] for prox in proximities: - state = self.hass.states.get("proximity." + prox) + state = self.hass.states.get(f"proximity.{prox}") assert state.state == "not set" assert state.attributes.get("nearest") == "not set" assert state.attributes.get("dir_of_travel") == "not set" - self.hass.states.set("proximity." + prox, "0") + self.hass.states.set(f"proximity.{prox}", "0") self.hass.block_till_done() - state = self.hass.states.get("proximity." + prox) + state = self.hass.states.get(f"proximity.{prox}") assert state.state == "0" def test_proximities_setup(self): diff --git a/tests/components/rflink/test_sensor.py b/tests/components/rflink/test_sensor.py index a4904f5bc9b..f60b1c3584c 100644 --- a/tests/components/rflink/test_sensor.py +++ b/tests/components/rflink/test_sensor.py @@ -181,7 +181,7 @@ async def test_race_condition(hass, monkeypatch): assert updated_sensor # test state of new sensor - new_sensor = hass.states.get(DOMAIN + ".test3") + new_sensor = hass.states.get(f"{DOMAIN}.test3") assert new_sensor assert new_sensor.state == "ok" @@ -191,6 +191,6 @@ async def test_race_condition(hass, monkeypatch): assert tmp_entity not in hass.data[DATA_ENTITY_LOOKUP][EVENT_KEY_SENSOR]["test3"] # test state of new sensor - new_sensor = hass.states.get(DOMAIN + ".test3") + new_sensor = hass.states.get(f"{DOMAIN}.test3") assert new_sensor assert new_sensor.state == "ko" diff --git a/tests/components/smartthings/test_binary_sensor.py b/tests/components/smartthings/test_binary_sensor.py index 300e2ac4b46..b007fff7caf 100644 --- a/tests/components/smartthings/test_binary_sensor.py +++ b/tests/components/smartthings/test_binary_sensor.py @@ -40,7 +40,7 @@ async def test_entity_state(hass, device_factory): await setup_platform(hass, BINARY_SENSOR_DOMAIN, devices=[device]) state = hass.states.get("binary_sensor.motion_sensor_1_motion") assert state.state == "off" - assert state.attributes[ATTR_FRIENDLY_NAME] == device.label + " " + Attribute.motion + assert state.attributes[ATTR_FRIENDLY_NAME] == f"{device.label} {Attribute.motion}" async def test_entity_and_device_attributes(hass, device_factory): @@ -56,7 +56,7 @@ async def test_entity_and_device_attributes(hass, device_factory): # Assert entry = entity_registry.async_get("binary_sensor.motion_sensor_1_motion") assert entry - assert entry.unique_id == device.device_id + "." + Attribute.motion + assert entry.unique_id == f"{device.device_id}.{Attribute.motion}" entry = device_registry.async_get_device({(DOMAIN, device.device_id)}, []) assert entry assert entry.name == device.label diff --git a/tests/components/smartthings/test_sensor.py b/tests/components/smartthings/test_sensor.py index f61172c3b97..6d2b73d787d 100644 --- a/tests/components/smartthings/test_sensor.py +++ b/tests/components/smartthings/test_sensor.py @@ -84,7 +84,7 @@ async def test_entity_and_device_attributes(hass, device_factory): # Assert entry = entity_registry.async_get("sensor.sensor_1_battery") assert entry - assert entry.unique_id == f"{device.device_id}." + Attribute.battery + assert entry.unique_id == f"{device.device_id}.{Attribute.battery}" entry = device_registry.async_get_device({(DOMAIN, device.device_id)}, []) assert entry assert entry.name == device.label diff --git a/tests/components/tts/conftest.py b/tests/components/tts/conftest.py index 7f5b06b71ee..3580880fedb 100644 --- a/tests/components/tts/conftest.py +++ b/tests/components/tts/conftest.py @@ -15,4 +15,4 @@ def pytest_runtest_makereport(item, call): # set a report attribute for each phase of a call, which can # be "setup", "call", "teardown" - setattr(item, "rep_" + rep.when, rep) + setattr(item, f"rep_{rep.when}", rep) diff --git a/tests/components/wunderground/test_sensor.py b/tests/components/wunderground/test_sensor.py index 5f74a837cf3..a2f681f8e97 100644 --- a/tests/components/wunderground/test_sensor.py +++ b/tests/components/wunderground/test_sensor.py @@ -138,7 +138,7 @@ async def test_invalid_data(hass, aioclient_mock): await async_setup_component(hass, "sensor", {"sensor": VALID_CONFIG}) for condition in VALID_CONFIG["monitored_conditions"]: - state = hass.states.get("sensor.pws_" + condition) + state = hass.states.get(f"sensor.pws_{condition}") assert state.state == STATE_UNKNOWN diff --git a/tests/components/xiaomi/test_device_tracker.py b/tests/components/xiaomi/test_device_tracker.py index 76788d0c3e8..5d65aee7616 100644 --- a/tests/components/xiaomi/test_device_tracker.py +++ b/tests/components/xiaomi/test_device_tracker.py @@ -70,7 +70,7 @@ def mocked_requests(*args, **kwargs): }, 200, ) - if str(args[0]).endswith("timedOut/" + URL_LIST_END) and FIRST_CALL is True: + if str(args[0]).endswith(f"timedOut/{URL_LIST_END}") and FIRST_CALL is True: FIRST_CALL = False # deliver an error when called with expired token return MockResponse({"code": "401", "msg": "Invalid token"}, 200) diff --git a/tests/components/yessssms/test_notify.py b/tests/components/yessssms/test_notify.py index f1eec4da942..94f9c846d64 100644 --- a/tests/components/yessssms/test_notify.py +++ b/tests/components/yessssms/test_notify.py @@ -245,7 +245,7 @@ class TestNotifyYesssSMS(unittest.TestCase): # pylint: disable=protected-access self.yessssms.yesss._kontomanager, status_code=200, - text="test..." + login + "", + text=f"test...{login}", ) mock.register_uri( "POST", @@ -312,7 +312,7 @@ class TestNotifyYesssSMS(unittest.TestCase): # pylint: disable=protected-access self.yessssms.yesss._kontomanager, status_code=200, - text="test..." + login + "", + text=f"test...{login}", ) mock.register_uri( "POST", diff --git a/tests/util/test_json.py b/tests/util/test_json.py index bc93ef54a4b..ed699c8eded 100644 --- a/tests/util/test_json.py +++ b/tests/util/test_json.py @@ -38,7 +38,7 @@ def teardown(): def _path_for(leaf_name): - return os.path.join(TMP_DIR, leaf_name + ".json") + return os.path.join(TMP_DIR, f"{leaf_name}.json") def test_save_and_load(): diff --git a/tests/util/test_ruamel_yaml.py b/tests/util/test_ruamel_yaml.py index 79ed4a4f4d1..b4e78a883af 100644 --- a/tests/util/test_ruamel_yaml.py +++ b/tests/util/test_ruamel_yaml.py @@ -129,7 +129,7 @@ def teardown(): def _path_for(leaf_name): - return os.path.join(TMP_DIR, leaf_name + ".yaml") + return os.path.join(TMP_DIR, f"{leaf_name}.yaml") def test_save_and_load():