From 8bc1509afab09aada67860f2e656becf1b3a585c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Fri, 22 Oct 2021 17:28:56 +0300 Subject: [PATCH] Use HTTPStatus instead of HTTP_ consts and magic values in comp.../[de]* (#57990) --- .../components/ddwrt/device_tracker.py | 7 +- homeassistant/components/doorbird/__init__.py | 3 +- .../components/doorbird/config_flow.py | 13 +- .../components/downloader/__init__.py | 4 +- .../components/dte_energy_bridge/sensor.py | 5 +- .../components/dublin_bus_transport/sensor.py | 5 +- homeassistant/components/emoncms/sensor.py | 4 +- .../components/emoncms_history/__init__.py | 4 +- homeassistant/components/evohome/__init__.py | 7 +- tests/components/demo/test_media_player.py | 3 +- tests/components/demo/test_stt.py | 10 +- tests/components/dialogflow/test_init.py | 35 ++--- tests/components/ecobee/test_climate.py | 3 +- tests/components/emulated_hue/test_hue_api.py | 122 +++++++++--------- tests/components/emulated_hue/test_upnp.py | 11 +- 15 files changed, 119 insertions(+), 117 deletions(-) diff --git a/homeassistant/components/ddwrt/device_tracker.py b/homeassistant/components/ddwrt/device_tracker.py index bc4ef7f8f82..303cfe72b97 100644 --- a/homeassistant/components/ddwrt/device_tracker.py +++ b/homeassistant/components/ddwrt/device_tracker.py @@ -1,4 +1,5 @@ """Support for DD-WRT routers.""" +from http import HTTPStatus import logging import re @@ -16,8 +17,6 @@ from homeassistant.const import ( CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, - HTTP_OK, - HTTP_UNAUTHORIZED, ) import homeassistant.helpers.config_validation as cv @@ -152,9 +151,9 @@ class DdWrtDeviceScanner(DeviceScanner): except requests.exceptions.Timeout: _LOGGER.exception("Connection to the router timed out") return - if response.status_code == HTTP_OK: + if response.status_code == HTTPStatus.OK: return _parse_ddwrt_response(response.text) - if response.status_code == HTTP_UNAUTHORIZED: + if response.status_code == HTTPStatus.UNAUTHORIZED: # Authentication error _LOGGER.exception( "Failed to authenticate, check your username and password" diff --git a/homeassistant/components/doorbird/__init__.py b/homeassistant/components/doorbird/__init__.py index 63270ee1f1b..3bd82a7ff8e 100644 --- a/homeassistant/components/doorbird/__init__.py +++ b/homeassistant/components/doorbird/__init__.py @@ -16,7 +16,6 @@ from homeassistant.const import ( CONF_PASSWORD, CONF_TOKEN, CONF_USERNAME, - HTTP_UNAUTHORIZED, ) from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import ConfigEntryNotReady @@ -106,7 +105,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: try: status, info = await hass.async_add_executor_job(_init_doorbird_device, device) except requests.exceptions.HTTPError as err: - if err.response.status_code == HTTP_UNAUTHORIZED: + if err.response.status_code == HTTPStatus.UNAUTHORIZED: _LOGGER.error( "Authorization rejected by DoorBird for %s@%s", username, device_ip ) diff --git a/homeassistant/components/doorbird/config_flow.py b/homeassistant/components/doorbird/config_flow.py index 16b9725cf83..4c62fab17ef 100644 --- a/homeassistant/components/doorbird/config_flow.py +++ b/homeassistant/components/doorbird/config_flow.py @@ -1,4 +1,5 @@ """Config flow for DoorBird integration.""" +from http import HTTPStatus from ipaddress import ip_address import logging @@ -7,13 +8,7 @@ import requests import voluptuous as vol from homeassistant import config_entries, core, exceptions -from homeassistant.const import ( - CONF_HOST, - CONF_NAME, - CONF_PASSWORD, - CONF_USERNAME, - HTTP_UNAUTHORIZED, -) +from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME from homeassistant.core import callback from homeassistant.util.network import is_link_local @@ -45,7 +40,7 @@ async def validate_input(hass: core.HomeAssistant, data): try: status, info = await hass.async_add_executor_job(_check_device, device) except requests.exceptions.HTTPError as err: - if err.response.status_code == HTTP_UNAUTHORIZED: + if err.response.status_code == HTTPStatus.UNAUTHORIZED: raise InvalidAuth from err raise CannotConnect from err except OSError as err: @@ -66,7 +61,7 @@ async def async_verify_supported_device(hass, host): try: await hass.async_add_executor_job(device.doorbell_state) except requests.exceptions.HTTPError as err: - if err.response.status_code == HTTP_UNAUTHORIZED: + if err.response.status_code == HTTPStatus.UNAUTHORIZED: return True except OSError: return False diff --git a/homeassistant/components/downloader/__init__.py b/homeassistant/components/downloader/__init__.py index 89aa4a465cf..7cc64a1507b 100644 --- a/homeassistant/components/downloader/__init__.py +++ b/homeassistant/components/downloader/__init__.py @@ -1,4 +1,5 @@ """Support for functionality to download files.""" +from http import HTTPStatus import logging import os import re @@ -7,7 +8,6 @@ import threading import requests import voluptuous as vol -from homeassistant.const import HTTP_OK import homeassistant.helpers.config_validation as cv from homeassistant.util import raise_if_invalid_filename, raise_if_invalid_path @@ -78,7 +78,7 @@ def setup(hass, config): req = requests.get(url, stream=True, timeout=10) - if req.status_code != HTTP_OK: + if req.status_code != HTTPStatus.OK: _LOGGER.warning( "Downloading '%s' failed, status_code=%d", url, req.status_code ) diff --git a/homeassistant/components/dte_energy_bridge/sensor.py b/homeassistant/components/dte_energy_bridge/sensor.py index 5b08e8e142c..d443047a171 100644 --- a/homeassistant/components/dte_energy_bridge/sensor.py +++ b/homeassistant/components/dte_energy_bridge/sensor.py @@ -1,4 +1,5 @@ """Support for monitoring energy usage using the DTE energy bridge.""" +from http import HTTPStatus import logging import requests @@ -9,7 +10,7 @@ from homeassistant.components.sensor import ( STATE_CLASS_MEASUREMENT, SensorEntity, ) -from homeassistant.const import CONF_NAME, HTTP_OK +from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -90,7 +91,7 @@ class DteEnergyBridgeSensor(SensorEntity): ) return - if response.status_code != HTTP_OK: + if response.status_code != HTTPStatus.OK: _LOGGER.warning( "Invalid status_code from DTE Energy Bridge: %s (%s)", response.status_code, diff --git a/homeassistant/components/dublin_bus_transport/sensor.py b/homeassistant/components/dublin_bus_transport/sensor.py index b7daf661e63..8fcbb4dcfed 100644 --- a/homeassistant/components/dublin_bus_transport/sensor.py +++ b/homeassistant/components/dublin_bus_transport/sensor.py @@ -6,12 +6,13 @@ https://data.gov.ie/dataset/real-time-passenger-information-rtpi-for-dublin-bus- """ from contextlib import suppress from datetime import datetime, timedelta +from http import HTTPStatus import requests import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity -from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME, HTTP_OK, TIME_MINUTES +from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME, TIME_MINUTES import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util @@ -144,7 +145,7 @@ class PublicTransportData: response = requests.get(_RESOURCE, params, timeout=10) - if response.status_code != HTTP_OK: + if response.status_code != HTTPStatus.OK: self.info = [ {ATTR_DUE_AT: "n/a", ATTR_ROUTE: self.route, ATTR_DUE_IN: "n/a"} ] diff --git a/homeassistant/components/emoncms/sensor.py b/homeassistant/components/emoncms/sensor.py index 125e5e6c333..68a28cf2846 100644 --- a/homeassistant/components/emoncms/sensor.py +++ b/homeassistant/components/emoncms/sensor.py @@ -1,5 +1,6 @@ """Support for monitoring emoncms feeds.""" from datetime import timedelta +from http import HTTPStatus import logging import requests @@ -20,7 +21,6 @@ from homeassistant.const import ( CONF_VALUE_TEMPLATE, DEVICE_CLASS_ENERGY, DEVICE_CLASS_POWER, - HTTP_OK, POWER_WATT, STATE_UNKNOWN, ) @@ -256,7 +256,7 @@ class EmonCmsData: _LOGGER.error(exception) return else: - if req.status_code == HTTP_OK: + if req.status_code == HTTPStatus.OK: self.data = req.json() else: _LOGGER.error( diff --git a/homeassistant/components/emoncms_history/__init__.py b/homeassistant/components/emoncms_history/__init__.py index 85b48c55755..5cb639de67c 100644 --- a/homeassistant/components/emoncms_history/__init__.py +++ b/homeassistant/components/emoncms_history/__init__.py @@ -1,5 +1,6 @@ """Support for sending data to Emoncms.""" from datetime import timedelta +from http import HTTPStatus import logging import requests @@ -10,7 +11,6 @@ from homeassistant.const import ( CONF_SCAN_INTERVAL, CONF_URL, CONF_WHITELIST, - HTTP_OK, STATE_UNAVAILABLE, STATE_UNKNOWN, ) @@ -59,7 +59,7 @@ def setup(hass, config): _LOGGER.error("Error saving data '%s' to '%s'", payload, fullurl) else: - if req.status_code != HTTP_OK: + if req.status_code != HTTPStatus.OK: _LOGGER.error( "Error saving data %s to %s (http status code = %d)", payload, diff --git a/homeassistant/components/evohome/__init__.py b/homeassistant/components/evohome/__init__.py index cec59742992..d7b1407642d 100644 --- a/homeassistant/components/evohome/__init__.py +++ b/homeassistant/components/evohome/__init__.py @@ -5,6 +5,7 @@ Such systems include evohome, Round Thermostat, and others. from __future__ import annotations from datetime import datetime as dt, timedelta +from http import HTTPStatus import logging import re from typing import Any @@ -19,8 +20,6 @@ from homeassistant.const import ( CONF_PASSWORD, CONF_SCAN_INTERVAL, CONF_USERNAME, - HTTP_SERVICE_UNAVAILABLE, - HTTP_TOO_MANY_REQUESTS, TEMP_CELSIUS, ) from homeassistant.core import HomeAssistant, callback @@ -158,13 +157,13 @@ def _handle_exception(err) -> bool: ) except aiohttp.ClientResponseError: - if err.status == HTTP_SERVICE_UNAVAILABLE: + if err.status == HTTPStatus.SERVICE_UNAVAILABLE: _LOGGER.warning( "The vendor says their server is currently unavailable. " "Check the vendor's service status page" ) - elif err.status == HTTP_TOO_MANY_REQUESTS: + elif err.status == HTTPStatus.TOO_MANY_REQUESTS: _LOGGER.warning( "The vendor's API rate limit has been exceeded. " "If this message persists, consider increasing the %s", diff --git a/tests/components/demo/test_media_player.py b/tests/components/demo/test_media_player.py index 9cc01d18b03..4a40795613f 100644 --- a/tests/components/demo/test_media_player.py +++ b/tests/components/demo/test_media_player.py @@ -1,4 +1,5 @@ """The tests for the Demo Media player platform.""" +from http import HTTPStatus from unittest.mock import patch import pytest @@ -460,7 +461,7 @@ async def test_media_image_proxy(hass, hass_client): assert state.state == STATE_PLAYING client = await hass_client() req = await client.get(state.attributes.get(ATTR_ENTITY_PICTURE)) - assert req.status == 200 + assert req.status == HTTPStatus.OK assert await req.text() == fake_picture_data diff --git a/tests/components/demo/test_stt.py b/tests/components/demo/test_stt.py index f749d6288a7..eced954a837 100644 --- a/tests/components/demo/test_stt.py +++ b/tests/components/demo/test_stt.py @@ -1,4 +1,6 @@ """The tests for the demo stt component.""" +from http import HTTPStatus + import pytest from homeassistant.components import stt @@ -19,7 +21,7 @@ async def test_demo_settings(hass_client): response = await client.get("/api/stt/demo") response_data = await response.json() - assert response.status == 200 + assert response.status == HTTPStatus.OK assert response_data == { "languages": ["en", "de"], "bit_rates": [16], @@ -35,7 +37,7 @@ async def test_demo_speech_no_metadata(hass_client): client = await hass_client() response = await client.post("/api/stt/demo", data=b"Test") - assert response.status == 400 + assert response.status == HTTPStatus.BAD_REQUEST async def test_demo_speech_wrong_metadata(hass_client): @@ -49,7 +51,7 @@ async def test_demo_speech_wrong_metadata(hass_client): }, data=b"Test", ) - assert response.status == 415 + assert response.status == HTTPStatus.UNSUPPORTED_MEDIA_TYPE async def test_demo_speech(hass_client): @@ -65,5 +67,5 @@ async def test_demo_speech(hass_client): ) response_data = await response.json() - assert response.status == 200 + assert response.status == HTTPStatus.OK assert response_data == {"text": "Turn the Kitchen Lights on", "result": "success"} diff --git a/tests/components/dialogflow/test_init.py b/tests/components/dialogflow/test_init.py index 1f5b5bccfa9..5c4ef3e99f9 100644 --- a/tests/components/dialogflow/test_init.py +++ b/tests/components/dialogflow/test_init.py @@ -1,5 +1,6 @@ """The tests for the Dialogflow component.""" import copy +from http import HTTPStatus import json import pytest @@ -171,7 +172,7 @@ async def test_intent_action_incomplete_v1(fixture): response = await mock_client.post( f"/api/webhook/{webhook_id}", data=json.dumps(data) ) - assert response.status == 200 + assert response.status == HTTPStatus.OK assert await response.text() == "" @@ -184,7 +185,7 @@ async def test_intent_action_incomplete_v2(fixture): response = await mock_client.post( f"/api/webhook/{webhook_id}", data=json.dumps(data) ) - assert response.status == 200 + assert response.status == HTTPStatus.OK assert await response.text() == "" @@ -226,7 +227,7 @@ async def test_intent_slot_filling_v1(fixture): response = await mock_client.post( f"/api/webhook/{webhook_id}", data=json.dumps(data) ) - assert response.status == 200 + assert response.status == HTTPStatus.OK assert await response.text() == "" @@ -237,7 +238,7 @@ async def test_intent_request_with_parameters_v1(fixture): response = await mock_client.post( f"/api/webhook/{webhook_id}", data=json.dumps(data) ) - assert response.status == 200 + assert response.status == HTTPStatus.OK text = (await response.json()).get("speech") assert text == "You told us your sign is virgo." @@ -249,7 +250,7 @@ async def test_intent_request_with_parameters_v2(fixture): response = await mock_client.post( f"/api/webhook/{webhook_id}", data=json.dumps(data) ) - assert response.status == 200 + assert response.status == HTTPStatus.OK text = (await response.json()).get("fulfillmentText") assert text == "You told us your sign is virgo." @@ -262,7 +263,7 @@ async def test_intent_request_with_parameters_but_empty_v1(fixture): response = await mock_client.post( f"/api/webhook/{webhook_id}", data=json.dumps(data) ) - assert response.status == 200 + assert response.status == HTTPStatus.OK text = (await response.json()).get("speech") assert text == "You told us your sign is ." @@ -275,7 +276,7 @@ async def test_intent_request_with_parameters_but_empty_v2(fixture): response = await mock_client.post( f"/api/webhook/{webhook_id}", data=json.dumps(data) ) - assert response.status == 200 + assert response.status == HTTPStatus.OK text = (await response.json()).get("fulfillmentText") assert text == "You told us your sign is ." @@ -294,7 +295,7 @@ async def test_intent_request_without_slots_v1(hass, fixture): response = await mock_client.post( f"/api/webhook/{webhook_id}", data=json.dumps(data) ) - assert response.status == 200 + assert response.status == HTTPStatus.OK text = (await response.json()).get("speech") assert text == "Anne Therese is at unknown and Paulus is at unknown" @@ -305,7 +306,7 @@ async def test_intent_request_without_slots_v1(hass, fixture): response = await mock_client.post( f"/api/webhook/{webhook_id}", data=json.dumps(data) ) - assert response.status == 200 + assert response.status == HTTPStatus.OK text = (await response.json()).get("speech") assert text == "You are both home, you silly" @@ -324,7 +325,7 @@ async def test_intent_request_without_slots_v2(hass, fixture): response = await mock_client.post( f"/api/webhook/{webhook_id}", data=json.dumps(data) ) - assert response.status == 200 + assert response.status == HTTPStatus.OK text = (await response.json()).get("fulfillmentText") assert text == "Anne Therese is at unknown and Paulus is at unknown" @@ -335,7 +336,7 @@ async def test_intent_request_without_slots_v2(hass, fixture): response = await mock_client.post( f"/api/webhook/{webhook_id}", data=json.dumps(data) ) - assert response.status == 200 + assert response.status == HTTPStatus.OK text = (await response.json()).get("fulfillmentText") assert text == "You are both home, you silly" @@ -353,7 +354,7 @@ async def test_intent_request_calling_service_v1(fixture, calls): response = await mock_client.post( f"/api/webhook/{webhook_id}", data=json.dumps(data) ) - assert response.status == 200 + assert response.status == HTTPStatus.OK assert len(calls) == call_count + 1 call = calls[-1] assert call.domain == "test" @@ -375,7 +376,7 @@ async def test_intent_request_calling_service_v2(fixture, calls): response = await mock_client.post( f"/api/webhook/{webhook_id}", data=json.dumps(data) ) - assert response.status == 200 + assert response.status == HTTPStatus.OK assert len(calls) == call_count + 1 call = calls[-1] assert call.domain == "test" @@ -393,7 +394,7 @@ async def test_intent_with_no_action_v1(fixture): response = await mock_client.post( f"/api/webhook/{webhook_id}", data=json.dumps(data) ) - assert response.status == 200 + assert response.status == HTTPStatus.OK text = (await response.json()).get("speech") assert text == "You have not defined an action in your Dialogflow intent." @@ -407,7 +408,7 @@ async def test_intent_with_no_action_v2(fixture): response = await mock_client.post( f"/api/webhook/{webhook_id}", data=json.dumps(data) ) - assert response.status == 200 + assert response.status == HTTPStatus.OK text = (await response.json()).get("fulfillmentText") assert text == "You have not defined an action in your Dialogflow intent." @@ -420,7 +421,7 @@ async def test_intent_with_unknown_action_v1(fixture): response = await mock_client.post( f"/api/webhook/{webhook_id}", data=json.dumps(data) ) - assert response.status == 200 + assert response.status == HTTPStatus.OK text = (await response.json()).get("speech") assert text == "This intent is not yet configured within Home Assistant." @@ -433,6 +434,6 @@ async def test_intent_with_unknown_action_v2(fixture): response = await mock_client.post( f"/api/webhook/{webhook_id}", data=json.dumps(data) ) - assert response.status == 200 + assert response.status == HTTPStatus.OK text = (await response.json()).get("fulfillmentText") assert text == "This intent is not yet configured within Home Assistant." diff --git a/tests/components/ecobee/test_climate.py b/tests/components/ecobee/test_climate.py index ec466197995..195c086adda 100644 --- a/tests/components/ecobee/test_climate.py +++ b/tests/components/ecobee/test_climate.py @@ -1,4 +1,5 @@ """The test for the Ecobee thermostat module.""" +from http import HTTPStatus from unittest import mock import pytest @@ -78,7 +79,7 @@ async def test_name(thermostat): async def test_current_temperature(ecobee_fixture, thermostat): """Test current temperature.""" assert thermostat.current_temperature == 30 - ecobee_fixture["runtime"]["actualTemperature"] = const.HTTP_NOT_FOUND + ecobee_fixture["runtime"]["actualTemperature"] = HTTPStatus.NOT_FOUND assert thermostat.current_temperature == 40.4 diff --git a/tests/components/emulated_hue/test_hue_api.py b/tests/components/emulated_hue/test_hue_api.py index e4d422f9802..19a31b4566b 100644 --- a/tests/components/emulated_hue/test_hue_api.py +++ b/tests/components/emulated_hue/test_hue_api.py @@ -1,6 +1,7 @@ """The tests for the emulated Hue component.""" import asyncio from datetime import timedelta +from http import HTTPStatus from ipaddress import ip_address import json from unittest.mock import patch @@ -43,9 +44,6 @@ from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_SUPPORTED_FEATURES, CONTENT_TYPE_JSON, - HTTP_NOT_FOUND, - HTTP_OK, - HTTP_UNAUTHORIZED, SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_OFF, @@ -263,7 +261,7 @@ async def test_discover_lights(hue_client): """Test the discovery of lights.""" result = await hue_client.get("/api/username/lights") - assert result.status == HTTP_OK + assert result.status == HTTPStatus.OK assert CONTENT_TYPE_JSON in result.headers["content-type"] result_json = await result.json() @@ -296,7 +294,7 @@ async def test_discover_lights(hue_client): async def test_light_without_brightness_supported(hass_hue, hue_client): """Test that light without brightness is supported.""" light_without_brightness_json = await perform_get_light_state( - hue_client, "light.no_brightness", HTTP_OK + hue_client, "light.no_brightness", HTTPStatus.OK ) assert light_without_brightness_json["state"][HUE_API_STATE_ON] is True @@ -329,7 +327,7 @@ async def test_lights_all_dimmable(hass, hass_client_no_auth): HueOneLightStateView(config).register(web_app, web_app.router) client = await hass_client_no_auth() light_without_brightness_json = await perform_get_light_state( - client, "light.no_brightness", HTTP_OK + client, "light.no_brightness", HTTPStatus.OK ) assert light_without_brightness_json["state"][HUE_API_STATE_ON] is True assert light_without_brightness_json["type"] == "Dimmable light" @@ -360,7 +358,7 @@ async def test_light_without_brightness_can_be_turned_off(hass_hue, hue_client): ) no_brightness_result_json = await no_brightness_result.json() - assert no_brightness_result.status == HTTP_OK + assert no_brightness_result.status == HTTPStatus.OK assert CONTENT_TYPE_JSON in no_brightness_result.headers["content-type"] assert len(no_brightness_result_json) == 1 @@ -402,7 +400,7 @@ async def test_light_without_brightness_can_be_turned_on(hass_hue, hue_client): no_brightness_result_json = await no_brightness_result.json() - assert no_brightness_result.status == HTTP_OK + assert no_brightness_result.status == HTTPStatus.OK assert CONTENT_TYPE_JSON in no_brightness_result.headers["content-type"] assert len(no_brightness_result_json) == 1 @@ -430,7 +428,7 @@ async def test_reachable_for_state(hass_hue, hue_client, state, is_reachable): hass_hue.states.async_set(entity_id, state) - state_json = await perform_get_light_state(hue_client, entity_id, HTTP_OK) + state_json = await perform_get_light_state(hue_client, entity_id, HTTPStatus.OK) assert state_json["state"]["reachable"] == is_reachable, state_json @@ -439,7 +437,7 @@ async def test_discover_full_state(hue_client): """Test the discovery of full state.""" result = await hue_client.get(f"/api/{HUE_API_USERNAME}") - assert result.status == HTTP_OK + assert result.status == HTTPStatus.OK assert CONTENT_TYPE_JSON in result.headers["content-type"] result_json = await result.json() @@ -489,7 +487,7 @@ async def test_discover_config(hue_client): """Test the discovery of configuration.""" result = await hue_client.get(f"/api/{HUE_API_USERNAME}/config") - assert result.status == 200 + assert result.status == HTTPStatus.OK assert CONTENT_TYPE_JSON in result.headers["content-type"] config_json = await result.json() @@ -526,7 +524,7 @@ async def test_discover_config(hue_client): # Test without username result = await hue_client.get("/api/config") - assert result.status == 200 + assert result.status == HTTPStatus.OK assert CONTENT_TYPE_JSON in result.headers["content-type"] config_json = await result.json() @@ -535,7 +533,7 @@ async def test_discover_config(hue_client): # Test with wrong username username result = await hue_client.get("/api/wronguser/config") - assert result.status == 200 + assert result.status == HTTPStatus.OK assert CONTENT_TYPE_JSON in result.headers["content-type"] config_json = await result.json() @@ -557,7 +555,7 @@ async def test_get_light_state(hass_hue, hue_client): ) office_json = await perform_get_light_state( - hue_client, "light.ceiling_lights", HTTP_OK + hue_client, "light.ceiling_lights", HTTPStatus.OK ) assert office_json["state"][HUE_API_STATE_ON] is True @@ -568,7 +566,7 @@ async def test_get_light_state(hass_hue, hue_client): # Check all lights view result = await hue_client.get("/api/username/lights") - assert result.status == HTTP_OK + assert result.status == HTTPStatus.OK assert CONTENT_TYPE_JSON in result.headers["content-type"] result_json = await result.json() @@ -590,7 +588,7 @@ async def test_get_light_state(hass_hue, hue_client): ) office_json = await perform_get_light_state( - hue_client, "light.ceiling_lights", HTTP_OK + hue_client, "light.ceiling_lights", HTTPStatus.OK ) assert office_json["state"][HUE_API_STATE_ON] is False @@ -599,10 +597,14 @@ async def test_get_light_state(hass_hue, hue_client): assert office_json["state"][HUE_API_STATE_SAT] == 0 # Make sure bedroom light isn't accessible - await perform_get_light_state(hue_client, "light.bed_light", HTTP_UNAUTHORIZED) + await perform_get_light_state( + hue_client, "light.bed_light", HTTPStatus.UNAUTHORIZED + ) # Make sure kitchen light isn't accessible - await perform_get_light_state(hue_client, "light.kitchen_lights", HTTP_UNAUTHORIZED) + await perform_get_light_state( + hue_client, "light.kitchen_lights", HTTPStatus.UNAUTHORIZED + ) async def test_put_light_state(hass, hass_hue, hue_client): @@ -653,7 +655,7 @@ async def test_put_light_state(hass, hass_hue, hue_client): # go through api to get the state back ceiling_json = await perform_get_light_state( - hue_client, "light.ceiling_lights", HTTP_OK + hue_client, "light.ceiling_lights", HTTPStatus.OK ) assert ceiling_json["state"][HUE_API_STATE_BRI] == 123 assert ceiling_json["state"][HUE_API_STATE_HUE] == 4369 @@ -672,7 +674,7 @@ async def test_put_light_state(hass, hass_hue, hue_client): # go through api to get the state back ceiling_json = await perform_get_light_state( - hue_client, "light.ceiling_lights", HTTP_OK + hue_client, "light.ceiling_lights", HTTPStatus.OK ) assert ceiling_json["state"][HUE_API_STATE_BRI] == 254 assert ceiling_json["state"][HUE_API_STATE_HUE] == 4369 @@ -690,7 +692,7 @@ async def test_put_light_state(hass, hass_hue, hue_client): # go through api to get the state back ceiling_json = await perform_get_light_state( - hue_client, "light.ceiling_lights", HTTP_OK + hue_client, "light.ceiling_lights", HTTPStatus.OK ) assert ceiling_json["state"][HUE_API_STATE_BRI] == 100 assert hass.states.get("light.ceiling_lights").attributes[light.ATTR_XY_COLOR] == ( @@ -704,7 +706,7 @@ async def test_put_light_state(hass, hass_hue, hue_client): ceiling_result_json = await ceiling_result.json() - assert ceiling_result.status == HTTP_OK + assert ceiling_result.status == HTTPStatus.OK assert CONTENT_TYPE_JSON in ceiling_result.headers["content-type"] assert len(ceiling_result_json) == 1 @@ -713,7 +715,7 @@ async def test_put_light_state(hass, hass_hue, hue_client): ceiling_lights = hass_hue.states.get("light.ceiling_lights") assert ceiling_lights.state == STATE_OFF ceiling_json = await perform_get_light_state( - hue_client, "light.ceiling_lights", HTTP_OK + hue_client, "light.ceiling_lights", HTTPStatus.OK ) # Removed assert HUE_API_STATE_BRI == 0 as Hue API states bri must be 1..254 assert ceiling_json["state"][HUE_API_STATE_HUE] == 0 @@ -723,13 +725,13 @@ async def test_put_light_state(hass, hass_hue, hue_client): bedroom_result = await perform_put_light_state( hass_hue, hue_client, "light.bed_light", True ) - assert bedroom_result.status == HTTP_UNAUTHORIZED + assert bedroom_result.status == HTTPStatus.UNAUTHORIZED # Make sure we can't change the kitchen light state kitchen_result = await perform_put_light_state( hass_hue, hue_client, "light.kitchen_lights", True ) - assert kitchen_result.status == HTTP_UNAUTHORIZED + assert kitchen_result.status == HTTPStatus.UNAUTHORIZED # Turn the ceiling lights on first and color temp. await hass_hue.services.async_call( @@ -794,7 +796,7 @@ async def test_put_light_state_script(hass, hass_hue, hue_client): script_result_json = await script_result.json() - assert script_result.status == HTTP_OK + assert script_result.status == HTTPStatus.OK assert len(script_result_json) == 2 kitchen_light = hass_hue.states.get("light.kitchen_lights") @@ -817,7 +819,7 @@ async def test_put_light_state_climate_set_temperature(hass_hue, hue_client): hvac_result_json = await hvac_result.json() - assert hvac_result.status == HTTP_OK + assert hvac_result.status == HTTPStatus.OK assert len(hvac_result_json) == 2 hvac = hass_hue.states.get("climate.hvac") @@ -828,7 +830,7 @@ async def test_put_light_state_climate_set_temperature(hass_hue, hue_client): ecobee_result = await perform_put_light_state( hass_hue, hue_client, "climate.ecobee", True ) - assert ecobee_result.status == HTTP_UNAUTHORIZED + assert ecobee_result.status == HTTPStatus.UNAUTHORIZED async def test_put_light_state_humidifier_set_humidity(hass_hue, hue_client): @@ -850,7 +852,7 @@ async def test_put_light_state_humidifier_set_humidity(hass_hue, hue_client): humidifier_result_json = await humidifier_result.json() - assert humidifier_result.status == HTTP_OK + assert humidifier_result.status == HTTPStatus.OK assert len(humidifier_result_json) == 2 hvac = hass_hue.states.get("humidifier.humidifier") @@ -861,7 +863,7 @@ async def test_put_light_state_humidifier_set_humidity(hass_hue, hue_client): hygrostat_result = await perform_put_light_state( hass_hue, hue_client, "humidifier.hygrostat", True ) - assert hygrostat_result.status == HTTP_UNAUTHORIZED + assert hygrostat_result.status == HTTPStatus.UNAUTHORIZED async def test_put_light_state_media_player(hass_hue, hue_client): @@ -884,7 +886,7 @@ async def test_put_light_state_media_player(hass_hue, hue_client): mp_result_json = await mp_result.json() - assert mp_result.status == HTTP_OK + assert mp_result.status == HTTPStatus.OK assert len(mp_result_json) == 2 walkman = hass_hue.states.get("media_player.walkman") @@ -917,7 +919,7 @@ async def test_open_cover_without_position(hass_hue, hue_client): # Go through the API to turn it on cover_result = await perform_put_light_state(hass_hue, hue_client, cover_id, True) - assert cover_result.status == HTTP_OK + assert cover_result.status == HTTPStatus.OK assert CONTENT_TYPE_JSON in cover_result.headers["content-type"] for _ in range(11): @@ -937,7 +939,7 @@ async def test_open_cover_without_position(hass_hue, hue_client): # Go through the API to turn it off cover_result = await perform_put_light_state(hass_hue, hue_client, cover_id, False) - assert cover_result.status == HTTP_OK + assert cover_result.status == HTTPStatus.OK assert CONTENT_TYPE_JSON in cover_result.headers["content-type"] for _ in range(11): @@ -986,7 +988,7 @@ async def test_set_position_cover(hass_hue, hue_client): hass_hue, hue_client, cover_id, False, brightness ) - assert cover_result.status == HTTP_OK + assert cover_result.status == HTTPStatus.OK assert CONTENT_TYPE_JSON in cover_result.headers["content-type"] cover_result_json = await cover_result.json() @@ -1026,7 +1028,7 @@ async def test_put_light_state_fan(hass_hue, hue_client): fan_result_json = await fan_result.json() - assert fan_result.status == HTTP_OK + assert fan_result.status == HTTPStatus.OK assert len(fan_result_json) == 2 living_room_fan = hass_hue.states.get("fan.living_room_fan") @@ -1056,7 +1058,7 @@ async def test_put_light_state_fan(hass_hue, hue_client): with patch.object(hue_api, "STATE_CACHED_TIMEOUT", 0.000001): await asyncio.sleep(0.000001) fan_json = await perform_get_light_state( - hue_client, "fan.living_room_fan", HTTP_OK + hue_client, "fan.living_room_fan", HTTPStatus.OK ) assert round(fan_json["state"][HUE_API_STATE_BRI] * 100 / 254) == 33 @@ -1074,7 +1076,7 @@ async def test_put_light_state_fan(hass_hue, hue_client): with patch.object(hue_api, "STATE_CACHED_TIMEOUT", 0.000001): await asyncio.sleep(0.000001) fan_json = await perform_get_light_state( - hue_client, "fan.living_room_fan", HTTP_OK + hue_client, "fan.living_room_fan", HTTPStatus.OK ) assert ( round(fan_json["state"][HUE_API_STATE_BRI] * 100 / 254) == 67 @@ -1094,7 +1096,7 @@ async def test_put_light_state_fan(hass_hue, hue_client): with patch.object(hue_api, "STATE_CACHED_TIMEOUT", 0.000001): await asyncio.sleep(0.000001) fan_json = await perform_get_light_state( - hue_client, "fan.living_room_fan", HTTP_OK + hue_client, "fan.living_room_fan", HTTPStatus.OK ) assert round(fan_json["state"][HUE_API_STATE_BRI] * 100 / 254) == 100 @@ -1116,18 +1118,18 @@ async def test_put_with_form_urlencoded_content_type(hass_hue, hue_client): data=data, ) - assert result.status == 400 + assert result.status == HTTPStatus.BAD_REQUEST async def test_entity_not_found(hue_client): """Test for entity which are not found.""" result = await hue_client.get("/api/username/lights/98") - assert result.status == HTTP_NOT_FOUND + assert result.status == HTTPStatus.NOT_FOUND result = await hue_client.put("/api/username/lights/98/state") - assert result.status == HTTP_NOT_FOUND + assert result.status == HTTPStatus.NOT_FOUND async def test_allowed_methods(hue_client): @@ -1136,17 +1138,17 @@ async def test_allowed_methods(hue_client): "/api/username/lights/ENTITY_NUMBERS_BY_ID[light.ceiling_lights]/state" ) - assert result.status == 405 + assert result.status == HTTPStatus.METHOD_NOT_ALLOWED result = await hue_client.put( "/api/username/lights/ENTITY_NUMBERS_BY_ID[light.ceiling_lights]" ) - assert result.status == 405 + assert result.status == HTTPStatus.METHOD_NOT_ALLOWED result = await hue_client.put("/api/username/lights") - assert result.status == 405 + assert result.status == HTTPStatus.METHOD_NOT_ALLOWED async def test_proper_put_state_request(hue_client): @@ -1159,7 +1161,7 @@ async def test_proper_put_state_request(hue_client): data=json.dumps({HUE_API_STATE_ON: 1234}), ) - assert result.status == 400 + assert result.status == HTTPStatus.BAD_REQUEST # Test proper brightness value parsing result = await hue_client.put( @@ -1169,7 +1171,7 @@ async def test_proper_put_state_request(hue_client): data=json.dumps({HUE_API_STATE_ON: True, HUE_API_STATE_BRI: "Hello world!"}), ) - assert result.status == 400 + assert result.status == HTTPStatus.BAD_REQUEST async def test_get_empty_groups_state(hue_client): @@ -1177,7 +1179,7 @@ async def test_get_empty_groups_state(hue_client): # Test proper on value parsing result = await hue_client.get("/api/username/groups") - assert result.status == HTTP_OK + assert result.status == HTTPStatus.OK result_json = await result.json() @@ -1205,7 +1207,7 @@ async def perform_put_test_on_ceiling_lights( hass_hue, hue_client, "light.ceiling_lights", True, 56, content_type ) - assert office_result.status == HTTP_OK + assert office_result.status == HTTPStatus.OK assert CONTENT_TYPE_JSON in office_result.headers["content-type"] office_result_json = await office_result.json() @@ -1224,7 +1226,7 @@ async def perform_get_light_state_by_number(client, entity_number, expected_stat assert result.status == expected_status - if expected_status == HTTP_OK: + if expected_status == HTTPStatus.OK: assert CONTENT_TYPE_JSON in result.headers["content-type"] return await result.json() @@ -1305,15 +1307,15 @@ async def test_external_ip_blocked(hue_client): ): for getUrl in getUrls: result = await hue_client.get(getUrl) - assert result.status == HTTP_UNAUTHORIZED + assert result.status == HTTPStatus.UNAUTHORIZED for postUrl in postUrls: result = await hue_client.post(postUrl) - assert result.status == HTTP_UNAUTHORIZED + assert result.status == HTTPStatus.UNAUTHORIZED for putUrl in putUrls: result = await hue_client.put(putUrl) - assert result.status == HTTP_UNAUTHORIZED + assert result.status == HTTPStatus.UNAUTHORIZED async def test_unauthorized_user_blocked(hue_client): @@ -1323,7 +1325,7 @@ async def test_unauthorized_user_blocked(hue_client): ] for getUrl in getUrls: result = await hue_client.get(getUrl) - assert result.status == HTTP_OK + assert result.status == HTTPStatus.OK result_json = await result.json() assert result_json[0]["error"]["description"] == "unauthorized user" @@ -1371,7 +1373,7 @@ async def test_put_then_get_cached_properly(hass, hass_hue, hue_client): # go through api to get the state back, the value returned should match those set in the last PUT request. ceiling_json = await perform_get_light_state( - hue_client, "light.ceiling_lights", HTTP_OK + hue_client, "light.ceiling_lights", HTTPStatus.OK ) assert ceiling_json["state"][HUE_API_STATE_HUE] == 4369 @@ -1388,7 +1390,7 @@ async def test_put_then_get_cached_properly(hass, hass_hue, hue_client): # go through api to get the state back ceiling_json = await perform_get_light_state( - hue_client, "light.ceiling_lights", HTTP_OK + hue_client, "light.ceiling_lights", HTTPStatus.OK ) # Now it should be the real value as the state of the entity has changed to OFF. @@ -1430,7 +1432,7 @@ async def test_put_then_get_cached_properly(hass, hass_hue, hue_client): # go through api to get the state back, the value returned should match those set in the last PUT request. ceiling_json = await perform_get_light_state( - hue_client, "light.ceiling_lights", HTTP_OK + hue_client, "light.ceiling_lights", HTTPStatus.OK ) # With no wait, we must be reading what we set via the PUT call. @@ -1443,7 +1445,7 @@ async def test_put_then_get_cached_properly(hass, hass_hue, hue_client): # go through api to get the state back, the value returned should now match the actual values. ceiling_json = await perform_get_light_state( - hue_client, "light.ceiling_lights", HTTP_OK + hue_client, "light.ceiling_lights", HTTPStatus.OK ) # Once we're after the cached duration, we should see the real value. @@ -1496,7 +1498,7 @@ async def test_put_than_get_when_service_call_fails(hass, hass_hue, hue_client): # go through api to get the state back, the value returned should NOT match those set in the last PUT request # as the waiting to check the state change timed out ceiling_json = await perform_get_light_state( - hue_client, "light.ceiling_lights", HTTP_OK + hue_client, "light.ceiling_lights", HTTPStatus.OK ) assert ceiling_json["state"][HUE_API_STATE_ON] is False @@ -1506,7 +1508,7 @@ async def test_get_invalid_entity(hass, hass_hue, hue_client): """Test the setting of light states and an immediate readback reads the same values.""" # Check that we get an error with an invalid entity number. - await perform_get_light_state_by_number(hue_client, 999, HTTP_NOT_FOUND) + await perform_get_light_state_by_number(hue_client, 999, HTTPStatus.NOT_FOUND) async def test_put_light_state_scene(hass, hass_hue, hue_client): @@ -1524,7 +1526,7 @@ async def test_put_light_state_scene(hass, hass_hue, hue_client): ) scene_result_json = await scene_result.json() - assert scene_result.status == HTTP_OK + assert scene_result.status == HTTPStatus.OK assert len(scene_result_json) == 1 assert hass_hue.states.get("light.kitchen_lights").state == STATE_ON diff --git a/tests/components/emulated_hue/test_upnp.py b/tests/components/emulated_hue/test_upnp.py index d918b378614..ec04ee7e19c 100644 --- a/tests/components/emulated_hue/test_upnp.py +++ b/tests/components/emulated_hue/test_upnp.py @@ -1,4 +1,5 @@ """The tests for the emulated Hue component.""" +from http import HTTPStatus import json import unittest @@ -9,7 +10,7 @@ import pytest from homeassistant import setup from homeassistant.components import emulated_hue from homeassistant.components.emulated_hue import upnp -from homeassistant.const import CONTENT_TYPE_JSON, HTTP_OK +from homeassistant.const import CONTENT_TYPE_JSON from tests.common import get_test_instance_port @@ -149,7 +150,7 @@ async def test_description_xml(hass, hue_client): client = await hue_client() result = await client.get("/description.xml", timeout=5) - assert result.status == HTTP_OK + assert result.status == HTTPStatus.OK assert "text/xml" in result.headers["content-type"] try: @@ -168,7 +169,7 @@ async def test_create_username(hass, hue_client): result = await client.post("/api", data=json.dumps(request_json), timeout=5) - assert result.status == HTTP_OK + assert result.status == HTTPStatus.OK assert CONTENT_TYPE_JSON in result.headers["content-type"] resp_json = await result.json() @@ -188,7 +189,7 @@ async def test_unauthorized_view(hass, hue_client): "/api/unauthorized", data=json.dumps(request_json), timeout=5 ) - assert result.status == HTTP_OK + assert result.status == HTTPStatus.OK assert CONTENT_TYPE_JSON in result.headers["content-type"] resp_json = await result.json() @@ -212,4 +213,4 @@ async def test_valid_username_request(hass, hue_client): result = await client.post("/api", data=json.dumps(request_json), timeout=5) - assert result.status == 400 + assert result.status == HTTPStatus.BAD_REQUEST