String formatting improvements for tests (2) (#33666)

This commit is contained in:
Franck Nijhof 2020-04-05 00:33:07 +02:00 committed by GitHub
parent 906385172a
commit d7e9959442
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 65 additions and 76 deletions

View File

@ -50,7 +50,7 @@ from tests.common import (
HTTP_SERVER_PORT = get_test_instance_port()
BRIDGE_SERVER_PORT = get_test_instance_port()
BRIDGE_URL_BASE = "http://127.0.0.1:{}".format(BRIDGE_SERVER_PORT) + "{}"
BRIDGE_URL_BASE = f"http://127.0.0.1:{BRIDGE_SERVER_PORT}" + "{}"
JSON_HEADERS = {CONTENT_TYPE: const.CONTENT_TYPE_JSON}
@ -773,7 +773,7 @@ async def perform_put_test_on_ceiling_lights(
async def perform_get_light_state(client, entity_id, expected_status):
"""Test the getting of a light state."""
result = await client.get("/api/username/lights/{}".format(entity_id))
result = await client.get(f"/api/username/lights/{entity_id}")
assert result.status == expected_status
@ -808,7 +808,7 @@ async def perform_put_light_state(
data[HUE_API_STATE_SAT] = saturation
result = await client.put(
"/api/username/lights/{}/state".format(entity_id),
f"/api/username/lights/{entity_id}/state",
headers=req_headers,
data=json.dumps(data).encode(),
)

View File

@ -15,7 +15,7 @@ from tests.common import get_test_home_assistant, get_test_instance_port
HTTP_SERVER_PORT = get_test_instance_port()
BRIDGE_SERVER_PORT = get_test_instance_port()
BRIDGE_URL_BASE = "http://127.0.0.1:{}".format(BRIDGE_SERVER_PORT) + "{}"
BRIDGE_URL_BASE = f"http://127.0.0.1:{BRIDGE_SERVER_PORT}" + "{}"
JSON_HEADERS = {CONTENT_TYPE: const.CONTENT_TYPE_JSON}

View File

@ -25,7 +25,7 @@ async def test_forward_request(hassio_client, aioclient_mock):
)
async def test_auth_required_forward_request(hassio_noauth_client, build_type):
"""Test auth required for normal request."""
resp = await hassio_noauth_client.post("/api/hassio/{}".format(build_type))
resp = await hassio_noauth_client.post(f"/api/hassio/{build_type}")
# Check we got right response
assert resp.status == 401
@ -46,9 +46,9 @@ async def test_forward_request_no_auth_for_panel(
hassio_client, build_type, aioclient_mock
):
"""Test no auth needed for ."""
aioclient_mock.get("http://127.0.0.1/{}".format(build_type), text="response")
aioclient_mock.get(f"http://127.0.0.1/{build_type}", text="response")
resp = await hassio_client.get("/api/hassio/{}".format(build_type))
resp = await hassio_client.get(f"/api/hassio/{build_type}")
# Check we got right response
assert resp.status == 200

View File

@ -147,12 +147,12 @@ async def test_cannot_access_with_trusted_ip(
for remote_addr in UNTRUSTED_ADDRESSES:
set_mock_ip(remote_addr)
resp = await client.get("/")
assert resp.status == 401, "{} shouldn't be trusted".format(remote_addr)
assert resp.status == 401, f"{remote_addr} shouldn't be trusted"
for remote_addr in TRUSTED_ADDRESSES:
set_mock_ip(remote_addr)
resp = await client.get("/")
assert resp.status == 401, "{} shouldn't be trusted".format(remote_addr)
assert resp.status == 401, f"{remote_addr} shouldn't be trusted"
async def test_auth_active_access_with_access_token_in_header(
@ -164,27 +164,27 @@ async def test_auth_active_access_with_access_token_in_header(
client = await aiohttp_client(app)
refresh_token = await hass.auth.async_validate_access_token(hass_access_token)
req = await client.get("/", headers={"Authorization": "Bearer {}".format(token)})
req = await client.get("/", headers={"Authorization": f"Bearer {token}"})
assert req.status == 200
assert await req.json() == {"user_id": refresh_token.user.id}
req = await client.get("/", headers={"AUTHORIZATION": "Bearer {}".format(token)})
req = await client.get("/", headers={"AUTHORIZATION": f"Bearer {token}"})
assert req.status == 200
assert await req.json() == {"user_id": refresh_token.user.id}
req = await client.get("/", headers={"authorization": "Bearer {}".format(token)})
req = await client.get("/", headers={"authorization": f"Bearer {token}"})
assert req.status == 200
assert await req.json() == {"user_id": refresh_token.user.id}
req = await client.get("/", headers={"Authorization": token})
assert req.status == 401
req = await client.get("/", headers={"Authorization": "BEARER {}".format(token)})
req = await client.get("/", headers={"Authorization": f"BEARER {token}"})
assert req.status == 401
refresh_token = await hass.auth.async_validate_access_token(hass_access_token)
refresh_token.user.is_active = False
req = await client.get("/", headers={"Authorization": "Bearer {}".format(token)})
req = await client.get("/", headers={"Authorization": f"Bearer {token}"})
assert req.status == 401
@ -200,12 +200,12 @@ async def test_auth_active_access_with_trusted_ip(
for remote_addr in UNTRUSTED_ADDRESSES:
set_mock_ip(remote_addr)
resp = await client.get("/")
assert resp.status == 401, "{} shouldn't be trusted".format(remote_addr)
assert resp.status == 401, f"{remote_addr} shouldn't be trusted"
for remote_addr in TRUSTED_ADDRESSES:
set_mock_ip(remote_addr)
resp = await client.get("/")
assert resp.status == 401, "{} shouldn't be trusted".format(remote_addr)
assert resp.status == 401, f"{remote_addr} shouldn't be trusted"
async def test_auth_legacy_support_api_password_cannot_access(

View File

@ -28,16 +28,16 @@ async def test_config_flow_registers_webhook(hass, aiohttp_client):
hass.bus.async_listen(ifttt.EVENT_RECEIVED, handle_event)
client = await aiohttp_client(hass.http.app)
await client.post("/api/webhook/{}".format(webhook_id), json={"hello": "ifttt"})
await client.post(f"/api/webhook/{webhook_id}", json={"hello": "ifttt"})
assert len(ifttt_events) == 1
assert ifttt_events[0].data["webhook_id"] == webhook_id
assert ifttt_events[0].data["hello"] == "ifttt"
# Invalid JSON
await client.post("/api/webhook/{}".format(webhook_id), data="not a dict")
await client.post(f"/api/webhook/{webhook_id}", data="not a dict")
assert len(ifttt_events) == 1
# Not a dict
await client.post("/api/webhook/{}".format(webhook_id), json="not a dict")
await client.post(f"/api/webhook/{webhook_id}", json="not a dict")
assert len(ifttt_events) == 1

View File

@ -81,14 +81,14 @@ async def test_mailgun_webhook_with_missing_signature(
event_count = len(mailgun_events)
await http_client.post(
"/api/webhook/{}".format(webhook_id_with_api_key),
f"/api/webhook/{webhook_id_with_api_key}",
json={"hello": "mailgun", "signature": {}},
)
assert len(mailgun_events) == event_count
await http_client.post(
"/api/webhook/{}".format(webhook_id_with_api_key), json={"hello": "mailgun"}
f"/api/webhook/{webhook_id_with_api_key}", json={"hello": "mailgun"}
)
assert len(mailgun_events) == event_count
@ -104,13 +104,13 @@ async def test_mailgun_webhook_with_different_api_key(
event_count = len(mailgun_events)
await http_client.post(
"/api/webhook/{}".format(webhook_id_with_api_key),
f"/api/webhook/{webhook_id_with_api_key}",
json={
"hello": "mailgun",
"signature": {
"signature": hmac.new(
key=b"random_api_key",
msg=bytes("{}{}".format(timestamp, token), "utf-8"),
msg=bytes(f"{timestamp}{token}", "utf-8"),
digestmod=hashlib.sha256,
).hexdigest(),
"timestamp": timestamp,
@ -132,13 +132,13 @@ async def test_mailgun_webhook_event_with_correct_api_key(
event_count = len(mailgun_events)
await http_client.post(
"/api/webhook/{}".format(webhook_id_with_api_key),
f"/api/webhook/{webhook_id_with_api_key}",
json={
"hello": "mailgun",
"signature": {
"signature": hmac.new(
key=bytes(API_KEY, "utf-8"),
msg=bytes("{}{}".format(timestamp, token), "utf-8"),
msg=bytes(f"{timestamp}{token}", "utf-8"),
digestmod=hashlib.sha256,
).hexdigest(),
"timestamp": timestamp,
@ -159,7 +159,7 @@ async def test_mailgun_webhook_with_missing_signature_without_api_key(
event_count = len(mailgun_events)
await http_client.post(
"/api/webhook/{}".format(webhook_id_without_api_key),
f"/api/webhook/{webhook_id_without_api_key}",
json={"hello": "mailgun", "signature": {}},
)
@ -168,7 +168,7 @@ async def test_mailgun_webhook_with_missing_signature_without_api_key(
assert mailgun_events[-1].data["hello"] == "mailgun"
await http_client.post(
"/api/webhook/{}".format(webhook_id_without_api_key), json={"hello": "mailgun"}
f"/api/webhook/{webhook_id_without_api_key}", json={"hello": "mailgun"}
)
assert len(mailgun_events) == event_count + 1
@ -186,13 +186,13 @@ async def test_mailgun_webhook_event_without_an_api_key(
event_count = len(mailgun_events)
await http_client.post(
"/api/webhook/{}".format(webhook_id_without_api_key),
f"/api/webhook/{webhook_id_without_api_key}",
json={
"hello": "mailgun",
"signature": {
"signature": hmac.new(
key=bytes(API_KEY, "utf-8"),
msg=bytes("{}{}".format(timestamp, token), "utf-8"),
msg=bytes(f"{timestamp}{token}", "utf-8"),
digestmod=hashlib.sha256,
).hexdigest(),
"timestamp": timestamp,

View File

@ -89,7 +89,7 @@ class TestMicrosoftFaceSetup:
self.config = {mf.DOMAIN: {"api_key": "12345678abcdef"}}
self.endpoint_url = "https://westus.{0}".format(mf.FACE_API_URL)
self.endpoint_url = f"https://westus.{mf.FACE_API_URL}"
def teardown_method(self):
"""Stop everything that was started."""

View File

@ -86,7 +86,7 @@ class TestMicrosoftFaceDetect:
mf.DOMAIN: {"api_key": "12345678abcdef6"},
}
self.endpoint_url = "https://westus.{0}".format(mf.FACE_API_URL)
self.endpoint_url = f"https://westus.{mf.FACE_API_URL}"
def teardown_method(self):
"""Stop everything that was started."""
@ -115,9 +115,7 @@ class TestMicrosoftFaceDetect:
setup_component(self.hass, ip.DOMAIN, self.config)
state = self.hass.states.get("camera.demo_camera")
url = "{0}{1}".format(
self.hass.config.api.base_url, state.attributes.get(ATTR_ENTITY_PICTURE)
)
url = f"{self.hass.config.api.base_url}{state.attributes.get(ATTR_ENTITY_PICTURE)}"
face_events = []

View File

@ -87,7 +87,7 @@ class TestMicrosoftFaceIdentify:
mf.DOMAIN: {"api_key": "12345678abcdef6"},
}
self.endpoint_url = "https://westus.{0}".format(mf.FACE_API_URL)
self.endpoint_url = f"https://westus.{mf.FACE_API_URL}"
def teardown_method(self):
"""Stop everything that was started."""
@ -116,9 +116,7 @@ class TestMicrosoftFaceIdentify:
setup_component(self.hass, ip.DOMAIN, self.config)
state = self.hass.states.get("camera.demo_camera")
url = "{0}{1}".format(
self.hass.config.api.base_url, state.attributes.get(ATTR_ENTITY_PICTURE)
)
url = f"{self.hass.config.api.base_url}{state.attributes.get(ATTR_ENTITY_PICTURE)}"
face_events = []

View File

@ -127,7 +127,7 @@ async def test_webhook_update_registration(webhook_client, authed_api_client):
update_container = {"type": "update_registration", "data": UPDATE}
update_resp = await webhook_client.post(
"/api/webhook/{}".format(webhook_id), json=update_container
f"/api/webhook/{webhook_id}", json=update_container
)
assert update_resp.status == 200
@ -263,7 +263,7 @@ async def test_webhook_enable_encryption(hass, webhook_client, create_registrati
webhook_id = create_registrations[1]["webhook_id"]
enable_enc_resp = await webhook_client.post(
"/api/webhook/{}".format(webhook_id), json={"type": "enable_encryption"},
f"/api/webhook/{webhook_id}", json={"type": "enable_encryption"},
)
assert enable_enc_resp.status == 200
@ -275,7 +275,7 @@ async def test_webhook_enable_encryption(hass, webhook_client, create_registrati
key = enable_enc_json["secret"]
enc_required_resp = await webhook_client.post(
"/api/webhook/{}".format(webhook_id), json=RENDER_TEMPLATE,
f"/api/webhook/{webhook_id}", json=RENDER_TEMPLATE,
)
assert enc_required_resp.status == 400
@ -293,9 +293,7 @@ async def test_webhook_enable_encryption(hass, webhook_client, create_registrati
"encrypted_data": enc_data,
}
enc_resp = await webhook_client.post(
"/api/webhook/{}".format(webhook_id), json=container
)
enc_resp = await webhook_client.post(f"/api/webhook/{webhook_id}", json=container)
assert enc_resp.status == 200

View File

@ -100,12 +100,12 @@ async def test_only_valid_components(hass, mqtt_mock, caplog):
await async_start(hass, "homeassistant", {}, entry)
async_fire_mqtt_message(
hass, "homeassistant/{}/bla/config".format(invalid_component), "{}"
hass, f"homeassistant/{invalid_component}/bla/config", "{}"
)
await hass.async_block_till_done()
assert "Integration {} is not supported".format(invalid_component) in caplog.text
assert f"Integration {invalid_component} is not supported" in caplog.text
assert not mock_dispatcher_send.called

View File

@ -96,7 +96,7 @@ class TestNSWFuelStation(unittest.TestCase):
fake_entities = ["my_fake_station_p95", "my_fake_station_e10"]
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
@patch(

View File

@ -18,16 +18,16 @@ from tests.common import (
USER = "greg"
DEVICE = "phone"
LOCATION_TOPIC = "owntracks/{}/{}".format(USER, DEVICE)
EVENT_TOPIC = "owntracks/{}/{}/event".format(USER, DEVICE)
WAYPOINTS_TOPIC = "owntracks/{}/{}/waypoints".format(USER, DEVICE)
WAYPOINT_TOPIC = "owntracks/{}/{}/waypoint".format(USER, DEVICE)
LOCATION_TOPIC = f"owntracks/{USER}/{DEVICE}"
EVENT_TOPIC = f"owntracks/{USER}/{DEVICE}/event"
WAYPOINTS_TOPIC = f"owntracks/{USER}/{DEVICE}/waypoints"
WAYPOINT_TOPIC = f"owntracks/{USER}/{DEVICE}/waypoint"
USER_BLACKLIST = "ram"
WAYPOINTS_TOPIC_BLOCKED = "owntracks/{}/{}/waypoints".format(USER_BLACKLIST, DEVICE)
LWT_TOPIC = "owntracks/{}/{}/lwt".format(USER, DEVICE)
BAD_TOPIC = "owntracks/{}/{}/unsupported".format(USER, DEVICE)
WAYPOINTS_TOPIC_BLOCKED = f"owntracks/{USER_BLACKLIST}/{DEVICE}/waypoints"
LWT_TOPIC = f"owntracks/{USER}/{DEVICE}/lwt"
BAD_TOPIC = f"owntracks/{USER}/{DEVICE}/unsupported"
DEVICE_TRACKER_STATE = "device_tracker.{}_{}".format(USER, DEVICE)
DEVICE_TRACKER_STATE = f"device_tracker.{USER}_{DEVICE}"
IBEACON_DEVICE = "keys"
MOBILE_BEACON_FMT = "device_tracker.beacon_{}"
@ -1510,7 +1510,7 @@ async def test_customized_mqtt_topic(hass, setup_comp):
"""Test subscribing to a custom mqtt topic."""
await setup_owntracks(hass, {CONF_MQTT_TOPIC: "mytracks/#"})
topic = "mytracks/{}/{}".format(USER, DEVICE)
topic = f"mytracks/{USER}/{DEVICE}"
await send_message(hass, topic, LOCATION_MESSAGE)
assert_location_latitude(hass, LOCATION_MESSAGE["lat"])

View File

@ -138,7 +138,7 @@ async def test_config_flow_entry_migrate(hass):
mock_entry = MOCK_ENTRY_VERSION_1
mock_entry.add_to_manager(manager)
mock_e_registry = mock_registry(hass)
mock_entity_id = "media_player.ps4_{}".format(MOCK_UNIQUE_ID)
mock_entity_id = f"media_player.ps4_{MOCK_UNIQUE_ID}"
mock_e_entry = mock_e_registry.async_get_or_create(
"media_player",
"ps4",
@ -278,7 +278,7 @@ async def test_send_command(hass):
mock_devices = hass.data[PS4_DATA].devices
assert len(mock_devices) == 1
mock_entity = mock_devices[0]
assert mock_entity.entity_id == "media_player.{}".format(MOCK_NAME)
assert mock_entity.entity_id == f"media_player.{MOCK_NAME}"
# Test that all commands call service function.
with patch(mock_func, return_value=mock_coro(True)) as mock_service:

View File

@ -426,6 +426,7 @@ async def test_if_fires_on_state_change_with_for(hass, calls):
await hass.async_block_till_done()
assert len(calls) == 1
await hass.async_block_till_done()
assert calls[0].data[
"some"
] == "turn_off device - {} - unknown - 11 - 0:00:05".format(sensor1.entity_id)
assert (
calls[0].data["some"]
== f"turn_off device - {sensor1.entity_id} - unknown - 11 - 0:00:05"
)

View File

@ -65,7 +65,7 @@ async def test_flow_works(hass):
},
)
assert result["type"] == "create_entry"
assert result["title"] == "Application {}".format(TEST_APP_ID)
assert result["title"] == f"Application {TEST_APP_ID}"
async def test_step_auth_app_code_falls(hass):

View File

@ -297,9 +297,7 @@ async def test_setup_component_and_test_with_service_options_def(hass, empty_cac
assert os.path.isfile(
os.path.join(
empty_cache_dir,
"42f18378fd4393d18c8dd11d03fa9563c1e54491_de_{0}_demo.mp3".format(
opt_hash
),
f"42f18378fd4393d18c8dd11d03fa9563c1e54491_de_{opt_hash}_demo.mp3",
)
)

View File

@ -31,9 +31,7 @@ async def test_config_flow_registers_webhook(hass, aiohttp_client):
hass.bus.async_listen(twilio.RECEIVED_DATA, handle_event)
client = await aiohttp_client(hass.http.app)
await client.post(
"/api/webhook/{}".format(webhook_id), data={"hello": "twilio"}
)
await client.post(f"/api/webhook/{webhook_id}", data={"hello": "twilio"})
assert len(twilio_events) == 1
assert twilio_events[0].data["webhook_id"] == webhook_id

View File

@ -271,14 +271,14 @@ def test_logarithm(hass):
for value, base, expected in tests:
assert (
template.Template(
"{{ %s | log(%s) | round(1) }}" % (value, base), hass
f"{{{{ {value} | log({base}) | round(1) }}}}", hass
).async_render()
== expected
)
assert (
template.Template(
"{{ log(%s, %s) | round(1) }}" % (value, base), hass
f"{{{{ log({value}, {base}) | round(1) }}}}", hass
).async_render()
== expected
)
@ -439,13 +439,13 @@ def test_arc_tan2(hass):
for y, x, expected in tests:
assert (
template.Template(
"{{ (%s, %s) | atan2 | round(3) }}" % (y, x), hass
f"{{{{ ({y}, {x}) | atan2 | round(3) }}}}", hass
).async_render()
== expected
)
assert (
template.Template(
"{{ atan2(%s, %s) | round(3) }}" % (y, x), hass
f"{{{{ atan2({y}, {x}) | round(3) }}}}", hass
).async_render()
== expected
)
@ -468,7 +468,7 @@ def test_strptime(hass):
if expected is None:
expected = datetime.strptime(inp, fmt)
temp = "{{ strptime('%s', '%s') }}" % (inp, fmt)
temp = f"{{{{ strptime('{inp}', '{fmt}') }}}}"
assert template.Template(temp, hass).async_render() == str(expected)
@ -492,9 +492,7 @@ def test_timestamp_custom(hass):
else:
fil = "timestamp_custom"
assert (
template.Template("{{ %s | %s }}" % (inp, fil), hass).async_render() == out
)
assert template.Template(f"{{{{ {inp} | {fil} }}}}", hass).async_render() == out
def test_timestamp_local(hass):