From b52c5c82b18e016f3420cd7cf2f4d0c6f1b8b36b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Sat, 23 Oct 2021 21:34:53 +0300 Subject: [PATCH] Use http.HTTPStatus in components/[gh]* (#58246) --- .../components/google_assistant/helpers.py | 3 +- .../components/google_assistant/http.py | 9 ++- homeassistant/components/habitica/sensor.py | 7 ++- .../components/hangouts/hangouts_bot.py | 4 +- homeassistant/components/hassio/handler.py | 5 +- .../components/haveibeenpwned/sensor.py | 13 ++-- .../components/hitron_coda/device_tracker.py | 13 ++-- homeassistant/components/http/ban.py | 6 +- homeassistant/components/http/view.py | 4 +- homeassistant/components/hue/bridge.py | 4 +- .../garages_amsterdam/test_config_flow.py | 6 +- tests/components/generic/test_camera.py | 41 ++++++------ tests/components/geofency/test_init.py | 28 ++++----- .../google_assistant/test_google_assistant.py | 14 +++-- .../google_assistant/test_helpers.py | 9 +-- .../components/google_assistant/test_http.py | 9 +-- .../components/google_assistant/test_init.py | 6 +- tests/components/google_wifi/test_sensor.py | 7 ++- tests/components/gpslogger/test_init.py | 26 ++++---- tests/components/habitica/test_init.py | 4 +- tests/components/hassio/test_addon_panel.py | 5 +- tests/components/hassio/test_auth.py | 23 +++---- tests/components/hassio/test_discovery.py | 3 +- tests/components/hassio/test_http.py | 25 ++++---- tests/components/hassio/test_ingress.py | 16 ++--- tests/components/history/test_init.py | 23 +++---- .../home_connect/test_config_flow.py | 3 +- .../home_plus_control/test_config_flow.py | 5 +- tests/components/html5/test_notify.py | 32 +++++----- tests/components/http/test_auth.py | 63 +++++++++++-------- tests/components/http/test_ban.py | 25 ++++---- tests/components/http/test_cors.py | 15 ++--- tests/components/http/test_data_validator.py | 13 ++-- tests/components/http/test_forwarded.py | 35 ++++++----- tests/components/http/test_init.py | 3 +- tests/components/http/test_request_context.py | 3 +- tests/components/http/test_security_filter.py | 6 +- tests/components/http/test_view.py | 3 +- 38 files changed, 272 insertions(+), 247 deletions(-) diff --git a/homeassistant/components/google_assistant/helpers.py b/homeassistant/components/google_assistant/helpers.py index 67f4e0c60df..14667dbb303 100644 --- a/homeassistant/components/google_assistant/helpers.py +++ b/homeassistant/components/google_assistant/helpers.py @@ -4,6 +4,7 @@ from __future__ import annotations from abc import ABC, abstractmethod from asyncio import gather from collections.abc import Mapping +from http import HTTPStatus import logging import pprint @@ -203,7 +204,7 @@ class AbstractConfig(ABC): # Remove any pending sync self._google_sync_unsub.pop(agent_user_id, lambda: None)() 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) return status diff --git a/homeassistant/components/google_assistant/http.py b/homeassistant/components/google_assistant/http.py index d5489aad05a..ba7dc2597bc 100644 --- a/homeassistant/components/google_assistant/http.py +++ b/homeassistant/components/google_assistant/http.py @@ -1,6 +1,7 @@ """Support for Google Actions Smart Home Control.""" import asyncio from datetime import timedelta +from http import HTTPStatus import logging from uuid import uuid4 @@ -14,8 +15,6 @@ from homeassistant.const import ( CLOUD_NEVER_EXPOSED_ENTITIES, ENTITY_CATEGORY_CONFIG, ENTITY_CATEGORY_DIAGNOSTIC, - HTTP_INTERNAL_SERVER_ERROR, - HTTP_UNAUTHORIZED, ) from homeassistant.helpers import entity_registry as er from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -157,7 +156,7 @@ class GoogleConfig(AbstractConfig): ) _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): if CONF_SERVICE_ACCOUNT not in self._config: @@ -198,7 +197,7 @@ class GoogleConfig(AbstractConfig): try: return await _call() except ClientResponseError as error: - if error.status == HTTP_UNAUTHORIZED: + if error.status == HTTPStatus.UNAUTHORIZED: _LOGGER.warning( "Request for %s unauthorized, renewing token and retrying", url ) @@ -210,7 +209,7 @@ class GoogleConfig(AbstractConfig): return error.status except (asyncio.TimeoutError, ClientError): _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): """Send a state report to Google.""" diff --git a/homeassistant/components/habitica/sensor.py b/homeassistant/components/habitica/sensor.py index 64494fb9694..cd488819eda 100644 --- a/homeassistant/components/habitica/sensor.py +++ b/homeassistant/components/habitica/sensor.py @@ -1,12 +1,13 @@ """Support for Habitica sensors.""" from collections import namedtuple from datetime import timedelta +from http import HTTPStatus import logging from aiohttp import ClientResponseError 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 .const import DOMAIN @@ -94,7 +95,7 @@ class HabitipyData: try: self.data = await self.api.user.get() except ClientResponseError as error: - if error.status == HTTP_TOO_MANY_REQUESTS: + if error.status == HTTPStatus.TOO_MANY_REQUESTS: _LOGGER.warning( "Sensor data update for %s has too many API requests;" " Skipping the update", @@ -111,7 +112,7 @@ class HabitipyData: try: self.tasks[task_type] = await self.api.tasks.user.get(type=task_type) except ClientResponseError as error: - if error.status == HTTP_TOO_MANY_REQUESTS: + if error.status == HTTPStatus.TOO_MANY_REQUESTS: _LOGGER.warning( "Sensor data update for %s has too many API requests;" " Skipping the update", diff --git a/homeassistant/components/hangouts/hangouts_bot.py b/homeassistant/components/hangouts/hangouts_bot.py index 24be9fff779..16872079be3 100644 --- a/homeassistant/components/hangouts/hangouts_bot.py +++ b/homeassistant/components/hangouts/hangouts_bot.py @@ -1,6 +1,7 @@ """The Hangouts Bot.""" import asyncio from contextlib import suppress +from http import HTTPStatus import io import logging @@ -8,7 +9,6 @@ import aiohttp import hangups from hangups import ChatMessageEvent, ChatMessageSegment, Client, get_auth, hangouts_pb2 -from homeassistant.const import HTTP_OK from homeassistant.core import callback from homeassistant.helpers import dispatcher, intent from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -273,7 +273,7 @@ class HangoutsBot: try: websession = async_get_clientsession(self.hass) async with websession.get(uri, timeout=5) as response: - if response.status != HTTP_OK: + if response.status != HTTPStatus.OK: _LOGGER.error( "Fetch image failed, %s, %s", response.status, response ) diff --git a/homeassistant/components/hassio/handler.py b/homeassistant/components/hassio/handler.py index 7d4b5da8f5f..4a0312bcecb 100644 --- a/homeassistant/components/hassio/handler.py +++ b/homeassistant/components/hassio/handler.py @@ -1,5 +1,6 @@ """Handler for Hass.io.""" import asyncio +from http import HTTPStatus import logging import os @@ -10,7 +11,7 @@ from homeassistant.components.http import ( CONF_SERVER_PORT, 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 @@ -225,7 +226,7 @@ class HassIO: 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) raise HassioAPIError() diff --git a/homeassistant/components/haveibeenpwned/sensor.py b/homeassistant/components/haveibeenpwned/sensor.py index 738837989b9..cdcc526c8d8 100644 --- a/homeassistant/components/haveibeenpwned/sensor.py +++ b/homeassistant/components/haveibeenpwned/sensor.py @@ -1,5 +1,6 @@ """Support for haveibeenpwned (email breaches) sensor.""" from datetime import timedelta +from http import HTTPStatus import logging from aiohttp.hdrs import USER_AGENT @@ -7,13 +8,7 @@ import requests import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity -from homeassistant.const import ( - ATTR_ATTRIBUTION, - CONF_API_KEY, - CONF_EMAIL, - HTTP_NOT_FOUND, - HTTP_OK, -) +from homeassistant.const import ATTR_ATTRIBUTION, CONF_API_KEY, CONF_EMAIL import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event import track_point_in_time from homeassistant.util import Throttle @@ -163,7 +158,7 @@ class HaveIBeenPwnedData: _LOGGER.error("Failed fetching data for %s", self._email) return - if req.status_code == HTTP_OK: + if req.status_code == HTTPStatus.OK: self.data[self._email] = sorted( req.json(), key=lambda k: k["AddedDate"], reverse=True ) @@ -172,7 +167,7 @@ class HaveIBeenPwnedData: # the forced updates try this current email again self.set_next_email() - elif req.status_code == HTTP_NOT_FOUND: + elif req.status_code == HTTPStatus.NOT_FOUND: self.data[self._email] = [] # only goto next email if we had data so that diff --git a/homeassistant/components/hitron_coda/device_tracker.py b/homeassistant/components/hitron_coda/device_tracker.py index 666f6796d4c..ac362f173e4 100644 --- a/homeassistant/components/hitron_coda/device_tracker.py +++ b/homeassistant/components/hitron_coda/device_tracker.py @@ -1,5 +1,6 @@ """Support for the Hitron CODA-4582U, provided by Rogers.""" from collections import namedtuple +from http import HTTPStatus import logging import requests @@ -10,13 +11,7 @@ from homeassistant.components.device_tracker import ( PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) -from homeassistant.const import ( - CONF_HOST, - CONF_PASSWORD, - CONF_TYPE, - CONF_USERNAME, - HTTP_OK, -) +from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_TYPE, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -88,7 +83,7 @@ class HitronCODADeviceScanner(DeviceScanner): except requests.exceptions.Timeout: _LOGGER.error("Connection to the router timed out at URL %s", self._url) 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) return False try: @@ -113,7 +108,7 @@ class HitronCODADeviceScanner(DeviceScanner): except requests.exceptions.Timeout: _LOGGER.error("Connection to the router timed out at URL %s", self._url) 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) return False try: diff --git a/homeassistant/components/http/ban.py b/homeassistant/components/http/ban.py index 6e4f5c0a661..a1d50dbdcb5 100644 --- a/homeassistant/components/http/ban.py +++ b/homeassistant/components/http/ban.py @@ -5,6 +5,7 @@ from collections import defaultdict from collections.abc import Awaitable, Callable from contextlib import suppress from datetime import datetime +from http import HTTPStatus from ipaddress import ip_address import logging from socket import gethostbyaddr, herror @@ -15,7 +16,6 @@ from aiohttp.web_exceptions import HTTPForbidden, HTTPUnauthorized import voluptuous as vol from homeassistant.config import load_yaml_config_file -from homeassistant.const import HTTP_BAD_REQUEST from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError import homeassistant.helpers.config_validation as cv @@ -89,9 +89,9 @@ def log_invalid_auth( async def handle_req( view: HomeAssistantView, request: Request, *args: Any, **kwargs: Any ) -> 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) - if resp.status >= HTTP_BAD_REQUEST: + if resp.status >= HTTPStatus.BAD_REQUEST: await process_wrong_login(request) return resp diff --git a/homeassistant/components/http/view.py b/homeassistant/components/http/view.py index 949813ca4ad..bf8dc4b432b 100644 --- a/homeassistant/components/http/view.py +++ b/homeassistant/components/http/view.py @@ -19,7 +19,7 @@ from aiohttp.web_urldispatcher import AbstractRoute import voluptuous as vol 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.helpers.json import JSONEncoder @@ -144,7 +144,7 @@ def request_handler_factory( # The method handler returned a ready-made Response, how nice of it return result - status_code = HTTP_OK + status_code = HTTPStatus.OK if isinstance(result, tuple): result, status_code = result diff --git a/homeassistant/components/hue/bridge.py b/homeassistant/components/hue/bridge.py index 1f19138b28f..19ab2128d62 100644 --- a/homeassistant/components/hue/bridge.py +++ b/homeassistant/components/hue/bridge.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio from functools import partial +from http import HTTPStatus import logging from aiohttp import client_exceptions @@ -11,7 +12,6 @@ import async_timeout import slugify as unicode_slug from homeassistant import core -from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR from homeassistant.exceptions import ConfigEntryNotReady 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. if ( isinstance(err, client_exceptions.ClientResponseError) - and err.status < HTTP_INTERNAL_SERVER_ERROR + and err.status < HTTPStatus.INTERNAL_SERVER_ERROR ): raise diff --git a/tests/components/garages_amsterdam/test_config_flow.py b/tests/components/garages_amsterdam/test_config_flow.py index 4ff064ca9d4..a9f5f2c58ad 100644 --- a/tests/components/garages_amsterdam/test_config_flow.py +++ b/tests/components/garages_amsterdam/test_config_flow.py @@ -1,4 +1,5 @@ """Test the Garages Amsterdam config flow.""" +from http import HTTPStatus from unittest.mock import patch from aiohttp import ClientResponseError @@ -44,7 +45,10 @@ async def test_full_flow(hass: HomeAssistant) -> None: "side_effect,reason", [ (RuntimeError, "unknown"), - (ClientResponseError(None, None, status=500), "cannot_connect"), + ( + ClientResponseError(None, None, status=HTTPStatus.INTERNAL_SERVER_ERROR), + "cannot_connect", + ), ], ) async def test_error_handling( diff --git a/tests/components/generic/test_camera.py b/tests/components/generic/test_camera.py index 8642a6a7fac..36a9304cdc1 100644 --- a/tests/components/generic/test_camera.py +++ b/tests/components/generic/test_camera.py @@ -1,5 +1,6 @@ """The tests for generic camera component.""" import asyncio +from http import HTTPStatus from os import path from unittest.mock import patch @@ -9,11 +10,7 @@ import respx from homeassistant import config as hass_config from homeassistant.components.generic import DOMAIN from homeassistant.components.websocket_api.const import TYPE_RESULT -from homeassistant.const import ( - HTTP_INTERNAL_SERVER_ERROR, - HTTP_NOT_FOUND, - SERVICE_RELOAD, -) +from homeassistant.const import SERVICE_RELOAD 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") - assert resp.status == 200 + assert resp.status == HTTPStatus.OK assert respx.calls.call_count == 1 body = await resp.text() 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") - assert resp.status == 200 + assert resp.status == HTTPStatus.OK @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") - assert resp.status == 200 + assert resp.status == HTTPStatus.OK @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/10a").respond(text="hello world") 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( hass, @@ -137,19 +134,19 @@ async def test_limit_refetch(hass, hass_client): with patch("async_timeout.timeout", side_effect=asyncio.TimeoutError()): resp = await client.get("/api/camera_proxy/camera.config_test") 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") resp = await client.get("/api/camera_proxy/camera.config_test") assert respx.calls.call_count == 1 - assert resp.status == 200 + assert resp.status == HTTPStatus.OK body = await resp.text() assert body == "hello world" resp = await client.get("/api/camera_proxy/camera.config_test") assert respx.calls.call_count == 1 - assert resp.status == 200 + assert resp.status == HTTPStatus.OK body = await resp.text() assert body == "hello world" @@ -158,7 +155,7 @@ async def test_limit_refetch(hass, hass_client): # Url change = fetch new image resp = await client.get("/api/camera_proxy/camera.config_test") assert respx.calls.call_count == 2 - assert resp.status == 200 + assert resp.status == HTTPStatus.OK body = await resp.text() assert body == "hello planet" @@ -166,7 +163,7 @@ async def test_limit_refetch(hass, hass_client): hass.states.async_remove("sensor.temp") resp = await client.get("/api/camera_proxy/camera.config_test") assert respx.calls.call_count == 2 - assert resp.status == 200 + assert resp.status == HTTPStatus.OK body = await resp.text() 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") 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" body = await resp_1.text() assert body == svg_image resp_2 = await client.get("/api/camera_proxy/camera.config_test_jpg") assert respx.calls.call_count == 2 - assert resp_2.status == 200 + assert resp_2.status == HTTPStatus.OK assert resp_2.content_type == "image/jpeg" body = await resp_2.text() 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") - assert resp.status == 200 + assert resp.status == HTTPStatus.OK assert respx.calls.call_count == 1 body = await resp.text() 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") - assert resp.status == 404 + assert resp.status == HTTPStatus.NOT_FOUND resp = await client.get("/api/camera_proxy/camera.reload") - assert resp.status == 200 + assert resp.status == HTTPStatus.OK assert respx.calls.call_count == 2 body = await resp.text() 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") - assert resp.status == 200 + assert resp.status == HTTPStatus.OK assert respx.calls.call_count == 1 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") assert respx.calls.call_count == 1 - assert resp.status == 500 + assert resp.status == HTTPStatus.INTERNAL_SERVER_ERROR respx.get("http://example.com").side_effect = [ httpx.RequestError, @@ -457,7 +454,7 @@ async def test_timeout_cancelled(hass, hass_client): for total_calls in range(2, 4): resp = await client.get("/api/camera_proxy/camera.config_test") assert respx.calls.call_count == total_calls - assert resp.status == 200 + assert resp.status == HTTPStatus.OK assert await resp.text() == "hello world" diff --git a/tests/components/geofency/test_init.py b/tests/components/geofency/test_init.py index 44d4e954d28..013450212ed 100644 --- a/tests/components/geofency/test_init.py +++ b/tests/components/geofency/test_init.py @@ -1,4 +1,6 @@ """The tests for the Geofency device tracker platform.""" +from http import HTTPStatus + # pylint: disable=redefined-outer-name from unittest.mock import patch @@ -11,8 +13,6 @@ from homeassistant.config import async_process_ha_core_config from homeassistant.const import ( ATTR_LATITUDE, ATTR_LONGITUDE, - HTTP_OK, - HTTP_UNPROCESSABLE_ENTITY, STATE_HOME, STATE_NOT_HOME, ) @@ -172,7 +172,7 @@ async def test_data_validation(geofency_client, webhook_id): # No data 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"] @@ -181,7 +181,7 @@ async def test_data_validation(geofency_client, webhook_id): copy = GPS_ENTER_HOME.copy() del copy[attribute] 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): @@ -191,7 +191,7 @@ async def test_gps_enter_and_exit_home(hass, geofency_client, webhook_id): # Enter the Home zone req = await geofency_client.post(url, data=GPS_ENTER_HOME) await hass.async_block_till_done() - assert req.status == HTTP_OK + assert req.status == HTTPStatus.OK device_name = slugify(GPS_ENTER_HOME["device"]) state_name = hass.states.get(f"device_tracker.{device_name}").state 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 req = await geofency_client.post(url, data=GPS_EXIT_HOME) await hass.async_block_till_done() - assert req.status == HTTP_OK + assert req.status == HTTPStatus.OK device_name = slugify(GPS_EXIT_HOME["device"]) state_name = hass.states.get(f"device_tracker.{device_name}").state 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) await hass.async_block_till_done() - assert req.status == HTTP_OK + assert req.status == HTTPStatus.OK device_name = slugify(GPS_EXIT_HOME["device"]) current_latitude = hass.states.get(f"device_tracker.{device_name}").attributes[ "latitude" @@ -236,7 +236,7 @@ async def test_beacon_enter_and_exit_home(hass, geofency_client, webhook_id): # Enter the Home zone req = await geofency_client.post(url, data=BEACON_ENTER_HOME) 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']}") state_name = hass.states.get(f"device_tracker.{device_name}").state 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 req = await geofency_client.post(url, data=BEACON_EXIT_HOME) 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']}") state_name = hass.states.get(f"device_tracker.{device_name}").state 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 req = await geofency_client.post(url, data=BEACON_ENTER_CAR) 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']}") state_name = hass.states.get(f"device_tracker.{device_name}").state 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 req = await geofency_client.post(url, data=BEACON_EXIT_CAR) 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']}") state_name = hass.states.get(f"device_tracker.{device_name}").state 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 req = await geofency_client.post(url, data=data) await hass.async_block_till_done() - assert req.status == HTTP_OK + assert req.status == HTTPStatus.OK device_name = slugify(f"beacon_{data['name']}") state_name = hass.states.get(f"device_tracker.{device_name}").state 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 req = await geofency_client.post(url, data=data) await hass.async_block_till_done() - assert req.status == HTTP_OK + assert req.status == HTTPStatus.OK device_name = slugify(f"beacon_{data['name']}") state_name = hass.states.get(f"device_tracker.{device_name}").state assert state_name == STATE_HOME @@ -297,7 +297,7 @@ async def test_load_unload_entry(hass, geofency_client, webhook_id): # Enter the Home zone req = await geofency_client.post(url, data=GPS_ENTER_HOME) await hass.async_block_till_done() - assert req.status == HTTP_OK + assert req.status == HTTPStatus.OK device_name = slugify(GPS_ENTER_HOME["device"]) state_1 = hass.states.get(f"device_tracker.{device_name}") assert state_1.state == STATE_HOME diff --git a/tests/components/google_assistant/test_google_assistant.py b/tests/components/google_assistant/test_google_assistant.py index c17a05ddb3d..ded7429bdee 100644 --- a/tests/components/google_assistant/test_google_assistant.py +++ b/tests/components/google_assistant/test_google_assistant.py @@ -1,4 +1,6 @@ """The tests for the Google Assistant component.""" +from http import HTTPStatus + # pylint: disable=protected-access import json @@ -154,7 +156,7 @@ async def test_sync_request(hass_fixture, assistant_client, auth_header): data=json.dumps(data), headers=auth_header, ) - assert result.status == 200 + assert result.status == HTTPStatus.OK body = await result.json() assert body.get("requestId") == reqid devices = body["payload"]["devices"] @@ -198,7 +200,7 @@ async def test_query_request(hass_fixture, assistant_client, auth_header): data=json.dumps(data), headers=auth_header, ) - assert result.status == 200 + assert result.status == HTTPStatus.OK body = await result.json() assert body.get("requestId") == reqid devices = body["payload"]["devices"] @@ -238,7 +240,7 @@ async def test_query_climate_request(hass_fixture, assistant_client, auth_header data=json.dumps(data), headers=auth_header, ) - assert result.status == 200 + assert result.status == HTTPStatus.OK body = await result.json() assert body.get("requestId") == reqid 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), headers=auth_header, ) - assert result.status == 200 + assert result.status == HTTPStatus.OK body = await result.json() assert body.get("requestId") == reqid devices = body["payload"]["devices"] @@ -350,7 +352,7 @@ async def test_query_humidifier_request(hass_fixture, assistant_client, auth_hea data=json.dumps(data), headers=auth_header, ) - assert result.status == 200 + assert result.status == HTTPStatus.OK body = await result.json() assert body.get("requestId") == reqid devices = body["payload"]["devices"] @@ -464,7 +466,7 @@ async def test_execute_request(hass_fixture, assistant_client, auth_header): data=json.dumps(data), headers=auth_header, ) - assert result.status == 200 + assert result.status == HTTPStatus.OK body = await result.json() assert body.get("requestId") == reqid commands = body["payload"]["commands"] diff --git a/tests/components/google_assistant/test_helpers.py b/tests/components/google_assistant/test_helpers.py index e86156fa614..9e54e6cff3f 100644 --- a/tests/components/google_assistant/test_helpers.py +++ b/tests/components/google_assistant/test_helpers.py @@ -1,5 +1,6 @@ """Test Google Assistant helpers.""" from datetime import timedelta +from http import HTTPStatus from unittest.mock import Mock, call, patch import pytest @@ -112,7 +113,7 @@ async def test_config_local_sdk(hass, hass_client): "requestId": "mock-req-id", }, ) - assert resp.status == 200 + assert resp.status == HTTPStatus.OK result = await resp.json() assert result["requestId"] == "mock-req-id" @@ -126,7 +127,7 @@ async def test_config_local_sdk(hass, hass_client): # Webhook is no longer active resp = await client.post("/api/webhook/mock-webhook-id") - assert resp.status == 200 + assert resp.status == HTTPStatus.OK assert await resp.read() == b"" @@ -148,7 +149,7 @@ async def test_config_local_sdk_if_disabled(hass, hass_client): resp = await client.post( "/api/webhook/mock-webhook-id", json={"requestId": "mock-req-id"} ) - assert resp.status == 200 + assert resp.status == HTTPStatus.OK result = await resp.json() assert result == { "payload": {"errorCode": "deviceTurnedOff"}, @@ -159,7 +160,7 @@ async def test_config_local_sdk_if_disabled(hass, hass_client): # Webhook is no longer active resp = await client.post("/api/webhook/mock-webhook-id") - assert resp.status == 200 + assert resp.status == HTTPStatus.OK assert await resp.read() == b"" diff --git a/tests/components/google_assistant/test_http.py b/tests/components/google_assistant/test_http.py index 013fa3c1d0c..1d62d034703 100644 --- a/tests/components/google_assistant/test_http.py +++ b/tests/components/google_assistant/test_http.py @@ -1,5 +1,6 @@ """Test Google http services.""" from datetime import datetime, timedelta, timezone +from http import HTTPStatus from unittest.mock import ANY, patch 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( HOMEGRAPH_TOKEN_URL, - status=200, + status=HTTPStatus.OK, 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: 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) - assert res == 200 + assert res == HTTPStatus.OK assert mock_get_token.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: 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) diff --git a/tests/components/google_assistant/test_init.py b/tests/components/google_assistant/test_init.py index e663df19d88..69198b99aaa 100644 --- a/tests/components/google_assistant/test_init.py +++ b/tests/components/google_assistant/test_init.py @@ -1,4 +1,6 @@ """The tests for google-assistant init.""" +from http import HTTPStatus + from homeassistant.components import google_assistant as ga from homeassistant.core import Context 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.""" aioclient_mock.post( ga.const.HOMEGRAPH_TOKEN_URL, - status=200, + status=HTTPStatus.OK, 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( hass, diff --git a/tests/components/google_wifi/test_sensor.py b/tests/components/google_wifi/test_sensor.py index 59c95d9883b..add8ec04cbe 100644 --- a/tests/components/google_wifi/test_sensor.py +++ b/tests/components/google_wifi/test_sensor.py @@ -1,5 +1,6 @@ """The tests for the Google Wifi platform.""" from datetime import datetime, timedelta +from http import HTTPStatus from unittest.mock import Mock, patch 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): """Test setup with minimum configuration.""" 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( hass, "sensor", @@ -45,7 +46,7 @@ async def test_setup_minimum(hass, requests_mock): async def test_setup_get(hass, requests_mock): """Test setup with full configuration.""" 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( hass, "sensor", @@ -74,7 +75,7 @@ def setup_api(hass, data, requests_mock): now = datetime(1970, month=1, day=1) sensor_dict = {} 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 api = google_wifi.GoogleWifiAPI("localhost", conditions) for desc in google_wifi.SENSOR_TYPES: diff --git a/tests/components/gpslogger/test_init.py b/tests/components/gpslogger/test_init.py index dc9a3720709..a885699ca05 100644 --- a/tests/components/gpslogger/test_init.py +++ b/tests/components/gpslogger/test_init.py @@ -1,4 +1,5 @@ """The tests the for GPSLogger device tracker platform.""" +from http import HTTPStatus from unittest.mock import patch 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.gpslogger import DOMAIN, TRACKER_UPDATE from homeassistant.config import async_process_ha_core_config -from homeassistant.const import ( - HTTP_OK, - HTTP_UNPROCESSABLE_ENTITY, - STATE_HOME, - STATE_NOT_HOME, -) +from homeassistant.const import STATE_HOME, STATE_NOT_HOME from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.dispatcher import DATA_DISPATCHER from homeassistant.setup import async_setup_component @@ -87,21 +83,21 @@ async def test_missing_data(hass, gpslogger_client, webhook_id): # No data req = await gpslogger_client.post(url) await hass.async_block_till_done() - assert req.status == HTTP_UNPROCESSABLE_ENTITY + assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY # No latitude copy = data.copy() del copy["latitude"] req = await gpslogger_client.post(url, data=copy) await hass.async_block_till_done() - assert req.status == HTTP_UNPROCESSABLE_ENTITY + assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY # No device copy = data.copy() del copy["device"] req = await gpslogger_client.post(url, data=copy) 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): @@ -113,14 +109,14 @@ async def test_enter_and_exit(hass, gpslogger_client, webhook_id): # Enter the Home req = await gpslogger_client.post(url, data=data) 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 assert state_name == STATE_HOME # Enter Home again req = await gpslogger_client.post(url, data=data) 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 assert state_name == STATE_HOME @@ -130,7 +126,7 @@ async def test_enter_and_exit(hass, gpslogger_client, webhook_id): # Enter Somewhere else req = await gpslogger_client.post(url, data=data) 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 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) 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']}") assert state.state == STATE_NOT_HOME 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) 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']}") assert state.state == STATE_HOME assert state.attributes["gps_accuracy"] == 123 @@ -209,7 +205,7 @@ async def test_load_unload_entry(hass, gpslogger_client, webhook_id): # Enter the Home req = await gpslogger_client.post(url, data=data) 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 assert state_name == STATE_HOME assert len(hass.data[DATA_DISPATCHER][TRACKER_UPDATE]) == 1 diff --git a/tests/components/habitica/test_init.py b/tests/components/habitica/test_init.py index 97d4fb092fc..564379aa9d1 100644 --- a/tests/components/habitica/test_init.py +++ b/tests/components/habitica/test_init.py @@ -1,4 +1,6 @@ """Test the habitica module.""" +from http import HTTPStatus + import pytest from homeassistant.components.habitica.const import ( @@ -82,7 +84,7 @@ def common_requests(aioclient_mock): aioclient_mock.post( "https://habitica.com/api/v3/tasks/user", - status=201, + status=HTTPStatus.CREATED, json={"data": TEST_API_CALL_ARGS}, ) diff --git a/tests/components/hassio/test_addon_panel.py b/tests/components/hassio/test_addon_panel.py index 3f6db4dc430..c69ceb2cb5c 100644 --- a/tests/components/hassio/test_addon_panel.py +++ b/tests/components/hassio/test_addon_panel.py @@ -1,4 +1,5 @@ """Test add-on panel.""" +from http import HTTPStatus from unittest.mock import patch 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() 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") - assert resp.status == 200 + assert resp.status == HTTPStatus.OK assert mock_panel.call_count == 2 mock_panel.assert_called_with( diff --git a/tests/components/hassio/test_auth.py b/tests/components/hassio/test_auth.py index a533d468069..e5f1f848fcb 100644 --- a/tests/components/hassio/test_auth.py +++ b/tests/components/hassio/test_auth.py @@ -1,5 +1,6 @@ """The tests for the hassio component.""" +from http import HTTPStatus from unittest.mock import Mock, patch 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 - assert resp.status == 200 + assert resp.status == HTTPStatus.OK 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 - assert resp.status == 401 + assert resp.status == HTTPStatus.UNAUTHORIZED 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 - assert resp.status == 401 + assert resp.status == HTTPStatus.UNAUTHORIZED assert not mock_login.called @@ -66,7 +67,7 @@ async def test_login_error(hass, hassio_client_supervisor): ) # Check we got right response - assert resp.status == 404 + assert resp.status == HTTPStatus.NOT_FOUND 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") # Check we got right response - assert resp.status == 400 + assert resp.status == HTTPStatus.BAD_REQUEST assert not mock_login.called @@ -96,7 +97,7 @@ async def test_login_no_username(hass, hassio_client_supervisor): ) # Check we got right response - assert resp.status == 400 + assert resp.status == HTTPStatus.BAD_REQUEST assert not mock_login.called @@ -117,7 +118,7 @@ async def test_login_success_extra(hass, hassio_client_supervisor): ) # Check we got right response - assert resp.status == 200 + assert resp.status == HTTPStatus.OK 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 - assert resp.status == 200 + assert resp.status == HTTPStatus.OK 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 - assert resp.status == 401 + assert resp.status == HTTPStatus.UNAUTHORIZED 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 - assert resp.status == 401 + assert resp.status == HTTPStatus.UNAUTHORIZED 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 - assert resp.status == 404 + assert resp.status == HTTPStatus.NOT_FOUND diff --git a/tests/components/hassio/test_discovery.py b/tests/components/hassio/test_discovery.py index c23ee40de6e..fc99b06619f 100644 --- a/tests/components/hassio/test_discovery.py +++ b/tests/components/hassio/test_discovery.py @@ -1,4 +1,5 @@ """Test config flow.""" +from http import HTTPStatus from unittest.mock import Mock, patch 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() - assert resp.status == 200 + assert resp.status == HTTPStatus.OK assert aioclient_mock.call_count == 2 assert mock_mqtt.called mock_mqtt.assert_called_with( diff --git a/tests/components/hassio/test_http.py b/tests/components/hassio/test_http.py index 16121393170..7947f7cccae 100644 --- a/tests/components/hassio/test_http.py +++ b/tests/components/hassio/test_http.py @@ -1,5 +1,6 @@ """The tests for the hassio component.""" import asyncio +from http import HTTPStatus from aiohttp import StreamReader import pytest @@ -14,7 +15,7 @@ async def test_forward_request(hassio_client, aioclient_mock): resp = await hassio_client.post("/api/hassio/beer") # Check we got right response - assert resp.status == 200 + assert resp.status == HTTPStatus.OK body = await resp.text() 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}") # Check we got right response - assert resp.status == 401 + assert resp.status == HTTPStatus.UNAUTHORIZED @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}") # Check we got right response - assert resp.status == 200 + assert resp.status == HTTPStatus.OK body = await resp.text() 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") # Check we got right response - assert resp.status == 200 + assert resp.status == HTTPStatus.OK body = await resp.text() 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") # Check we got right response - assert resp.status == 200 + assert resp.status == HTTPStatus.OK body = await resp.text() 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") # Check we got right response - assert resp.status == 200 + assert resp.status == HTTPStatus.OK body = await resp.text() 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) 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): @@ -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") # Check we got right response - assert resp.status == 200 + assert resp.status == HTTPStatus.OK 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 - assert resp.status == 200 + assert resp.status == HTTPStatus.OK 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") # Check we got right response - assert resp.status == 200 + assert resp.status == HTTPStatus.OK 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") # Check we got right response - assert resp1.status == 200 - assert resp2.status == 200 + assert resp1.status == HTTPStatus.OK + assert resp2.status == HTTPStatus.OK assert len(aioclient_mock.mock_calls) == 2 assert resp1.headers["Cache-Control"] == "no-store, max-age=0" diff --git a/tests/components/hassio/test_ingress.py b/tests/components/hassio/test_ingress.py index 8f7d97213e0..60fea96d4ea 100644 --- a/tests/components/hassio/test_ingress.py +++ b/tests/components/hassio/test_ingress.py @@ -1,5 +1,5 @@ """The tests for the hassio component.""" - +from http import HTTPStatus from unittest.mock import MagicMock, patch 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 - assert resp.status == 200 + assert resp.status == HTTPStatus.OK body = await resp.text() assert body == "test" @@ -69,7 +69,7 @@ async def test_ingress_request_post(hassio_client, build_type, aioclient_mock): ) # Check we got right response - assert resp.status == 200 + assert resp.status == HTTPStatus.OK body = await resp.text() assert body == "test" @@ -109,7 +109,7 @@ async def test_ingress_request_put(hassio_client, build_type, aioclient_mock): ) # Check we got right response - assert resp.status == 200 + assert resp.status == HTTPStatus.OK body = await resp.text() assert body == "test" @@ -149,7 +149,7 @@ async def test_ingress_request_delete(hassio_client, build_type, aioclient_mock) ) # Check we got right response - assert resp.status == 200 + assert resp.status == HTTPStatus.OK body = await resp.text() assert body == "test" @@ -189,7 +189,7 @@ async def test_ingress_request_patch(hassio_client, build_type, aioclient_mock): ) # Check we got right response - assert resp.status == 200 + assert resp.status == HTTPStatus.OK body = await resp.text() assert body == "test" @@ -229,7 +229,7 @@ async def test_ingress_request_options(hassio_client, build_type, aioclient_mock ) # Check we got right response - assert resp.status == 200 + assert resp.status == HTTPStatus.OK body = await resp.text() 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 # Check we got right response - assert resp.status == 400 + assert resp.status == HTTPStatus.BAD_REQUEST diff --git a/tests/components/history/test_init.py b/tests/components/history/test_init.py index 35075d79241..422bccf100d 100644 --- a/tests/components/history/test_init.py +++ b/tests/components/history/test_init.py @@ -1,6 +1,7 @@ """The tests the History component.""" # pylint: disable=protected-access,invalid-name from datetime import timedelta +from http import HTTPStatus import json 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) client = await hass_client() 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): @@ -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) client = await hass_client() 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): @@ -610,7 +611,7 @@ async def test_fetch_period_api_with_minimal_response(hass, hass_client): response = await client.get( 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): @@ -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) client = await hass_client() 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): @@ -642,7 +643,7 @@ async def test_fetch_period_api_with_include_order(hass, hass_client): f"/api/history/period/{dt_util.utcnow().isoformat()}", 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): @@ -672,7 +673,7 @@ async def test_fetch_period_api_with_entity_glob_include(hass, hass_client): response = await client.get( f"/api/history/period/{dt_util.utcnow().isoformat()}", ) - assert response.status == 200 + assert response.status == HTTPStatus.OK response_json = await response.json() 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( f"/api/history/period/{dt_util.utcnow().isoformat()}", ) - assert response.status == 200 + assert response.status == HTTPStatus.OK response_json = await response.json() assert len(response_json) == 2 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( f"/api/history/period/{dt_util.utcnow().isoformat()}", ) - assert response.status == 200 + assert response.status == HTTPStatus.OK response_json = await response.json() assert len(response_json) == 3 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( 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() assert len(response_json) == 2 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( 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() 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( 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() assert len(response_json) == 2 assert response_json[0][0]["entity_id"] == "light.kitchen" diff --git a/tests/components/home_connect/test_config_flow.py b/tests/components/home_connect/test_config_flow.py index 1f4120115ea..fa7d3fee8f0 100644 --- a/tests/components/home_connect/test_config_flow.py +++ b/tests/components/home_connect/test_config_flow.py @@ -1,4 +1,5 @@ """Test the Home Connect config flow.""" +from http import HTTPStatus from unittest.mock import patch from homeassistant import config_entries, data_entry_flow, setup @@ -50,7 +51,7 @@ async def test_full_flow( client = await hass_client_no_auth() 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" aioclient_mock.post( diff --git a/tests/components/home_plus_control/test_config_flow.py b/tests/components/home_plus_control/test_config_flow.py index 5eb4115f031..cdf1f85f187 100644 --- a/tests/components/home_plus_control/test_config_flow.py +++ b/tests/components/home_plus_control/test_config_flow.py @@ -1,4 +1,5 @@ """Test the Legrand Home+ Control config flow.""" +from http import HTTPStatus from unittest.mock import patch from homeassistant import config_entries, data_entry_flow, setup @@ -56,7 +57,7 @@ async def test_full_flow( client = await hass_client_no_auth() 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" aioclient_mock.post( @@ -174,7 +175,7 @@ async def test_abort_if_invalid_token( client = await hass_client_no_auth() 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" aioclient_mock.post( diff --git a/tests/components/html5/test_notify.py b/tests/components/html5/test_notify.py index 4a62eb76c27..116b4437d61 100644 --- a/tests/components/html5/test_notify.py +++ b/tests/components/html5/test_notify.py @@ -1,11 +1,11 @@ """Test HTML5 notify platform.""" +from http import HTTPStatus import json from unittest.mock import MagicMock, mock_open, patch from aiohttp.hdrs import AUTHORIZATION import homeassistant.components.html5.notify as html5 -from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR from homeassistant.exceptions import HomeAssistantError 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: 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 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: 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 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: 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} @@ -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)) - assert resp.status == HTTP_INTERNAL_SERVER_ERROR + assert resp.status == HTTPStatus.INTERNAL_SERVER_ERROR 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)) 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 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)) 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 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 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} @@ -393,17 +393,17 @@ async def test_registering_new_device_validation(hass, hass_client): REGISTER_URL, 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"})) - assert resp.status == 400 + assert resp.status == HTTPStatus.BAD_REQUEST with patch("homeassistant.components.html5.notify.save_json", return_value=False): resp = await client.post( REGISTER_URL, 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): @@ -417,7 +417,7 @@ async def test_unregistering_device_view(hass, hass_client): data=json.dumps({"subscription": SUBSCRIPTION_1["subscription"]}), ) - assert resp.status == 200 + assert resp.status == HTTPStatus.OK assert len(mock_save.mock_calls) == 1 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"]}), ) - assert resp.status == 200, resp.response + assert resp.status == HTTPStatus.OK, resp.response assert registrations == {} 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"]}), ) - assert resp.status == HTTP_INTERNAL_SERVER_ERROR, resp.response + assert resp.status == HTTPStatus.INTERNAL_SERVER_ERROR, resp.response assert registrations == { "some device": SUBSCRIPTION_1, "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): @@ -504,7 +504,7 @@ async def test_callback_view_with_jwt(hass, hass_client): PUBLISH_URL, json={"type": "push"}, headers={AUTHORIZATION: bearer_token} ) - assert resp.status == 200 + assert resp.status == HTTPStatus.OK body = await resp.json() assert body == {"event": "push", "status": "ok"} diff --git a/tests/components/http/test_auth.py b/tests/components/http/test_auth.py index 71d848d12ab..8e2703cd51b 100644 --- a/tests/components/http/test_auth.py +++ b/tests/components/http/test_auth.py @@ -1,5 +1,6 @@ """The tests for the Home Assistant HTTP component.""" from datetime import timedelta +from http import HTTPStatus from ipaddress import ip_network from unittest.mock import patch @@ -94,10 +95,10 @@ async def test_cant_access_with_password_in_header( client = await aiohttp_client(app) 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"}) - assert req.status == 401 + assert req.status == HTTPStatus.UNAUTHORIZED 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) resp = await client.get("/", params={"api_password": API_PASSWORD}) - assert resp.status == 401 + assert resp.status == HTTPStatus.UNAUTHORIZED resp = await client.get("/") - assert resp.status == 401 + assert resp.status == HTTPStatus.UNAUTHORIZED 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): @@ -123,16 +124,16 @@ async def test_basic_auth_does_not_work(app, aiohttp_client, hass, legacy_auth): client = await aiohttp_client(app) 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)) - assert req.status == 401 + assert req.status == HTTPStatus.UNAUTHORIZED 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"}) - assert req.status == 401 + assert req.status == HTTPStatus.UNAUTHORIZED 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: set_mock_ip(remote_addr) 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: set_mock_ip(remote_addr) 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( @@ -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) 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} 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} 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} 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}"}) - assert req.status == 401 + assert req.status == HTTPStatus.UNAUTHORIZED refresh_token = await hass.auth.async_validate_access_token(hass_access_token) refresh_token.user.is_active = False 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( @@ -200,12 +205,16 @@ async def test_auth_active_access_with_trusted_ip( for remote_addr in UNTRUSTED_ADDRESSES: set_mock_ip(remote_addr) resp = await client.get("/") - assert resp.status == 401, 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: set_mock_ip(remote_addr) 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( @@ -216,13 +225,13 @@ async def test_auth_legacy_support_api_password_cannot_access( client = await aiohttp_client(app) 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}) - assert resp.status == 401 + assert resp.status == HTTPStatus.UNAUTHORIZED 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): @@ -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)) req = await client.get(signed_path) - assert req.status == 200 + assert req.status == HTTPStatus.OK data = await req.json() assert data["user_id"] == refresh_token.user.id # Use signature on other path req = await client.get("/another_path?{}".format(signed_path.split("?")[1])) - assert req.status == 401 + assert req.status == HTTPStatus.UNAUTHORIZED # We only allow GET req = await client.post(signed_path) - assert req.status == 401 + assert req.status == HTTPStatus.UNAUTHORIZED # Never valid as expired in the past. 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) - assert req.status == 401 + assert req.status == HTTPStatus.UNAUTHORIZED # refresh token gone should also invalidate signature await hass.auth.async_remove_refresh_token(refresh_token) req = await client.get(signed_path) - assert req.status == 401 + assert req.status == HTTPStatus.UNAUTHORIZED diff --git a/tests/components/http/test_ban.py b/tests/components/http/test_ban.py index ed3c2ad23af..fbd545e0506 100644 --- a/tests/components/http/test_ban.py +++ b/tests/components/http/test_ban.py @@ -1,4 +1,6 @@ """The tests for the Home Assistant HTTP component.""" +from http import HTTPStatus + # pylint: disable=protected-access from ipaddress import ip_address import os @@ -19,7 +21,6 @@ from homeassistant.components.http.ban import ( setup_bans, ) from homeassistant.components.http.view import request_handler_factory -from homeassistant.const import HTTP_FORBIDDEN from homeassistant.setup import async_setup_component 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: set_real_ip(remote_addr) resp = await client.get("/") - assert resp.status == HTTP_FORBIDDEN + assert resp.status == HTTPStatus.FORBIDDEN @pytest.mark.parametrize( "remote_addr, bans, status", list( 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 ): resp = await client.get("/") - assert resp.status == 401 + assert resp.status == HTTPStatus.UNAUTHORIZED assert len(app[KEY_BANNED_IPS]) == 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): resp = await client.get("/") - assert resp.status == 401 + assert resp.status == HTTPStatus.UNAUTHORIZED assert len(app[KEY_BANNED_IPS]) == len(BANNED_IPS) assert m_open.call_count == 0 resp = await client.get("/") - assert resp.status == 401 + assert resp.status == HTTPStatus.UNAUTHORIZED assert len(app[KEY_BANNED_IPS]) == len(BANNED_IPS) + 1 m_open.assert_called_once_with( hass.config.path(IP_BANS_FILE), "a", encoding="utf8" ) resp = await client.get("/") - assert resp.status == HTTP_FORBIDDEN + assert resp.status == HTTPStatus.FORBIDDEN assert m_open.call_count == 1 assert ( @@ -216,19 +219,19 @@ async def test_failed_login_attempts_counter(hass, aiohttp_client): client = await aiohttp_client(app) resp = await client.get("/auth_false") - assert resp.status == 401 + assert resp.status == HTTPStatus.UNAUTHORIZED assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 1 resp = await client.get("/auth_false") - assert resp.status == 401 + assert resp.status == HTTPStatus.UNAUTHORIZED assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 2 resp = await client.get("/") - assert resp.status == 200 + assert resp.status == HTTPStatus.OK assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 2 # This used to check that with trusted networks we reset login attempts # We no longer support trusted networks. resp = await client.get("/auth_true") - assert resp.status == 200 + assert resp.status == HTTPStatus.OK assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 2 diff --git a/tests/components/http/test_cors.py b/tests/components/http/test_cors.py index d03b40b2df3..141627c7763 100644 --- a/tests/components/http/test_cors.py +++ b/tests/components/http/test_cors.py @@ -1,4 +1,5 @@ """Test cors for the HTTP component.""" +from http import HTTPStatus from pathlib import Path from unittest.mock import patch @@ -59,28 +60,28 @@ def client(loop, aiohttp_client): async def test_cors_requests(client): """Test cross origin requests.""" 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 # With password in URL req = await client.get( "/", 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 # With password in headers req = await client.get( "/", 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 # With auth token in headers req = await client.get( "/", 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 @@ -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_HEADERS] == "X-REQUESTED-WITH" @@ -139,7 +140,7 @@ async def test_cors_works_with_frontend(hass, hass_client): ) client = await hass_client() resp = await client.get("/") - assert resp.status == 200 + assert resp.status == HTTPStatus.OK 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", }, ) - assert resp.status == 200 + assert resp.status == HTTPStatus.OK assert resp.headers[ACCESS_CONTROL_ALLOW_ORIGIN] == "http://www.example.com" diff --git a/tests/components/http/test_data_validator.py b/tests/components/http/test_data_validator.py index a6e812ccdfe..4ff6d3e8c2a 100644 --- a/tests/components/http/test_data_validator.py +++ b/tests/components/http/test_data_validator.py @@ -1,4 +1,5 @@ """Test data validator decorator.""" +from http import HTTPStatus from unittest.mock import Mock from aiohttp import web @@ -35,13 +36,13 @@ async def test_validator(aiohttp_client): ) resp = await client.post("/", json={"test": "bla"}) - assert resp.status == 200 + assert resp.status == HTTPStatus.OK resp = await client.post("/", json={"test": 100}) - assert resp.status == 400 + assert resp.status == HTTPStatus.BAD_REQUEST resp = await client.post("/") - assert resp.status == 400 + assert resp.status == HTTPStatus.BAD_REQUEST 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"}) - assert resp.status == 200 + assert resp.status == HTTPStatus.OK resp = await client.post("/", json={"test": 100}) - assert resp.status == 400 + assert resp.status == HTTPStatus.BAD_REQUEST resp = await client.post("/") - assert resp.status == 200 + assert resp.status == HTTPStatus.OK diff --git a/tests/components/http/test_forwarded.py b/tests/components/http/test_forwarded.py index 42e67416044..c6eb421fcf3 100644 --- a/tests/components/http/test_forwarded.py +++ b/tests/components/http/test_forwarded.py @@ -1,4 +1,5 @@ """Test real forwarded middleware.""" +from http import HTTPStatus from ipaddress import ip_network 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) 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 ( "Received X-Forwarded-For header from an untrusted proxy 127.0.0.1" in caplog.text @@ -81,7 +82,7 @@ async def test_x_forwarded_for_with_trusted_proxy( mock_api_client = await aiohttp_client(app) 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): @@ -104,7 +105,7 @@ async def test_x_forwarded_for_disabled_with_proxy(aiohttp_client, caplog): mock_api_client = await aiohttp_client(app) 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 ( "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 @@ -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"} ) - assert resp.status == 200 + assert resp.status == HTTPStatus.OK @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}) - assert resp.status == 400 + assert resp.status == HTTPStatus.BAD_REQUEST 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 @@ -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): @@ -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): @@ -287,7 +288,7 @@ async def test_x_forwarded_proto_not_processed_without_for(aiohttp_client): mock_api_client = await aiohttp_client(app) 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): @@ -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 @@ -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}, ) - assert resp.status == 400 + assert resp.status == HTTPStatus.BAD_REQUEST 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 ( f"Incorrect number of elements in X-Forward-Proto. Expected 1 or {expected}, got {got}" 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"}, ) - assert resp.status == 200 + assert resp.status == HTTPStatus.OK 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) 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): @@ -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 @@ -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: ""} ) - assert resp.status == 400 + assert resp.status == HTTPStatus.BAD_REQUEST 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. - assert resp.status == 200 + assert resp.status == HTTPStatus.OK diff --git a/tests/components/http/test_init.py b/tests/components/http/test_init.py index 446b6c218bb..c03c8143bad 100644 --- a/tests/components/http/test_init.py +++ b/tests/components/http/test_init.py @@ -1,5 +1,6 @@ """The tests for the Home Assistant HTTP component.""" from datetime import timedelta +from http import HTTPStatus from ipaddress import ip_network import logging 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"}) - assert resp.status == 401 + assert resp.status == HTTPStatus.UNAUTHORIZED logs = caplog.text # Ensure we don't log API passwords diff --git a/tests/components/http/test_request_context.py b/tests/components/http/test_request_context.py index f511b860dca..57cf6d4e17d 100644 --- a/tests/components/http/test_request_context.py +++ b/tests/components/http/test_request_context.py @@ -1,5 +1,6 @@ """Test request context middleware.""" from contextvars import ContextVar +from http import HTTPStatus from aiohttp import web @@ -24,7 +25,7 @@ async def test_request_context_middleware(aiohttp_client): mock_api_client = await aiohttp_client(app) resp = await mock_api_client.get("/") - assert resp.status == 200 + assert resp.status == HTTPStatus.OK text = await resp.text() assert text == "hi!" diff --git a/tests/components/http/test_security_filter.py b/tests/components/http/test_security_filter.py index eb1ac54d8f6..5897da50929 100644 --- a/tests/components/http/test_security_filter.py +++ b/tests/components/http/test_security_filter.py @@ -1,4 +1,6 @@ """Test security filter middleware.""" +from http import HTTPStatus + from aiohttp import web import pytest import urllib3 @@ -31,7 +33,7 @@ async def test_ok_requests(request_path, request_params, aiohttp_client): mock_api_client = await aiohttp_client(app) 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" @@ -80,7 +82,7 @@ async def test_bad_requests( request_params, ) - assert resp.status == 400 + assert resp.status == HTTPStatus.BAD_REQUEST message = "Filtered a potential harmful request to:" if fail_on_query_string: diff --git a/tests/components/http/test_view.py b/tests/components/http/test_view.py index 522344461cb..fdd4fbc7808 100644 --- a/tests/components/http/test_view.py +++ b/tests/components/http/test_view.py @@ -1,4 +1,5 @@ """Tests for Home Assistant View.""" +from http import HTTPStatus from unittest.mock import AsyncMock, Mock from aiohttp.web_exceptions import ( @@ -68,4 +69,4 @@ async def test_not_running(mock_request_with_stopping): response = await request_handler_factory( Mock(requires_auth=False), AsyncMock(side_effect=Unauthorized) )(mock_request_with_stopping) - assert response.status == 503 + assert response.status == HTTPStatus.SERVICE_UNAVAILABLE