Use http.HTTPStatus in components/m* (#58251)

This commit is contained in:
Ville Skyttä 2021-10-23 00:54:36 +03:00 committed by GitHub
parent b49b975999
commit 77120a5137
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 119 additions and 112 deletions

View File

@ -31,9 +31,6 @@ from homeassistant.components.websocket_api.const import (
) )
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( from homeassistant.const import (
HTTP_NOT_FOUND,
HTTP_OK,
HTTP_UNAUTHORIZED,
SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_NEXT_TRACK,
SERVICE_MEDIA_PAUSE, SERVICE_MEDIA_PAUSE,
SERVICE_MEDIA_PLAY, SERVICE_MEDIA_PLAY,
@ -978,7 +975,7 @@ class MediaPlayerEntity(Entity):
websession = async_get_clientsession(self.hass) websession = async_get_clientsession(self.hass)
with suppress(asyncio.TimeoutError), async_timeout.timeout(10): with suppress(asyncio.TimeoutError), async_timeout.timeout(10):
response = await websession.get(url) response = await websession.get(url)
if response.status == HTTP_OK: if response.status == HTTPStatus.OK:
content = await response.read() content = await response.read()
if content_type := response.headers.get(CONTENT_TYPE): if content_type := response.headers.get(CONTENT_TYPE):
content_type = content_type.split(";")[0] content_type = content_type.split(";")[0]
@ -1031,7 +1028,11 @@ class MediaPlayerImageView(HomeAssistantView):
"""Start a get request.""" """Start a get request."""
player = self.component.get_entity(entity_id) player = self.component.get_entity(entity_id)
if player is None: if player is None:
status = HTTP_NOT_FOUND if request[KEY_AUTHENTICATED] else HTTP_UNAUTHORIZED status = (
HTTPStatus.NOT_FOUND
if request[KEY_AUTHENTICATED]
else HTTPStatus.UNAUTHORIZED
)
return web.Response(status=status) return web.Response(status=status)
authenticated = ( authenticated = (

View File

@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
from http import HTTPStatus
from aiohttp import ClientError, ClientResponseError from aiohttp import ClientError, ClientResponseError
from async_timeout import timeout from async_timeout import timeout
@ -9,13 +10,7 @@ import pymelcloud
import voluptuous as vol import voluptuous as vol
from homeassistant import config_entries from homeassistant import config_entries
from homeassistant.const import ( from homeassistant.const import CONF_PASSWORD, CONF_TOKEN, CONF_USERNAME
CONF_PASSWORD,
CONF_TOKEN,
CONF_USERNAME,
HTTP_FORBIDDEN,
HTTP_UNAUTHORIZED,
)
from .const import DOMAIN from .const import DOMAIN
@ -59,7 +54,7 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
self.hass.helpers.aiohttp_client.async_get_clientsession(), self.hass.helpers.aiohttp_client.async_get_clientsession(),
) )
except ClientResponseError as err: except ClientResponseError as err:
if err.status in (HTTP_UNAUTHORIZED, HTTP_FORBIDDEN): if err.status in (HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN):
return self.async_abort(reason="invalid_auth") return self.async_abort(reason="invalid_auth")
return self.async_abort(reason="cannot_connect") return self.async_abort(reason="cannot_connect")
except (asyncio.TimeoutError, ClientError): except (asyncio.TimeoutError, ClientError):

View File

@ -1,6 +1,7 @@
"""Support for mobile_app push notifications.""" """Support for mobile_app push notifications."""
import asyncio import asyncio
from functools import partial from functools import partial
from http import HTTPStatus
import logging import logging
import aiohttp import aiohttp
@ -14,12 +15,6 @@ from homeassistant.components.notify import (
ATTR_TITLE_DEFAULT, ATTR_TITLE_DEFAULT,
BaseNotificationService, BaseNotificationService,
) )
from homeassistant.const import (
HTTP_ACCEPTED,
HTTP_CREATED,
HTTP_OK,
HTTP_TOO_MANY_REQUESTS,
)
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
@ -160,7 +155,11 @@ class MobileAppNotificationService(BaseNotificationService):
) )
result = await response.json() result = await response.json()
if response.status in (HTTP_OK, HTTP_CREATED, HTTP_ACCEPTED): if response.status in (
HTTPStatus.OK,
HTTPStatus.CREATED,
HTTPStatus.ACCEPTED,
):
log_rate_limits(self.hass, entry_data[ATTR_DEVICE_NAME], result) log_rate_limits(self.hass, entry_data[ATTR_DEVICE_NAME], result)
return return
@ -175,7 +174,7 @@ class MobileAppNotificationService(BaseNotificationService):
message += "." message += "."
message += " This message is generated externally to Home Assistant." message += " This message is generated externally to Home Assistant."
if response.status == HTTP_TOO_MANY_REQUESTS: if response.status == HTTPStatus.TOO_MANY_REQUESTS:
_LOGGER.warning(message) _LOGGER.warning(message)
log_rate_limits( log_rate_limits(
self.hass, entry_data[ATTR_DEVICE_NAME], result, logging.WARNING self.hass, entry_data[ATTR_DEVICE_NAME], result, logging.WARNING

View File

@ -1,9 +1,9 @@
"""Support for the myStrom buttons.""" """Support for the myStrom buttons."""
from http import HTTPStatus
import logging import logging
from homeassistant.components.binary_sensor import DOMAIN, BinarySensorEntity from homeassistant.components.binary_sensor import DOMAIN, BinarySensorEntity
from homeassistant.components.http import HomeAssistantView from homeassistant.components.http import HomeAssistantView
from homeassistant.const import HTTP_UNPROCESSABLE_ENTITY
from homeassistant.core import callback from homeassistant.core import callback
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -42,7 +42,10 @@ class MyStromView(HomeAssistantView):
if button_action is None: if button_action is None:
_LOGGER.error("Received unidentified message from myStrom button: %s", data) _LOGGER.error("Received unidentified message from myStrom button: %s", data)
return (f"Received unidentified message: {data}", HTTP_UNPROCESSABLE_ENTITY) return (
f"Received unidentified message: {data}",
HTTPStatus.UNPROCESSABLE_ENTITY,
)
button_id = data[button_action] button_id = data[button_action]
entity_id = f"{DOMAIN}.{button_id}_{button_action}" entity_id = f"{DOMAIN}.{button_id}_{button_action}"

View File

@ -1,11 +1,11 @@
"""The tests for the mailbox component.""" """The tests for the mailbox component."""
from hashlib import sha1 from hashlib import sha1
from http import HTTPStatus
import pytest import pytest
from homeassistant.bootstrap import async_setup_component from homeassistant.bootstrap import async_setup_component
import homeassistant.components.mailbox as mailbox import homeassistant.components.mailbox as mailbox
from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR, HTTP_NOT_FOUND
@pytest.fixture @pytest.fixture
@ -21,7 +21,7 @@ async def test_get_platforms_from_mailbox(mock_http_client):
url = "/api/mailbox/platforms" url = "/api/mailbox/platforms"
req = await mock_http_client.get(url) req = await mock_http_client.get(url)
assert req.status == 200 assert req.status == HTTPStatus.OK
result = await req.json() result = await req.json()
assert len(result) == 1 assert len(result) == 1
assert result[0].get("name") == "DemoMailbox" assert result[0].get("name") == "DemoMailbox"
@ -32,7 +32,7 @@ async def test_get_messages_from_mailbox(mock_http_client):
url = "/api/mailbox/messages/DemoMailbox" url = "/api/mailbox/messages/DemoMailbox"
req = await mock_http_client.get(url) req = await mock_http_client.get(url)
assert req.status == 200 assert req.status == HTTPStatus.OK
result = await req.json() result = await req.json()
assert len(result) == 10 assert len(result) == 10
@ -45,7 +45,7 @@ async def test_get_media_from_mailbox(mock_http_client):
url = f"/api/mailbox/media/DemoMailbox/{msgsha}" url = f"/api/mailbox/media/DemoMailbox/{msgsha}"
req = await mock_http_client.get(url) req = await mock_http_client.get(url)
assert req.status == 200 assert req.status == HTTPStatus.OK
data = await req.read() data = await req.read()
assert sha1(data).hexdigest() == mp3sha assert sha1(data).hexdigest() == mp3sha
@ -60,11 +60,11 @@ async def test_delete_from_mailbox(mock_http_client):
for msg in [msgsha1, msgsha2]: for msg in [msgsha1, msgsha2]:
url = f"/api/mailbox/delete/DemoMailbox/{msg}" url = f"/api/mailbox/delete/DemoMailbox/{msg}"
req = await mock_http_client.delete(url) req = await mock_http_client.delete(url)
assert req.status == 200 assert req.status == HTTPStatus.OK
url = "/api/mailbox/messages/DemoMailbox" url = "/api/mailbox/messages/DemoMailbox"
req = await mock_http_client.get(url) req = await mock_http_client.get(url)
assert req.status == 200 assert req.status == HTTPStatus.OK
result = await req.json() result = await req.json()
assert len(result) == 8 assert len(result) == 8
@ -74,7 +74,7 @@ async def test_get_messages_from_invalid_mailbox(mock_http_client):
url = "/api/mailbox/messages/mailbox.invalid_mailbox" url = "/api/mailbox/messages/mailbox.invalid_mailbox"
req = await mock_http_client.get(url) req = await mock_http_client.get(url)
assert req.status == HTTP_NOT_FOUND assert req.status == HTTPStatus.NOT_FOUND
async def test_get_media_from_invalid_mailbox(mock_http_client): async def test_get_media_from_invalid_mailbox(mock_http_client):
@ -83,7 +83,7 @@ async def test_get_media_from_invalid_mailbox(mock_http_client):
url = f"/api/mailbox/media/mailbox.invalid_mailbox/{msgsha}" url = f"/api/mailbox/media/mailbox.invalid_mailbox/{msgsha}"
req = await mock_http_client.get(url) req = await mock_http_client.get(url)
assert req.status == HTTP_NOT_FOUND assert req.status == HTTPStatus.NOT_FOUND
async def test_get_media_from_invalid_msgid(mock_http_client): async def test_get_media_from_invalid_msgid(mock_http_client):
@ -92,7 +92,7 @@ async def test_get_media_from_invalid_msgid(mock_http_client):
url = f"/api/mailbox/media/DemoMailbox/{msgsha}" url = f"/api/mailbox/media/DemoMailbox/{msgsha}"
req = await mock_http_client.get(url) req = await mock_http_client.get(url)
assert req.status == HTTP_INTERNAL_SERVER_ERROR assert req.status == HTTPStatus.INTERNAL_SERVER_ERROR
async def test_delete_from_invalid_mailbox(mock_http_client): async def test_delete_from_invalid_mailbox(mock_http_client):
@ -101,4 +101,4 @@ async def test_delete_from_invalid_mailbox(mock_http_client):
url = f"/api/mailbox/delete/mailbox.invalid_mailbox/{msgsha}" url = f"/api/mailbox/delete/mailbox.invalid_mailbox/{msgsha}"
req = await mock_http_client.delete(url) req = await mock_http_client.delete(url)
assert req.status == HTTP_NOT_FOUND assert req.status == HTTPStatus.NOT_FOUND

View File

@ -1,4 +1,6 @@
"""Test Local Media Source.""" """Test Local Media Source."""
from http import HTTPStatus
import pytest import pytest
from homeassistant.components import media_source from homeassistant.components import media_source
@ -78,25 +80,25 @@ async def test_media_view(hass, hass_client):
# Protects against non-existent files # Protects against non-existent files
resp = await client.get("/media/local/invalid.txt") resp = await client.get("/media/local/invalid.txt")
assert resp.status == 404 assert resp.status == HTTPStatus.NOT_FOUND
resp = await client.get("/media/recordings/invalid.txt") resp = await client.get("/media/recordings/invalid.txt")
assert resp.status == 404 assert resp.status == HTTPStatus.NOT_FOUND
# Protects against non-media files # Protects against non-media files
resp = await client.get("/media/local/not_media.txt") resp = await client.get("/media/local/not_media.txt")
assert resp.status == 404 assert resp.status == HTTPStatus.NOT_FOUND
# Protects against unknown local media sources # Protects against unknown local media sources
resp = await client.get("/media/unknown_source/not_media.txt") resp = await client.get("/media/unknown_source/not_media.txt")
assert resp.status == 404 assert resp.status == HTTPStatus.NOT_FOUND
# Fetch available media # Fetch available media
resp = await client.get("/media/local/test.mp3") resp = await client.get("/media/local/test.mp3")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
resp = await client.get("/media/local/Epic Sax Guy 10 Hours.mp4") resp = await client.get("/media/local/Epic Sax Guy 10 Hours.mp4")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
resp = await client.get("/media/recordings/test.mp3") resp = await client.get("/media/recordings/test.mp3")
assert resp.status == 200 assert resp.status == HTTPStatus.OK

View File

@ -1,5 +1,6 @@
"""Test the MELCloud config flow.""" """Test the MELCloud config flow."""
import asyncio import asyncio
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
from aiohttp import ClientError, ClientResponseError from aiohttp import ClientError, ClientResponseError
@ -8,7 +9,6 @@ import pytest
from homeassistant import config_entries from homeassistant import config_entries
from homeassistant.components.melcloud.const import DOMAIN from homeassistant.components.melcloud.const import DOMAIN
from homeassistant.const import HTTP_FORBIDDEN, HTTP_INTERNAL_SERVER_ERROR
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
@ -95,9 +95,9 @@ async def test_form_errors(hass, mock_login, mock_get_devices, error, reason):
@pytest.mark.parametrize( @pytest.mark.parametrize(
"error,message", "error,message",
[ [
(401, "invalid_auth"), (HTTPStatus.UNAUTHORIZED, "invalid_auth"),
(HTTP_FORBIDDEN, "invalid_auth"), (HTTPStatus.FORBIDDEN, "invalid_auth"),
(HTTP_INTERNAL_SERVER_ERROR, "cannot_connect"), (HTTPStatus.INTERNAL_SERVER_ERROR, "cannot_connect"),
], ],
) )
async def test_form_response_errors( async def test_form_response_errors(

View File

@ -1,4 +1,5 @@
"""The tests the for Meraki device tracker.""" """The tests the for Meraki device tracker."""
from http import HTTPStatus
import json import json
import pytest import pytest
@ -37,35 +38,35 @@ async def test_invalid_or_missing_data(mock_device_tracker_conf, meraki_client):
"""Test validator with invalid or missing data.""" """Test validator with invalid or missing data."""
req = await meraki_client.get(URL) req = await meraki_client.get(URL)
text = await req.text() text = await req.text()
assert req.status == 200 assert req.status == HTTPStatus.OK
assert text == "validator" assert text == "validator"
req = await meraki_client.post(URL, data=b"invalid") req = await meraki_client.post(URL, data=b"invalid")
text = await req.json() text = await req.json()
assert req.status == 400 assert req.status == HTTPStatus.BAD_REQUEST
assert text["message"] == "Invalid JSON" assert text["message"] == "Invalid JSON"
req = await meraki_client.post(URL, data=b"{}") req = await meraki_client.post(URL, data=b"{}")
text = await req.json() text = await req.json()
assert req.status == 422 assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
assert text["message"] == "No secret" assert text["message"] == "No secret"
data = {"version": "1.0", "secret": "secret"} data = {"version": "1.0", "secret": "secret"}
req = await meraki_client.post(URL, data=json.dumps(data)) req = await meraki_client.post(URL, data=json.dumps(data))
text = await req.json() text = await req.json()
assert req.status == 422 assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
assert text["message"] == "Invalid version" assert text["message"] == "Invalid version"
data = {"version": "2.0", "secret": "invalid"} data = {"version": "2.0", "secret": "invalid"}
req = await meraki_client.post(URL, data=json.dumps(data)) req = await meraki_client.post(URL, data=json.dumps(data))
text = await req.json() text = await req.json()
assert req.status == 422 assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
assert text["message"] == "Invalid secret" assert text["message"] == "Invalid secret"
data = {"version": "2.0", "secret": "secret", "type": "InvalidType"} data = {"version": "2.0", "secret": "secret", "type": "InvalidType"}
req = await meraki_client.post(URL, data=json.dumps(data)) req = await meraki_client.post(URL, data=json.dumps(data))
text = await req.json() text = await req.json()
assert req.status == 422 assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
assert text["message"] == "Invalid device type" assert text["message"] == "Invalid device type"
data = { data = {
@ -75,7 +76,7 @@ async def test_invalid_or_missing_data(mock_device_tracker_conf, meraki_client):
"data": {"observations": []}, "data": {"observations": []},
} }
req = await meraki_client.post(URL, data=json.dumps(data)) req = await meraki_client.post(URL, data=json.dumps(data))
assert req.status == 200 assert req.status == HTTPStatus.OK
async def test_data_will_be_saved(mock_device_tracker_conf, hass, meraki_client): async def test_data_will_be_saved(mock_device_tracker_conf, hass, meraki_client):
@ -120,7 +121,7 @@ async def test_data_will_be_saved(mock_device_tracker_conf, hass, meraki_client)
}, },
} }
req = await meraki_client.post(URL, data=json.dumps(data)) req = await meraki_client.post(URL, data=json.dumps(data))
assert req.status == 200 assert req.status == HTTPStatus.OK
await hass.async_block_till_done() await hass.async_block_till_done()
state_name = hass.states.get( state_name = hass.states.get(
"{}.{}".format("device_tracker", "00_26_ab_b8_a9_a4") "{}.{}".format("device_tracker", "00_26_ab_b8_a9_a4")

View File

@ -1,4 +1,6 @@
"""Tests for mobile_app component.""" """Tests for mobile_app component."""
from http import HTTPStatus
# pylint: disable=redefined-outer-name,unused-import # pylint: disable=redefined-outer-name,unused-import
import pytest import pytest
@ -17,14 +19,14 @@ async def create_registrations(hass, authed_api_client):
"/api/mobile_app/registrations", json=REGISTER "/api/mobile_app/registrations", json=REGISTER
) )
assert enc_reg.status == 201 assert enc_reg.status == HTTPStatus.CREATED
enc_reg_json = await enc_reg.json() enc_reg_json = await enc_reg.json()
clear_reg = await authed_api_client.post( clear_reg = await authed_api_client.post(
"/api/mobile_app/registrations", json=REGISTER_CLEARTEXT "/api/mobile_app/registrations", json=REGISTER_CLEARTEXT
) )
assert clear_reg.status == 201 assert clear_reg.status == HTTPStatus.CREATED
clear_reg_json = await clear_reg.json() clear_reg_json = await clear_reg.json()
await hass.async_block_till_done() await hass.async_block_till_done()
@ -48,7 +50,7 @@ async def push_registration(hass, authed_api_client):
}, },
) )
assert enc_reg.status == 201 assert enc_reg.status == HTTPStatus.CREATED
return await enc_reg.json() return await enc_reg.json()

View File

@ -1,4 +1,6 @@
"""Entity tests for mobile_app.""" """Entity tests for mobile_app."""
from http import HTTPStatus
from homeassistant.const import STATE_OFF from homeassistant.const import STATE_OFF
from homeassistant.helpers import device_registry as dr from homeassistant.helpers import device_registry as dr
@ -24,7 +26,7 @@ async def test_sensor(hass, create_registrations, webhook_client):
}, },
) )
assert reg_resp.status == 201 assert reg_resp.status == HTTPStatus.CREATED
json = await reg_resp.json() json = await reg_resp.json()
assert json == {"success": True} assert json == {"success": True}
@ -61,7 +63,7 @@ async def test_sensor(hass, create_registrations, webhook_client):
}, },
) )
assert update_resp.status == 200 assert update_resp.status == HTTPStatus.OK
json = await update_resp.json() json = await update_resp.json()
assert json["invalid_state"]["success"] is False assert json["invalid_state"]["success"] is False
@ -101,7 +103,7 @@ async def test_sensor_must_register(hass, create_registrations, webhook_client):
}, },
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
json = await resp.json() json = await resp.json()
assert json["battery_state"]["success"] is False assert json["battery_state"]["success"] is False
@ -128,7 +130,7 @@ async def test_sensor_id_no_dupes(hass, create_registrations, webhook_client, ca
reg_resp = await webhook_client.post(webhook_url, json=payload) reg_resp = await webhook_client.post(webhook_url, json=payload)
assert reg_resp.status == 201 assert reg_resp.status == HTTPStatus.CREATED
reg_json = await reg_resp.json() reg_json = await reg_resp.json()
assert reg_json == {"success": True} assert reg_json == {"success": True}
@ -149,7 +151,7 @@ async def test_sensor_id_no_dupes(hass, create_registrations, webhook_client, ca
payload["data"]["state"] = False payload["data"]["state"] = False
dupe_resp = await webhook_client.post(webhook_url, json=payload) dupe_resp = await webhook_client.post(webhook_url, json=payload)
assert dupe_resp.status == 201 assert dupe_resp.status == HTTPStatus.CREATED
dupe_reg_json = await dupe_resp.json() dupe_reg_json = await dupe_resp.json()
assert dupe_reg_json == {"success": True} assert dupe_reg_json == {"success": True}
await hass.async_block_till_done() await hass.async_block_till_done()
@ -185,7 +187,7 @@ async def test_register_sensor_no_state(hass, create_registrations, webhook_clie
}, },
) )
assert reg_resp.status == 201 assert reg_resp.status == HTTPStatus.CREATED
json = await reg_resp.json() json = await reg_resp.json()
assert json == {"success": True} assert json == {"success": True}
@ -210,7 +212,7 @@ async def test_register_sensor_no_state(hass, create_registrations, webhook_clie
}, },
) )
assert reg_resp.status == 201 assert reg_resp.status == HTTPStatus.CREATED
json = await reg_resp.json() json = await reg_resp.json()
assert json == {"success": True} assert json == {"success": True}
@ -242,7 +244,7 @@ async def test_update_sensor_no_state(hass, create_registrations, webhook_client
}, },
) )
assert reg_resp.status == 201 assert reg_resp.status == HTTPStatus.CREATED
json = await reg_resp.json() json = await reg_resp.json()
assert json == {"success": True} assert json == {"success": True}
@ -262,7 +264,7 @@ async def test_update_sensor_no_state(hass, create_registrations, webhook_client
}, },
) )
assert update_resp.status == 200 assert update_resp.status == HTTPStatus.OK
json = await update_resp.json() json = await update_resp.json()
assert json == {"is_charging": {"success": True}} assert json == {"is_charging": {"success": True}}

View File

@ -1,5 +1,7 @@
"""Test mobile app device tracker.""" """Test mobile app device tracker."""
from http import HTTPStatus
async def test_sending_location(hass, create_registrations, webhook_client): async def test_sending_location(hass, create_registrations, webhook_client):
"""Test sending a location via a webhook.""" """Test sending a location via a webhook."""
@ -20,7 +22,7 @@ async def test_sending_location(hass, create_registrations, webhook_client):
}, },
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
await hass.async_block_till_done() await hass.async_block_till_done()
state = hass.states.get("device_tracker.test_1_2") state = hass.states.get("device_tracker.test_1_2")
assert state is not None assert state is not None
@ -53,7 +55,7 @@ async def test_sending_location(hass, create_registrations, webhook_client):
}, },
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
await hass.async_block_till_done() await hass.async_block_till_done()
state = hass.states.get("device_tracker.test_1_2") state = hass.states.get("device_tracker.test_1_2")
assert state is not None assert state is not None
@ -87,7 +89,7 @@ async def test_restoring_location(hass, create_registrations, webhook_client):
}, },
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
await hass.async_block_till_done() await hass.async_block_till_done()
state_1 = hass.states.get("device_tracker.test_1_2") state_1 = hass.states.get("device_tracker.test_1_2")
assert state_1 is not None assert state_1 is not None

View File

@ -1,4 +1,5 @@
"""Tests for the mobile_app HTTP API.""" """Tests for the mobile_app HTTP API."""
from http import HTTPStatus
import json import json
from unittest.mock import patch from unittest.mock import patch
@ -32,7 +33,7 @@ async def test_registration(hass, hass_client, hass_admin_user):
assert add_user_dev_track.mock_calls[0][1][1] == hass_admin_user.id assert add_user_dev_track.mock_calls[0][1][1] == hass_admin_user.id
assert add_user_dev_track.mock_calls[0][1][2] == "device_tracker.test_1" assert add_user_dev_track.mock_calls[0][1][2] == "device_tracker.test_1"
assert resp.status == 201 assert resp.status == HTTPStatus.CREATED
register_json = await resp.json() register_json = await resp.json()
assert CONF_WEBHOOK_ID in register_json assert CONF_WEBHOOK_ID in register_json
assert CONF_SECRET in register_json assert CONF_SECRET in register_json
@ -71,7 +72,7 @@ async def test_registration_encryption(hass, hass_client):
resp = await api_client.post("/api/mobile_app/registrations", json=REGISTER) resp = await api_client.post("/api/mobile_app/registrations", json=REGISTER)
assert resp.status == 201 assert resp.status == HTTPStatus.CREATED
register_json = await resp.json() register_json = await resp.json()
keylen = SecretBox.KEY_SIZE keylen = SecretBox.KEY_SIZE
@ -89,7 +90,7 @@ async def test_registration_encryption(hass, hass_client):
f"/api/webhook/{register_json[CONF_WEBHOOK_ID]}", json=container f"/api/webhook/{register_json[CONF_WEBHOOK_ID]}", json=container
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
webhook_json = await resp.json() webhook_json = await resp.json()
assert "encrypted_data" in webhook_json assert "encrypted_data" in webhook_json

View File

@ -1,4 +1,6 @@
"""Entity tests for mobile_app.""" """Entity tests for mobile_app."""
from http import HTTPStatus
from homeassistant.const import PERCENTAGE, STATE_UNKNOWN from homeassistant.const import PERCENTAGE, STATE_UNKNOWN
from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers import device_registry as dr, entity_registry as er
@ -27,7 +29,7 @@ async def test_sensor(hass, create_registrations, webhook_client):
}, },
) )
assert reg_resp.status == 201 assert reg_resp.status == HTTPStatus.CREATED
json = await reg_resp.json() json = await reg_resp.json()
assert json == {"success": True} assert json == {"success": True}
@ -67,7 +69,7 @@ async def test_sensor(hass, create_registrations, webhook_client):
}, },
) )
assert update_resp.status == 200 assert update_resp.status == HTTPStatus.OK
json = await update_resp.json() json = await update_resp.json()
assert json["invalid_state"]["success"] is False assert json["invalid_state"]["success"] is False
@ -105,7 +107,7 @@ async def test_sensor_must_register(hass, create_registrations, webhook_client):
}, },
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
json = await resp.json() json = await resp.json()
assert json["battery_state"]["success"] is False assert json["battery_state"]["success"] is False
@ -133,7 +135,7 @@ async def test_sensor_id_no_dupes(hass, create_registrations, webhook_client, ca
reg_resp = await webhook_client.post(webhook_url, json=payload) reg_resp = await webhook_client.post(webhook_url, json=payload)
assert reg_resp.status == 201 assert reg_resp.status == HTTPStatus.CREATED
reg_json = await reg_resp.json() reg_json = await reg_resp.json()
assert reg_json == {"success": True} assert reg_json == {"success": True}
@ -155,7 +157,7 @@ async def test_sensor_id_no_dupes(hass, create_registrations, webhook_client, ca
payload["data"]["state"] = 99 payload["data"]["state"] = 99
dupe_resp = await webhook_client.post(webhook_url, json=payload) dupe_resp = await webhook_client.post(webhook_url, json=payload)
assert dupe_resp.status == 201 assert dupe_resp.status == HTTPStatus.CREATED
dupe_reg_json = await dupe_resp.json() dupe_reg_json = await dupe_resp.json()
assert dupe_reg_json == {"success": True} assert dupe_reg_json == {"success": True}
await hass.async_block_till_done() await hass.async_block_till_done()
@ -192,7 +194,7 @@ async def test_register_sensor_no_state(hass, create_registrations, webhook_clie
}, },
) )
assert reg_resp.status == 201 assert reg_resp.status == HTTPStatus.CREATED
json = await reg_resp.json() json = await reg_resp.json()
assert json == {"success": True} assert json == {"success": True}
@ -217,7 +219,7 @@ async def test_register_sensor_no_state(hass, create_registrations, webhook_clie
}, },
) )
assert reg_resp.status == 201 assert reg_resp.status == HTTPStatus.CREATED
json = await reg_resp.json() json = await reg_resp.json()
assert json == {"success": True} assert json == {"success": True}
@ -249,7 +251,7 @@ async def test_update_sensor_no_state(hass, create_registrations, webhook_client
}, },
) )
assert reg_resp.status == 201 assert reg_resp.status == HTTPStatus.CREATED
json = await reg_resp.json() json = await reg_resp.json()
assert json == {"success": True} assert json == {"success": True}
@ -267,7 +269,7 @@ async def test_update_sensor_no_state(hass, create_registrations, webhook_client
}, },
) )
assert update_resp.status == 200 assert update_resp.status == HTTPStatus.OK
json = await update_resp.json() json = await update_resp.json()
assert json == {"battery_state": {"success": True}} assert json == {"battery_state": {"success": True}}

View File

@ -1,4 +1,5 @@
"""Webhook tests for mobile_app.""" """Webhook tests for mobile_app."""
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
import pytest import pytest
@ -76,7 +77,7 @@ async def test_webhook_handle_render_template(create_registrations, webhook_clie
}, },
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
json = await resp.json() json = await resp.json()
assert json == { assert json == {
@ -97,7 +98,7 @@ async def test_webhook_handle_call_services(hass, create_registrations, webhook_
json=CALL_SERVICE, json=CALL_SERVICE,
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert len(calls) == 1 assert len(calls) == 1
@ -117,7 +118,7 @@ async def test_webhook_handle_fire_event(hass, create_registrations, webhook_cli
"/api/webhook/{}".format(create_registrations[1]["webhook_id"]), json=FIRE_EVENT "/api/webhook/{}".format(create_registrations[1]["webhook_id"]), json=FIRE_EVENT
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
json = await resp.json() json = await resp.json()
assert json == {} assert json == {}
@ -131,7 +132,7 @@ async def test_webhook_update_registration(webhook_client, authed_api_client):
"/api/mobile_app/registrations", json=REGISTER_CLEARTEXT "/api/mobile_app/registrations", json=REGISTER_CLEARTEXT
) )
assert register_resp.status == 201 assert register_resp.status == HTTPStatus.CREATED
register_json = await register_resp.json() register_json = await register_resp.json()
webhook_id = register_json[CONF_WEBHOOK_ID] webhook_id = register_json[CONF_WEBHOOK_ID]
@ -142,7 +143,7 @@ async def test_webhook_update_registration(webhook_client, authed_api_client):
f"/api/webhook/{webhook_id}", json=update_container f"/api/webhook/{webhook_id}", json=update_container
) )
assert update_resp.status == 200 assert update_resp.status == HTTPStatus.OK
update_json = await update_resp.json() update_json = await update_resp.json()
assert update_json["app_version"] == "2.0.0" assert update_json["app_version"] == "2.0.0"
assert CONF_WEBHOOK_ID not in update_json assert CONF_WEBHOOK_ID not in update_json
@ -180,7 +181,7 @@ async def test_webhook_handle_get_zones(hass, create_registrations, webhook_clie
json={"type": "get_zones"}, json={"type": "get_zones"},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
json = await resp.json() json = await resp.json()
assert len(json) == 3 assert len(json) == 3
@ -206,7 +207,7 @@ async def test_webhook_handle_get_config(hass, create_registrations, webhook_cli
json={"type": "get_config"}, json={"type": "get_config"},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
json = await resp.json() json = await resp.json()
if "components" in json: if "components" in json:
@ -239,7 +240,7 @@ async def test_webhook_returns_error_incorrect_json(
"/api/webhook/{}".format(create_registrations[1]["webhook_id"]), data="not json" "/api/webhook/{}".format(create_registrations[1]["webhook_id"]), data="not json"
) )
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
json = await resp.json() json = await resp.json()
assert json == {} assert json == {}
assert "invalid JSON" in caplog.text assert "invalid JSON" in caplog.text
@ -256,7 +257,7 @@ async def test_webhook_handle_decryption(webhook_client, create_registrations):
"/api/webhook/{}".format(create_registrations[0]["webhook_id"]), json=container "/api/webhook/{}".format(create_registrations[0]["webhook_id"]), json=container
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
webhook_json = await resp.json() webhook_json = await resp.json()
assert "encrypted_data" in webhook_json assert "encrypted_data" in webhook_json
@ -273,7 +274,7 @@ async def test_webhook_requires_encryption(webhook_client, create_registrations)
json=RENDER_TEMPLATE, json=RENDER_TEMPLATE,
) )
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
webhook_json = await resp.json() webhook_json = await resp.json()
assert "error" in webhook_json assert "error" in webhook_json
@ -291,7 +292,7 @@ async def test_webhook_update_location(hass, webhook_client, create_registration
}, },
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
state = hass.states.get("device_tracker.test_1_2") state = hass.states.get("device_tracker.test_1_2")
assert state is not None assert state is not None
@ -310,7 +311,7 @@ async def test_webhook_enable_encryption(hass, webhook_client, create_registrati
json={"type": "enable_encryption"}, json={"type": "enable_encryption"},
) )
assert enable_enc_resp.status == 200 assert enable_enc_resp.status == HTTPStatus.OK
enable_enc_json = await enable_enc_resp.json() enable_enc_json = await enable_enc_resp.json()
assert len(enable_enc_json) == 1 assert len(enable_enc_json) == 1
@ -323,7 +324,7 @@ async def test_webhook_enable_encryption(hass, webhook_client, create_registrati
json=RENDER_TEMPLATE, json=RENDER_TEMPLATE,
) )
assert enc_required_resp.status == 400 assert enc_required_resp.status == HTTPStatus.BAD_REQUEST
enc_required_json = await enc_required_resp.json() enc_required_json = await enc_required_resp.json()
assert "error" in enc_required_json assert "error" in enc_required_json
@ -340,7 +341,7 @@ async def test_webhook_enable_encryption(hass, webhook_client, create_registrati
enc_resp = await webhook_client.post(f"/api/webhook/{webhook_id}", json=container) enc_resp = await webhook_client.post(f"/api/webhook/{webhook_id}", json=container)
assert enc_resp.status == 200 assert enc_resp.status == HTTPStatus.OK
enc_json = await enc_resp.json() enc_json = await enc_resp.json()
assert "encrypted_data" in enc_json assert "encrypted_data" in enc_json
@ -364,7 +365,7 @@ async def test_webhook_camera_stream_non_existent(
}, },
) )
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
webhook_json = await resp.json() webhook_json = await resp.json()
assert webhook_json["success"] is False assert webhook_json["success"] is False
@ -385,7 +386,7 @@ async def test_webhook_camera_stream_non_hls(
}, },
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
webhook_json = await resp.json() webhook_json = await resp.json()
assert webhook_json["hls_path"] is None assert webhook_json["hls_path"] is None
assert ( assert (
@ -416,7 +417,7 @@ async def test_webhook_camera_stream_stream_available(
}, },
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
webhook_json = await resp.json() webhook_json = await resp.json()
assert webhook_json["hls_path"] == "/api/streams/some_hls_stream" assert webhook_json["hls_path"] == "/api/streams/some_hls_stream"
assert webhook_json["mjpeg_path"] == "/api/camera_proxy_stream/camera.stream_camera" assert webhook_json["mjpeg_path"] == "/api/camera_proxy_stream/camera.stream_camera"
@ -444,7 +445,7 @@ async def test_webhook_camera_stream_stream_available_but_errors(
}, },
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
webhook_json = await resp.json() webhook_json = await resp.json()
assert webhook_json["hls_path"] is None assert webhook_json["hls_path"] is None
assert webhook_json["mjpeg_path"] == "/api/camera_proxy_stream/camera.stream_camera" assert webhook_json["mjpeg_path"] == "/api/camera_proxy_stream/camera.stream_camera"
@ -466,7 +467,7 @@ async def test_webhook_handle_scan_tag(hass, create_registrations, webhook_clien
json={"type": "scan_tag", "data": {"tag_id": "mock-tag-id"}}, json={"type": "scan_tag", "data": {"tag_id": "mock-tag-id"}},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
json = await resp.json() json = await resp.json()
assert json == {} assert json == {}
@ -496,7 +497,7 @@ async def test_register_sensor_limits_state_class(
}, },
) )
assert reg_resp.status == 201 assert reg_resp.status == HTTPStatus.CREATED
reg_resp = await webhook_client.post( reg_resp = await webhook_client.post(
webhook_url, webhook_url,
@ -513,4 +514,4 @@ async def test_register_sensor_limits_state_class(
) )
# This means it was ignored. # This means it was ignored.
assert reg_resp.status == 200 assert reg_resp.status == HTTPStatus.OK

View File

@ -1,5 +1,6 @@
"""Test the motionEye camera web hooks.""" """Test the motionEye camera web hooks."""
import copy import copy
from http import HTTPStatus
from typing import Any from typing import Any
from unittest.mock import AsyncMock, call, patch from unittest.mock import AsyncMock, call, patch
@ -22,13 +23,7 @@ from homeassistant.components.motioneye.const import (
EVENT_MOTION_DETECTED, EVENT_MOTION_DETECTED,
) )
from homeassistant.components.webhook import URL_WEBHOOK_PATH from homeassistant.components.webhook import URL_WEBHOOK_PATH
from homeassistant.const import ( from homeassistant.const import ATTR_DEVICE_ID, CONF_URL, CONF_WEBHOOK_ID
ATTR_DEVICE_ID,
CONF_URL,
CONF_WEBHOOK_ID,
HTTP_BAD_REQUEST,
HTTP_OK,
)
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.network import NoURLAvailableError from homeassistant.helpers.network import NoURLAvailableError
@ -308,7 +303,7 @@ async def test_good_query(hass: HomeAssistant, hass_client_no_auth: Any) -> None
ATTR_EVENT_TYPE: event, ATTR_EVENT_TYPE: event,
}, },
) )
assert resp.status == HTTP_OK assert resp.status == HTTPStatus.OK
assert len(events) == 1 assert len(events) == 1
assert events[0].data == { assert events[0].data == {
@ -332,7 +327,7 @@ async def test_bad_query_missing_parameters(
resp = await client.post( resp = await client.post(
URL_WEBHOOK_PATH.format(webhook_id=config_entry.data[CONF_WEBHOOK_ID]), json={} URL_WEBHOOK_PATH.format(webhook_id=config_entry.data[CONF_WEBHOOK_ID]), json={}
) )
assert resp.status == HTTP_BAD_REQUEST assert resp.status == HTTPStatus.BAD_REQUEST
async def test_bad_query_no_such_device( async def test_bad_query_no_such_device(
@ -351,7 +346,7 @@ async def test_bad_query_no_such_device(
ATTR_DEVICE_ID: "not-a-real-device", ATTR_DEVICE_ID: "not-a-real-device",
}, },
) )
assert resp.status == HTTP_BAD_REQUEST assert resp.status == HTTPStatus.BAD_REQUEST
async def test_bad_query_cannot_decode( async def test_bad_query_cannot_decode(
@ -370,6 +365,6 @@ async def test_bad_query_cannot_decode(
URL_WEBHOOK_PATH.format(webhook_id=config_entry.data[CONF_WEBHOOK_ID]), URL_WEBHOOK_PATH.format(webhook_id=config_entry.data[CONF_WEBHOOK_ID]),
data=b"this is not json", data=b"this is not json",
) )
assert resp.status == HTTP_BAD_REQUEST assert resp.status == HTTPStatus.BAD_REQUEST
assert not motion_events assert not motion_events
assert not storage_events assert not storage_events

View File

@ -1,4 +1,5 @@
"""The tests for mqtt camera component.""" """The tests for mqtt camera component."""
from http import HTTPStatus
import json import json
from unittest.mock import patch from unittest.mock import patch
@ -56,7 +57,7 @@ async def test_run_camera_setup(hass, hass_client_no_auth, mqtt_mock):
client = await hass_client_no_auth() client = await hass_client_no_auth()
resp = await client.get(url) resp = await client.get(url)
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.text() body = await resp.text()
assert body == "beer" assert body == "beer"