String formatting improvements for tests (#33663)

This commit is contained in:
Franck Nijhof 2020-04-05 00:26:08 +02:00 committed by GitHub
parent 1c25468b21
commit 906385172a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
33 changed files with 129 additions and 155 deletions

View file

@ -205,4 +205,4 @@ class ReportedProperties:
assert prop["value"] == value assert prop["value"] == value
return prop return prop
assert False, "property %s:%s not in %r" % (namespace, name, self.properties) assert False, f"property {namespace}:{name} not in {self.properties!r}"

View file

@ -50,7 +50,7 @@ def mocked_requests(*args, **kwargs):
if re.match(r"^/fwo/[\w]+/[\w.]+\.json", url.path): if re.match(r"^/fwo/[\w]+/[\w.]+\.json", url.path):
return MockResponse(json.loads(load_fixture("bom_weather.json")), 200) return MockResponse(json.loads(load_fixture("bom_weather.json")), 200)
raise NotImplementedError("Unknown route {}".format(url.path)) raise NotImplementedError(f"Unknown route {url.path}")
class TestBOMWeatherSensor(unittest.TestCase): class TestBOMWeatherSensor(unittest.TestCase):
@ -78,7 +78,7 @@ class TestBOMWeatherSensor(unittest.TestCase):
] ]
for entity_id in fake_entities: for entity_id in fake_entities:
state = self.hass.states.get("sensor.{}".format(entity_id)) state = self.hass.states.get(f"sensor.{entity_id}")
assert state is not None assert state is not None
@patch("requests.get", side_effect=mocked_requests) @patch("requests.get", side_effect=mocked_requests)

View file

@ -69,7 +69,7 @@ async def test_learn(hass):
assert mock_create.call_count == 1 assert mock_create.call_count == 1
assert mock_create.call_args == call( assert mock_create.call_args == call(
"Received packet is: {}".format(DUMMY_IR_PACKET), title="Broadlink switch" f"Received packet is: {DUMMY_IR_PACKET}", title="Broadlink switch"
) )

View file

@ -54,10 +54,10 @@ async def test_state_value(hass):
with tempfile.TemporaryDirectory() as tempdirname: with tempfile.TemporaryDirectory() as tempdirname:
path = os.path.join(tempdirname, "cover_status") path = os.path.join(tempdirname, "cover_status")
test_cover = { test_cover = {
"command_state": "cat {}".format(path), "command_state": f"cat {path}",
"command_open": "echo 1 > {}".format(path), "command_open": f"echo 1 > {path}",
"command_close": "echo 1 > {}".format(path), "command_close": f"echo 1 > {path}",
"command_stop": "echo 0 > {}".format(path), "command_stop": f"echo 0 > {path}",
"value_template": "{{ value }}", "value_template": "{{ value }}",
} }
assert ( assert (

View file

@ -57,7 +57,7 @@ class TestCommandLine(unittest.TestCase):
"notify": { "notify": {
"name": "test", "name": "test",
"platform": "command_line", "platform": "command_line",
"command": "echo $(cat) > {}".format(filename), "command": f"echo $(cat) > {filename}",
} }
}, },
) )
@ -69,7 +69,7 @@ class TestCommandLine(unittest.TestCase):
with open(filename) as fil: with open(filename) as fil:
# the echo command adds a line break # the echo command adds a line break
assert fil.read() == "{}\n".format(message) assert fil.read() == f"{message}\n"
@patch("homeassistant.components.command_line.notify._LOGGER.error") @patch("homeassistant.components.command_line.notify._LOGGER.error")
def test_error_for_none_zero_exit_code(self, mock_error): def test_error_for_none_zero_exit_code(self, mock_error):

View file

@ -30,8 +30,8 @@ class TestCommandSwitch(unittest.TestCase):
with tempfile.TemporaryDirectory() as tempdirname: with tempfile.TemporaryDirectory() as tempdirname:
path = os.path.join(tempdirname, "switch_status") path = os.path.join(tempdirname, "switch_status")
test_switch = { test_switch = {
"command_on": "echo 1 > {}".format(path), "command_on": f"echo 1 > {path}",
"command_off": "echo 0 > {}".format(path), "command_off": f"echo 0 > {path}",
} }
assert setup_component( assert setup_component(
self.hass, self.hass,
@ -64,9 +64,9 @@ class TestCommandSwitch(unittest.TestCase):
with tempfile.TemporaryDirectory() as tempdirname: with tempfile.TemporaryDirectory() as tempdirname:
path = os.path.join(tempdirname, "switch_status") path = os.path.join(tempdirname, "switch_status")
test_switch = { test_switch = {
"command_state": "cat {}".format(path), "command_state": f"cat {path}",
"command_on": "echo 1 > {}".format(path), "command_on": f"echo 1 > {path}",
"command_off": "echo 0 > {}".format(path), "command_off": f"echo 0 > {path}",
"value_template": '{{ value=="1" }}', "value_template": '{{ value=="1" }}',
} }
assert setup_component( assert setup_component(
@ -102,9 +102,9 @@ class TestCommandSwitch(unittest.TestCase):
oncmd = json.dumps({"status": "ok"}) oncmd = json.dumps({"status": "ok"})
offcmd = json.dumps({"status": "nope"}) offcmd = json.dumps({"status": "nope"})
test_switch = { test_switch = {
"command_state": "cat {}".format(path), "command_state": f"cat {path}",
"command_on": "echo '{}' > {}".format(oncmd, path), "command_on": f"echo '{oncmd}' > {path}",
"command_off": "echo '{}' > {}".format(offcmd, path), "command_off": f"echo '{offcmd}' > {path}",
"value_template": '{{ value_json.status=="ok" }}', "value_template": '{{ value_json.status=="ok" }}',
} }
assert setup_component( assert setup_component(
@ -138,9 +138,9 @@ class TestCommandSwitch(unittest.TestCase):
with tempfile.TemporaryDirectory() as tempdirname: with tempfile.TemporaryDirectory() as tempdirname:
path = os.path.join(tempdirname, "switch_status") path = os.path.join(tempdirname, "switch_status")
test_switch = { test_switch = {
"command_state": "cat {}".format(path), "command_state": f"cat {path}",
"command_on": "echo 1 > {}".format(path), "command_on": f"echo 1 > {path}",
"command_off": "echo 0 > {}".format(path), "command_off": f"echo 0 > {path}",
} }
assert setup_component( assert setup_component(
self.hass, self.hass,

View file

@ -97,9 +97,7 @@ async def test_remove_entry(hass, client):
"""Test removing an entry via the API.""" """Test removing an entry via the API."""
entry = MockConfigEntry(domain="demo", state=core_ce.ENTRY_STATE_LOADED) entry = MockConfigEntry(domain="demo", state=core_ce.ENTRY_STATE_LOADED)
entry.add_to_hass(hass) entry.add_to_hass(hass)
resp = await client.delete( resp = await client.delete(f"/api/config/config_entries/entry/{entry.entry_id}")
"/api/config/config_entries/entry/{}".format(entry.entry_id)
)
assert resp.status == 200 assert resp.status == 200
data = await resp.json() data = await resp.json()
assert data == {"require_restart": True} assert data == {"require_restart": True}
@ -111,9 +109,7 @@ async def test_remove_entry_unauth(hass, client, hass_admin_user):
hass_admin_user.groups = [] hass_admin_user.groups = []
entry = MockConfigEntry(domain="demo", state=core_ce.ENTRY_STATE_LOADED) entry = MockConfigEntry(domain="demo", state=core_ce.ENTRY_STATE_LOADED)
entry.add_to_hass(hass) entry.add_to_hass(hass)
resp = await client.delete( resp = await client.delete(f"/api/config/config_entries/entry/{entry.entry_id}")
"/api/config/config_entries/entry/{}".format(entry.entry_id)
)
assert resp.status == 401 assert resp.status == 401
assert len(hass.config_entries.async_entries()) == 1 assert len(hass.config_entries.async_entries()) == 1
@ -124,7 +120,7 @@ async def test_available_flows(hass, client):
resp = await client.get("/api/config/config_entries/flow_handlers") resp = await client.get("/api/config/config_entries/flow_handlers")
assert resp.status == 200 assert resp.status == 200
data = await resp.json() data = await resp.json()
assert set(data) == set(["hello", "world"]) assert set(data) == {"hello", "world"}
############################ ############################
@ -294,7 +290,7 @@ async def test_two_step_flow(hass, client):
with patch.dict(HANDLERS, {"test": TestFlow}): with patch.dict(HANDLERS, {"test": TestFlow}):
resp = await client.post( resp = await client.post(
"/api/config/config_entries/flow/{}".format(flow_id), f"/api/config/config_entries/flow/{flow_id}",
json={"user_title": "user-title"}, json={"user_title": "user-title"},
) )
assert resp.status == 200 assert resp.status == 200
@ -352,8 +348,7 @@ async def test_continue_flow_unauth(hass, client, hass_admin_user):
hass_admin_user.groups = [] hass_admin_user.groups = []
resp = await client.post( resp = await client.post(
"/api/config/config_entries/flow/{}".format(flow_id), f"/api/config/config_entries/flow/{flow_id}", json={"user_title": "user-title"},
json={"user_title": "user-title"},
) )
assert resp.status == 401 assert resp.status == 401
@ -559,7 +554,7 @@ async def test_two_step_options_flow(hass, client):
with patch.dict(HANDLERS, {"test": TestFlow}): with patch.dict(HANDLERS, {"test": TestFlow}):
resp = await client.post( resp = await client.post(
"/api/config/config_entries/options/flow/{}".format(flow_id), f"/api/config/config_entries/options/flow/{flow_id}",
json={"enabled": True}, json={"enabled": True},
) )
assert resp.status == 200 assert resp.status == 200

View file

@ -156,7 +156,7 @@ class TestDarkSkySetup(unittest.TestCase):
url = "https://api.darksky.net/forecast/{}/{},{}?units=auto".format( url = "https://api.darksky.net/forecast/{}/{},{}?units=auto".format(
self.key, str(self.lat), str(self.lon) self.key, str(self.lat), str(self.lon)
) )
msg = "400 Client Error: Bad Request for url: {}".format(url) msg = f"400 Client Error: Bad Request for url: {url}"
mock_get_forecast.side_effect = HTTPError(msg) mock_get_forecast.side_effect = HTTPError(msg)
response = darksky.setup_platform( response = darksky.setup_platform(

View file

@ -150,19 +150,16 @@ class TestDatadog(unittest.TestCase):
mock_client.gauge.assert_has_calls( mock_client.gauge.assert_has_calls(
[ [
mock.call( mock.call(
"ha.sensor.{}".format(attribute), f"ha.sensor.{attribute}",
value, value,
sample_rate=1, sample_rate=1,
tags=["entity:{}".format(state.entity_id)], tags=[f"entity:{state.entity_id}"],
) )
] ]
) )
assert mock_client.gauge.call_args == mock.call( assert mock_client.gauge.call_args == mock.call(
"ha.sensor", "ha.sensor", out, sample_rate=1, tags=[f"entity:{state.entity_id}"],
out,
sample_rate=1,
tags=["entity:{}".format(state.entity_id)],
) )
mock_client.gauge.reset_mock() mock_client.gauge.reset_mock()

View file

@ -39,12 +39,12 @@ from homeassistant.setup import setup_component
from tests.common import get_test_home_assistant, mock_service from tests.common import get_test_home_assistant, mock_service
from tests.components.vacuum import common from tests.components.vacuum import common
ENTITY_VACUUM_BASIC = "{}.{}".format(DOMAIN, DEMO_VACUUM_BASIC).lower() ENTITY_VACUUM_BASIC = f"{DOMAIN}.{DEMO_VACUUM_BASIC}".lower()
ENTITY_VACUUM_COMPLETE = "{}.{}".format(DOMAIN, DEMO_VACUUM_COMPLETE).lower() ENTITY_VACUUM_COMPLETE = f"{DOMAIN}.{DEMO_VACUUM_COMPLETE}".lower()
ENTITY_VACUUM_MINIMAL = "{}.{}".format(DOMAIN, DEMO_VACUUM_MINIMAL).lower() ENTITY_VACUUM_MINIMAL = f"{DOMAIN}.{DEMO_VACUUM_MINIMAL}".lower()
ENTITY_VACUUM_MOST = "{}.{}".format(DOMAIN, DEMO_VACUUM_MOST).lower() ENTITY_VACUUM_MOST = f"{DOMAIN}.{DEMO_VACUUM_MOST}".lower()
ENTITY_VACUUM_NONE = "{}.{}".format(DOMAIN, DEMO_VACUUM_NONE).lower() ENTITY_VACUUM_NONE = f"{DOMAIN}.{DEMO_VACUUM_NONE}".lower()
ENTITY_VACUUM_STATE = "{}.{}".format(DOMAIN, DEMO_VACUUM_STATE).lower() ENTITY_VACUUM_STATE = f"{DOMAIN}.{DEMO_VACUUM_STATE}".lower()
class TestVacuumDemo(unittest.TestCase): class TestVacuumDemo(unittest.TestCase):

View file

@ -548,7 +548,7 @@ async def test_async_added_to_hass(hass):
for key, val in attr.items(): for key, val in attr.items():
atr = state.attributes.get(key) atr = state.attributes.get(key)
assert atr == val, "{}={} expected: {}".format(key, atr, val) assert atr == val, f"{key}={atr} expected: {val}"
async def test_bad_platform(hass): async def test_bad_platform(hass):

View file

@ -165,7 +165,7 @@ async def test_intent_action_incomplete_v1(fixture):
data["result"]["actionIncomplete"] = True data["result"]["actionIncomplete"] = True
response = await mock_client.post( response = await mock_client.post(
"/api/webhook/{}".format(webhook_id), data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert 200 == response.status assert 200 == response.status
assert "" == await response.text() assert "" == await response.text()
@ -178,7 +178,7 @@ async def test_intent_action_incomplete_v2(fixture):
data["queryResult"]["allRequiredParamsPresent"] = False data["queryResult"]["allRequiredParamsPresent"] = False
response = await mock_client.post( response = await mock_client.post(
"/api/webhook/{}".format(webhook_id), data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert 200 == response.status assert 200 == response.status
assert "" == await response.text() assert "" == await response.text()
@ -220,7 +220,7 @@ async def test_intent_slot_filling_v1(fixture):
data["result"]["metadata"].update(webhookForSlotFillingUsed="true") data["result"]["metadata"].update(webhookForSlotFillingUsed="true")
response = await mock_client.post( response = await mock_client.post(
"/api/webhook/{}".format(webhook_id), data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert 200 == response.status assert 200 == response.status
assert "" == await response.text() assert "" == await response.text()
@ -231,7 +231,7 @@ async def test_intent_request_with_parameters_v1(fixture):
mock_client, webhook_id = fixture mock_client, webhook_id = fixture
data = Data.v1 data = Data.v1
response = await mock_client.post( response = await mock_client.post(
"/api/webhook/{}".format(webhook_id), data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert 200 == response.status assert 200 == response.status
text = (await response.json()).get("speech") text = (await response.json()).get("speech")
@ -243,7 +243,7 @@ async def test_intent_request_with_parameters_v2(fixture):
mock_client, webhook_id = fixture mock_client, webhook_id = fixture
data = Data.v2 data = Data.v2
response = await mock_client.post( response = await mock_client.post(
"/api/webhook/{}".format(webhook_id), data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert 200 == response.status assert 200 == response.status
text = (await response.json()).get("fulfillmentText") text = (await response.json()).get("fulfillmentText")
@ -256,7 +256,7 @@ async def test_intent_request_with_parameters_but_empty_v1(fixture):
data = Data.v1 data = Data.v1
data["result"].update(parameters={"ZodiacSign": ""}) data["result"].update(parameters={"ZodiacSign": ""})
response = await mock_client.post( response = await mock_client.post(
"/api/webhook/{}".format(webhook_id), data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert 200 == response.status assert 200 == response.status
text = (await response.json()).get("speech") text = (await response.json()).get("speech")
@ -269,7 +269,7 @@ async def test_intent_request_with_parameters_but_empty_v2(fixture):
data = Data.v2 data = Data.v2
data["queryResult"].update(parameters={"ZodiacSign": ""}) data["queryResult"].update(parameters={"ZodiacSign": ""})
response = await mock_client.post( response = await mock_client.post(
"/api/webhook/{}".format(webhook_id), data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert 200 == response.status assert 200 == response.status
text = (await response.json()).get("fulfillmentText") text = (await response.json()).get("fulfillmentText")
@ -288,7 +288,7 @@ async def test_intent_request_without_slots_v1(hass, fixture):
) )
response = await mock_client.post( response = await mock_client.post(
"/api/webhook/{}".format(webhook_id), data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert 200 == response.status assert 200 == response.status
text = (await response.json()).get("speech") text = (await response.json()).get("speech")
@ -299,7 +299,7 @@ async def test_intent_request_without_slots_v1(hass, fixture):
hass.states.async_set("device_tracker.anne_therese", "home") hass.states.async_set("device_tracker.anne_therese", "home")
response = await mock_client.post( response = await mock_client.post(
"/api/webhook/{}".format(webhook_id), data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert 200 == response.status assert 200 == response.status
text = (await response.json()).get("speech") text = (await response.json()).get("speech")
@ -318,7 +318,7 @@ async def test_intent_request_without_slots_v2(hass, fixture):
) )
response = await mock_client.post( response = await mock_client.post(
"/api/webhook/{}".format(webhook_id), data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert 200 == response.status assert 200 == response.status
text = (await response.json()).get("fulfillmentText") text = (await response.json()).get("fulfillmentText")
@ -329,7 +329,7 @@ async def test_intent_request_without_slots_v2(hass, fixture):
hass.states.async_set("device_tracker.anne_therese", "home") hass.states.async_set("device_tracker.anne_therese", "home")
response = await mock_client.post( response = await mock_client.post(
"/api/webhook/{}".format(webhook_id), data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert 200 == response.status assert 200 == response.status
text = (await response.json()).get("fulfillmentText") text = (await response.json()).get("fulfillmentText")
@ -347,7 +347,7 @@ async def test_intent_request_calling_service_v1(fixture, calls):
data["result"]["action"] = "CallServiceIntent" data["result"]["action"] = "CallServiceIntent"
call_count = len(calls) call_count = len(calls)
response = await mock_client.post( response = await mock_client.post(
"/api/webhook/{}".format(webhook_id), data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert 200 == response.status assert 200 == response.status
assert call_count + 1 == len(calls) assert call_count + 1 == len(calls)
@ -369,7 +369,7 @@ async def test_intent_request_calling_service_v2(fixture, calls):
data["queryResult"]["action"] = "CallServiceIntent" data["queryResult"]["action"] = "CallServiceIntent"
call_count = len(calls) call_count = len(calls)
response = await mock_client.post( response = await mock_client.post(
"/api/webhook/{}".format(webhook_id), data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert 200 == response.status assert 200 == response.status
assert call_count + 1 == len(calls) assert call_count + 1 == len(calls)
@ -387,7 +387,7 @@ async def test_intent_with_no_action_v1(fixture):
del data["result"]["action"] del data["result"]["action"]
assert "action" not in data["result"] assert "action" not in data["result"]
response = await mock_client.post( response = await mock_client.post(
"/api/webhook/{}".format(webhook_id), data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert 200 == response.status assert 200 == response.status
text = (await response.json()).get("speech") text = (await response.json()).get("speech")
@ -401,7 +401,7 @@ async def test_intent_with_no_action_v2(fixture):
del data["queryResult"]["action"] del data["queryResult"]["action"]
assert "action" not in data["queryResult"] assert "action" not in data["queryResult"]
response = await mock_client.post( response = await mock_client.post(
"/api/webhook/{}".format(webhook_id), data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert 200 == response.status assert 200 == response.status
text = (await response.json()).get("fulfillmentText") text = (await response.json()).get("fulfillmentText")
@ -414,7 +414,7 @@ async def test_intent_with_unknown_action_v1(fixture):
data = Data.v1 data = Data.v1
data["result"]["action"] = "unknown" data["result"]["action"] = "unknown"
response = await mock_client.post( response = await mock_client.post(
"/api/webhook/{}".format(webhook_id), data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert 200 == response.status assert 200 == response.status
text = (await response.json()).get("speech") text = (await response.json()).get("speech")
@ -427,7 +427,7 @@ async def test_intent_with_unknown_action_v2(fixture):
data = Data.v2 data = Data.v2
data["queryResult"]["action"] = "unknown" data["queryResult"]["action"] = "unknown"
response = await mock_client.post( response = await mock_client.post(
"/api/webhook/{}".format(webhook_id), data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert 200 == response.status assert 200 == response.status
text = (await response.json()).get("fulfillmentText") text = (await response.json()).get("fulfillmentText")

View file

@ -35,27 +35,25 @@ def mock_responses(mock):
"""Mock responses for Efergy.""" """Mock responses for Efergy."""
base_url = "https://engage.efergy.com/mobile_proxy/" base_url = "https://engage.efergy.com/mobile_proxy/"
mock.get( mock.get(
"{}getInstant?token={}".format(base_url, token), f"{base_url}getInstant?token={token}", text=load_fixture("efergy_instant.json"),
text=load_fixture("efergy_instant.json"),
) )
mock.get( mock.get(
"{}getEnergy?token={}&offset=300&period=day".format(base_url, token), f"{base_url}getEnergy?token={token}&offset=300&period=day",
text=load_fixture("efergy_energy.json"), text=load_fixture("efergy_energy.json"),
) )
mock.get( mock.get(
"{}getBudget?token={}".format(base_url, token), f"{base_url}getBudget?token={token}", text=load_fixture("efergy_budget.json"),
text=load_fixture("efergy_budget.json"),
) )
mock.get( mock.get(
"{}getCost?token={}&offset=300&period=day".format(base_url, token), f"{base_url}getCost?token={token}&offset=300&period=day",
text=load_fixture("efergy_cost.json"), text=load_fixture("efergy_cost.json"),
) )
mock.get( mock.get(
"{}getCurrentValuesSummary?token={}".format(base_url, token), f"{base_url}getCurrentValuesSummary?token={token}",
text=load_fixture("efergy_current_values_single.json"), text=load_fixture("efergy_current_values_single.json"),
) )
mock.get( mock.get(
"{}getCurrentValuesSummary?token={}".format(base_url, multi_sensor_token), f"{base_url}getCurrentValuesSummary?token={multi_sensor_token}",
text=load_fixture("efergy_current_values_multi.json"), text=load_fixture("efergy_current_values_multi.json"),
) )

View file

@ -66,7 +66,7 @@ class TestComponentHistory(unittest.TestCase):
for i in range(5): for i in range(5):
state = ha.State( state = ha.State(
"test.point_in_time_{}".format(i % 5), "test.point_in_time_{}".format(i % 5),
"State {}".format(i), f"State {i}",
{"attribute_test": i}, {"attribute_test": i},
) )
@ -83,7 +83,7 @@ class TestComponentHistory(unittest.TestCase):
for i in range(5): for i in range(5):
state = ha.State( state = ha.State(
"test.point_in_time_{}".format(i % 5), "test.point_in_time_{}".format(i % 5),
"State {}".format(i), f"State {i}",
{"attribute_test": i}, {"attribute_test": i},
) )
@ -677,9 +677,7 @@ async def test_fetch_period_api(hass, hass_client):
await async_setup_component(hass, "history", {}) await async_setup_component(hass, "history", {})
await hass.async_add_job(hass.data[recorder.DATA_INSTANCE].block_till_done) await hass.async_add_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client() client = await hass_client()
response = await client.get( response = await client.get(f"/api/history/period/{dt_util.utcnow().isoformat()}")
"/api/history/period/{}".format(dt_util.utcnow().isoformat())
)
assert response.status == 200 assert response.status == 200
@ -699,7 +697,7 @@ async def test_fetch_period_api_with_include_order(hass, hass_client):
await hass.async_add_job(hass.data[recorder.DATA_INSTANCE].block_till_done) await hass.async_add_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client() client = await hass_client()
response = await client.get( response = await client.get(
"/api/history/period/{}".format(dt_util.utcnow().isoformat()), f"/api/history/period/{dt_util.utcnow().isoformat()}",
params={"filter_entity_id": "non.existing,something.else"}, params={"filter_entity_id": "non.existing,something.else"},
) )
assert response.status == 200 assert response.status == 200

View file

@ -62,9 +62,7 @@ class TestImageProcessing:
setup_component(self.hass, ip.DOMAIN, config) setup_component(self.hass, ip.DOMAIN, config)
state = self.hass.states.get("camera.demo_camera") state = self.hass.states.get("camera.demo_camera")
self.url = "{0}{1}".format( self.url = f"{self.hass.config.api.base_url}{state.attributes.get(ATTR_ENTITY_PICTURE)}"
self.hass.config.api.base_url, state.attributes.get(ATTR_ENTITY_PICTURE)
)
def teardown_method(self): def teardown_method(self):
"""Stop everything that was started.""" """Stop everything that was started."""
@ -120,9 +118,7 @@ class TestImageProcessingAlpr:
setup_component(self.hass, ip.DOMAIN, config) setup_component(self.hass, ip.DOMAIN, config)
state = self.hass.states.get("camera.demo_camera") state = self.hass.states.get("camera.demo_camera")
self.url = "{0}{1}".format( self.url = f"{self.hass.config.api.base_url}{state.attributes.get(ATTR_ENTITY_PICTURE)}"
self.hass.config.api.base_url, state.attributes.get(ATTR_ENTITY_PICTURE)
)
self.alpr_events = [] self.alpr_events = []
@ -227,9 +223,7 @@ class TestImageProcessingFace:
setup_component(self.hass, ip.DOMAIN, config) setup_component(self.hass, ip.DOMAIN, config)
state = self.hass.states.get("camera.demo_camera") state = self.hass.states.get("camera.demo_camera")
self.url = "{0}{1}".format( self.url = f"{self.hass.config.api.base_url}{state.attributes.get(ATTR_ENTITY_PICTURE)}"
self.hass.config.api.base_url, state.attributes.get(ATTR_ENTITY_PICTURE)
)
self.face_events = [] self.face_events = []

View file

@ -252,14 +252,14 @@ class TestInfluxDB(unittest.TestCase):
state = mock.MagicMock( state = mock.MagicMock(
state=1, state=1,
domain="fake", domain="fake",
entity_id="fake.{}".format(entity_id), entity_id=f"fake.{entity_id}",
object_id=entity_id, object_id=entity_id,
attributes={}, attributes={},
) )
event = mock.MagicMock(data={"new_state": state}, time_fired=12345) event = mock.MagicMock(data={"new_state": state}, time_fired=12345)
body = [ body = [
{ {
"measurement": "fake.{}".format(entity_id), "measurement": f"fake.{entity_id}",
"tags": {"domain": "fake", "entity_id": entity_id}, "tags": {"domain": "fake", "entity_id": entity_id},
"time": 12345, "time": 12345,
"fields": {"value": 1}, "fields": {"value": 1},
@ -284,14 +284,14 @@ class TestInfluxDB(unittest.TestCase):
state = mock.MagicMock( state = mock.MagicMock(
state=1, state=1,
domain=domain, domain=domain,
entity_id="{}.something".format(domain), entity_id=f"{domain}.something",
object_id="something", object_id="something",
attributes={}, attributes={},
) )
event = mock.MagicMock(data={"new_state": state}, time_fired=12345) event = mock.MagicMock(data={"new_state": state}, time_fired=12345)
body = [ body = [
{ {
"measurement": "{}.something".format(domain), "measurement": f"{domain}.something",
"tags": {"domain": domain, "entity_id": "something"}, "tags": {"domain": domain, "entity_id": "something"},
"time": 12345, "time": 12345,
"fields": {"value": 1}, "fields": {"value": 1},
@ -326,14 +326,14 @@ class TestInfluxDB(unittest.TestCase):
state = mock.MagicMock( state = mock.MagicMock(
state=1, state=1,
domain="fake", domain="fake",
entity_id="fake.{}".format(entity_id), entity_id=f"fake.{entity_id}",
object_id=entity_id, object_id=entity_id,
attributes={}, attributes={},
) )
event = mock.MagicMock(data={"new_state": state}, time_fired=12345) event = mock.MagicMock(data={"new_state": state}, time_fired=12345)
body = [ body = [
{ {
"measurement": "fake.{}".format(entity_id), "measurement": f"fake.{entity_id}",
"tags": {"domain": "fake", "entity_id": entity_id}, "tags": {"domain": "fake", "entity_id": entity_id},
"time": 12345, "time": 12345,
"fields": {"value": 1}, "fields": {"value": 1},
@ -368,14 +368,14 @@ class TestInfluxDB(unittest.TestCase):
state = mock.MagicMock( state = mock.MagicMock(
state=1, state=1,
domain=domain, domain=domain,
entity_id="{}.something".format(domain), entity_id=f"{domain}.something",
object_id="something", object_id="something",
attributes={}, attributes={},
) )
event = mock.MagicMock(data={"new_state": state}, time_fired=12345) event = mock.MagicMock(data={"new_state": state}, time_fired=12345)
body = [ body = [
{ {
"measurement": "{}.something".format(domain), "measurement": f"{domain}.something",
"tags": {"domain": domain, "entity_id": "something"}, "tags": {"domain": domain, "entity_id": "something"},
"time": 12345, "time": 12345,
"fields": {"value": 1}, "fields": {"value": 1},
@ -410,14 +410,14 @@ class TestInfluxDB(unittest.TestCase):
state = mock.MagicMock( state = mock.MagicMock(
state=1, state=1,
domain=domain, domain=domain,
entity_id="{}.something".format(domain), entity_id=f"{domain}.something",
object_id="something", object_id="something",
attributes={}, attributes={},
) )
event = mock.MagicMock(data={"new_state": state}, time_fired=12345) event = mock.MagicMock(data={"new_state": state}, time_fired=12345)
body = [ body = [
{ {
"measurement": "{}.something".format(domain), "measurement": f"{domain}.something",
"tags": {"domain": domain, "entity_id": "something"}, "tags": {"domain": domain, "entity_id": "something"},
"time": 12345, "time": 12345,
"fields": {"value": 1}, "fields": {"value": 1},
@ -438,14 +438,14 @@ class TestInfluxDB(unittest.TestCase):
state = mock.MagicMock( state = mock.MagicMock(
state=1, state=1,
domain="other", domain="other",
entity_id="other.{}".format(entity_id), entity_id=f"other.{entity_id}",
object_id=entity_id, object_id=entity_id,
attributes={}, attributes={},
) )
event = mock.MagicMock(data={"new_state": state}, time_fired=12345) event = mock.MagicMock(data={"new_state": state}, time_fired=12345)
body = [ body = [
{ {
"measurement": "other.{}".format(entity_id), "measurement": f"other.{entity_id}",
"tags": {"domain": "other", "entity_id": entity_id}, "tags": {"domain": "other", "entity_id": entity_id},
"time": 12345, "time": 12345,
"fields": {"value": 1}, "fields": {"value": 1},
@ -532,7 +532,7 @@ class TestInfluxDB(unittest.TestCase):
state = mock.MagicMock( state = mock.MagicMock(
state=1, state=1,
domain="fake", domain="fake",
entity_id="fake.{}".format(entity_id), entity_id=f"fake.{entity_id}",
object_id=entity_id, object_id=entity_id,
attributes={}, attributes={},
) )

View file

@ -48,7 +48,7 @@ async def webhook_id(hass, locative_client):
async def test_missing_data(locative_client, webhook_id): async def test_missing_data(locative_client, webhook_id):
"""Test missing data.""" """Test missing data."""
url = "/api/webhook/{}".format(webhook_id) url = f"/api/webhook/{webhook_id}"
data = { data = {
"latitude": 1.0, "latitude": 1.0,
@ -108,7 +108,7 @@ async def test_missing_data(locative_client, webhook_id):
async def test_enter_and_exit(hass, locative_client, webhook_id): async def test_enter_and_exit(hass, locative_client, webhook_id):
"""Test when there is a known zone.""" """Test when there is a known zone."""
url = "/api/webhook/{}".format(webhook_id) url = f"/api/webhook/{webhook_id}"
data = { data = {
"latitude": 40.7855, "latitude": 40.7855,
@ -177,7 +177,7 @@ async def test_enter_and_exit(hass, locative_client, webhook_id):
async def test_exit_after_enter(hass, locative_client, webhook_id): async def test_exit_after_enter(hass, locative_client, webhook_id):
"""Test when an exit message comes after an enter message.""" """Test when an exit message comes after an enter message."""
url = "/api/webhook/{}".format(webhook_id) url = f"/api/webhook/{webhook_id}"
data = { data = {
"latitude": 40.7855, "latitude": 40.7855,
@ -219,7 +219,7 @@ async def test_exit_after_enter(hass, locative_client, webhook_id):
async def test_exit_first(hass, locative_client, webhook_id): async def test_exit_first(hass, locative_client, webhook_id):
"""Test when an exit message is sent first on a new device.""" """Test when an exit message is sent first on a new device."""
url = "/api/webhook/{}".format(webhook_id) url = f"/api/webhook/{webhook_id}"
data = { data = {
"latitude": 40.7855, "latitude": 40.7855,
@ -240,7 +240,7 @@ async def test_exit_first(hass, locative_client, webhook_id):
async def test_two_devices(hass, locative_client, webhook_id): async def test_two_devices(hass, locative_client, webhook_id):
"""Test updating two different devices.""" """Test updating two different devices."""
url = "/api/webhook/{}".format(webhook_id) url = f"/api/webhook/{webhook_id}"
data_device_1 = { data_device_1 = {
"latitude": 40.7855, "latitude": 40.7855,
@ -283,7 +283,7 @@ async def test_two_devices(hass, locative_client, webhook_id):
) )
async def test_load_unload_entry(hass, locative_client, webhook_id): async def test_load_unload_entry(hass, locative_client, webhook_id):
"""Test that the appropriate dispatch signals are added and removed.""" """Test that the appropriate dispatch signals are added and removed."""
url = "/api/webhook/{}".format(webhook_id) url = f"/api/webhook/{webhook_id}"
data = { data = {
"latitude": 40.7855, "latitude": 40.7855,

View file

@ -1274,7 +1274,7 @@ async def test_logbook_view(hass, hass_client):
await async_setup_component(hass, "logbook", {}) await async_setup_component(hass, "logbook", {})
await hass.async_add_job(hass.data[recorder.DATA_INSTANCE].block_till_done) await hass.async_add_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client() client = await hass_client()
response = await client.get("/api/logbook/{}".format(dt_util.utcnow().isoformat())) response = await client.get(f"/api/logbook/{dt_util.utcnow().isoformat()}")
assert response.status == 200 assert response.status == 200
@ -1301,7 +1301,7 @@ async def test_logbook_view_period_entity(hass, hass_client):
start_date = datetime(start.year, start.month, start.day) start_date = datetime(start.year, start.month, start.day)
# Test today entries without filters # Test today entries without filters
response = await client.get("/api/logbook/{}".format(start_date.isoformat())) response = await client.get(f"/api/logbook/{start_date.isoformat()}")
assert response.status == 200 assert response.status == 200
json = await response.json() json = await response.json()
assert len(json) == 2 assert len(json) == 2
@ -1309,9 +1309,7 @@ async def test_logbook_view_period_entity(hass, hass_client):
assert json[1]["entity_id"] == entity_id_second assert json[1]["entity_id"] == entity_id_second
# Test today entries with filter by period # Test today entries with filter by period
response = await client.get( response = await client.get(f"/api/logbook/{start_date.isoformat()}?period=1")
"/api/logbook/{}?period=1".format(start_date.isoformat())
)
assert response.status == 200 assert response.status == 200
json = await response.json() json = await response.json()
assert len(json) == 2 assert len(json) == 2
@ -1320,7 +1318,7 @@ async def test_logbook_view_period_entity(hass, hass_client):
# Test today entries with filter by entity_id # Test today entries with filter by entity_id
response = await client.get( response = await client.get(
"/api/logbook/{}?entity=switch.test".format(start_date.isoformat()) f"/api/logbook/{start_date.isoformat()}?entity=switch.test"
) )
assert response.status == 200 assert response.status == 200
json = await response.json() json = await response.json()
@ -1329,7 +1327,7 @@ async def test_logbook_view_period_entity(hass, hass_client):
# Test entries for 3 days with filter by entity_id # Test entries for 3 days with filter by entity_id
response = await client.get( response = await client.get(
"/api/logbook/{}?period=3&entity=switch.test".format(start_date.isoformat()) f"/api/logbook/{start_date.isoformat()}?period=3&entity=switch.test"
) )
assert response.status == 200 assert response.status == 200
json = await response.json() json = await response.json()
@ -1341,14 +1339,14 @@ async def test_logbook_view_period_entity(hass, hass_client):
start_date = datetime(start.year, start.month, start.day) start_date = datetime(start.year, start.month, start.day)
# Test tomorrow entries without filters # Test tomorrow entries without filters
response = await client.get("/api/logbook/{}".format(start_date.isoformat())) response = await client.get(f"/api/logbook/{start_date.isoformat()}")
assert response.status == 200 assert response.status == 200
json = await response.json() json = await response.json()
assert len(json) == 0 assert len(json) == 0
# Test tomorrow entries with filter by entity_id # Test tomorrow entries with filter by entity_id
response = await client.get( response = await client.get(
"/api/logbook/{}?entity=switch.test".format(start_date.isoformat()) f"/api/logbook/{start_date.isoformat()}?entity=switch.test"
) )
assert response.status == 200 assert response.status == 200
json = await response.json() json = await response.json()
@ -1356,7 +1354,7 @@ async def test_logbook_view_period_entity(hass, hass_client):
# Test entries from tomorrow to 3 days ago with filter by entity_id # Test entries from tomorrow to 3 days ago with filter by entity_id
response = await client.get( response = await client.get(
"/api/logbook/{}?period=3&entity=switch.test".format(start_date.isoformat()) f"/api/logbook/{start_date.isoformat()}?period=3&entity=switch.test"
) )
assert response.status == 200 assert response.status == 200
json = await response.json() json = await response.json()

View file

@ -11,7 +11,7 @@ _LOGGER = logging.getLogger(__name__)
async def test_sensor(hass, create_registrations, webhook_client): async def test_sensor(hass, create_registrations, webhook_client):
"""Test that sensors can be registered and updated.""" """Test that sensors can be registered and updated."""
webhook_id = create_registrations[1]["webhook_id"] webhook_id = create_registrations[1]["webhook_id"]
webhook_url = "/api/webhook/{}".format(webhook_id) webhook_url = f"/api/webhook/{webhook_id}"
reg_resp = await webhook_client.post( reg_resp = await webhook_client.post(
webhook_url, webhook_url,
@ -74,7 +74,7 @@ async def test_sensor(hass, create_registrations, webhook_client):
async def test_sensor_must_register(hass, create_registrations, webhook_client): async def test_sensor_must_register(hass, create_registrations, webhook_client):
"""Test that sensors must be registered before updating.""" """Test that sensors must be registered before updating."""
webhook_id = create_registrations[1]["webhook_id"] webhook_id = create_registrations[1]["webhook_id"]
webhook_url = "/api/webhook/{}".format(webhook_id) webhook_url = f"/api/webhook/{webhook_id}"
resp = await webhook_client.post( resp = await webhook_client.post(
webhook_url, webhook_url,
json={ json={
@ -93,7 +93,7 @@ async def test_sensor_must_register(hass, create_registrations, webhook_client):
async def test_sensor_id_no_dupes(hass, create_registrations, webhook_client): async def test_sensor_id_no_dupes(hass, create_registrations, webhook_client):
"""Test that sensors must have a unique ID.""" """Test that sensors must have a unique ID."""
webhook_id = create_registrations[1]["webhook_id"] webhook_id = create_registrations[1]["webhook_id"]
webhook_url = "/api/webhook/{}".format(webhook_id) webhook_url = f"/api/webhook/{webhook_id}"
payload = { payload = {
"type": "register_sensor", "type": "register_sensor",

View file

@ -16,10 +16,10 @@ NAME = "test_device"
BEDROOM = "bedroom" BEDROOM = "bedroom"
LIVING_ROOM = "living_room" LIVING_ROOM = "living_room"
BEDROOM_TOPIC = "room_presence/{}".format(BEDROOM) BEDROOM_TOPIC = f"room_presence/{BEDROOM}"
LIVING_ROOM_TOPIC = "room_presence/{}".format(LIVING_ROOM) LIVING_ROOM_TOPIC = f"room_presence/{LIVING_ROOM}"
SENSOR_STATE = "sensor.{}".format(NAME) SENSOR_STATE = f"sensor.{NAME}"
CONF_DEVICE_ID = "device_id" CONF_DEVICE_ID = "device_id"
CONF_TIMEOUT = "timeout" CONF_TIMEOUT = "timeout"

View file

@ -104,9 +104,7 @@ class TestOpenAlprLocal:
setup_component(self.hass, ip.DOMAIN, config) setup_component(self.hass, ip.DOMAIN, config)
state = self.hass.states.get("camera.demo_camera") state = self.hass.states.get("camera.demo_camera")
self.url = "{0}{1}".format( self.url = f"{self.hass.config.api.base_url}{state.attributes.get(ATTR_ENTITY_PICTURE)}"
self.hass.config.api.base_url, state.attributes.get(ATTR_ENTITY_PICTURE)
)
self.alpr_events = [] self.alpr_events = []

View file

@ -156,7 +156,7 @@ async def mock_ddp_response(hass, mock_status_data, games=None):
mock_code = mock_status_data.get("status_code") mock_code = mock_status_data.get("status_code")
mock_status = mock_status_data.get("status") mock_status = mock_status_data.get("status")
mock_status_header = "{} {}".format(mock_code, mock_status) mock_status_header = f"{mock_code} {mock_status}"
mock_response = get_ddp_message(mock_status_header, mock_status_data).encode() mock_response = get_ddp_message(mock_status_header, mock_status_data).encode()
if games is None: if games is None:
@ -179,7 +179,7 @@ async def test_media_player_is_setup_correctly_with_entry(hass):
# Test that entity is added to hass. # Test that entity is added to hass.
assert hass.data[PS4_DATA].protocol is not None assert hass.data[PS4_DATA].protocol is not None
assert mock_entity_id == "media_player.{}".format(MOCK_NAME) assert mock_entity_id == f"media_player.{MOCK_NAME}"
assert mock_state == STATE_UNKNOWN assert mock_state == STATE_UNKNOWN

View file

@ -162,7 +162,7 @@ async def test_accessing_forbidden_methods(hass, caplog):
caplog.records.clear() caplog.records.clear()
hass.async_add_job(execute, hass, "test.py", source, {}) hass.async_add_job(execute, hass, "test.py", source, {})
await hass.async_block_till_done() await hass.async_block_till_done()
assert "Not allowed to access {}".format(name) in caplog.text assert f"Not allowed to access {name}" in caplog.text
async def test_iterating(hass): async def test_iterating(hass):

View file

@ -109,7 +109,7 @@ def _add_entities(hass, entity_ids):
"""Add entities.""" """Add entities."""
attributes = {"test_attr": 5, "test_attr_10": "nice"} attributes = {"test_attr": 5, "test_attr_10": "nice"}
for idx, entity_id in enumerate(entity_ids): for idx, entity_id in enumerate(entity_ids):
hass.states.set(entity_id, "state{}".format(idx), attributes) hass.states.set(entity_id, f"state{idx}", attributes)
wait_recording_done(hass) wait_recording_done(hass)
with session_scope(hass=hass) as session: with session_scope(hass=hass) as session:

View file

@ -24,7 +24,7 @@ class MockDeviceInfo(object):
def __repr__(self): def __repr__(self):
"""Return the object representation of DeviceInfo.""" """Return the object representation of DeviceInfo."""
return "<DeviceInfo: %s-%s, SW v%s, Ser# %s (%s)>" % ( return "<DeviceInfo: {}-{}, SW v{}, Ser# {} ({})>".format(
self.model_name, self.model_name,
self.model_num, self.model_num,
self.software_version, self.software_version,

View file

@ -87,11 +87,11 @@ class TestScene(unittest.TestCase):
"scene:\n" "scene:\n"
" - name: test\n" " - name: test\n"
" entities:\n" " entities:\n"
" {0}: on\n" f" {self.light_1.entity_id}: on\n"
" {1}:\n" f" {self.light_2.entity_id}:\n"
" state: on\n" " state: on\n"
" brightness: 100\n" " brightness: 100\n"
).format(self.light_1.entity_id, self.light_2.entity_id) )
with io.StringIO(config) as file: with io.StringIO(config) as file:
doc = yaml_loader.yaml.safe_load(file) doc = yaml_loader.yaml.safe_load(file)

View file

@ -94,7 +94,7 @@ class TestScriptComponent(unittest.TestCase):
): ):
assert not setup_component( assert not setup_component(
self.hass, "script", {"script": value} self.hass, "script", {"script": value}
), "Script loaded with wrong config {}".format(value) ), f"Script loaded with wrong config {value}"
assert 0 == len(self.hass.states.entity_ids("script")) assert 0 == len(self.hass.states.entity_ids("script"))

View file

@ -53,7 +53,7 @@ class TestShellCommand(unittest.TestCase):
assert setup_component( assert setup_component(
self.hass, self.hass,
shell_command.DOMAIN, shell_command.DOMAIN,
{shell_command.DOMAIN: {"test_service": "date > {}".format(path)}}, {shell_command.DOMAIN: {"test_service": f"date > {path}"}},
) )
self.hass.services.call("shell_command", "test_service", blocking=True) self.hass.services.call("shell_command", "test_service", blocking=True)
@ -137,7 +137,7 @@ class TestShellCommand(unittest.TestCase):
assert setup_component( assert setup_component(
self.hass, self.hass,
shell_command.DOMAIN, shell_command.DOMAIN,
{shell_command.DOMAIN: {"test_service": "touch {}".format(path)}}, {shell_command.DOMAIN: {"test_service": f"touch {path}"}},
) )
self.hass.services.call("shell_command", "test_service", blocking=True) self.hass.services.call("shell_command", "test_service", blocking=True)
@ -154,7 +154,7 @@ class TestShellCommand(unittest.TestCase):
assert setup_component( assert setup_component(
self.hass, self.hass,
shell_command.DOMAIN, shell_command.DOMAIN,
{shell_command.DOMAIN: {"test_service": "echo {}".format(test_phrase)}}, {shell_command.DOMAIN: {"test_service": f"echo {test_phrase}"}},
) )
self.hass.services.call("shell_command", "test_service", blocking=True) self.hass.services.call("shell_command", "test_service", blocking=True)
@ -170,7 +170,7 @@ class TestShellCommand(unittest.TestCase):
assert setup_component( assert setup_component(
self.hass, self.hass,
shell_command.DOMAIN, shell_command.DOMAIN,
{shell_command.DOMAIN: {"test_service": ">&2 echo {}".format(test_phrase)}}, {shell_command.DOMAIN: {"test_service": f">&2 echo {test_phrase}"}},
) )
self.hass.services.call("shell_command", "test_service", blocking=True) self.hass.services.call("shell_command", "test_service", blocking=True)

View file

@ -99,7 +99,7 @@ async def test_deprecated_api_update(hass, hass_client, sl_setup):
client = await hass_client() client = await hass_client()
resp = await client.post( resp = await client.post(
"/api/shopping_list/item/{}".format(beer_id), json={"name": "soda"} f"/api/shopping_list/item/{beer_id}", json={"name": "soda"}
) )
assert resp.status == 200 assert resp.status == 200
@ -107,7 +107,7 @@ async def test_deprecated_api_update(hass, hass_client, sl_setup):
assert data == {"id": beer_id, "name": "soda", "complete": False} assert data == {"id": beer_id, "name": "soda", "complete": False}
resp = await client.post( resp = await client.post(
"/api/shopping_list/item/{}".format(wine_id), json={"complete": True} f"/api/shopping_list/item/{wine_id}", json={"complete": True}
) )
assert resp.status == 200 assert resp.status == 200
@ -174,9 +174,7 @@ async def test_api_update_fails(hass, hass_client, sl_setup):
assert resp.status == 404 assert resp.status == 404
beer_id = hass.data["shopping_list"].items[0]["id"] beer_id = hass.data["shopping_list"].items[0]["id"]
resp = await client.post( resp = await client.post(f"/api/shopping_list/item/{beer_id}", json={"name": 123})
"/api/shopping_list/item/{}".format(beer_id), json={"name": 123}
)
assert resp.status == 400 assert resp.status == 400
@ -221,7 +219,7 @@ async def test_deprecated_api_clear_completed(hass, hass_client, sl_setup):
# Mark beer as completed # Mark beer as completed
resp = await client.post( resp = await client.post(
"/api/shopping_list/item/{}".format(beer_id), json={"complete": True} f"/api/shopping_list/item/{beer_id}", json={"complete": True}
) )
assert resp.status == 200 assert resp.status == 200

View file

@ -18,13 +18,11 @@ def mock_responses(mock, single=False):
else: else:
suffix = "" suffix = ""
mock.put(base_url + "login", text=load_fixture("sleepiq-login.json")) mock.put(base_url + "login", text=load_fixture("sleepiq-login.json"))
mock.get( mock.get(base_url + "bed?_k=0987", text=load_fixture(f"sleepiq-bed{suffix}.json"))
base_url + "bed?_k=0987", text=load_fixture("sleepiq-bed{}.json".format(suffix))
)
mock.get(base_url + "sleeper?_k=0987", text=load_fixture("sleepiq-sleeper.json")) mock.get(base_url + "sleeper?_k=0987", text=load_fixture("sleepiq-sleeper.json"))
mock.get( mock.get(
base_url + "bed/familyStatus?_k=0987", base_url + "bed/familyStatus?_k=0987",
text=load_fixture("sleepiq-familystatus{}.json".format(suffix)), text=load_fixture(f"sleepiq-familystatus{suffix}.json"),
) )

View file

@ -77,7 +77,7 @@ class TestSwitch(unittest.TestCase):
switch.DOMAIN, switch.DOMAIN,
{ {
switch.DOMAIN: {CONF_PLATFORM: "test"}, switch.DOMAIN: {CONF_PLATFORM: "test"},
"{} 2".format(switch.DOMAIN): {CONF_PLATFORM: "test2"}, f"{switch.DOMAIN} 2": {CONF_PLATFORM: "test2"},
}, },
) )

View file

@ -73,7 +73,7 @@ async def test_configuring_device_types(hass, name, cls, platform, count):
"homeassistant.components.tplink.common.SmartDevice._query_helper" "homeassistant.components.tplink.common.SmartDevice._query_helper"
): ):
discovery_data = { discovery_data = {
"123.123.123.{}".format(c): cls("123.123.123.123") for c in range(count) f"123.123.123.{c}": cls("123.123.123.123") for c in range(count)
} }
discover.return_value = discovery_data discover.return_value = discovery_data
await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}})
@ -242,7 +242,7 @@ async def test_unload(hass, platform):
with patch( with patch(
"homeassistant.components.tplink.common.SmartDevice._query_helper" "homeassistant.components.tplink.common.SmartDevice._query_helper"
), patch( ), patch(
"homeassistant.components.tplink.{}.async_setup_entry".format(platform), f"homeassistant.components.tplink.{platform}.async_setup_entry",
return_value=mock_coro(True), return_value=mock_coro(True),
) as light_setup: ) as light_setup:
config = { config = {

View file

@ -75,7 +75,7 @@ async def webhook_id_fixture(hass, client):
async def test_missing_data(hass, client, webhook_id): async def test_missing_data(hass, client, webhook_id):
"""Test missing data.""" """Test missing data."""
url = "/api/webhook/{}".format(webhook_id) url = f"/api/webhook/{webhook_id}"
data = {"lat": "1.0", "lon": "1.1", "id": "123"} data = {"lat": "1.0", "lon": "1.1", "id": "123"}
# No data # No data
@ -100,7 +100,7 @@ async def test_missing_data(hass, client, webhook_id):
async def test_enter_and_exit(hass, client, webhook_id): async def test_enter_and_exit(hass, client, webhook_id):
"""Test when there is a known zone.""" """Test when there is a known zone."""
url = "/api/webhook/{}".format(webhook_id) url = f"/api/webhook/{webhook_id}"
data = {"lat": str(HOME_LATITUDE), "lon": str(HOME_LONGITUDE), "id": "123"} data = {"lat": str(HOME_LATITUDE), "lon": str(HOME_LONGITUDE), "id": "123"}
# Enter the Home # Enter the Home
@ -142,7 +142,7 @@ async def test_enter_and_exit(hass, client, webhook_id):
async def test_enter_with_attrs(hass, client, webhook_id): async def test_enter_with_attrs(hass, client, webhook_id):
"""Test when additional attributes are present.""" """Test when additional attributes are present."""
url = "/api/webhook/{}".format(webhook_id) url = f"/api/webhook/{webhook_id}"
data = { data = {
"timestamp": 123456789, "timestamp": 123456789,
"lat": "1.0", "lat": "1.0",
@ -191,7 +191,7 @@ async def test_enter_with_attrs(hass, client, webhook_id):
async def test_two_devices(hass, client, webhook_id): async def test_two_devices(hass, client, webhook_id):
"""Test updating two different devices.""" """Test updating two different devices."""
url = "/api/webhook/{}".format(webhook_id) url = f"/api/webhook/{webhook_id}"
data_device_1 = {"lat": "1.0", "lon": "1.1", "id": "device_1"} data_device_1 = {"lat": "1.0", "lon": "1.1", "id": "device_1"}
@ -223,7 +223,7 @@ async def test_two_devices(hass, client, webhook_id):
) )
async def test_load_unload_entry(hass, client, webhook_id): async def test_load_unload_entry(hass, client, webhook_id):
"""Test that the appropriate dispatch signals are added and removed.""" """Test that the appropriate dispatch signals are added and removed."""
url = "/api/webhook/{}".format(webhook_id) url = f"/api/webhook/{webhook_id}"
data = {"lat": str(HOME_LATITUDE), "lon": str(HOME_LONGITUDE), "id": "123"} data = {"lat": str(HOME_LATITUDE), "lon": str(HOME_LONGITUDE), "id": "123"}
# Enter the Home # Enter the Home