mirror of
https://github.com/home-assistant/core.git
synced 2025-07-24 13:47:35 +00:00
Improve string formatting v6 (#33698)
This commit is contained in:
parent
d7e3b0b755
commit
eae21be5b9
@ -86,7 +86,7 @@ SET_ZONE_OVERRIDE_SCHEMA = vol.Schema(
|
|||||||
vol.Coerce(float), vol.Range(min=4.0, max=35.0)
|
vol.Coerce(float), vol.Range(min=4.0, max=35.0)
|
||||||
),
|
),
|
||||||
vol.Optional(ATTR_DURATION_UNTIL): vol.All(
|
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."""
|
"""Convert a string to snake_case."""
|
||||||
string = re.sub(r"[\-\.\s]", "_", str(key))
|
string = re.sub(r"[\-\.\s]", "_", str(key))
|
||||||
return (string[0]).lower() + re.sub(
|
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 {
|
return {
|
||||||
|
@ -321,7 +321,7 @@ class GoogleTravelTimeSensor(Entity):
|
|||||||
def _get_location_from_attributes(entity):
|
def _get_location_from_attributes(entity):
|
||||||
"""Get the lat/long string from an entities attributes."""
|
"""Get the lat/long string from an entities attributes."""
|
||||||
attr = entity.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):
|
def _resolve_zone(self, friendly_name):
|
||||||
entities = self._hass.states.all()
|
entities = self._hass.states.all()
|
||||||
|
@ -100,7 +100,7 @@ class NestFlowHandler(config_entries.ConfigFlow):
|
|||||||
with async_timeout.timeout(10):
|
with async_timeout.timeout(10):
|
||||||
tokens = await flow["convert_code"](user_input["code"])
|
tokens = await flow["convert_code"](user_input["code"])
|
||||||
return self._entry_from_tokens(
|
return self._entry_from_tokens(
|
||||||
"Nest (via {})".format(flow["name"]), flow, tokens
|
f"Nest (via {flow['name']})", flow, tokens
|
||||||
)
|
)
|
||||||
|
|
||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
|
@ -203,6 +203,6 @@ class NestTempSensor(NestSensorDevice):
|
|||||||
|
|
||||||
if isinstance(temp, tuple):
|
if isinstance(temp, tuple):
|
||||||
low, high = temp
|
low, high = temp
|
||||||
self._state = "{}-{}".format(int(low), int(high))
|
self._state = f"{int(low)}-{int(high)}"
|
||||||
else:
|
else:
|
||||||
self._state = round(temp, 1)
|
self._state = round(temp, 1)
|
||||||
|
@ -28,7 +28,7 @@ class LeafPluggedInSensor(LeafEntity, BinarySensorDevice):
|
|||||||
@property
|
@property
|
||||||
def name(self):
|
def name(self):
|
||||||
"""Sensor name."""
|
"""Sensor name."""
|
||||||
return "{} {}".format(self.car.leaf.nickname, "Plug Status")
|
return f"{self.car.leaf.nickname} Plug Status"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def is_on(self):
|
def is_on(self):
|
||||||
@ -49,7 +49,7 @@ class LeafChargingSensor(LeafEntity, BinarySensorDevice):
|
|||||||
@property
|
@property
|
||||||
def name(self):
|
def name(self):
|
||||||
"""Sensor name."""
|
"""Sensor name."""
|
||||||
return "{} {}".format(self.car.leaf.nickname, "Charging Status")
|
return f"{self.car.leaf.nickname} Charging Status"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def is_on(self):
|
def is_on(self):
|
||||||
|
@ -27,7 +27,7 @@ class LeafClimateSwitch(LeafEntity, ToggleEntity):
|
|||||||
@property
|
@property
|
||||||
def name(self):
|
def name(self):
|
||||||
"""Switch name."""
|
"""Switch name."""
|
||||||
return "{} {}".format(self.car.leaf.nickname, "Climate Control")
|
return f"{self.car.leaf.nickname} Climate Control"
|
||||||
|
|
||||||
def log_registration(self):
|
def log_registration(self):
|
||||||
"""Log registration."""
|
"""Log registration."""
|
||||||
|
@ -109,7 +109,7 @@ class NmapDeviceScanner(DeviceScanner):
|
|||||||
last_results = []
|
last_results = []
|
||||||
exclude_hosts = self.exclude
|
exclude_hosts = self.exclude
|
||||||
if exclude_hosts:
|
if exclude_hosts:
|
||||||
options += " --exclude {}".format(",".join(exclude_hosts))
|
options += f" --exclude {','.join(exclude_hosts)}"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
result = scanner.scan(hosts=" ".join(self.hosts), arguments=options)
|
result = scanner.scan(hosts=" ".join(self.hosts), arguments=options)
|
||||||
|
@ -159,8 +159,8 @@ class NMBSLiveBoard(Entity):
|
|||||||
next_departure = liveboard["departures"]["departure"][0]
|
next_departure = liveboard["departures"]["departure"][0]
|
||||||
|
|
||||||
self._attrs = next_departure
|
self._attrs = next_departure
|
||||||
self._state = "Track {} - {}".format(
|
self._state = (
|
||||||
next_departure["platform"], next_departure["station"]
|
f"Track {next_departure['platform']} - {next_departure['station']}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@ -83,7 +83,7 @@ async def _update_no_ip(hass, session, domain, auth_str, timeout):
|
|||||||
params = {"hostname": domain}
|
params = {"hostname": domain}
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
AUTHORIZATION: "Basic {}".format(auth_str.decode("utf-8")),
|
AUTHORIZATION: f"Basic {auth_str.decode('utf-8')}",
|
||||||
USER_AGENT: HA_USER_AGENT,
|
USER_AGENT: HA_USER_AGENT,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -254,9 +254,7 @@ class NotionEntity(Entity):
|
|||||||
@property
|
@property
|
||||||
def name(self):
|
def name(self):
|
||||||
"""Return the name of the sensor."""
|
"""Return the name of the sensor."""
|
||||||
return "{}: {}".format(
|
return f"{self._notion.sensors[self._sensor_id]['name']}: {self._name}"
|
||||||
self._notion.sensors[self._sensor_id]["name"], self._name
|
|
||||||
)
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def should_poll(self):
|
def should_poll(self):
|
||||||
@ -267,7 +265,7 @@ class NotionEntity(Entity):
|
|||||||
def unique_id(self):
|
def unique_id(self):
|
||||||
"""Return a unique, unchanging string that represents this sensor."""
|
"""Return a unique, unchanging string that represents this sensor."""
|
||||||
task = self._notion.tasks[self._task_id]
|
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):
|
async def _update_bridge_id(self):
|
||||||
"""Update the entity's bridge ID if it has changed.
|
"""Update the entity's bridge ID if it has changed.
|
||||||
|
@ -122,7 +122,7 @@ class NUTSensor(Entity):
|
|||||||
self._firmware = firmware
|
self._firmware = firmware
|
||||||
self._model = model
|
self._model = model
|
||||||
self._device_name = name
|
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._unit = SENSOR_TYPES[sensor_type][1]
|
||||||
self._state = None
|
self._state = None
|
||||||
self._unique_id = unique_id
|
self._unique_id = unique_id
|
||||||
|
@ -145,8 +145,9 @@ def setup(hass, config):
|
|||||||
for printer in config[DOMAIN]:
|
for printer in config[DOMAIN]:
|
||||||
name = printer[CONF_NAME]
|
name = printer[CONF_NAME]
|
||||||
ssl = "s" if printer[CONF_SSL] else ""
|
ssl = "s" if printer[CONF_SSL] else ""
|
||||||
base_url = "http{}://{}:{}{}api/".format(
|
base_url = (
|
||||||
ssl, printer[CONF_HOST], printer[CONF_PORT], printer[CONF_PATH]
|
f"http{ssl}://{printer[CONF_HOST]}:{printer[CONF_PORT]}"
|
||||||
|
f"{printer[CONF_PATH]}api/"
|
||||||
)
|
)
|
||||||
api_key = printer[CONF_API_KEY]
|
api_key = printer[CONF_API_KEY]
|
||||||
number_of_tools = printer[CONF_NUMBER_OF_TOOLS]
|
number_of_tools = printer[CONF_NUMBER_OF_TOOLS]
|
||||||
|
@ -91,7 +91,7 @@ class OctoPrintSensor(Entity):
|
|||||||
if tool is None:
|
if tool is None:
|
||||||
self._name = f"{sensor_name} {condition}"
|
self._name = f"{sensor_name} {condition}"
|
||||||
else:
|
else:
|
||||||
self._name = "{} {} {} {}".format(sensor_name, condition, tool, "temp")
|
self._name = f"{sensor_name} {condition} {tool} temp"
|
||||||
self.sensor_type = sensor_type
|
self.sensor_type = sensor_type
|
||||||
self.api = api
|
self.api = api
|
||||||
self._state = None
|
self._state = None
|
||||||
|
@ -183,7 +183,7 @@ class ONVIFHassCamera(Camera):
|
|||||||
self._port,
|
self._port,
|
||||||
self._username,
|
self._username,
|
||||||
self._password,
|
self._password,
|
||||||
"{}/wsdl/".format(os.path.dirname(onvif.__file__)),
|
f"{os.path.dirname(onvif.__file__)}/wsdl/",
|
||||||
transport=transport,
|
transport=transport,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -86,7 +86,7 @@ class OpenAlprCloudEntity(ImageProcessingAlprEntity):
|
|||||||
if name:
|
if name:
|
||||||
self._name = name
|
self._name = name
|
||||||
else:
|
else:
|
||||||
self._name = "OpenAlpr {}".format(split_entity_id(camera_entity)[1])
|
self._name = f"OpenAlpr {split_entity_id(camera_entity)[1]}"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def confidence(self):
|
def confidence(self):
|
||||||
|
@ -161,7 +161,7 @@ class OpenAlprLocalEntity(ImageProcessingAlprEntity):
|
|||||||
if name:
|
if name:
|
||||||
self._name = name
|
self._name = name
|
||||||
else:
|
else:
|
||||||
self._name = "OpenAlpr {}".format(split_entity_id(camera_entity)[1])
|
self._name = f"OpenAlpr {split_entity_id(camera_entity)[1]}"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def confidence(self):
|
def confidence(self):
|
||||||
|
@ -75,9 +75,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
|||||||
def _create_processor_from_config(hass, camera_entity, config):
|
def _create_processor_from_config(hass, camera_entity, config):
|
||||||
"""Create an OpenCV processor from configuration."""
|
"""Create an OpenCV processor from configuration."""
|
||||||
classifier_config = config.get(CONF_CLASSIFIER)
|
classifier_config = config.get(CONF_CLASSIFIER)
|
||||||
name = "{} {}".format(
|
name = f"{config[CONF_NAME]} {split_entity_id(camera_entity)[1].replace('_', ' ')}"
|
||||||
config[CONF_NAME], split_entity_id(camera_entity)[1].replace("_", " ")
|
|
||||||
)
|
|
||||||
|
|
||||||
processor = OpenCVImageProcessor(hass, camera_entity, name, classifier_config)
|
processor = OpenCVImageProcessor(hass, camera_entity, name, classifier_config)
|
||||||
|
|
||||||
@ -132,7 +130,7 @@ class OpenCVImageProcessor(ImageProcessingEntity):
|
|||||||
if name:
|
if name:
|
||||||
self._name = name
|
self._name = name
|
||||||
else:
|
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._classifiers = classifiers
|
||||||
self._matches = {}
|
self._matches = {}
|
||||||
self._total_matches = 0
|
self._total_matches = 0
|
||||||
|
@ -79,8 +79,9 @@ class OpenGarageCover(CoverDevice):
|
|||||||
|
|
||||||
def __init__(self, args):
|
def __init__(self, args):
|
||||||
"""Initialize the cover."""
|
"""Initialize the cover."""
|
||||||
self.opengarage_url = "{}://{}:{}".format(
|
self.opengarage_url = (
|
||||||
"https" if args[CONF_SSL] else "http", args[CONF_HOST], args[CONF_PORT]
|
f"http{'s' if args[CONF_SSL] else ''}://"
|
||||||
|
f"{args[CONF_HOST]}:{args[CONF_PORT]}"
|
||||||
)
|
)
|
||||||
self._name = args[CONF_NAME]
|
self._name = args[CONF_NAME]
|
||||||
self._device_key = args[CONF_DEVICE_KEY]
|
self._device_key = args[CONF_DEVICE_KEY]
|
||||||
|
@ -125,8 +125,9 @@ class OpenHardwareMonitorData:
|
|||||||
|
|
||||||
def refresh(self):
|
def refresh(self):
|
||||||
"""Download and parse JSON from OHM."""
|
"""Download and parse JSON from OHM."""
|
||||||
data_url = "http://{}:{}/data.json".format(
|
data_url = (
|
||||||
self._config.get(CONF_HOST), self._config.get(CONF_PORT)
|
f"http://{self._config.get(CONF_HOST)}:"
|
||||||
|
f"{self._config.get(CONF_PORT)}/data.json"
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
@ -82,9 +82,9 @@ async def async_setup(hass, config):
|
|||||||
|
|
||||||
conf = config[DOMAIN]
|
conf = config[DOMAIN]
|
||||||
|
|
||||||
identifier = "{}, {}".format(
|
identifier = (
|
||||||
conf.get(CONF_LATITUDE, hass.config.latitude),
|
f"{conf.get(CONF_LATITUDE, hass.config.latitude)}, "
|
||||||
conf.get(CONF_LONGITUDE, hass.config.longitude),
|
f"{conf.get(CONF_LONGITUDE, hass.config.longitude)}"
|
||||||
)
|
)
|
||||||
if identifier in configured_instances(hass):
|
if identifier in configured_instances(hass):
|
||||||
return True
|
return True
|
||||||
|
@ -20,10 +20,8 @@ from .const import DOMAIN
|
|||||||
def configured_instances(hass):
|
def configured_instances(hass):
|
||||||
"""Return a set of configured OpenUV instances."""
|
"""Return a set of configured OpenUV instances."""
|
||||||
return {
|
return {
|
||||||
"{}, {}".format(
|
f"{entry.data.get(CONF_LATITUDE, hass.config.latitude)}, "
|
||||||
entry.data.get(CONF_LATITUDE, hass.config.latitude),
|
f"{entry.data.get(CONF_LONGITUDE, hass.config.longitude)}"
|
||||||
entry.data.get(CONF_LONGITUDE, hass.config.longitude),
|
|
||||||
)
|
|
||||||
for entry in hass.config_entries.async_entries(DOMAIN)
|
for entry in hass.config_entries.async_entries(DOMAIN)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -60,9 +58,9 @@ class OpenUvFlowHandler(config_entries.ConfigFlow):
|
|||||||
if not user_input:
|
if not user_input:
|
||||||
return await self._show_form()
|
return await self._show_form()
|
||||||
|
|
||||||
identifier = "{}, {}".format(
|
identifier = (
|
||||||
user_input.get(CONF_LATITUDE, self.hass.config.latitude),
|
f"{user_input.get(CONF_LATITUDE, self.hass.config.latitude)}, "
|
||||||
user_input.get(CONF_LONGITUDE, self.hass.config.longitude),
|
f"{user_input.get(CONF_LONGITUDE, self.hass.config.longitude)}"
|
||||||
)
|
)
|
||||||
if identifier in configured_instances(self.hass):
|
if identifier in configured_instances(self.hass):
|
||||||
return await self._show_form({CONF_LATITUDE: "identifier_exists"})
|
return await self._show_form({CONF_LATITUDE: "identifier_exists"})
|
||||||
|
@ -53,7 +53,7 @@ def repr_helper(inp: Any) -> str:
|
|||||||
"""Help creating a more readable string representation of objects."""
|
"""Help creating a more readable string representation of objects."""
|
||||||
if isinstance(inp, (dict, MappingProxyType)):
|
if isinstance(inp, (dict, MappingProxyType)):
|
||||||
return ", ".join(
|
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):
|
if isinstance(inp, datetime):
|
||||||
return as_local(inp).isoformat()
|
return as_local(inp).isoformat()
|
||||||
|
@ -64,10 +64,7 @@ async def _create_august_with_devices(
|
|||||||
if api_call_side_effects is None:
|
if api_call_side_effects is None:
|
||||||
api_call_side_effects = {}
|
api_call_side_effects = {}
|
||||||
|
|
||||||
device_data = {
|
device_data = {"doorbells": [], "locks": []}
|
||||||
"doorbells": [],
|
|
||||||
"locks": [],
|
|
||||||
}
|
|
||||||
for device in devices:
|
for device in devices:
|
||||||
if isinstance(device, LockDetail):
|
if isinstance(device, LockDetail):
|
||||||
device_data["locks"].append(
|
device_data["locks"].append(
|
||||||
@ -212,7 +209,7 @@ def _mock_august_doorbell_data(deviceid="mockdeviceid1", houseid="mockhouseid1")
|
|||||||
return {
|
return {
|
||||||
"_id": deviceid,
|
"_id": deviceid,
|
||||||
"DeviceID": deviceid,
|
"DeviceID": deviceid,
|
||||||
"name": deviceid + " Name",
|
"name": f"{deviceid} Name",
|
||||||
"HouseID": houseid,
|
"HouseID": houseid,
|
||||||
"UserType": "owner",
|
"UserType": "owner",
|
||||||
"serialNumber": "mockserial",
|
"serialNumber": "mockserial",
|
||||||
@ -232,7 +229,7 @@ def _mock_august_lock_data(lockid="mocklockid1", houseid="mockhouseid1"):
|
|||||||
return {
|
return {
|
||||||
"_id": lockid,
|
"_id": lockid,
|
||||||
"LockID": lockid,
|
"LockID": lockid,
|
||||||
"LockName": lockid + " Name",
|
"LockName": f"{lockid} Name",
|
||||||
"HouseID": houseid,
|
"HouseID": houseid,
|
||||||
"UserType": "owner",
|
"UserType": "owner",
|
||||||
"SerialNumber": "mockserial",
|
"SerialNumber": "mockserial",
|
||||||
|
@ -28,7 +28,7 @@ def calls(hass):
|
|||||||
|
|
||||||
def get_switch_name(number):
|
def get_switch_name(number):
|
||||||
"""Get a mock switch name."""
|
"""Get a mock switch name."""
|
||||||
return "Mock Switch #" + str(number)
|
return f"Mock Switch #{number}"
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
|
@ -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):
|
async def test_discover_full_state(hue_client):
|
||||||
"""Test the discovery of full state."""
|
"""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 result.status == 200
|
||||||
assert "application/json" in result.headers["content-type"]
|
assert "application/json" in result.headers["content-type"]
|
||||||
|
@ -285,7 +285,7 @@ class TestComponentsGroup(unittest.TestCase):
|
|||||||
|
|
||||||
group_conf = OrderedDict()
|
group_conf = OrderedDict()
|
||||||
group_conf["second_group"] = {
|
group_conf["second_group"] = {
|
||||||
"entities": "light.Bowl, " + test_group.entity_id,
|
"entities": f"light.Bowl, {test_group.entity_id}",
|
||||||
"icon": "mdi:work",
|
"icon": "mdi:work",
|
||||||
}
|
}
|
||||||
group_conf["test_group"] = "hello.world,sensor.happy"
|
group_conf["test_group"] = "hello.world,sensor.happy"
|
||||||
|
@ -110,7 +110,7 @@ class TestHDDTempSensor(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
assert (
|
assert (
|
||||||
state.attributes.get("friendly_name")
|
state.attributes.get("friendly_name")
|
||||||
== "HD Temperature " + reference["device"]
|
== f"HD Temperature {reference['device']}"
|
||||||
)
|
)
|
||||||
|
|
||||||
@patch("telnetlib.Telnet", new=TelnetMock)
|
@patch("telnetlib.Telnet", new=TelnetMock)
|
||||||
@ -123,7 +123,7 @@ class TestHDDTempSensor(unittest.TestCase):
|
|||||||
|
|
||||||
reference = self.reference[state.attributes.get("device")]
|
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)
|
@patch("telnetlib.Telnet", new=TelnetMock)
|
||||||
def test_hddtemp_one_disk(self):
|
def test_hddtemp_one_disk(self):
|
||||||
@ -143,7 +143,7 @@ class TestHDDTempSensor(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
assert (
|
assert (
|
||||||
state.attributes.get("friendly_name")
|
state.attributes.get("friendly_name")
|
||||||
== "HD Temperature " + reference["device"]
|
== f"HD Temperature {reference['device']}"
|
||||||
)
|
)
|
||||||
|
|
||||||
@patch("telnetlib.Telnet", new=TelnetMock)
|
@patch("telnetlib.Telnet", new=TelnetMock)
|
||||||
@ -179,7 +179,7 @@ class TestHDDTempSensor(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
assert (
|
assert (
|
||||||
state.attributes.get("friendly_name")
|
state.attributes.get("friendly_name")
|
||||||
== "HD Temperature " + reference["device"]
|
== f"HD Temperature {reference['device']}"
|
||||||
)
|
)
|
||||||
|
|
||||||
@patch("telnetlib.Telnet", new=TelnetMock)
|
@patch("telnetlib.Telnet", new=TelnetMock)
|
||||||
|
@ -666,7 +666,7 @@ class TestInfluxDB(unittest.TestCase):
|
|||||||
state = mock.MagicMock(
|
state = mock.MagicMock(
|
||||||
state=1,
|
state=1,
|
||||||
domain=comp["domain"],
|
domain=comp["domain"],
|
||||||
entity_id=comp["domain"] + "." + comp["id"],
|
entity_id=f"{comp['domain']}.{comp['id']}",
|
||||||
object_id=comp["id"],
|
object_id=comp["id"],
|
||||||
attributes={},
|
attributes={},
|
||||||
)
|
)
|
||||||
|
@ -31,7 +31,7 @@ class TestLiteJetLight(unittest.TestCase):
|
|||||||
self.load_deactivated_callbacks = {}
|
self.load_deactivated_callbacks = {}
|
||||||
|
|
||||||
def get_load_name(number):
|
def get_load_name(number):
|
||||||
return "Mock Load #" + str(number)
|
return f"Mock Load #{number}"
|
||||||
|
|
||||||
def on_load_activated(number, callback):
|
def on_load_activated(number, callback):
|
||||||
self.load_activated_callbacks[number] = callback
|
self.load_activated_callbacks[number] = callback
|
||||||
|
@ -27,7 +27,7 @@ class TestLiteJetScene(unittest.TestCase):
|
|||||||
self.hass.start()
|
self.hass.start()
|
||||||
|
|
||||||
def get_scene_name(number):
|
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 = mock_pylitejet.return_value
|
||||||
self.mock_lj.loads.return_value = range(0)
|
self.mock_lj.loads.return_value = range(0)
|
||||||
|
@ -31,7 +31,7 @@ class TestLiteJetSwitch(unittest.TestCase):
|
|||||||
self.switch_released_callbacks = {}
|
self.switch_released_callbacks = {}
|
||||||
|
|
||||||
def get_switch_name(number):
|
def get_switch_name(number):
|
||||||
return "Mock Switch #" + str(number)
|
return f"Mock Switch #{number}"
|
||||||
|
|
||||||
def on_switch_pressed(number, callback):
|
def on_switch_pressed(number, callback):
|
||||||
self.switch_pressed_callbacks[number] = callback
|
self.switch_pressed_callbacks[number] = callback
|
||||||
|
@ -189,7 +189,7 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase):
|
|||||||
|
|
||||||
assert STATE_ALARM_DISARMED == self.hass.states.get(entity_id).state
|
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()
|
self.hass.block_till_done()
|
||||||
|
|
||||||
assert STATE_ALARM_DISARMED == self.hass.states.get(entity_id).state
|
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
|
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()
|
self.hass.block_till_done()
|
||||||
|
|
||||||
assert STATE_ALARM_DISARMED == self.hass.states.get(entity_id).state
|
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
|
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()
|
self.hass.block_till_done()
|
||||||
|
|
||||||
assert STATE_ALARM_DISARMED == self.hass.states.get(entity_id).state
|
assert STATE_ALARM_DISARMED == self.hass.states.get(entity_id).state
|
||||||
@ -942,7 +942,7 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase):
|
|||||||
"platform": "manual_mqtt",
|
"platform": "manual_mqtt",
|
||||||
"name": "test",
|
"name": "test",
|
||||||
"pending_time": 5,
|
"pending_time": 5,
|
||||||
"code": CODE + "2",
|
"code": f"{CODE}2",
|
||||||
"disarm_after_trigger": False,
|
"disarm_after_trigger": False,
|
||||||
"command_topic": "alarm/command",
|
"command_topic": "alarm/command",
|
||||||
"state_topic": "alarm/state",
|
"state_topic": "alarm/state",
|
||||||
|
@ -99,7 +99,7 @@ class TestPlant(unittest.TestCase):
|
|||||||
self.hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
|
self.hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
|
||||||
)
|
)
|
||||||
self.hass.block_till_done()
|
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]
|
assert 5 == state.attributes[plant.READING_MOISTURE]
|
||||||
|
|
||||||
def test_update_states(self):
|
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.states.set(MOISTURE_ENTITY, 5, {ATTR_UNIT_OF_MEASUREMENT: "us/cm"})
|
||||||
self.hass.block_till_done()
|
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 STATE_PROBLEM == state.state
|
||||||
assert 5 == state.attributes[plant.READING_MOISTURE]
|
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"}
|
MOISTURE_ENTITY, STATE_UNAVAILABLE, {ATTR_UNIT_OF_MEASUREMENT: "us/cm"}
|
||||||
)
|
)
|
||||||
self.hass.block_till_done()
|
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.state == STATE_PROBLEM
|
||||||
assert state.attributes[plant.READING_MOISTURE] == STATE_UNAVAILABLE
|
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.states.set(MOISTURE_ENTITY, 42, {ATTR_UNIT_OF_MEASUREMENT: "us/cm"})
|
||||||
self.hass.block_till_done()
|
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.state == STATE_OK
|
||||||
assert state.attributes[plant.READING_MOISTURE] == 42
|
assert state.attributes[plant.READING_MOISTURE] == 42
|
||||||
self.hass.states.set(
|
self.hass.states.set(
|
||||||
MOISTURE_ENTITY, STATE_UNAVAILABLE, {ATTR_UNIT_OF_MEASUREMENT: "us/cm"}
|
MOISTURE_ENTITY, STATE_UNAVAILABLE, {ATTR_UNIT_OF_MEASUREMENT: "us/cm"}
|
||||||
)
|
)
|
||||||
self.hass.block_till_done()
|
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.state == STATE_PROBLEM
|
||||||
assert state.attributes[plant.READING_MOISTURE] == STATE_UNAVAILABLE
|
assert state.attributes[plant.READING_MOISTURE] == STATE_UNAVAILABLE
|
||||||
|
|
||||||
@ -184,7 +184,7 @@ class TestPlant(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
self.hass.block_till_done()
|
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
|
assert STATE_UNKNOWN == state.state
|
||||||
max_brightness = state.attributes.get(plant.ATTR_MAX_BRIGHTNESS_HISTORY)
|
max_brightness = state.attributes.get(plant.ATTR_MAX_BRIGHTNESS_HISTORY)
|
||||||
assert 30 == max_brightness
|
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.states.set(BRIGHTNESS_ENTITY, 100, {ATTR_UNIT_OF_MEASUREMENT: "lux"})
|
||||||
self.hass.block_till_done()
|
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 STATE_PROBLEM == state.state
|
||||||
|
|
||||||
self.hass.states.set(BRIGHTNESS_ENTITY, 600, {ATTR_UNIT_OF_MEASUREMENT: "lux"})
|
self.hass.states.set(BRIGHTNESS_ENTITY, 600, {ATTR_UNIT_OF_MEASUREMENT: "lux"})
|
||||||
self.hass.block_till_done()
|
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
|
assert STATE_OK == state.state
|
||||||
|
|
||||||
self.hass.states.set(BRIGHTNESS_ENTITY, 100, {ATTR_UNIT_OF_MEASUREMENT: "lux"})
|
self.hass.states.set(BRIGHTNESS_ENTITY, 100, {ATTR_UNIT_OF_MEASUREMENT: "lux"})
|
||||||
self.hass.block_till_done()
|
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
|
assert STATE_OK == state.state
|
||||||
|
|
||||||
|
|
||||||
|
@ -48,14 +48,14 @@ class TestProximity(unittest.TestCase):
|
|||||||
proximities = ["home", "work"]
|
proximities = ["home", "work"]
|
||||||
|
|
||||||
for prox in proximities:
|
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.state == "not set"
|
||||||
assert state.attributes.get("nearest") == "not set"
|
assert state.attributes.get("nearest") == "not set"
|
||||||
assert state.attributes.get("dir_of_travel") == "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()
|
self.hass.block_till_done()
|
||||||
state = self.hass.states.get("proximity." + prox)
|
state = self.hass.states.get(f"proximity.{prox}")
|
||||||
assert state.state == "0"
|
assert state.state == "0"
|
||||||
|
|
||||||
def test_proximities_setup(self):
|
def test_proximities_setup(self):
|
||||||
|
@ -181,7 +181,7 @@ async def test_race_condition(hass, monkeypatch):
|
|||||||
assert updated_sensor
|
assert updated_sensor
|
||||||
|
|
||||||
# test state of new 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
|
||||||
assert new_sensor.state == "ok"
|
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"]
|
assert tmp_entity not in hass.data[DATA_ENTITY_LOOKUP][EVENT_KEY_SENSOR]["test3"]
|
||||||
|
|
||||||
# test state of new 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
|
||||||
assert new_sensor.state == "ko"
|
assert new_sensor.state == "ko"
|
||||||
|
@ -40,7 +40,7 @@ async def test_entity_state(hass, device_factory):
|
|||||||
await setup_platform(hass, BINARY_SENSOR_DOMAIN, devices=[device])
|
await setup_platform(hass, BINARY_SENSOR_DOMAIN, devices=[device])
|
||||||
state = hass.states.get("binary_sensor.motion_sensor_1_motion")
|
state = hass.states.get("binary_sensor.motion_sensor_1_motion")
|
||||||
assert state.state == "off"
|
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):
|
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
|
# Assert
|
||||||
entry = entity_registry.async_get("binary_sensor.motion_sensor_1_motion")
|
entry = entity_registry.async_get("binary_sensor.motion_sensor_1_motion")
|
||||||
assert entry
|
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)}, [])
|
entry = device_registry.async_get_device({(DOMAIN, device.device_id)}, [])
|
||||||
assert entry
|
assert entry
|
||||||
assert entry.name == device.label
|
assert entry.name == device.label
|
||||||
|
@ -84,7 +84,7 @@ async def test_entity_and_device_attributes(hass, device_factory):
|
|||||||
# Assert
|
# Assert
|
||||||
entry = entity_registry.async_get("sensor.sensor_1_battery")
|
entry = entity_registry.async_get("sensor.sensor_1_battery")
|
||||||
assert entry
|
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)}, [])
|
entry = device_registry.async_get_device({(DOMAIN, device.device_id)}, [])
|
||||||
assert entry
|
assert entry
|
||||||
assert entry.name == device.label
|
assert entry.name == device.label
|
||||||
|
@ -15,4 +15,4 @@ def pytest_runtest_makereport(item, call):
|
|||||||
|
|
||||||
# set a report attribute for each phase of a call, which can
|
# set a report attribute for each phase of a call, which can
|
||||||
# be "setup", "call", "teardown"
|
# be "setup", "call", "teardown"
|
||||||
setattr(item, "rep_" + rep.when, rep)
|
setattr(item, f"rep_{rep.when}", rep)
|
||||||
|
@ -138,7 +138,7 @@ async def test_invalid_data(hass, aioclient_mock):
|
|||||||
await async_setup_component(hass, "sensor", {"sensor": VALID_CONFIG})
|
await async_setup_component(hass, "sensor", {"sensor": VALID_CONFIG})
|
||||||
|
|
||||||
for condition in VALID_CONFIG["monitored_conditions"]:
|
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
|
assert state.state == STATE_UNKNOWN
|
||||||
|
|
||||||
|
|
||||||
|
@ -70,7 +70,7 @@ def mocked_requests(*args, **kwargs):
|
|||||||
},
|
},
|
||||||
200,
|
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
|
FIRST_CALL = False
|
||||||
# deliver an error when called with expired token
|
# deliver an error when called with expired token
|
||||||
return MockResponse({"code": "401", "msg": "Invalid token"}, 200)
|
return MockResponse({"code": "401", "msg": "Invalid token"}, 200)
|
||||||
|
@ -245,7 +245,7 @@ class TestNotifyYesssSMS(unittest.TestCase):
|
|||||||
# pylint: disable=protected-access
|
# pylint: disable=protected-access
|
||||||
self.yessssms.yesss._kontomanager,
|
self.yessssms.yesss._kontomanager,
|
||||||
status_code=200,
|
status_code=200,
|
||||||
text="test..." + login + "</a>",
|
text=f"test...{login}</a>",
|
||||||
)
|
)
|
||||||
mock.register_uri(
|
mock.register_uri(
|
||||||
"POST",
|
"POST",
|
||||||
@ -312,7 +312,7 @@ class TestNotifyYesssSMS(unittest.TestCase):
|
|||||||
# pylint: disable=protected-access
|
# pylint: disable=protected-access
|
||||||
self.yessssms.yesss._kontomanager,
|
self.yessssms.yesss._kontomanager,
|
||||||
status_code=200,
|
status_code=200,
|
||||||
text="test..." + login + "</a>",
|
text=f"test...{login}</a>",
|
||||||
)
|
)
|
||||||
mock.register_uri(
|
mock.register_uri(
|
||||||
"POST",
|
"POST",
|
||||||
|
@ -38,7 +38,7 @@ def teardown():
|
|||||||
|
|
||||||
|
|
||||||
def _path_for(leaf_name):
|
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():
|
def test_save_and_load():
|
||||||
|
@ -129,7 +129,7 @@ def teardown():
|
|||||||
|
|
||||||
|
|
||||||
def _path_for(leaf_name):
|
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():
|
def test_save_and_load():
|
||||||
|
Loading…
x
Reference in New Issue
Block a user