Use http.HTTPStatus in components/[gh]* (#58246)

This commit is contained in:
Ville Skyttä 2021-10-23 21:34:53 +03:00 committed by GitHub
parent 583ae3c953
commit b52c5c82b1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
38 changed files with 272 additions and 247 deletions

View File

@ -4,6 +4,7 @@ from __future__ import annotations
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from asyncio import gather from asyncio import gather
from collections.abc import Mapping from collections.abc import Mapping
from http import HTTPStatus
import logging import logging
import pprint import pprint
@ -203,7 +204,7 @@ class AbstractConfig(ABC):
# Remove any pending sync # Remove any pending sync
self._google_sync_unsub.pop(agent_user_id, lambda: None)() self._google_sync_unsub.pop(agent_user_id, lambda: None)()
status = await self._async_request_sync_devices(agent_user_id) status = await self._async_request_sync_devices(agent_user_id)
if status == 404: if status == HTTPStatus.NOT_FOUND:
await self.async_disconnect_agent_user(agent_user_id) await self.async_disconnect_agent_user(agent_user_id)
return status return status

View File

@ -1,6 +1,7 @@
"""Support for Google Actions Smart Home Control.""" """Support for Google Actions Smart Home Control."""
import asyncio import asyncio
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
import logging import logging
from uuid import uuid4 from uuid import uuid4
@ -14,8 +15,6 @@ from homeassistant.const import (
CLOUD_NEVER_EXPOSED_ENTITIES, CLOUD_NEVER_EXPOSED_ENTITIES,
ENTITY_CATEGORY_CONFIG, ENTITY_CATEGORY_CONFIG,
ENTITY_CATEGORY_DIAGNOSTIC, ENTITY_CATEGORY_DIAGNOSTIC,
HTTP_INTERNAL_SERVER_ERROR,
HTTP_UNAUTHORIZED,
) )
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
@ -157,7 +156,7 @@ class GoogleConfig(AbstractConfig):
) )
_LOGGER.error("No configuration for request_sync available") _LOGGER.error("No configuration for request_sync available")
return HTTP_INTERNAL_SERVER_ERROR return HTTPStatus.INTERNAL_SERVER_ERROR
async def _async_update_token(self, force=False): async def _async_update_token(self, force=False):
if CONF_SERVICE_ACCOUNT not in self._config: if CONF_SERVICE_ACCOUNT not in self._config:
@ -198,7 +197,7 @@ class GoogleConfig(AbstractConfig):
try: try:
return await _call() return await _call()
except ClientResponseError as error: except ClientResponseError as error:
if error.status == HTTP_UNAUTHORIZED: if error.status == HTTPStatus.UNAUTHORIZED:
_LOGGER.warning( _LOGGER.warning(
"Request for %s unauthorized, renewing token and retrying", url "Request for %s unauthorized, renewing token and retrying", url
) )
@ -210,7 +209,7 @@ class GoogleConfig(AbstractConfig):
return error.status return error.status
except (asyncio.TimeoutError, ClientError): except (asyncio.TimeoutError, ClientError):
_LOGGER.error("Could not contact %s", url) _LOGGER.error("Could not contact %s", url)
return HTTP_INTERNAL_SERVER_ERROR return HTTPStatus.INTERNAL_SERVER_ERROR
async def async_report_state(self, message, agent_user_id: str): async def async_report_state(self, message, agent_user_id: str):
"""Send a state report to Google.""" """Send a state report to Google."""

View File

@ -1,12 +1,13 @@
"""Support for Habitica sensors.""" """Support for Habitica sensors."""
from collections import namedtuple from collections import namedtuple
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
import logging import logging
from aiohttp import ClientResponseError from aiohttp import ClientResponseError
from homeassistant.components.sensor import SensorEntity from homeassistant.components.sensor import SensorEntity
from homeassistant.const import CONF_NAME, HTTP_TOO_MANY_REQUESTS from homeassistant.const import CONF_NAME
from homeassistant.util import Throttle from homeassistant.util import Throttle
from .const import DOMAIN from .const import DOMAIN
@ -94,7 +95,7 @@ class HabitipyData:
try: try:
self.data = await self.api.user.get() self.data = await self.api.user.get()
except ClientResponseError as error: except ClientResponseError as error:
if error.status == HTTP_TOO_MANY_REQUESTS: if error.status == HTTPStatus.TOO_MANY_REQUESTS:
_LOGGER.warning( _LOGGER.warning(
"Sensor data update for %s has too many API requests;" "Sensor data update for %s has too many API requests;"
" Skipping the update", " Skipping the update",
@ -111,7 +112,7 @@ class HabitipyData:
try: try:
self.tasks[task_type] = await self.api.tasks.user.get(type=task_type) self.tasks[task_type] = await self.api.tasks.user.get(type=task_type)
except ClientResponseError as error: except ClientResponseError as error:
if error.status == HTTP_TOO_MANY_REQUESTS: if error.status == HTTPStatus.TOO_MANY_REQUESTS:
_LOGGER.warning( _LOGGER.warning(
"Sensor data update for %s has too many API requests;" "Sensor data update for %s has too many API requests;"
" Skipping the update", " Skipping the update",

View File

@ -1,6 +1,7 @@
"""The Hangouts Bot.""" """The Hangouts Bot."""
import asyncio import asyncio
from contextlib import suppress from contextlib import suppress
from http import HTTPStatus
import io import io
import logging import logging
@ -8,7 +9,6 @@ import aiohttp
import hangups import hangups
from hangups import ChatMessageEvent, ChatMessageSegment, Client, get_auth, hangouts_pb2 from hangups import ChatMessageEvent, ChatMessageSegment, Client, get_auth, hangouts_pb2
from homeassistant.const import HTTP_OK
from homeassistant.core import callback from homeassistant.core import callback
from homeassistant.helpers import dispatcher, intent from homeassistant.helpers import dispatcher, intent
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
@ -273,7 +273,7 @@ class HangoutsBot:
try: try:
websession = async_get_clientsession(self.hass) websession = async_get_clientsession(self.hass)
async with websession.get(uri, timeout=5) as response: async with websession.get(uri, timeout=5) as response:
if response.status != HTTP_OK: if response.status != HTTPStatus.OK:
_LOGGER.error( _LOGGER.error(
"Fetch image failed, %s, %s", response.status, response "Fetch image failed, %s, %s", response.status, response
) )

View File

@ -1,5 +1,6 @@
"""Handler for Hass.io.""" """Handler for Hass.io."""
import asyncio import asyncio
from http import HTTPStatus
import logging import logging
import os import os
@ -10,7 +11,7 @@ from homeassistant.components.http import (
CONF_SERVER_PORT, CONF_SERVER_PORT,
CONF_SSL_CERTIFICATE, CONF_SSL_CERTIFICATE,
) )
from homeassistant.const import HTTP_BAD_REQUEST, HTTP_OK, SERVER_PORT from homeassistant.const import SERVER_PORT
from .const import X_HASSIO from .const import X_HASSIO
@ -225,7 +226,7 @@ class HassIO:
timeout=aiohttp.ClientTimeout(total=timeout), timeout=aiohttp.ClientTimeout(total=timeout),
) )
if request.status not in (HTTP_OK, HTTP_BAD_REQUEST): if request.status not in (HTTPStatus.OK, HTTPStatus.BAD_REQUEST):
_LOGGER.error("%s return code %d", command, request.status) _LOGGER.error("%s return code %d", command, request.status)
raise HassioAPIError() raise HassioAPIError()

View File

@ -1,5 +1,6 @@
"""Support for haveibeenpwned (email breaches) sensor.""" """Support for haveibeenpwned (email breaches) sensor."""
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
import logging import logging
from aiohttp.hdrs import USER_AGENT from aiohttp.hdrs import USER_AGENT
@ -7,13 +8,7 @@ import requests
import voluptuous as vol import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import ( from homeassistant.const import ATTR_ATTRIBUTION, CONF_API_KEY, CONF_EMAIL
ATTR_ATTRIBUTION,
CONF_API_KEY,
CONF_EMAIL,
HTTP_NOT_FOUND,
HTTP_OK,
)
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import track_point_in_time from homeassistant.helpers.event import track_point_in_time
from homeassistant.util import Throttle from homeassistant.util import Throttle
@ -163,7 +158,7 @@ class HaveIBeenPwnedData:
_LOGGER.error("Failed fetching data for %s", self._email) _LOGGER.error("Failed fetching data for %s", self._email)
return return
if req.status_code == HTTP_OK: if req.status_code == HTTPStatus.OK:
self.data[self._email] = sorted( self.data[self._email] = sorted(
req.json(), key=lambda k: k["AddedDate"], reverse=True req.json(), key=lambda k: k["AddedDate"], reverse=True
) )
@ -172,7 +167,7 @@ class HaveIBeenPwnedData:
# the forced updates try this current email again # the forced updates try this current email again
self.set_next_email() self.set_next_email()
elif req.status_code == HTTP_NOT_FOUND: elif req.status_code == HTTPStatus.NOT_FOUND:
self.data[self._email] = [] self.data[self._email] = []
# only goto next email if we had data so that # only goto next email if we had data so that

View File

@ -1,5 +1,6 @@
"""Support for the Hitron CODA-4582U, provided by Rogers.""" """Support for the Hitron CODA-4582U, provided by Rogers."""
from collections import namedtuple from collections import namedtuple
from http import HTTPStatus
import logging import logging
import requests import requests
@ -10,13 +11,7 @@ from homeassistant.components.device_tracker import (
PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA,
DeviceScanner, DeviceScanner,
) )
from homeassistant.const import ( from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_TYPE, CONF_USERNAME
CONF_HOST,
CONF_PASSWORD,
CONF_TYPE,
CONF_USERNAME,
HTTP_OK,
)
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -88,7 +83,7 @@ class HitronCODADeviceScanner(DeviceScanner):
except requests.exceptions.Timeout: except requests.exceptions.Timeout:
_LOGGER.error("Connection to the router timed out at URL %s", self._url) _LOGGER.error("Connection to the router timed out at URL %s", self._url)
return False return False
if res.status_code != HTTP_OK: if res.status_code != HTTPStatus.OK:
_LOGGER.error("Connection failed with http code %s", res.status_code) _LOGGER.error("Connection failed with http code %s", res.status_code)
return False return False
try: try:
@ -113,7 +108,7 @@ class HitronCODADeviceScanner(DeviceScanner):
except requests.exceptions.Timeout: except requests.exceptions.Timeout:
_LOGGER.error("Connection to the router timed out at URL %s", self._url) _LOGGER.error("Connection to the router timed out at URL %s", self._url)
return False return False
if res.status_code != HTTP_OK: if res.status_code != HTTPStatus.OK:
_LOGGER.error("Connection failed with http code %s", res.status_code) _LOGGER.error("Connection failed with http code %s", res.status_code)
return False return False
try: try:

View File

@ -5,6 +5,7 @@ from collections import defaultdict
from collections.abc import Awaitable, Callable from collections.abc import Awaitable, Callable
from contextlib import suppress from contextlib import suppress
from datetime import datetime from datetime import datetime
from http import HTTPStatus
from ipaddress import ip_address from ipaddress import ip_address
import logging import logging
from socket import gethostbyaddr, herror from socket import gethostbyaddr, herror
@ -15,7 +16,6 @@ from aiohttp.web_exceptions import HTTPForbidden, HTTPUnauthorized
import voluptuous as vol import voluptuous as vol
from homeassistant.config import load_yaml_config_file from homeassistant.config import load_yaml_config_file
from homeassistant.const import HTTP_BAD_REQUEST
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -89,9 +89,9 @@ def log_invalid_auth(
async def handle_req( async def handle_req(
view: HomeAssistantView, request: Request, *args: Any, **kwargs: Any view: HomeAssistantView, request: Request, *args: Any, **kwargs: Any
) -> StreamResponse: ) -> StreamResponse:
"""Try to log failed login attempts if response status >= 400.""" """Try to log failed login attempts if response status >= BAD_REQUEST."""
resp = await func(view, request, *args, **kwargs) resp = await func(view, request, *args, **kwargs)
if resp.status >= HTTP_BAD_REQUEST: if resp.status >= HTTPStatus.BAD_REQUEST:
await process_wrong_login(request) await process_wrong_login(request)
return resp return resp

View File

@ -19,7 +19,7 @@ from aiohttp.web_urldispatcher import AbstractRoute
import voluptuous as vol import voluptuous as vol
from homeassistant import exceptions from homeassistant import exceptions
from homeassistant.const import CONTENT_TYPE_JSON, HTTP_OK from homeassistant.const import CONTENT_TYPE_JSON
from homeassistant.core import Context, is_callback from homeassistant.core import Context, is_callback
from homeassistant.helpers.json import JSONEncoder from homeassistant.helpers.json import JSONEncoder
@ -144,7 +144,7 @@ def request_handler_factory(
# The method handler returned a ready-made Response, how nice of it # The method handler returned a ready-made Response, how nice of it
return result return result
status_code = HTTP_OK status_code = HTTPStatus.OK
if isinstance(result, tuple): if isinstance(result, tuple):
result, status_code = result result, status_code = result

View File

@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio import asyncio
from functools import partial from functools import partial
from http import HTTPStatus
import logging import logging
from aiohttp import client_exceptions from aiohttp import client_exceptions
@ -11,7 +12,6 @@ import async_timeout
import slugify as unicode_slug import slugify as unicode_slug
from homeassistant import core from homeassistant import core
from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR
from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import aiohttp_client from homeassistant.helpers import aiohttp_client
@ -148,7 +148,7 @@ class HueBridge:
# We only retry if it's a server error. So raise on all 4XX errors. # We only retry if it's a server error. So raise on all 4XX errors.
if ( if (
isinstance(err, client_exceptions.ClientResponseError) isinstance(err, client_exceptions.ClientResponseError)
and err.status < HTTP_INTERNAL_SERVER_ERROR and err.status < HTTPStatus.INTERNAL_SERVER_ERROR
): ):
raise raise

View File

@ -1,4 +1,5 @@
"""Test the Garages Amsterdam config flow.""" """Test the Garages Amsterdam config flow."""
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
from aiohttp import ClientResponseError from aiohttp import ClientResponseError
@ -44,7 +45,10 @@ async def test_full_flow(hass: HomeAssistant) -> None:
"side_effect,reason", "side_effect,reason",
[ [
(RuntimeError, "unknown"), (RuntimeError, "unknown"),
(ClientResponseError(None, None, status=500), "cannot_connect"), (
ClientResponseError(None, None, status=HTTPStatus.INTERNAL_SERVER_ERROR),
"cannot_connect",
),
], ],
) )
async def test_error_handling( async def test_error_handling(

View File

@ -1,5 +1,6 @@
"""The tests for generic camera component.""" """The tests for generic camera component."""
import asyncio import asyncio
from http import HTTPStatus
from os import path from os import path
from unittest.mock import patch from unittest.mock import patch
@ -9,11 +10,7 @@ import respx
from homeassistant import config as hass_config from homeassistant import config as hass_config
from homeassistant.components.generic import DOMAIN from homeassistant.components.generic import DOMAIN
from homeassistant.components.websocket_api.const import TYPE_RESULT from homeassistant.components.websocket_api.const import TYPE_RESULT
from homeassistant.const import ( from homeassistant.const import SERVICE_RELOAD
HTTP_INTERNAL_SERVER_ERROR,
HTTP_NOT_FOUND,
SERVICE_RELOAD,
)
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -41,7 +38,7 @@ async def test_fetching_url(hass, hass_client):
resp = await client.get("/api/camera_proxy/camera.config_test") resp = await client.get("/api/camera_proxy/camera.config_test")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert respx.calls.call_count == 1 assert respx.calls.call_count == 1
body = await resp.text() body = await resp.text()
assert body == "hello world" assert body == "hello world"
@ -75,7 +72,7 @@ async def test_fetching_without_verify_ssl(hass, hass_client):
resp = await client.get("/api/camera_proxy/camera.config_test") resp = await client.get("/api/camera_proxy/camera.config_test")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
@respx.mock @respx.mock
@ -103,7 +100,7 @@ async def test_fetching_url_with_verify_ssl(hass, hass_client):
resp = await client.get("/api/camera_proxy/camera.config_test") resp = await client.get("/api/camera_proxy/camera.config_test")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
@respx.mock @respx.mock
@ -112,7 +109,7 @@ async def test_limit_refetch(hass, hass_client):
respx.get("http://example.com/5a").respond(text="hello world") respx.get("http://example.com/5a").respond(text="hello world")
respx.get("http://example.com/10a").respond(text="hello world") respx.get("http://example.com/10a").respond(text="hello world")
respx.get("http://example.com/15a").respond(text="hello planet") respx.get("http://example.com/15a").respond(text="hello planet")
respx.get("http://example.com/20a").respond(status_code=HTTP_NOT_FOUND) respx.get("http://example.com/20a").respond(status_code=HTTPStatus.NOT_FOUND)
await async_setup_component( await async_setup_component(
hass, hass,
@ -137,19 +134,19 @@ async def test_limit_refetch(hass, hass_client):
with patch("async_timeout.timeout", side_effect=asyncio.TimeoutError()): with patch("async_timeout.timeout", side_effect=asyncio.TimeoutError()):
resp = await client.get("/api/camera_proxy/camera.config_test") resp = await client.get("/api/camera_proxy/camera.config_test")
assert respx.calls.call_count == 0 assert respx.calls.call_count == 0
assert resp.status == HTTP_INTERNAL_SERVER_ERROR assert resp.status == HTTPStatus.INTERNAL_SERVER_ERROR
hass.states.async_set("sensor.temp", "10") hass.states.async_set("sensor.temp", "10")
resp = await client.get("/api/camera_proxy/camera.config_test") resp = await client.get("/api/camera_proxy/camera.config_test")
assert respx.calls.call_count == 1 assert respx.calls.call_count == 1
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.text() body = await resp.text()
assert body == "hello world" assert body == "hello world"
resp = await client.get("/api/camera_proxy/camera.config_test") resp = await client.get("/api/camera_proxy/camera.config_test")
assert respx.calls.call_count == 1 assert respx.calls.call_count == 1
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.text() body = await resp.text()
assert body == "hello world" assert body == "hello world"
@ -158,7 +155,7 @@ async def test_limit_refetch(hass, hass_client):
# Url change = fetch new image # Url change = fetch new image
resp = await client.get("/api/camera_proxy/camera.config_test") resp = await client.get("/api/camera_proxy/camera.config_test")
assert respx.calls.call_count == 2 assert respx.calls.call_count == 2
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.text() body = await resp.text()
assert body == "hello planet" assert body == "hello planet"
@ -166,7 +163,7 @@ async def test_limit_refetch(hass, hass_client):
hass.states.async_remove("sensor.temp") hass.states.async_remove("sensor.temp")
resp = await client.get("/api/camera_proxy/camera.config_test") resp = await client.get("/api/camera_proxy/camera.config_test")
assert respx.calls.call_count == 2 assert respx.calls.call_count == 2
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.text() body = await resp.text()
assert body == "hello planet" assert body == "hello planet"
@ -340,14 +337,14 @@ async def test_camera_content_type(hass, hass_client):
resp_1 = await client.get("/api/camera_proxy/camera.config_test_svg") resp_1 = await client.get("/api/camera_proxy/camera.config_test_svg")
assert respx.calls.call_count == 1 assert respx.calls.call_count == 1
assert resp_1.status == 200 assert resp_1.status == HTTPStatus.OK
assert resp_1.content_type == "image/svg+xml" assert resp_1.content_type == "image/svg+xml"
body = await resp_1.text() body = await resp_1.text()
assert body == svg_image assert body == svg_image
resp_2 = await client.get("/api/camera_proxy/camera.config_test_jpg") resp_2 = await client.get("/api/camera_proxy/camera.config_test_jpg")
assert respx.calls.call_count == 2 assert respx.calls.call_count == 2
assert resp_2.status == 200 assert resp_2.status == HTTPStatus.OK
assert resp_2.content_type == "image/jpeg" assert resp_2.content_type == "image/jpeg"
body = await resp_2.text() body = await resp_2.text()
assert body == svg_image assert body == svg_image
@ -377,7 +374,7 @@ async def test_reloading(hass, hass_client):
resp = await client.get("/api/camera_proxy/camera.config_test") resp = await client.get("/api/camera_proxy/camera.config_test")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert respx.calls.call_count == 1 assert respx.calls.call_count == 1
body = await resp.text() body = await resp.text()
assert body == "hello world" assert body == "hello world"
@ -400,11 +397,11 @@ async def test_reloading(hass, hass_client):
resp = await client.get("/api/camera_proxy/camera.config_test") resp = await client.get("/api/camera_proxy/camera.config_test")
assert resp.status == 404 assert resp.status == HTTPStatus.NOT_FOUND
resp = await client.get("/api/camera_proxy/camera.reload") resp = await client.get("/api/camera_proxy/camera.reload")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert respx.calls.call_count == 2 assert respx.calls.call_count == 2
body = await resp.text() body = await resp.text()
assert body == "hello world" assert body == "hello world"
@ -435,7 +432,7 @@ async def test_timeout_cancelled(hass, hass_client):
resp = await client.get("/api/camera_proxy/camera.config_test") resp = await client.get("/api/camera_proxy/camera.config_test")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert respx.calls.call_count == 1 assert respx.calls.call_count == 1
assert await resp.text() == "hello world" assert await resp.text() == "hello world"
@ -447,7 +444,7 @@ async def test_timeout_cancelled(hass, hass_client):
): ):
resp = await client.get("/api/camera_proxy/camera.config_test") resp = await client.get("/api/camera_proxy/camera.config_test")
assert respx.calls.call_count == 1 assert respx.calls.call_count == 1
assert resp.status == 500 assert resp.status == HTTPStatus.INTERNAL_SERVER_ERROR
respx.get("http://example.com").side_effect = [ respx.get("http://example.com").side_effect = [
httpx.RequestError, httpx.RequestError,
@ -457,7 +454,7 @@ async def test_timeout_cancelled(hass, hass_client):
for total_calls in range(2, 4): for total_calls in range(2, 4):
resp = await client.get("/api/camera_proxy/camera.config_test") resp = await client.get("/api/camera_proxy/camera.config_test")
assert respx.calls.call_count == total_calls assert respx.calls.call_count == total_calls
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert await resp.text() == "hello world" assert await resp.text() == "hello world"

View File

@ -1,4 +1,6 @@
"""The tests for the Geofency device tracker platform.""" """The tests for the Geofency device tracker platform."""
from http import HTTPStatus
# pylint: disable=redefined-outer-name # pylint: disable=redefined-outer-name
from unittest.mock import patch from unittest.mock import patch
@ -11,8 +13,6 @@ from homeassistant.config import async_process_ha_core_config
from homeassistant.const import ( from homeassistant.const import (
ATTR_LATITUDE, ATTR_LATITUDE,
ATTR_LONGITUDE, ATTR_LONGITUDE,
HTTP_OK,
HTTP_UNPROCESSABLE_ENTITY,
STATE_HOME, STATE_HOME,
STATE_NOT_HOME, STATE_NOT_HOME,
) )
@ -172,7 +172,7 @@ async def test_data_validation(geofency_client, webhook_id):
# No data # No data
req = await geofency_client.post(url) req = await geofency_client.post(url)
assert req.status == HTTP_UNPROCESSABLE_ENTITY assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
missing_attributes = ["address", "device", "entry", "latitude", "longitude", "name"] missing_attributes = ["address", "device", "entry", "latitude", "longitude", "name"]
@ -181,7 +181,7 @@ async def test_data_validation(geofency_client, webhook_id):
copy = GPS_ENTER_HOME.copy() copy = GPS_ENTER_HOME.copy()
del copy[attribute] del copy[attribute]
req = await geofency_client.post(url, data=copy) req = await geofency_client.post(url, data=copy)
assert req.status == HTTP_UNPROCESSABLE_ENTITY assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
async def test_gps_enter_and_exit_home(hass, geofency_client, webhook_id): async def test_gps_enter_and_exit_home(hass, geofency_client, webhook_id):
@ -191,7 +191,7 @@ async def test_gps_enter_and_exit_home(hass, geofency_client, webhook_id):
# Enter the Home zone # Enter the Home zone
req = await geofency_client.post(url, data=GPS_ENTER_HOME) req = await geofency_client.post(url, data=GPS_ENTER_HOME)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
device_name = slugify(GPS_ENTER_HOME["device"]) device_name = slugify(GPS_ENTER_HOME["device"])
state_name = hass.states.get(f"device_tracker.{device_name}").state state_name = hass.states.get(f"device_tracker.{device_name}").state
assert state_name == STATE_HOME assert state_name == STATE_HOME
@ -199,7 +199,7 @@ async def test_gps_enter_and_exit_home(hass, geofency_client, webhook_id):
# Exit the Home zone # Exit the Home zone
req = await geofency_client.post(url, data=GPS_EXIT_HOME) req = await geofency_client.post(url, data=GPS_EXIT_HOME)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
device_name = slugify(GPS_EXIT_HOME["device"]) device_name = slugify(GPS_EXIT_HOME["device"])
state_name = hass.states.get(f"device_tracker.{device_name}").state state_name = hass.states.get(f"device_tracker.{device_name}").state
assert state_name == STATE_NOT_HOME assert state_name == STATE_NOT_HOME
@ -211,7 +211,7 @@ async def test_gps_enter_and_exit_home(hass, geofency_client, webhook_id):
req = await geofency_client.post(url, data=data) req = await geofency_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
device_name = slugify(GPS_EXIT_HOME["device"]) device_name = slugify(GPS_EXIT_HOME["device"])
current_latitude = hass.states.get(f"device_tracker.{device_name}").attributes[ current_latitude = hass.states.get(f"device_tracker.{device_name}").attributes[
"latitude" "latitude"
@ -236,7 +236,7 @@ async def test_beacon_enter_and_exit_home(hass, geofency_client, webhook_id):
# Enter the Home zone # Enter the Home zone
req = await geofency_client.post(url, data=BEACON_ENTER_HOME) req = await geofency_client.post(url, data=BEACON_ENTER_HOME)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
device_name = slugify(f"beacon_{BEACON_ENTER_HOME['name']}") device_name = slugify(f"beacon_{BEACON_ENTER_HOME['name']}")
state_name = hass.states.get(f"device_tracker.{device_name}").state state_name = hass.states.get(f"device_tracker.{device_name}").state
assert state_name == STATE_HOME assert state_name == STATE_HOME
@ -244,7 +244,7 @@ async def test_beacon_enter_and_exit_home(hass, geofency_client, webhook_id):
# Exit the Home zone # Exit the Home zone
req = await geofency_client.post(url, data=BEACON_EXIT_HOME) req = await geofency_client.post(url, data=BEACON_EXIT_HOME)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
device_name = slugify(f"beacon_{BEACON_ENTER_HOME['name']}") device_name = slugify(f"beacon_{BEACON_ENTER_HOME['name']}")
state_name = hass.states.get(f"device_tracker.{device_name}").state state_name = hass.states.get(f"device_tracker.{device_name}").state
assert state_name == STATE_NOT_HOME assert state_name == STATE_NOT_HOME
@ -257,7 +257,7 @@ async def test_beacon_enter_and_exit_car(hass, geofency_client, webhook_id):
# Enter the Car away from Home zone # Enter the Car away from Home zone
req = await geofency_client.post(url, data=BEACON_ENTER_CAR) req = await geofency_client.post(url, data=BEACON_ENTER_CAR)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
device_name = slugify(f"beacon_{BEACON_ENTER_CAR['name']}") device_name = slugify(f"beacon_{BEACON_ENTER_CAR['name']}")
state_name = hass.states.get(f"device_tracker.{device_name}").state state_name = hass.states.get(f"device_tracker.{device_name}").state
assert state_name == STATE_NOT_HOME assert state_name == STATE_NOT_HOME
@ -265,7 +265,7 @@ async def test_beacon_enter_and_exit_car(hass, geofency_client, webhook_id):
# Exit the Car away from Home zone # Exit the Car away from Home zone
req = await geofency_client.post(url, data=BEACON_EXIT_CAR) req = await geofency_client.post(url, data=BEACON_EXIT_CAR)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
device_name = slugify(f"beacon_{BEACON_ENTER_CAR['name']}") device_name = slugify(f"beacon_{BEACON_ENTER_CAR['name']}")
state_name = hass.states.get(f"device_tracker.{device_name}").state state_name = hass.states.get(f"device_tracker.{device_name}").state
assert state_name == STATE_NOT_HOME assert state_name == STATE_NOT_HOME
@ -276,7 +276,7 @@ async def test_beacon_enter_and_exit_car(hass, geofency_client, webhook_id):
data["longitude"] = HOME_LONGITUDE data["longitude"] = HOME_LONGITUDE
req = await geofency_client.post(url, data=data) req = await geofency_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
device_name = slugify(f"beacon_{data['name']}") device_name = slugify(f"beacon_{data['name']}")
state_name = hass.states.get(f"device_tracker.{device_name}").state state_name = hass.states.get(f"device_tracker.{device_name}").state
assert state_name == STATE_HOME assert state_name == STATE_HOME
@ -284,7 +284,7 @@ async def test_beacon_enter_and_exit_car(hass, geofency_client, webhook_id):
# Exit the Car in the Home zone # Exit the Car in the Home zone
req = await geofency_client.post(url, data=data) req = await geofency_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
device_name = slugify(f"beacon_{data['name']}") device_name = slugify(f"beacon_{data['name']}")
state_name = hass.states.get(f"device_tracker.{device_name}").state state_name = hass.states.get(f"device_tracker.{device_name}").state
assert state_name == STATE_HOME assert state_name == STATE_HOME
@ -297,7 +297,7 @@ async def test_load_unload_entry(hass, geofency_client, webhook_id):
# Enter the Home zone # Enter the Home zone
req = await geofency_client.post(url, data=GPS_ENTER_HOME) req = await geofency_client.post(url, data=GPS_ENTER_HOME)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
device_name = slugify(GPS_ENTER_HOME["device"]) device_name = slugify(GPS_ENTER_HOME["device"])
state_1 = hass.states.get(f"device_tracker.{device_name}") state_1 = hass.states.get(f"device_tracker.{device_name}")
assert state_1.state == STATE_HOME assert state_1.state == STATE_HOME

View File

@ -1,4 +1,6 @@
"""The tests for the Google Assistant component.""" """The tests for the Google Assistant component."""
from http import HTTPStatus
# pylint: disable=protected-access # pylint: disable=protected-access
import json import json
@ -154,7 +156,7 @@ async def test_sync_request(hass_fixture, assistant_client, auth_header):
data=json.dumps(data), data=json.dumps(data),
headers=auth_header, headers=auth_header,
) )
assert result.status == 200 assert result.status == HTTPStatus.OK
body = await result.json() body = await result.json()
assert body.get("requestId") == reqid assert body.get("requestId") == reqid
devices = body["payload"]["devices"] devices = body["payload"]["devices"]
@ -198,7 +200,7 @@ async def test_query_request(hass_fixture, assistant_client, auth_header):
data=json.dumps(data), data=json.dumps(data),
headers=auth_header, headers=auth_header,
) )
assert result.status == 200 assert result.status == HTTPStatus.OK
body = await result.json() body = await result.json()
assert body.get("requestId") == reqid assert body.get("requestId") == reqid
devices = body["payload"]["devices"] devices = body["payload"]["devices"]
@ -238,7 +240,7 @@ async def test_query_climate_request(hass_fixture, assistant_client, auth_header
data=json.dumps(data), data=json.dumps(data),
headers=auth_header, headers=auth_header,
) )
assert result.status == 200 assert result.status == HTTPStatus.OK
body = await result.json() body = await result.json()
assert body.get("requestId") == reqid assert body.get("requestId") == reqid
devices = body["payload"]["devices"] devices = body["payload"]["devices"]
@ -297,7 +299,7 @@ async def test_query_climate_request_f(hass_fixture, assistant_client, auth_head
data=json.dumps(data), data=json.dumps(data),
headers=auth_header, headers=auth_header,
) )
assert result.status == 200 assert result.status == HTTPStatus.OK
body = await result.json() body = await result.json()
assert body.get("requestId") == reqid assert body.get("requestId") == reqid
devices = body["payload"]["devices"] devices = body["payload"]["devices"]
@ -350,7 +352,7 @@ async def test_query_humidifier_request(hass_fixture, assistant_client, auth_hea
data=json.dumps(data), data=json.dumps(data),
headers=auth_header, headers=auth_header,
) )
assert result.status == 200 assert result.status == HTTPStatus.OK
body = await result.json() body = await result.json()
assert body.get("requestId") == reqid assert body.get("requestId") == reqid
devices = body["payload"]["devices"] devices = body["payload"]["devices"]
@ -464,7 +466,7 @@ async def test_execute_request(hass_fixture, assistant_client, auth_header):
data=json.dumps(data), data=json.dumps(data),
headers=auth_header, headers=auth_header,
) )
assert result.status == 200 assert result.status == HTTPStatus.OK
body = await result.json() body = await result.json()
assert body.get("requestId") == reqid assert body.get("requestId") == reqid
commands = body["payload"]["commands"] commands = body["payload"]["commands"]

View File

@ -1,5 +1,6 @@
"""Test Google Assistant helpers.""" """Test Google Assistant helpers."""
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
from unittest.mock import Mock, call, patch from unittest.mock import Mock, call, patch
import pytest import pytest
@ -112,7 +113,7 @@ async def test_config_local_sdk(hass, hass_client):
"requestId": "mock-req-id", "requestId": "mock-req-id",
}, },
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result["requestId"] == "mock-req-id" assert result["requestId"] == "mock-req-id"
@ -126,7 +127,7 @@ async def test_config_local_sdk(hass, hass_client):
# Webhook is no longer active # Webhook is no longer active
resp = await client.post("/api/webhook/mock-webhook-id") resp = await client.post("/api/webhook/mock-webhook-id")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert await resp.read() == b"" assert await resp.read() == b""
@ -148,7 +149,7 @@ async def test_config_local_sdk_if_disabled(hass, hass_client):
resp = await client.post( resp = await client.post(
"/api/webhook/mock-webhook-id", json={"requestId": "mock-req-id"} "/api/webhook/mock-webhook-id", json={"requestId": "mock-req-id"}
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == { assert result == {
"payload": {"errorCode": "deviceTurnedOff"}, "payload": {"errorCode": "deviceTurnedOff"},
@ -159,7 +160,7 @@ async def test_config_local_sdk_if_disabled(hass, hass_client):
# Webhook is no longer active # Webhook is no longer active
resp = await client.post("/api/webhook/mock-webhook-id") resp = await client.post("/api/webhook/mock-webhook-id")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert await resp.read() == b"" assert await resp.read() == b""

View File

@ -1,5 +1,6 @@
"""Test Google http services.""" """Test Google http services."""
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from http import HTTPStatus
from unittest.mock import ANY, patch from unittest.mock import ANY, patch
from homeassistant.components.google_assistant import GOOGLE_ASSISTANT_SCHEMA from homeassistant.components.google_assistant import GOOGLE_ASSISTANT_SCHEMA
@ -49,7 +50,7 @@ async def test_get_access_token(hass, aioclient_mock):
aioclient_mock.post( aioclient_mock.post(
HOMEGRAPH_TOKEN_URL, HOMEGRAPH_TOKEN_URL,
status=200, status=HTTPStatus.OK,
json={"access_token": "1234", "expires_in": 3600}, json={"access_token": "1234", "expires_in": 3600},
) )
@ -106,10 +107,10 @@ async def test_call_homegraph_api(hass, aioclient_mock, hass_storage):
) as mock_get_token: ) as mock_get_token:
mock_get_token.return_value = MOCK_TOKEN mock_get_token.return_value = MOCK_TOKEN
aioclient_mock.post(MOCK_URL, status=200, json={}) aioclient_mock.post(MOCK_URL, status=HTTPStatus.OK, json={})
res = await config.async_call_homegraph_api(MOCK_URL, MOCK_JSON) res = await config.async_call_homegraph_api(MOCK_URL, MOCK_JSON)
assert res == 200 assert res == HTTPStatus.OK
assert mock_get_token.call_count == 1 assert mock_get_token.call_count == 1
assert aioclient_mock.call_count == 1 assert aioclient_mock.call_count == 1
@ -129,7 +130,7 @@ async def test_call_homegraph_api_retry(hass, aioclient_mock, hass_storage):
) as mock_get_token: ) as mock_get_token:
mock_get_token.return_value = MOCK_TOKEN mock_get_token.return_value = MOCK_TOKEN
aioclient_mock.post(MOCK_URL, status=401, json={}) aioclient_mock.post(MOCK_URL, status=HTTPStatus.UNAUTHORIZED, json={})
await config.async_call_homegraph_api(MOCK_URL, MOCK_JSON) await config.async_call_homegraph_api(MOCK_URL, MOCK_JSON)

View File

@ -1,4 +1,6 @@
"""The tests for google-assistant init.""" """The tests for google-assistant init."""
from http import HTTPStatus
from homeassistant.components import google_assistant as ga from homeassistant.components import google_assistant as ga
from homeassistant.core import Context from homeassistant.core import Context
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -10,11 +12,11 @@ async def test_request_sync_service(aioclient_mock, hass):
"""Test that it posts to the request_sync url.""" """Test that it posts to the request_sync url."""
aioclient_mock.post( aioclient_mock.post(
ga.const.HOMEGRAPH_TOKEN_URL, ga.const.HOMEGRAPH_TOKEN_URL,
status=200, status=HTTPStatus.OK,
json={"access_token": "1234", "expires_in": 3600}, json={"access_token": "1234", "expires_in": 3600},
) )
aioclient_mock.post(ga.const.REQUEST_SYNC_BASE_URL, status=200) aioclient_mock.post(ga.const.REQUEST_SYNC_BASE_URL, status=HTTPStatus.OK)
await async_setup_component( await async_setup_component(
hass, hass,

View File

@ -1,5 +1,6 @@
"""The tests for the Google Wifi platform.""" """The tests for the Google Wifi platform."""
from datetime import datetime, timedelta from datetime import datetime, timedelta
from http import HTTPStatus
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
import homeassistant.components.google_wifi.sensor as google_wifi import homeassistant.components.google_wifi.sensor as google_wifi
@ -33,7 +34,7 @@ MOCK_DATA_MISSING = '{"software": {},' '"system": {},' '"wan": {}}'
async def test_setup_minimum(hass, requests_mock): async def test_setup_minimum(hass, requests_mock):
"""Test setup with minimum configuration.""" """Test setup with minimum configuration."""
resource = f"http://{google_wifi.DEFAULT_HOST}{google_wifi.ENDPOINT}" resource = f"http://{google_wifi.DEFAULT_HOST}{google_wifi.ENDPOINT}"
requests_mock.get(resource, status_code=200) requests_mock.get(resource, status_code=HTTPStatus.OK)
assert await async_setup_component( assert await async_setup_component(
hass, hass,
"sensor", "sensor",
@ -45,7 +46,7 @@ async def test_setup_minimum(hass, requests_mock):
async def test_setup_get(hass, requests_mock): async def test_setup_get(hass, requests_mock):
"""Test setup with full configuration.""" """Test setup with full configuration."""
resource = f"http://localhost{google_wifi.ENDPOINT}" resource = f"http://localhost{google_wifi.ENDPOINT}"
requests_mock.get(resource, status_code=200) requests_mock.get(resource, status_code=HTTPStatus.OK)
assert await async_setup_component( assert await async_setup_component(
hass, hass,
"sensor", "sensor",
@ -74,7 +75,7 @@ def setup_api(hass, data, requests_mock):
now = datetime(1970, month=1, day=1) now = datetime(1970, month=1, day=1)
sensor_dict = {} sensor_dict = {}
with patch("homeassistant.util.dt.now", return_value=now): with patch("homeassistant.util.dt.now", return_value=now):
requests_mock.get(resource, text=data, status_code=200) requests_mock.get(resource, text=data, status_code=HTTPStatus.OK)
conditions = google_wifi.SENSOR_KEYS conditions = google_wifi.SENSOR_KEYS
api = google_wifi.GoogleWifiAPI("localhost", conditions) api = google_wifi.GoogleWifiAPI("localhost", conditions)
for desc in google_wifi.SENSOR_TYPES: for desc in google_wifi.SENSOR_TYPES:

View File

@ -1,4 +1,5 @@
"""The tests the for GPSLogger device tracker platform.""" """The tests the for GPSLogger device tracker platform."""
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
import pytest import pytest
@ -8,12 +9,7 @@ from homeassistant.components import gpslogger, zone
from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER_DOMAIN from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER_DOMAIN
from homeassistant.components.gpslogger import DOMAIN, TRACKER_UPDATE from homeassistant.components.gpslogger import DOMAIN, TRACKER_UPDATE
from homeassistant.config import async_process_ha_core_config from homeassistant.config import async_process_ha_core_config
from homeassistant.const import ( from homeassistant.const import STATE_HOME, STATE_NOT_HOME
HTTP_OK,
HTTP_UNPROCESSABLE_ENTITY,
STATE_HOME,
STATE_NOT_HOME,
)
from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.dispatcher import DATA_DISPATCHER from homeassistant.helpers.dispatcher import DATA_DISPATCHER
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -87,21 +83,21 @@ async def test_missing_data(hass, gpslogger_client, webhook_id):
# No data # No data
req = await gpslogger_client.post(url) req = await gpslogger_client.post(url)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_UNPROCESSABLE_ENTITY assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
# No latitude # No latitude
copy = data.copy() copy = data.copy()
del copy["latitude"] del copy["latitude"]
req = await gpslogger_client.post(url, data=copy) req = await gpslogger_client.post(url, data=copy)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_UNPROCESSABLE_ENTITY assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
# No device # No device
copy = data.copy() copy = data.copy()
del copy["device"] del copy["device"]
req = await gpslogger_client.post(url, data=copy) req = await gpslogger_client.post(url, data=copy)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_UNPROCESSABLE_ENTITY assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
async def test_enter_and_exit(hass, gpslogger_client, webhook_id): async def test_enter_and_exit(hass, gpslogger_client, webhook_id):
@ -113,14 +109,14 @@ async def test_enter_and_exit(hass, gpslogger_client, webhook_id):
# Enter the Home # Enter the Home
req = await gpslogger_client.post(url, data=data) req = await gpslogger_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state_name = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}").state state_name = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}").state
assert state_name == STATE_HOME assert state_name == STATE_HOME
# Enter Home again # Enter Home again
req = await gpslogger_client.post(url, data=data) req = await gpslogger_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state_name = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}").state state_name = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}").state
assert state_name == STATE_HOME assert state_name == STATE_HOME
@ -130,7 +126,7 @@ async def test_enter_and_exit(hass, gpslogger_client, webhook_id):
# Enter Somewhere else # Enter Somewhere else
req = await gpslogger_client.post(url, data=data) req = await gpslogger_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state_name = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}").state state_name = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}").state
assert state_name == STATE_NOT_HOME assert state_name == STATE_NOT_HOME
@ -160,7 +156,7 @@ async def test_enter_with_attrs(hass, gpslogger_client, webhook_id):
req = await gpslogger_client.post(url, data=data) req = await gpslogger_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}") state = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}")
assert state.state == STATE_NOT_HOME assert state.state == STATE_NOT_HOME
assert state.attributes["gps_accuracy"] == 10.5 assert state.attributes["gps_accuracy"] == 10.5
@ -186,7 +182,7 @@ async def test_enter_with_attrs(hass, gpslogger_client, webhook_id):
req = await gpslogger_client.post(url, data=data) req = await gpslogger_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}") state = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}")
assert state.state == STATE_HOME assert state.state == STATE_HOME
assert state.attributes["gps_accuracy"] == 123 assert state.attributes["gps_accuracy"] == 123
@ -209,7 +205,7 @@ async def test_load_unload_entry(hass, gpslogger_client, webhook_id):
# Enter the Home # Enter the Home
req = await gpslogger_client.post(url, data=data) req = await gpslogger_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state_name = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}").state state_name = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}").state
assert state_name == STATE_HOME assert state_name == STATE_HOME
assert len(hass.data[DATA_DISPATCHER][TRACKER_UPDATE]) == 1 assert len(hass.data[DATA_DISPATCHER][TRACKER_UPDATE]) == 1

View File

@ -1,4 +1,6 @@
"""Test the habitica module.""" """Test the habitica module."""
from http import HTTPStatus
import pytest import pytest
from homeassistant.components.habitica.const import ( from homeassistant.components.habitica.const import (
@ -82,7 +84,7 @@ def common_requests(aioclient_mock):
aioclient_mock.post( aioclient_mock.post(
"https://habitica.com/api/v3/tasks/user", "https://habitica.com/api/v3/tasks/user",
status=201, status=HTTPStatus.CREATED,
json={"data": TEST_API_CALL_ARGS}, json={"data": TEST_API_CALL_ARGS},
) )

View File

@ -1,4 +1,5 @@
"""Test add-on panel.""" """Test add-on panel."""
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
import pytest import pytest
@ -104,10 +105,10 @@ async def test_hassio_addon_panel_api(hass, aioclient_mock, hassio_env, hass_cli
hass_client = await hass_client() hass_client = await hass_client()
resp = await hass_client.post("/api/hassio_push/panel/test2") resp = await hass_client.post("/api/hassio_push/panel/test2")
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
resp = await hass_client.post("/api/hassio_push/panel/test1") resp = await hass_client.post("/api/hassio_push/panel/test1")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert mock_panel.call_count == 2 assert mock_panel.call_count == 2
mock_panel.assert_called_with( mock_panel.assert_called_with(

View File

@ -1,5 +1,6 @@
"""The tests for the hassio component.""" """The tests for the hassio component."""
from http import HTTPStatus
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
from homeassistant.auth.providers.homeassistant import InvalidAuth from homeassistant.auth.providers.homeassistant import InvalidAuth
@ -17,7 +18,7 @@ async def test_auth_success(hass, hassio_client_supervisor):
) )
# Check we got right response # Check we got right response
assert resp.status == 200 assert resp.status == HTTPStatus.OK
mock_login.assert_called_with("test", "123456") mock_login.assert_called_with("test", "123456")
@ -33,7 +34,7 @@ async def test_auth_fails_no_supervisor(hass, hassio_client):
) )
# Check we got right response # Check we got right response
assert resp.status == 401 assert resp.status == HTTPStatus.UNAUTHORIZED
assert not mock_login.called assert not mock_login.called
@ -49,7 +50,7 @@ async def test_auth_fails_no_auth(hass, hassio_noauth_client):
) )
# Check we got right response # Check we got right response
assert resp.status == 401 assert resp.status == HTTPStatus.UNAUTHORIZED
assert not mock_login.called assert not mock_login.called
@ -66,7 +67,7 @@ async def test_login_error(hass, hassio_client_supervisor):
) )
# Check we got right response # Check we got right response
assert resp.status == 404 assert resp.status == HTTPStatus.NOT_FOUND
mock_login.assert_called_with("test", "123456") mock_login.assert_called_with("test", "123456")
@ -80,7 +81,7 @@ async def test_login_no_data(hass, hassio_client_supervisor):
resp = await hassio_client_supervisor.post("/api/hassio_auth") resp = await hassio_client_supervisor.post("/api/hassio_auth")
# Check we got right response # Check we got right response
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
assert not mock_login.called assert not mock_login.called
@ -96,7 +97,7 @@ async def test_login_no_username(hass, hassio_client_supervisor):
) )
# Check we got right response # Check we got right response
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
assert not mock_login.called assert not mock_login.called
@ -117,7 +118,7 @@ async def test_login_success_extra(hass, hassio_client_supervisor):
) )
# Check we got right response # Check we got right response
assert resp.status == 200 assert resp.status == HTTPStatus.OK
mock_login.assert_called_with("test", "123456") mock_login.assert_called_with("test", "123456")
@ -133,7 +134,7 @@ async def test_password_success(hass, hassio_client_supervisor):
) )
# Check we got right response # Check we got right response
assert resp.status == 200 assert resp.status == HTTPStatus.OK
mock_change.assert_called_with("test", "123456") mock_change.assert_called_with("test", "123456")
@ -145,7 +146,7 @@ async def test_password_fails_no_supervisor(hass, hassio_client):
) )
# Check we got right response # Check we got right response
assert resp.status == 401 assert resp.status == HTTPStatus.UNAUTHORIZED
async def test_password_fails_no_auth(hass, hassio_noauth_client): async def test_password_fails_no_auth(hass, hassio_noauth_client):
@ -156,7 +157,7 @@ async def test_password_fails_no_auth(hass, hassio_noauth_client):
) )
# Check we got right response # Check we got right response
assert resp.status == 401 assert resp.status == HTTPStatus.UNAUTHORIZED
async def test_password_no_user(hass, hassio_client_supervisor): async def test_password_no_user(hass, hassio_client_supervisor):
@ -167,4 +168,4 @@ async def test_password_no_user(hass, hassio_client_supervisor):
) )
# Check we got right response # Check we got right response
assert resp.status == 404 assert resp.status == HTTPStatus.NOT_FOUND

View File

@ -1,4 +1,5 @@
"""Test config flow.""" """Test config flow."""
from http import HTTPStatus
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
from homeassistant.components.hassio.handler import HassioAPIError from homeassistant.components.hassio.handler import HassioAPIError
@ -154,7 +155,7 @@ async def test_hassio_discovery_webhook(hass, aioclient_mock, hassio_client):
) )
await hass.async_block_till_done() await hass.async_block_till_done()
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert aioclient_mock.call_count == 2 assert aioclient_mock.call_count == 2
assert mock_mqtt.called assert mock_mqtt.called
mock_mqtt.assert_called_with( mock_mqtt.assert_called_with(

View File

@ -1,5 +1,6 @@
"""The tests for the hassio component.""" """The tests for the hassio component."""
import asyncio import asyncio
from http import HTTPStatus
from aiohttp import StreamReader from aiohttp import StreamReader
import pytest import pytest
@ -14,7 +15,7 @@ async def test_forward_request(hassio_client, aioclient_mock):
resp = await hassio_client.post("/api/hassio/beer") resp = await hassio_client.post("/api/hassio/beer")
# Check we got right response # Check we got right response
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.text() body = await resp.text()
assert body == "response" assert body == "response"
@ -30,7 +31,7 @@ async def test_auth_required_forward_request(hassio_noauth_client, build_type):
resp = await hassio_noauth_client.post(f"/api/hassio/{build_type}") resp = await hassio_noauth_client.post(f"/api/hassio/{build_type}")
# Check we got right response # Check we got right response
assert resp.status == 401 assert resp.status == HTTPStatus.UNAUTHORIZED
@pytest.mark.parametrize( @pytest.mark.parametrize(
@ -53,7 +54,7 @@ async def test_forward_request_no_auth_for_panel(
resp = await hassio_client.get(f"/api/hassio/{build_type}") resp = await hassio_client.get(f"/api/hassio/{build_type}")
# Check we got right response # Check we got right response
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.text() body = await resp.text()
assert body == "response" assert body == "response"
@ -68,7 +69,7 @@ async def test_forward_request_no_auth_for_logo(hassio_client, aioclient_mock):
resp = await hassio_client.get("/api/hassio/addons/bl_b392/logo") resp = await hassio_client.get("/api/hassio/addons/bl_b392/logo")
# Check we got right response # Check we got right response
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.text() body = await resp.text()
assert body == "response" assert body == "response"
@ -83,7 +84,7 @@ async def test_forward_request_no_auth_for_icon(hassio_client, aioclient_mock):
resp = await hassio_client.get("/api/hassio/addons/bl_b392/icon") resp = await hassio_client.get("/api/hassio/addons/bl_b392/icon")
# Check we got right response # Check we got right response
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.text() body = await resp.text()
assert body == "response" assert body == "response"
@ -98,7 +99,7 @@ async def test_forward_log_request(hassio_client, aioclient_mock):
resp = await hassio_client.get("/api/hassio/beer/logs") resp = await hassio_client.get("/api/hassio/beer/logs")
# Check we got right response # Check we got right response
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.text() body = await resp.text()
assert body == "\033[32mresponse\033[0m" assert body == "\033[32mresponse\033[0m"
@ -111,7 +112,7 @@ async def test_bad_gateway_when_cannot_find_supervisor(hassio_client, aioclient_
aioclient_mock.get("http://127.0.0.1/addons/test/info", exc=asyncio.TimeoutError) aioclient_mock.get("http://127.0.0.1/addons/test/info", exc=asyncio.TimeoutError)
resp = await hassio_client.get("/api/hassio/addons/test/info") resp = await hassio_client.get("/api/hassio/addons/test/info")
assert resp.status == 502 assert resp.status == HTTPStatus.BAD_GATEWAY
async def test_forwarding_user_info(hassio_client, hass_admin_user, aioclient_mock): async def test_forwarding_user_info(hassio_client, hass_admin_user, aioclient_mock):
@ -121,7 +122,7 @@ async def test_forwarding_user_info(hassio_client, hass_admin_user, aioclient_mo
resp = await hassio_client.get("/api/hassio/hello") resp = await hassio_client.get("/api/hassio/hello")
# Check we got right response # Check we got right response
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert len(aioclient_mock.mock_calls) == 1 assert len(aioclient_mock.mock_calls) == 1
@ -140,7 +141,7 @@ async def test_backup_upload_headers(hassio_client, aioclient_mock, caplog):
) )
# Check we got right response # Check we got right response
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert len(aioclient_mock.mock_calls) == 1 assert len(aioclient_mock.mock_calls) == 1
@ -162,7 +163,7 @@ async def test_backup_download_headers(hassio_client, aioclient_mock):
resp = await hassio_client.get("/api/hassio/backups/slug/download") resp = await hassio_client.get("/api/hassio/backups/slug/download")
# Check we got right response # Check we got right response
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert len(aioclient_mock.mock_calls) == 1 assert len(aioclient_mock.mock_calls) == 1
@ -196,8 +197,8 @@ async def test_entrypoint_cache_control(hassio_client, aioclient_mock):
resp2 = await hassio_client.get("/api/hassio/app/entrypoint.fdhkusd8y43r.js") resp2 = await hassio_client.get("/api/hassio/app/entrypoint.fdhkusd8y43r.js")
# Check we got right response # Check we got right response
assert resp1.status == 200 assert resp1.status == HTTPStatus.OK
assert resp2.status == 200 assert resp2.status == HTTPStatus.OK
assert len(aioclient_mock.mock_calls) == 2 assert len(aioclient_mock.mock_calls) == 2
assert resp1.headers["Cache-Control"] == "no-store, max-age=0" assert resp1.headers["Cache-Control"] == "no-store, max-age=0"

View File

@ -1,5 +1,5 @@
"""The tests for the hassio component.""" """The tests for the hassio component."""
from http import HTTPStatus
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
from aiohttp.hdrs import X_FORWARDED_FOR, X_FORWARDED_HOST, X_FORWARDED_PROTO from aiohttp.hdrs import X_FORWARDED_FOR, X_FORWARDED_HOST, X_FORWARDED_PROTO
@ -29,7 +29,7 @@ async def test_ingress_request_get(hassio_client, build_type, aioclient_mock):
) )
# Check we got right response # Check we got right response
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.text() body = await resp.text()
assert body == "test" assert body == "test"
@ -69,7 +69,7 @@ async def test_ingress_request_post(hassio_client, build_type, aioclient_mock):
) )
# Check we got right response # Check we got right response
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.text() body = await resp.text()
assert body == "test" assert body == "test"
@ -109,7 +109,7 @@ async def test_ingress_request_put(hassio_client, build_type, aioclient_mock):
) )
# Check we got right response # Check we got right response
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.text() body = await resp.text()
assert body == "test" assert body == "test"
@ -149,7 +149,7 @@ async def test_ingress_request_delete(hassio_client, build_type, aioclient_mock)
) )
# Check we got right response # Check we got right response
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.text() body = await resp.text()
assert body == "test" assert body == "test"
@ -189,7 +189,7 @@ async def test_ingress_request_patch(hassio_client, build_type, aioclient_mock):
) )
# Check we got right response # Check we got right response
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.text() body = await resp.text()
assert body == "test" assert body == "test"
@ -229,7 +229,7 @@ async def test_ingress_request_options(hassio_client, build_type, aioclient_mock
) )
# Check we got right response # Check we got right response
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.text() body = await resp.text()
assert body == "test" assert body == "test"
@ -302,4 +302,4 @@ async def test_ingress_missing_peername(hassio_client, aioclient_mock, caplog):
assert "Can't set forward_for header, missing peername" in caplog.text assert "Can't set forward_for header, missing peername" in caplog.text
# Check we got right response # Check we got right response
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST

View File

@ -1,6 +1,7 @@
"""The tests the History component.""" """The tests the History component."""
# pylint: disable=protected-access,invalid-name # pylint: disable=protected-access,invalid-name
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
import json import json
from unittest.mock import patch, sentinel from unittest.mock import patch, sentinel
@ -586,7 +587,7 @@ async def test_fetch_period_api(hass, hass_client):
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done) await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client() client = await hass_client()
response = await client.get(f"/api/history/period/{dt_util.utcnow().isoformat()}") response = await client.get(f"/api/history/period/{dt_util.utcnow().isoformat()}")
assert response.status == 200 assert response.status == HTTPStatus.OK
async def test_fetch_period_api_with_use_include_order(hass, hass_client): async def test_fetch_period_api_with_use_include_order(hass, hass_client):
@ -598,7 +599,7 @@ async def test_fetch_period_api_with_use_include_order(hass, hass_client):
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done) await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client() client = await hass_client()
response = await client.get(f"/api/history/period/{dt_util.utcnow().isoformat()}") response = await client.get(f"/api/history/period/{dt_util.utcnow().isoformat()}")
assert response.status == 200 assert response.status == HTTPStatus.OK
async def test_fetch_period_api_with_minimal_response(hass, hass_client): async def test_fetch_period_api_with_minimal_response(hass, hass_client):
@ -610,7 +611,7 @@ async def test_fetch_period_api_with_minimal_response(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/history/period/{dt_util.utcnow().isoformat()}?minimal_response" f"/api/history/period/{dt_util.utcnow().isoformat()}?minimal_response"
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
async def test_fetch_period_api_with_no_timestamp(hass, hass_client): async def test_fetch_period_api_with_no_timestamp(hass, hass_client):
@ -620,7 +621,7 @@ async def test_fetch_period_api_with_no_timestamp(hass, hass_client):
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done) await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client() client = await hass_client()
response = await client.get("/api/history/period") response = await client.get("/api/history/period")
assert response.status == 200 assert response.status == HTTPStatus.OK
async def test_fetch_period_api_with_include_order(hass, hass_client): async def test_fetch_period_api_with_include_order(hass, hass_client):
@ -642,7 +643,7 @@ async def test_fetch_period_api_with_include_order(hass, hass_client):
f"/api/history/period/{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 == HTTPStatus.OK
async def test_fetch_period_api_with_entity_glob_include(hass, hass_client): async def test_fetch_period_api_with_entity_glob_include(hass, hass_client):
@ -672,7 +673,7 @@ async def test_fetch_period_api_with_entity_glob_include(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/history/period/{dt_util.utcnow().isoformat()}", f"/api/history/period/{dt_util.utcnow().isoformat()}",
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert response_json[0][0]["entity_id"] == "light.kitchen" assert response_json[0][0]["entity_id"] == "light.kitchen"
@ -710,7 +711,7 @@ async def test_fetch_period_api_with_entity_glob_exclude(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/history/period/{dt_util.utcnow().isoformat()}", f"/api/history/period/{dt_util.utcnow().isoformat()}",
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 2 assert len(response_json) == 2
assert response_json[0][0]["entity_id"] == "light.cow" assert response_json[0][0]["entity_id"] == "light.cow"
@ -754,7 +755,7 @@ async def test_fetch_period_api_with_entity_glob_include_and_exclude(hass, hass_
response = await client.get( response = await client.get(
f"/api/history/period/{dt_util.utcnow().isoformat()}", f"/api/history/period/{dt_util.utcnow().isoformat()}",
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 3 assert len(response_json) == 3
assert response_json[0][0]["entity_id"] == "light.match" assert response_json[0][0]["entity_id"] == "light.match"
@ -785,7 +786,7 @@ async def test_entity_ids_limit_via_api(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/history/period/{dt_util.utcnow().isoformat()}?filter_entity_id=light.kitchen,light.cow", f"/api/history/period/{dt_util.utcnow().isoformat()}?filter_entity_id=light.kitchen,light.cow",
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 2 assert len(response_json) == 2
assert response_json[0][0]["entity_id"] == "light.kitchen" assert response_json[0][0]["entity_id"] == "light.kitchen"
@ -815,7 +816,7 @@ async def test_entity_ids_limit_via_api_with_skip_initial_state(hass, hass_clien
response = await client.get( response = await client.get(
f"/api/history/period/{dt_util.utcnow().isoformat()}?filter_entity_id=light.kitchen,light.cow&skip_initial_state", f"/api/history/period/{dt_util.utcnow().isoformat()}?filter_entity_id=light.kitchen,light.cow&skip_initial_state",
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 0 assert len(response_json) == 0
@ -823,7 +824,7 @@ async def test_entity_ids_limit_via_api_with_skip_initial_state(hass, hass_clien
response = await client.get( response = await client.get(
f"/api/history/period/{when.isoformat()}?filter_entity_id=light.kitchen,light.cow&skip_initial_state", f"/api/history/period/{when.isoformat()}?filter_entity_id=light.kitchen,light.cow&skip_initial_state",
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 2 assert len(response_json) == 2
assert response_json[0][0]["entity_id"] == "light.kitchen" assert response_json[0][0]["entity_id"] == "light.kitchen"

View File

@ -1,4 +1,5 @@
"""Test the Home Connect config flow.""" """Test the Home Connect config flow."""
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
from homeassistant import config_entries, data_entry_flow, setup from homeassistant import config_entries, data_entry_flow, setup
@ -50,7 +51,7 @@ async def test_full_flow(
client = await hass_client_no_auth() client = await hass_client_no_auth()
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert resp.headers["content-type"] == "text/html; charset=utf-8" assert resp.headers["content-type"] == "text/html; charset=utf-8"
aioclient_mock.post( aioclient_mock.post(

View File

@ -1,4 +1,5 @@
"""Test the Legrand Home+ Control config flow.""" """Test the Legrand Home+ Control config flow."""
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
from homeassistant import config_entries, data_entry_flow, setup from homeassistant import config_entries, data_entry_flow, setup
@ -56,7 +57,7 @@ async def test_full_flow(
client = await hass_client_no_auth() client = await hass_client_no_auth()
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert resp.headers["content-type"] == "text/html; charset=utf-8" assert resp.headers["content-type"] == "text/html; charset=utf-8"
aioclient_mock.post( aioclient_mock.post(
@ -174,7 +175,7 @@ async def test_abort_if_invalid_token(
client = await hass_client_no_auth() client = await hass_client_no_auth()
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert resp.headers["content-type"] == "text/html; charset=utf-8" assert resp.headers["content-type"] == "text/html; charset=utf-8"
aioclient_mock.post( aioclient_mock.post(

View File

@ -1,11 +1,11 @@
"""Test HTML5 notify platform.""" """Test HTML5 notify platform."""
from http import HTTPStatus
import json import json
from unittest.mock import MagicMock, mock_open, patch from unittest.mock import MagicMock, mock_open, patch
from aiohttp.hdrs import AUTHORIZATION from aiohttp.hdrs import AUTHORIZATION
import homeassistant.components.html5.notify as html5 import homeassistant.components.html5.notify as html5
from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -294,7 +294,7 @@ async def test_registering_new_device_view(hass, hass_client):
with patch("homeassistant.components.html5.notify.save_json") as mock_save: with patch("homeassistant.components.html5.notify.save_json") as mock_save:
resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1)) resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1))
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert len(mock_save.mock_calls) == 1 assert len(mock_save.mock_calls) == 1
assert mock_save.mock_calls[0][1][1] == {"unnamed device": SUBSCRIPTION_1} assert mock_save.mock_calls[0][1][1] == {"unnamed device": SUBSCRIPTION_1}
@ -309,7 +309,7 @@ async def test_registering_new_device_view_with_name(hass, hass_client):
with patch("homeassistant.components.html5.notify.save_json") as mock_save: with patch("homeassistant.components.html5.notify.save_json") as mock_save:
resp = await client.post(REGISTER_URL, data=json.dumps(SUB_WITH_NAME)) resp = await client.post(REGISTER_URL, data=json.dumps(SUB_WITH_NAME))
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert len(mock_save.mock_calls) == 1 assert len(mock_save.mock_calls) == 1
assert mock_save.mock_calls[0][1][1] == {"test device": SUBSCRIPTION_1} assert mock_save.mock_calls[0][1][1] == {"test device": SUBSCRIPTION_1}
@ -321,7 +321,7 @@ async def test_registering_new_device_expiration_view(hass, hass_client):
with patch("homeassistant.components.html5.notify.save_json") as mock_save: with patch("homeassistant.components.html5.notify.save_json") as mock_save:
resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4)) resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4))
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert mock_save.mock_calls[0][1][1] == {"unnamed device": SUBSCRIPTION_4} assert mock_save.mock_calls[0][1][1] == {"unnamed device": SUBSCRIPTION_4}
@ -336,7 +336,7 @@ async def test_registering_new_device_fails_view(hass, hass_client):
): ):
resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4)) resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4))
assert resp.status == HTTP_INTERNAL_SERVER_ERROR assert resp.status == HTTPStatus.INTERNAL_SERVER_ERROR
assert registrations == {} assert registrations == {}
@ -349,7 +349,7 @@ async def test_registering_existing_device_view(hass, hass_client):
await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1)) await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1))
resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4)) resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4))
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert mock_save.mock_calls[0][1][1] == {"unnamed device": SUBSCRIPTION_4} assert mock_save.mock_calls[0][1][1] == {"unnamed device": SUBSCRIPTION_4}
assert registrations == {"unnamed device": SUBSCRIPTION_4} assert registrations == {"unnamed device": SUBSCRIPTION_4}
@ -366,7 +366,7 @@ async def test_registering_existing_device_view_with_name(hass, hass_client):
await client.post(REGISTER_URL, data=json.dumps(SUB_WITH_NAME)) await client.post(REGISTER_URL, data=json.dumps(SUB_WITH_NAME))
resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4)) resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4))
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert mock_save.mock_calls[0][1][1] == {"test device": SUBSCRIPTION_4} assert mock_save.mock_calls[0][1][1] == {"test device": SUBSCRIPTION_4}
assert registrations == {"test device": SUBSCRIPTION_4} assert registrations == {"test device": SUBSCRIPTION_4}
@ -381,7 +381,7 @@ async def test_registering_existing_device_fails_view(hass, hass_client):
mock_save.side_effect = HomeAssistantError mock_save.side_effect = HomeAssistantError
resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4)) resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4))
assert resp.status == HTTP_INTERNAL_SERVER_ERROR assert resp.status == HTTPStatus.INTERNAL_SERVER_ERROR
assert registrations == {"unnamed device": SUBSCRIPTION_1} assert registrations == {"unnamed device": SUBSCRIPTION_1}
@ -393,17 +393,17 @@ async def test_registering_new_device_validation(hass, hass_client):
REGISTER_URL, REGISTER_URL,
data=json.dumps({"browser": "invalid browser", "subscription": "sub info"}), data=json.dumps({"browser": "invalid browser", "subscription": "sub info"}),
) )
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
resp = await client.post(REGISTER_URL, data=json.dumps({"browser": "chrome"})) resp = await client.post(REGISTER_URL, data=json.dumps({"browser": "chrome"}))
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
with patch("homeassistant.components.html5.notify.save_json", return_value=False): with patch("homeassistant.components.html5.notify.save_json", return_value=False):
resp = await client.post( resp = await client.post(
REGISTER_URL, REGISTER_URL,
data=json.dumps({"browser": "chrome", "subscription": "sub info"}), data=json.dumps({"browser": "chrome", "subscription": "sub info"}),
) )
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
async def test_unregistering_device_view(hass, hass_client): async def test_unregistering_device_view(hass, hass_client):
@ -417,7 +417,7 @@ async def test_unregistering_device_view(hass, hass_client):
data=json.dumps({"subscription": SUBSCRIPTION_1["subscription"]}), data=json.dumps({"subscription": SUBSCRIPTION_1["subscription"]}),
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert len(mock_save.mock_calls) == 1 assert len(mock_save.mock_calls) == 1
assert registrations == {"other device": SUBSCRIPTION_2} assert registrations == {"other device": SUBSCRIPTION_2}
@ -433,7 +433,7 @@ async def test_unregister_device_view_handle_unknown_subscription(hass, hass_cli
data=json.dumps({"subscription": SUBSCRIPTION_3["subscription"]}), data=json.dumps({"subscription": SUBSCRIPTION_3["subscription"]}),
) )
assert resp.status == 200, resp.response assert resp.status == HTTPStatus.OK, resp.response
assert registrations == {} assert registrations == {}
assert len(mock_save.mock_calls) == 0 assert len(mock_save.mock_calls) == 0
@ -452,7 +452,7 @@ async def test_unregistering_device_view_handles_save_error(hass, hass_client):
data=json.dumps({"subscription": SUBSCRIPTION_1["subscription"]}), data=json.dumps({"subscription": SUBSCRIPTION_1["subscription"]}),
) )
assert resp.status == HTTP_INTERNAL_SERVER_ERROR, resp.response assert resp.status == HTTPStatus.INTERNAL_SERVER_ERROR, resp.response
assert registrations == { assert registrations == {
"some device": SUBSCRIPTION_1, "some device": SUBSCRIPTION_1,
"other device": SUBSCRIPTION_2, "other device": SUBSCRIPTION_2,
@ -469,7 +469,7 @@ async def test_callback_view_no_jwt(hass, hass_client):
), ),
) )
assert resp.status == 401 assert resp.status == HTTPStatus.UNAUTHORIZED
async def test_callback_view_with_jwt(hass, hass_client): async def test_callback_view_with_jwt(hass, hass_client):
@ -504,7 +504,7 @@ async def test_callback_view_with_jwt(hass, hass_client):
PUBLISH_URL, json={"type": "push"}, headers={AUTHORIZATION: bearer_token} PUBLISH_URL, json={"type": "push"}, headers={AUTHORIZATION: bearer_token}
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.json() body = await resp.json()
assert body == {"event": "push", "status": "ok"} assert body == {"event": "push", "status": "ok"}

View File

@ -1,5 +1,6 @@
"""The tests for the Home Assistant HTTP component.""" """The tests for the Home Assistant HTTP component."""
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
from ipaddress import ip_network from ipaddress import ip_network
from unittest.mock import patch from unittest.mock import patch
@ -94,10 +95,10 @@ async def test_cant_access_with_password_in_header(
client = await aiohttp_client(app) client = await aiohttp_client(app)
req = await client.get("/", headers={HTTP_HEADER_HA_AUTH: API_PASSWORD}) req = await client.get("/", headers={HTTP_HEADER_HA_AUTH: API_PASSWORD})
assert req.status == 401 assert req.status == HTTPStatus.UNAUTHORIZED
req = await client.get("/", headers={HTTP_HEADER_HA_AUTH: "wrong-pass"}) req = await client.get("/", headers={HTTP_HEADER_HA_AUTH: "wrong-pass"})
assert req.status == 401 assert req.status == HTTPStatus.UNAUTHORIZED
async def test_cant_access_with_password_in_query( async def test_cant_access_with_password_in_query(
@ -108,13 +109,13 @@ async def test_cant_access_with_password_in_query(
client = await aiohttp_client(app) client = await aiohttp_client(app)
resp = await client.get("/", params={"api_password": API_PASSWORD}) resp = await client.get("/", params={"api_password": API_PASSWORD})
assert resp.status == 401 assert resp.status == HTTPStatus.UNAUTHORIZED
resp = await client.get("/") resp = await client.get("/")
assert resp.status == 401 assert resp.status == HTTPStatus.UNAUTHORIZED
resp = await client.get("/", params={"api_password": "wrong-password"}) resp = await client.get("/", params={"api_password": "wrong-password"})
assert resp.status == 401 assert resp.status == HTTPStatus.UNAUTHORIZED
async def test_basic_auth_does_not_work(app, aiohttp_client, hass, legacy_auth): async def test_basic_auth_does_not_work(app, aiohttp_client, hass, legacy_auth):
@ -123,16 +124,16 @@ async def test_basic_auth_does_not_work(app, aiohttp_client, hass, legacy_auth):
client = await aiohttp_client(app) client = await aiohttp_client(app)
req = await client.get("/", auth=BasicAuth("homeassistant", API_PASSWORD)) req = await client.get("/", auth=BasicAuth("homeassistant", API_PASSWORD))
assert req.status == 401 assert req.status == HTTPStatus.UNAUTHORIZED
req = await client.get("/", auth=BasicAuth("wrong_username", API_PASSWORD)) req = await client.get("/", auth=BasicAuth("wrong_username", API_PASSWORD))
assert req.status == 401 assert req.status == HTTPStatus.UNAUTHORIZED
req = await client.get("/", auth=BasicAuth("homeassistant", "wrong password")) req = await client.get("/", auth=BasicAuth("homeassistant", "wrong password"))
assert req.status == 401 assert req.status == HTTPStatus.UNAUTHORIZED
req = await client.get("/", headers={"authorization": "NotBasic abcdefg"}) req = await client.get("/", headers={"authorization": "NotBasic abcdefg"})
assert req.status == 401 assert req.status == HTTPStatus.UNAUTHORIZED
async def test_cannot_access_with_trusted_ip( async def test_cannot_access_with_trusted_ip(
@ -147,12 +148,16 @@ async def test_cannot_access_with_trusted_ip(
for remote_addr in UNTRUSTED_ADDRESSES: for remote_addr in UNTRUSTED_ADDRESSES:
set_mock_ip(remote_addr) set_mock_ip(remote_addr)
resp = await client.get("/") resp = await client.get("/")
assert resp.status == 401, f"{remote_addr} shouldn't be trusted" assert (
resp.status == HTTPStatus.UNAUTHORIZED
), f"{remote_addr} shouldn't be trusted"
for remote_addr in TRUSTED_ADDRESSES: for remote_addr in TRUSTED_ADDRESSES:
set_mock_ip(remote_addr) set_mock_ip(remote_addr)
resp = await client.get("/") resp = await client.get("/")
assert resp.status == 401, f"{remote_addr} shouldn't be trusted" assert (
resp.status == HTTPStatus.UNAUTHORIZED
), f"{remote_addr} shouldn't be trusted"
async def test_auth_active_access_with_access_token_in_header( async def test_auth_active_access_with_access_token_in_header(
@ -165,27 +170,27 @@ async def test_auth_active_access_with_access_token_in_header(
refresh_token = await hass.auth.async_validate_access_token(hass_access_token) refresh_token = await hass.auth.async_validate_access_token(hass_access_token)
req = await client.get("/", headers={"Authorization": f"Bearer {token}"}) req = await client.get("/", headers={"Authorization": f"Bearer {token}"})
assert req.status == 200 assert req.status == HTTPStatus.OK
assert await req.json() == {"user_id": refresh_token.user.id} assert await req.json() == {"user_id": refresh_token.user.id}
req = await client.get("/", headers={"AUTHORIZATION": f"Bearer {token}"}) req = await client.get("/", headers={"AUTHORIZATION": f"Bearer {token}"})
assert req.status == 200 assert req.status == HTTPStatus.OK
assert await req.json() == {"user_id": refresh_token.user.id} assert await req.json() == {"user_id": refresh_token.user.id}
req = await client.get("/", headers={"authorization": f"Bearer {token}"}) req = await client.get("/", headers={"authorization": f"Bearer {token}"})
assert req.status == 200 assert req.status == HTTPStatus.OK
assert await req.json() == {"user_id": refresh_token.user.id} assert await req.json() == {"user_id": refresh_token.user.id}
req = await client.get("/", headers={"Authorization": token}) req = await client.get("/", headers={"Authorization": token})
assert req.status == 401 assert req.status == HTTPStatus.UNAUTHORIZED
req = await client.get("/", headers={"Authorization": f"BEARER {token}"}) req = await client.get("/", headers={"Authorization": f"BEARER {token}"})
assert req.status == 401 assert req.status == HTTPStatus.UNAUTHORIZED
refresh_token = await hass.auth.async_validate_access_token(hass_access_token) refresh_token = await hass.auth.async_validate_access_token(hass_access_token)
refresh_token.user.is_active = False refresh_token.user.is_active = False
req = await client.get("/", headers={"Authorization": f"Bearer {token}"}) req = await client.get("/", headers={"Authorization": f"Bearer {token}"})
assert req.status == 401 assert req.status == HTTPStatus.UNAUTHORIZED
async def test_auth_active_access_with_trusted_ip( async def test_auth_active_access_with_trusted_ip(
@ -200,12 +205,16 @@ async def test_auth_active_access_with_trusted_ip(
for remote_addr in UNTRUSTED_ADDRESSES: for remote_addr in UNTRUSTED_ADDRESSES:
set_mock_ip(remote_addr) set_mock_ip(remote_addr)
resp = await client.get("/") resp = await client.get("/")
assert resp.status == 401, f"{remote_addr} shouldn't be trusted" assert (
resp.status == HTTPStatus.UNAUTHORIZED
), f"{remote_addr} shouldn't be trusted"
for remote_addr in TRUSTED_ADDRESSES: for remote_addr in TRUSTED_ADDRESSES:
set_mock_ip(remote_addr) set_mock_ip(remote_addr)
resp = await client.get("/") resp = await client.get("/")
assert resp.status == 401, f"{remote_addr} shouldn't be trusted" assert (
resp.status == HTTPStatus.UNAUTHORIZED
), f"{remote_addr} shouldn't be trusted"
async def test_auth_legacy_support_api_password_cannot_access( async def test_auth_legacy_support_api_password_cannot_access(
@ -216,13 +225,13 @@ async def test_auth_legacy_support_api_password_cannot_access(
client = await aiohttp_client(app) client = await aiohttp_client(app)
req = await client.get("/", headers={HTTP_HEADER_HA_AUTH: API_PASSWORD}) req = await client.get("/", headers={HTTP_HEADER_HA_AUTH: API_PASSWORD})
assert req.status == 401 assert req.status == HTTPStatus.UNAUTHORIZED
resp = await client.get("/", params={"api_password": API_PASSWORD}) resp = await client.get("/", params={"api_password": API_PASSWORD})
assert resp.status == 401 assert resp.status == HTTPStatus.UNAUTHORIZED
req = await client.get("/", auth=BasicAuth("homeassistant", API_PASSWORD)) req = await client.get("/", auth=BasicAuth("homeassistant", API_PASSWORD))
assert req.status == 401 assert req.status == HTTPStatus.UNAUTHORIZED
async def test_auth_access_signed_path(hass, app, aiohttp_client, hass_access_token): async def test_auth_access_signed_path(hass, app, aiohttp_client, hass_access_token):
@ -237,17 +246,17 @@ async def test_auth_access_signed_path(hass, app, aiohttp_client, hass_access_to
signed_path = async_sign_path(hass, refresh_token.id, "/", timedelta(seconds=5)) signed_path = async_sign_path(hass, refresh_token.id, "/", timedelta(seconds=5))
req = await client.get(signed_path) req = await client.get(signed_path)
assert req.status == 200 assert req.status == HTTPStatus.OK
data = await req.json() data = await req.json()
assert data["user_id"] == refresh_token.user.id assert data["user_id"] == refresh_token.user.id
# Use signature on other path # Use signature on other path
req = await client.get("/another_path?{}".format(signed_path.split("?")[1])) req = await client.get("/another_path?{}".format(signed_path.split("?")[1]))
assert req.status == 401 assert req.status == HTTPStatus.UNAUTHORIZED
# We only allow GET # We only allow GET
req = await client.post(signed_path) req = await client.post(signed_path)
assert req.status == 401 assert req.status == HTTPStatus.UNAUTHORIZED
# Never valid as expired in the past. # Never valid as expired in the past.
expired_signed_path = async_sign_path( expired_signed_path = async_sign_path(
@ -255,9 +264,9 @@ async def test_auth_access_signed_path(hass, app, aiohttp_client, hass_access_to
) )
req = await client.get(expired_signed_path) req = await client.get(expired_signed_path)
assert req.status == 401 assert req.status == HTTPStatus.UNAUTHORIZED
# refresh token gone should also invalidate signature # refresh token gone should also invalidate signature
await hass.auth.async_remove_refresh_token(refresh_token) await hass.auth.async_remove_refresh_token(refresh_token)
req = await client.get(signed_path) req = await client.get(signed_path)
assert req.status == 401 assert req.status == HTTPStatus.UNAUTHORIZED

View File

@ -1,4 +1,6 @@
"""The tests for the Home Assistant HTTP component.""" """The tests for the Home Assistant HTTP component."""
from http import HTTPStatus
# pylint: disable=protected-access # pylint: disable=protected-access
from ipaddress import ip_address from ipaddress import ip_address
import os import os
@ -19,7 +21,6 @@ from homeassistant.components.http.ban import (
setup_bans, setup_bans,
) )
from homeassistant.components.http.view import request_handler_factory from homeassistant.components.http.view import request_handler_factory
from homeassistant.const import HTTP_FORBIDDEN
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from . import mock_real_ip from . import mock_real_ip
@ -65,14 +66,16 @@ async def test_access_from_banned_ip(hass, aiohttp_client):
for remote_addr in BANNED_IPS: for remote_addr in BANNED_IPS:
set_real_ip(remote_addr) set_real_ip(remote_addr)
resp = await client.get("/") resp = await client.get("/")
assert resp.status == HTTP_FORBIDDEN assert resp.status == HTTPStatus.FORBIDDEN
@pytest.mark.parametrize( @pytest.mark.parametrize(
"remote_addr, bans, status", "remote_addr, bans, status",
list( list(
zip( zip(
BANNED_IPS_WITH_SUPERVISOR, [1, 1, 0], [HTTP_FORBIDDEN, HTTP_FORBIDDEN, 401] BANNED_IPS_WITH_SUPERVISOR,
[1, 1, 0],
[HTTPStatus.FORBIDDEN, HTTPStatus.FORBIDDEN, HTTPStatus.UNAUTHORIZED],
) )
), ),
) )
@ -104,7 +107,7 @@ async def test_access_from_supervisor_ip(
"homeassistant.components.http.ban.open", m_open, create=True "homeassistant.components.http.ban.open", m_open, create=True
): ):
resp = await client.get("/") resp = await client.get("/")
assert resp.status == 401 assert resp.status == HTTPStatus.UNAUTHORIZED
assert len(app[KEY_BANNED_IPS]) == bans assert len(app[KEY_BANNED_IPS]) == bans
assert m_open.call_count == bans assert m_open.call_count == bans
@ -155,19 +158,19 @@ async def test_ip_bans_file_creation(hass, aiohttp_client):
with patch("homeassistant.components.http.ban.open", m_open, create=True): with patch("homeassistant.components.http.ban.open", m_open, create=True):
resp = await client.get("/") resp = await client.get("/")
assert resp.status == 401 assert resp.status == HTTPStatus.UNAUTHORIZED
assert len(app[KEY_BANNED_IPS]) == len(BANNED_IPS) assert len(app[KEY_BANNED_IPS]) == len(BANNED_IPS)
assert m_open.call_count == 0 assert m_open.call_count == 0
resp = await client.get("/") resp = await client.get("/")
assert resp.status == 401 assert resp.status == HTTPStatus.UNAUTHORIZED
assert len(app[KEY_BANNED_IPS]) == len(BANNED_IPS) + 1 assert len(app[KEY_BANNED_IPS]) == len(BANNED_IPS) + 1
m_open.assert_called_once_with( m_open.assert_called_once_with(
hass.config.path(IP_BANS_FILE), "a", encoding="utf8" hass.config.path(IP_BANS_FILE), "a", encoding="utf8"
) )
resp = await client.get("/") resp = await client.get("/")
assert resp.status == HTTP_FORBIDDEN assert resp.status == HTTPStatus.FORBIDDEN
assert m_open.call_count == 1 assert m_open.call_count == 1
assert ( assert (
@ -216,19 +219,19 @@ async def test_failed_login_attempts_counter(hass, aiohttp_client):
client = await aiohttp_client(app) client = await aiohttp_client(app)
resp = await client.get("/auth_false") resp = await client.get("/auth_false")
assert resp.status == 401 assert resp.status == HTTPStatus.UNAUTHORIZED
assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 1 assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 1
resp = await client.get("/auth_false") resp = await client.get("/auth_false")
assert resp.status == 401 assert resp.status == HTTPStatus.UNAUTHORIZED
assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 2 assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 2
resp = await client.get("/") resp = await client.get("/")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 2 assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 2
# This used to check that with trusted networks we reset login attempts # This used to check that with trusted networks we reset login attempts
# We no longer support trusted networks. # We no longer support trusted networks.
resp = await client.get("/auth_true") resp = await client.get("/auth_true")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 2 assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 2

View File

@ -1,4 +1,5 @@
"""Test cors for the HTTP component.""" """Test cors for the HTTP component."""
from http import HTTPStatus
from pathlib import Path from pathlib import Path
from unittest.mock import patch from unittest.mock import patch
@ -59,28 +60,28 @@ def client(loop, aiohttp_client):
async def test_cors_requests(client): async def test_cors_requests(client):
"""Test cross origin requests.""" """Test cross origin requests."""
req = await client.get("/", headers={ORIGIN: TRUSTED_ORIGIN}) req = await client.get("/", headers={ORIGIN: TRUSTED_ORIGIN})
assert req.status == 200 assert req.status == HTTPStatus.OK
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN
# With password in URL # With password in URL
req = await client.get( req = await client.get(
"/", params={"api_password": "some-pass"}, headers={ORIGIN: TRUSTED_ORIGIN} "/", params={"api_password": "some-pass"}, headers={ORIGIN: TRUSTED_ORIGIN}
) )
assert req.status == 200 assert req.status == HTTPStatus.OK
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN
# With password in headers # With password in headers
req = await client.get( req = await client.get(
"/", headers={HTTP_HEADER_HA_AUTH: "some-pass", ORIGIN: TRUSTED_ORIGIN} "/", headers={HTTP_HEADER_HA_AUTH: "some-pass", ORIGIN: TRUSTED_ORIGIN}
) )
assert req.status == 200 assert req.status == HTTPStatus.OK
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN
# With auth token in headers # With auth token in headers
req = await client.get( req = await client.get(
"/", headers={AUTHORIZATION: "Bearer some-token", ORIGIN: TRUSTED_ORIGIN} "/", headers={AUTHORIZATION: "Bearer some-token", ORIGIN: TRUSTED_ORIGIN}
) )
assert req.status == 200 assert req.status == HTTPStatus.OK
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN
@ -95,7 +96,7 @@ async def test_cors_preflight_allowed(client):
}, },
) )
assert req.status == 200 assert req.status == HTTPStatus.OK
assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN assert req.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == TRUSTED_ORIGIN
assert req.headers[ACCESS_CONTROL_ALLOW_HEADERS] == "X-REQUESTED-WITH" assert req.headers[ACCESS_CONTROL_ALLOW_HEADERS] == "X-REQUESTED-WITH"
@ -139,7 +140,7 @@ async def test_cors_works_with_frontend(hass, hass_client):
) )
client = await hass_client() client = await hass_client()
resp = await client.get("/") resp = await client.get("/")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
async def test_cors_on_static_files(hass, hass_client): async def test_cors_on_static_files(hass, hass_client):
@ -157,5 +158,5 @@ async def test_cors_on_static_files(hass, hass_client):
ACCESS_CONTROL_REQUEST_METHOD: "GET", ACCESS_CONTROL_REQUEST_METHOD: "GET",
}, },
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert resp.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == "http://www.example.com" assert resp.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == "http://www.example.com"

View File

@ -1,4 +1,5 @@
"""Test data validator decorator.""" """Test data validator decorator."""
from http import HTTPStatus
from unittest.mock import Mock from unittest.mock import Mock
from aiohttp import web from aiohttp import web
@ -35,13 +36,13 @@ async def test_validator(aiohttp_client):
) )
resp = await client.post("/", json={"test": "bla"}) resp = await client.post("/", json={"test": "bla"})
assert resp.status == 200 assert resp.status == HTTPStatus.OK
resp = await client.post("/", json={"test": 100}) resp = await client.post("/", json={"test": 100})
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
resp = await client.post("/") resp = await client.post("/")
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
async def test_validator_allow_empty(aiohttp_client): async def test_validator_allow_empty(aiohttp_client):
@ -61,10 +62,10 @@ async def test_validator_allow_empty(aiohttp_client):
) )
resp = await client.post("/", json={"test": "bla"}) resp = await client.post("/", json={"test": "bla"})
assert resp.status == 200 assert resp.status == HTTPStatus.OK
resp = await client.post("/", json={"test": 100}) resp = await client.post("/", json={"test": 100})
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
resp = await client.post("/") resp = await client.post("/")
assert resp.status == 200 assert resp.status == HTTPStatus.OK

View File

@ -1,4 +1,5 @@
"""Test real forwarded middleware.""" """Test real forwarded middleware."""
from http import HTTPStatus
from ipaddress import ip_network from ipaddress import ip_network
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
@ -34,7 +35,7 @@ async def test_x_forwarded_for_without_trusted_proxy(aiohttp_client, caplog):
mock_api_client = await aiohttp_client(app) mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: "255.255.255.255"}) resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: "255.255.255.255"})
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
assert ( assert (
"Received X-Forwarded-For header from an untrusted proxy 127.0.0.1" "Received X-Forwarded-For header from an untrusted proxy 127.0.0.1"
in caplog.text in caplog.text
@ -81,7 +82,7 @@ async def test_x_forwarded_for_with_trusted_proxy(
mock_api_client = await aiohttp_client(app) mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: x_forwarded_for}) resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: x_forwarded_for})
assert resp.status == 200 assert resp.status == HTTPStatus.OK
async def test_x_forwarded_for_disabled_with_proxy(aiohttp_client, caplog): async def test_x_forwarded_for_disabled_with_proxy(aiohttp_client, caplog):
@ -104,7 +105,7 @@ async def test_x_forwarded_for_disabled_with_proxy(aiohttp_client, caplog):
mock_api_client = await aiohttp_client(app) mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: "255.255.255.255"}) resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: "255.255.255.255"})
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
assert ( assert (
"A request from a reverse proxy was received from 127.0.0.1, but your HTTP " "A request from a reverse proxy was received from 127.0.0.1, but your HTTP "
"integration is not set-up for reverse proxies" in caplog.text "integration is not set-up for reverse proxies" in caplog.text
@ -132,7 +133,7 @@ async def test_x_forwarded_for_with_spoofed_header(aiohttp_client):
"/", headers={X_FORWARDED_FOR: "222.222.222.222, 255.255.255.255"} "/", headers={X_FORWARDED_FOR: "222.222.222.222, 255.255.255.255"}
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
@pytest.mark.parametrize( @pytest.mark.parametrize(
@ -160,7 +161,7 @@ async def test_x_forwarded_for_with_malformed_header(
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: x_forwarded_for}) resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: x_forwarded_for})
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
assert "Invalid IP address in X-Forwarded-For" in caplog.text assert "Invalid IP address in X-Forwarded-For" in caplog.text
@ -180,7 +181,7 @@ async def test_x_forwarded_for_with_multiple_headers(aiohttp_client, caplog):
], ],
) )
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
assert "Too many headers for X-Forwarded-For" in caplog.text assert "Too many headers for X-Forwarded-For" in caplog.text
@ -237,7 +238,7 @@ async def test_x_forwarded_proto_with_trusted_proxy(
}, },
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
async def test_x_forwarded_proto_with_trusted_proxy_multiple_for(aiohttp_client): async def test_x_forwarded_proto_with_trusted_proxy_multiple_for(aiohttp_client):
@ -265,7 +266,7 @@ async def test_x_forwarded_proto_with_trusted_proxy_multiple_for(aiohttp_client)
}, },
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
async def test_x_forwarded_proto_not_processed_without_for(aiohttp_client): async def test_x_forwarded_proto_not_processed_without_for(aiohttp_client):
@ -287,7 +288,7 @@ async def test_x_forwarded_proto_not_processed_without_for(aiohttp_client):
mock_api_client = await aiohttp_client(app) mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_PROTO: "https"}) resp = await mock_api_client.get("/", headers={X_FORWARDED_PROTO: "https"})
assert resp.status == 200 assert resp.status == HTTPStatus.OK
async def test_x_forwarded_proto_with_multiple_headers(aiohttp_client, caplog): async def test_x_forwarded_proto_with_multiple_headers(aiohttp_client, caplog):
@ -306,7 +307,7 @@ async def test_x_forwarded_proto_with_multiple_headers(aiohttp_client, caplog):
], ],
) )
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
assert "Too many headers for X-Forward-Proto" in caplog.text assert "Too many headers for X-Forward-Proto" in caplog.text
@ -328,7 +329,7 @@ async def test_x_forwarded_proto_empty_element(
headers={X_FORWARDED_FOR: "1.1.1.1", X_FORWARDED_PROTO: x_forwarded_proto}, headers={X_FORWARDED_FOR: "1.1.1.1", X_FORWARDED_PROTO: x_forwarded_proto},
) )
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
assert "Empty item received in X-Forward-Proto header" in caplog.text assert "Empty item received in X-Forward-Proto header" in caplog.text
@ -356,7 +357,7 @@ async def test_x_forwarded_proto_incorrect_number_of_elements(
}, },
) )
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
assert ( assert (
f"Incorrect number of elements in X-Forward-Proto. Expected 1 or {expected}, got {got}" f"Incorrect number of elements in X-Forward-Proto. Expected 1 or {expected}, got {got}"
in caplog.text in caplog.text
@ -384,7 +385,7 @@ async def test_x_forwarded_host_with_trusted_proxy(aiohttp_client):
headers={X_FORWARDED_FOR: "255.255.255.255", X_FORWARDED_HOST: "example.com"}, headers={X_FORWARDED_FOR: "255.255.255.255", X_FORWARDED_HOST: "example.com"},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
async def test_x_forwarded_host_not_processed_without_for(aiohttp_client): async def test_x_forwarded_host_not_processed_without_for(aiohttp_client):
@ -406,7 +407,7 @@ async def test_x_forwarded_host_not_processed_without_for(aiohttp_client):
mock_api_client = await aiohttp_client(app) mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_HOST: "example.com"}) resp = await mock_api_client.get("/", headers={X_FORWARDED_HOST: "example.com"})
assert resp.status == 200 assert resp.status == HTTPStatus.OK
async def test_x_forwarded_host_with_multiple_headers(aiohttp_client, caplog): async def test_x_forwarded_host_with_multiple_headers(aiohttp_client, caplog):
@ -425,7 +426,7 @@ async def test_x_forwarded_host_with_multiple_headers(aiohttp_client, caplog):
], ],
) )
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
assert "Too many headers for X-Forwarded-Host" in caplog.text assert "Too many headers for X-Forwarded-Host" in caplog.text
@ -440,7 +441,7 @@ async def test_x_forwarded_host_with_empty_header(aiohttp_client, caplog):
"/", headers={X_FORWARDED_FOR: "222.222.222.222", X_FORWARDED_HOST: ""} "/", headers={X_FORWARDED_FOR: "222.222.222.222", X_FORWARDED_HOST: ""}
) )
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
assert "Empty value received in X-Forward-Host header" in caplog.text assert "Empty value received in X-Forward-Host header" in caplog.text
@ -460,4 +461,4 @@ async def test_x_forwarded_cloud(aiohttp_client, caplog):
) )
# This request would normally fail because it's invalid, now it works. # This request would normally fail because it's invalid, now it works.
assert resp.status == 200 assert resp.status == HTTPStatus.OK

View File

@ -1,5 +1,6 @@
"""The tests for the Home Assistant HTTP component.""" """The tests for the Home Assistant HTTP component."""
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
from ipaddress import ip_network from ipaddress import ip_network
import logging import logging
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
@ -72,7 +73,7 @@ async def test_not_log_password(hass, hass_client_no_auth, caplog, legacy_auth):
resp = await client.get("/api/", params={"api_password": "test-password"}) resp = await client.get("/api/", params={"api_password": "test-password"})
assert resp.status == 401 assert resp.status == HTTPStatus.UNAUTHORIZED
logs = caplog.text logs = caplog.text
# Ensure we don't log API passwords # Ensure we don't log API passwords

View File

@ -1,5 +1,6 @@
"""Test request context middleware.""" """Test request context middleware."""
from contextvars import ContextVar from contextvars import ContextVar
from http import HTTPStatus
from aiohttp import web from aiohttp import web
@ -24,7 +25,7 @@ async def test_request_context_middleware(aiohttp_client):
mock_api_client = await aiohttp_client(app) mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/") resp = await mock_api_client.get("/")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
text = await resp.text() text = await resp.text()
assert text == "hi!" assert text == "hi!"

View File

@ -1,4 +1,6 @@
"""Test security filter middleware.""" """Test security filter middleware."""
from http import HTTPStatus
from aiohttp import web from aiohttp import web
import pytest import pytest
import urllib3 import urllib3
@ -31,7 +33,7 @@ async def test_ok_requests(request_path, request_params, aiohttp_client):
mock_api_client = await aiohttp_client(app) mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(request_path, params=request_params) resp = await mock_api_client.get(request_path, params=request_params)
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert await resp.text() == "OK" assert await resp.text() == "OK"
@ -80,7 +82,7 @@ async def test_bad_requests(
request_params, request_params,
) )
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
message = "Filtered a potential harmful request to:" message = "Filtered a potential harmful request to:"
if fail_on_query_string: if fail_on_query_string:

View File

@ -1,4 +1,5 @@
"""Tests for Home Assistant View.""" """Tests for Home Assistant View."""
from http import HTTPStatus
from unittest.mock import AsyncMock, Mock from unittest.mock import AsyncMock, Mock
from aiohttp.web_exceptions import ( from aiohttp.web_exceptions import (
@ -68,4 +69,4 @@ async def test_not_running(mock_request_with_stopping):
response = await request_handler_factory( response = await request_handler_factory(
Mock(requires_auth=False), AsyncMock(side_effect=Unauthorized) Mock(requires_auth=False), AsyncMock(side_effect=Unauthorized)
)(mock_request_with_stopping) )(mock_request_with_stopping)
assert response.status == 503 assert response.status == HTTPStatus.SERVICE_UNAVAILABLE