Use HTTPStatus instead of HTTP_ consts and magic values in comp.../[de]* (#57990)

This commit is contained in:
Ville Skyttä 2021-10-22 17:28:56 +03:00 committed by GitHub
parent c84fee7c6e
commit 8bc1509afa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 119 additions and 117 deletions

View File

@ -1,4 +1,5 @@
"""Support for DD-WRT routers.""" """Support for DD-WRT routers."""
from http import HTTPStatus
import logging import logging
import re import re
@ -16,8 +17,6 @@ from homeassistant.const import (
CONF_SSL, CONF_SSL,
CONF_USERNAME, CONF_USERNAME,
CONF_VERIFY_SSL, CONF_VERIFY_SSL,
HTTP_OK,
HTTP_UNAUTHORIZED,
) )
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -152,9 +151,9 @@ class DdWrtDeviceScanner(DeviceScanner):
except requests.exceptions.Timeout: except requests.exceptions.Timeout:
_LOGGER.exception("Connection to the router timed out") _LOGGER.exception("Connection to the router timed out")
return return
if response.status_code == HTTP_OK: if response.status_code == HTTPStatus.OK:
return _parse_ddwrt_response(response.text) return _parse_ddwrt_response(response.text)
if response.status_code == HTTP_UNAUTHORIZED: if response.status_code == HTTPStatus.UNAUTHORIZED:
# Authentication error # Authentication error
_LOGGER.exception( _LOGGER.exception(
"Failed to authenticate, check your username and password" "Failed to authenticate, check your username and password"

View File

@ -16,7 +16,6 @@ from homeassistant.const import (
CONF_PASSWORD, CONF_PASSWORD,
CONF_TOKEN, CONF_TOKEN,
CONF_USERNAME, CONF_USERNAME,
HTTP_UNAUTHORIZED,
) )
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.exceptions import ConfigEntryNotReady
@ -106,7 +105,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try: try:
status, info = await hass.async_add_executor_job(_init_doorbird_device, device) status, info = await hass.async_add_executor_job(_init_doorbird_device, device)
except requests.exceptions.HTTPError as err: except requests.exceptions.HTTPError as err:
if err.response.status_code == HTTP_UNAUTHORIZED: if err.response.status_code == HTTPStatus.UNAUTHORIZED:
_LOGGER.error( _LOGGER.error(
"Authorization rejected by DoorBird for %s@%s", username, device_ip "Authorization rejected by DoorBird for %s@%s", username, device_ip
) )

View File

@ -1,4 +1,5 @@
"""Config flow for DoorBird integration.""" """Config flow for DoorBird integration."""
from http import HTTPStatus
from ipaddress import ip_address from ipaddress import ip_address
import logging import logging
@ -7,13 +8,7 @@ import requests
import voluptuous as vol import voluptuous as vol
from homeassistant import config_entries, core, exceptions from homeassistant import config_entries, core, exceptions
from homeassistant.const import ( from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME
CONF_HOST,
CONF_NAME,
CONF_PASSWORD,
CONF_USERNAME,
HTTP_UNAUTHORIZED,
)
from homeassistant.core import callback from homeassistant.core import callback
from homeassistant.util.network import is_link_local from homeassistant.util.network import is_link_local
@ -45,7 +40,7 @@ async def validate_input(hass: core.HomeAssistant, data):
try: try:
status, info = await hass.async_add_executor_job(_check_device, device) status, info = await hass.async_add_executor_job(_check_device, device)
except requests.exceptions.HTTPError as err: 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 InvalidAuth from err
raise CannotConnect from err raise CannotConnect from err
except OSError as err: except OSError as err:
@ -66,7 +61,7 @@ async def async_verify_supported_device(hass, host):
try: try:
await hass.async_add_executor_job(device.doorbell_state) await hass.async_add_executor_job(device.doorbell_state)
except requests.exceptions.HTTPError as err: except requests.exceptions.HTTPError as err:
if err.response.status_code == HTTP_UNAUTHORIZED: if err.response.status_code == HTTPStatus.UNAUTHORIZED:
return True return True
except OSError: except OSError:
return False return False

View File

@ -1,4 +1,5 @@
"""Support for functionality to download files.""" """Support for functionality to download files."""
from http import HTTPStatus
import logging import logging
import os import os
import re import re
@ -7,7 +8,6 @@ import threading
import requests import requests
import voluptuous as vol import voluptuous as vol
from homeassistant.const import HTTP_OK
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.util import raise_if_invalid_filename, raise_if_invalid_path 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) req = requests.get(url, stream=True, timeout=10)
if req.status_code != HTTP_OK: if req.status_code != HTTPStatus.OK:
_LOGGER.warning( _LOGGER.warning(
"Downloading '%s' failed, status_code=%d", url, req.status_code "Downloading '%s' failed, status_code=%d", url, req.status_code
) )

View File

@ -1,4 +1,5 @@
"""Support for monitoring energy usage using the DTE energy bridge.""" """Support for monitoring energy usage using the DTE energy bridge."""
from http import HTTPStatus
import logging import logging
import requests import requests
@ -9,7 +10,7 @@ from homeassistant.components.sensor import (
STATE_CLASS_MEASUREMENT, STATE_CLASS_MEASUREMENT,
SensorEntity, SensorEntity,
) )
from homeassistant.const import CONF_NAME, HTTP_OK from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -90,7 +91,7 @@ class DteEnergyBridgeSensor(SensorEntity):
) )
return return
if response.status_code != HTTP_OK: if response.status_code != HTTPStatus.OK:
_LOGGER.warning( _LOGGER.warning(
"Invalid status_code from DTE Energy Bridge: %s (%s)", "Invalid status_code from DTE Energy Bridge: %s (%s)",
response.status_code, response.status_code,

View File

@ -6,12 +6,13 @@ https://data.gov.ie/dataset/real-time-passenger-information-rtpi-for-dublin-bus-
""" """
from contextlib import suppress from contextlib import suppress
from datetime import datetime, timedelta from datetime import datetime, timedelta
from http import HTTPStatus
import requests import requests
import voluptuous as vol import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import 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.helpers.config_validation as cv
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
@ -144,7 +145,7 @@ class PublicTransportData:
response = requests.get(_RESOURCE, params, timeout=10) response = requests.get(_RESOURCE, params, timeout=10)
if response.status_code != HTTP_OK: if response.status_code != HTTPStatus.OK:
self.info = [ self.info = [
{ATTR_DUE_AT: "n/a", ATTR_ROUTE: self.route, ATTR_DUE_IN: "n/a"} {ATTR_DUE_AT: "n/a", ATTR_ROUTE: self.route, ATTR_DUE_IN: "n/a"}
] ]

View File

@ -1,5 +1,6 @@
"""Support for monitoring emoncms feeds.""" """Support for monitoring emoncms feeds."""
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
import logging import logging
import requests import requests
@ -20,7 +21,6 @@ from homeassistant.const import (
CONF_VALUE_TEMPLATE, CONF_VALUE_TEMPLATE,
DEVICE_CLASS_ENERGY, DEVICE_CLASS_ENERGY,
DEVICE_CLASS_POWER, DEVICE_CLASS_POWER,
HTTP_OK,
POWER_WATT, POWER_WATT,
STATE_UNKNOWN, STATE_UNKNOWN,
) )
@ -256,7 +256,7 @@ class EmonCmsData:
_LOGGER.error(exception) _LOGGER.error(exception)
return return
else: else:
if req.status_code == HTTP_OK: if req.status_code == HTTPStatus.OK:
self.data = req.json() self.data = req.json()
else: else:
_LOGGER.error( _LOGGER.error(

View File

@ -1,5 +1,6 @@
"""Support for sending data to Emoncms.""" """Support for sending data to Emoncms."""
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
import logging import logging
import requests import requests
@ -10,7 +11,6 @@ from homeassistant.const import (
CONF_SCAN_INTERVAL, CONF_SCAN_INTERVAL,
CONF_URL, CONF_URL,
CONF_WHITELIST, CONF_WHITELIST,
HTTP_OK,
STATE_UNAVAILABLE, STATE_UNAVAILABLE,
STATE_UNKNOWN, STATE_UNKNOWN,
) )
@ -59,7 +59,7 @@ def setup(hass, config):
_LOGGER.error("Error saving data '%s' to '%s'", payload, fullurl) _LOGGER.error("Error saving data '%s' to '%s'", payload, fullurl)
else: else:
if req.status_code != HTTP_OK: if req.status_code != HTTPStatus.OK:
_LOGGER.error( _LOGGER.error(
"Error saving data %s to %s (http status code = %d)", "Error saving data %s to %s (http status code = %d)",
payload, payload,

View File

@ -5,6 +5,7 @@ Such systems include evohome, Round Thermostat, and others.
from __future__ import annotations from __future__ import annotations
from datetime import datetime as dt, timedelta from datetime import datetime as dt, timedelta
from http import HTTPStatus
import logging import logging
import re import re
from typing import Any from typing import Any
@ -19,8 +20,6 @@ from homeassistant.const import (
CONF_PASSWORD, CONF_PASSWORD,
CONF_SCAN_INTERVAL, CONF_SCAN_INTERVAL,
CONF_USERNAME, CONF_USERNAME,
HTTP_SERVICE_UNAVAILABLE,
HTTP_TOO_MANY_REQUESTS,
TEMP_CELSIUS, TEMP_CELSIUS,
) )
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
@ -158,13 +157,13 @@ def _handle_exception(err) -> bool:
) )
except aiohttp.ClientResponseError: except aiohttp.ClientResponseError:
if err.status == HTTP_SERVICE_UNAVAILABLE: if err.status == HTTPStatus.SERVICE_UNAVAILABLE:
_LOGGER.warning( _LOGGER.warning(
"The vendor says their server is currently unavailable. " "The vendor says their server is currently unavailable. "
"Check the vendor's service status page" "Check the vendor's service status page"
) )
elif err.status == HTTP_TOO_MANY_REQUESTS: elif err.status == HTTPStatus.TOO_MANY_REQUESTS:
_LOGGER.warning( _LOGGER.warning(
"The vendor's API rate limit has been exceeded. " "The vendor's API rate limit has been exceeded. "
"If this message persists, consider increasing the %s", "If this message persists, consider increasing the %s",

View File

@ -1,4 +1,5 @@
"""The tests for the Demo Media player platform.""" """The tests for the Demo Media player platform."""
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
import pytest import pytest
@ -460,7 +461,7 @@ async def test_media_image_proxy(hass, hass_client):
assert state.state == STATE_PLAYING assert state.state == STATE_PLAYING
client = await hass_client() client = await hass_client()
req = await client.get(state.attributes.get(ATTR_ENTITY_PICTURE)) 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 assert await req.text() == fake_picture_data

View File

@ -1,4 +1,6 @@
"""The tests for the demo stt component.""" """The tests for the demo stt component."""
from http import HTTPStatus
import pytest import pytest
from homeassistant.components import stt from homeassistant.components import stt
@ -19,7 +21,7 @@ async def test_demo_settings(hass_client):
response = await client.get("/api/stt/demo") response = await client.get("/api/stt/demo")
response_data = await response.json() response_data = await response.json()
assert response.status == 200 assert response.status == HTTPStatus.OK
assert response_data == { assert response_data == {
"languages": ["en", "de"], "languages": ["en", "de"],
"bit_rates": [16], "bit_rates": [16],
@ -35,7 +37,7 @@ async def test_demo_speech_no_metadata(hass_client):
client = await hass_client() client = await hass_client()
response = await client.post("/api/stt/demo", data=b"Test") 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): 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", data=b"Test",
) )
assert response.status == 415 assert response.status == HTTPStatus.UNSUPPORTED_MEDIA_TYPE
async def test_demo_speech(hass_client): async def test_demo_speech(hass_client):
@ -65,5 +67,5 @@ async def test_demo_speech(hass_client):
) )
response_data = await response.json() 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"} assert response_data == {"text": "Turn the Kitchen Lights on", "result": "success"}

View File

@ -1,5 +1,6 @@
"""The tests for the Dialogflow component.""" """The tests for the Dialogflow component."""
import copy import copy
from http import HTTPStatus
import json import json
import pytest import pytest
@ -171,7 +172,7 @@ async def test_intent_action_incomplete_v1(fixture):
response = await mock_client.post( response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
assert await response.text() == "" assert await response.text() == ""
@ -184,7 +185,7 @@ async def test_intent_action_incomplete_v2(fixture):
response = await mock_client.post( response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
assert await response.text() == "" assert await response.text() == ""
@ -226,7 +227,7 @@ async def test_intent_slot_filling_v1(fixture):
response = await mock_client.post( response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
assert await response.text() == "" assert await response.text() == ""
@ -237,7 +238,7 @@ async def test_intent_request_with_parameters_v1(fixture):
response = await mock_client.post( response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
text = (await response.json()).get("speech") text = (await response.json()).get("speech")
assert text == "You told us your sign is virgo." 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( response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
text = (await response.json()).get("fulfillmentText") text = (await response.json()).get("fulfillmentText")
assert text == "You told us your sign is virgo." 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( response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
text = (await response.json()).get("speech") text = (await response.json()).get("speech")
assert text == "You told us your sign is ." 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( response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
text = (await response.json()).get("fulfillmentText") text = (await response.json()).get("fulfillmentText")
assert text == "You told us your sign is ." 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( response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
text = (await response.json()).get("speech") text = (await response.json()).get("speech")
assert text == "Anne Therese is at unknown and Paulus is at unknown" 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( response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
text = (await response.json()).get("speech") text = (await response.json()).get("speech")
assert text == "You are both home, you silly" 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( response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
text = (await response.json()).get("fulfillmentText") text = (await response.json()).get("fulfillmentText")
assert text == "Anne Therese is at unknown and Paulus is at unknown" 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( response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
text = (await response.json()).get("fulfillmentText") text = (await response.json()).get("fulfillmentText")
assert text == "You are both home, you silly" 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( response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
assert len(calls) == call_count + 1 assert len(calls) == call_count + 1
call = calls[-1] call = calls[-1]
assert call.domain == "test" assert call.domain == "test"
@ -375,7 +376,7 @@ async def test_intent_request_calling_service_v2(fixture, calls):
response = await mock_client.post( response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
assert len(calls) == call_count + 1 assert len(calls) == call_count + 1
call = calls[-1] call = calls[-1]
assert call.domain == "test" assert call.domain == "test"
@ -393,7 +394,7 @@ async def test_intent_with_no_action_v1(fixture):
response = await mock_client.post( response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
text = (await response.json()).get("speech") text = (await response.json()).get("speech")
assert text == "You have not defined an action in your Dialogflow intent." 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( response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
text = (await response.json()).get("fulfillmentText") text = (await response.json()).get("fulfillmentText")
assert text == "You have not defined an action in your Dialogflow intent." 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( response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
text = (await response.json()).get("speech") text = (await response.json()).get("speech")
assert text == "This intent is not yet configured within Home Assistant." 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( response = await mock_client.post(
f"/api/webhook/{webhook_id}", data=json.dumps(data) f"/api/webhook/{webhook_id}", data=json.dumps(data)
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
text = (await response.json()).get("fulfillmentText") text = (await response.json()).get("fulfillmentText")
assert text == "This intent is not yet configured within Home Assistant." assert text == "This intent is not yet configured within Home Assistant."

View File

@ -1,4 +1,5 @@
"""The test for the Ecobee thermostat module.""" """The test for the Ecobee thermostat module."""
from http import HTTPStatus
from unittest import mock from unittest import mock
import pytest import pytest
@ -78,7 +79,7 @@ async def test_name(thermostat):
async def test_current_temperature(ecobee_fixture, thermostat): async def test_current_temperature(ecobee_fixture, thermostat):
"""Test current temperature.""" """Test current temperature."""
assert thermostat.current_temperature == 30 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 assert thermostat.current_temperature == 40.4

View File

@ -1,6 +1,7 @@
"""The tests for the emulated Hue component.""" """The tests for the emulated Hue component."""
import asyncio import asyncio
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
from ipaddress import ip_address from ipaddress import ip_address
import json import json
from unittest.mock import patch from unittest.mock import patch
@ -43,9 +44,6 @@ from homeassistant.const import (
ATTR_ENTITY_ID, ATTR_ENTITY_ID,
ATTR_SUPPORTED_FEATURES, ATTR_SUPPORTED_FEATURES,
CONTENT_TYPE_JSON, CONTENT_TYPE_JSON,
HTTP_NOT_FOUND,
HTTP_OK,
HTTP_UNAUTHORIZED,
SERVICE_TURN_OFF, SERVICE_TURN_OFF,
SERVICE_TURN_ON, SERVICE_TURN_ON,
STATE_OFF, STATE_OFF,
@ -263,7 +261,7 @@ async def test_discover_lights(hue_client):
"""Test the discovery of lights.""" """Test the discovery of lights."""
result = await hue_client.get("/api/username/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"] assert CONTENT_TYPE_JSON in result.headers["content-type"]
result_json = await result.json() 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): async def test_light_without_brightness_supported(hass_hue, hue_client):
"""Test that light without brightness is supported.""" """Test that light without brightness is supported."""
light_without_brightness_json = await perform_get_light_state( 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 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) HueOneLightStateView(config).register(web_app, web_app.router)
client = await hass_client_no_auth() client = await hass_client_no_auth()
light_without_brightness_json = await perform_get_light_state( 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["state"][HUE_API_STATE_ON] is True
assert light_without_brightness_json["type"] == "Dimmable light" 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() 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 CONTENT_TYPE_JSON in no_brightness_result.headers["content-type"]
assert len(no_brightness_result_json) == 1 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() 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 CONTENT_TYPE_JSON in no_brightness_result.headers["content-type"]
assert len(no_brightness_result_json) == 1 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) 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 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.""" """Test the discovery of full state."""
result = await hue_client.get(f"/api/{HUE_API_USERNAME}") 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"] assert CONTENT_TYPE_JSON in result.headers["content-type"]
result_json = await result.json() result_json = await result.json()
@ -489,7 +487,7 @@ async def test_discover_config(hue_client):
"""Test the discovery of configuration.""" """Test the discovery of configuration."""
result = await hue_client.get(f"/api/{HUE_API_USERNAME}/config") 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"] assert CONTENT_TYPE_JSON in result.headers["content-type"]
config_json = await result.json() config_json = await result.json()
@ -526,7 +524,7 @@ async def test_discover_config(hue_client):
# Test without username # Test without username
result = await hue_client.get("/api/config") 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"] assert CONTENT_TYPE_JSON in result.headers["content-type"]
config_json = await result.json() config_json = await result.json()
@ -535,7 +533,7 @@ async def test_discover_config(hue_client):
# Test with wrong username username # Test with wrong username username
result = await hue_client.get("/api/wronguser/config") 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"] assert CONTENT_TYPE_JSON in result.headers["content-type"]
config_json = await result.json() 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( 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 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 # Check all lights view
result = await hue_client.get("/api/username/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"] assert CONTENT_TYPE_JSON in result.headers["content-type"]
result_json = await result.json() 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( 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 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 assert office_json["state"][HUE_API_STATE_SAT] == 0
# Make sure bedroom light isn't accessible # 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 # 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): 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 # go through api to get the state back
ceiling_json = await perform_get_light_state( 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_BRI] == 123
assert ceiling_json["state"][HUE_API_STATE_HUE] == 4369 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 # go through api to get the state back
ceiling_json = await perform_get_light_state( 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_BRI] == 254
assert ceiling_json["state"][HUE_API_STATE_HUE] == 4369 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 # go through api to get the state back
ceiling_json = await perform_get_light_state( 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 ceiling_json["state"][HUE_API_STATE_BRI] == 100
assert hass.states.get("light.ceiling_lights").attributes[light.ATTR_XY_COLOR] == ( 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() 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 CONTENT_TYPE_JSON in ceiling_result.headers["content-type"]
assert len(ceiling_result_json) == 1 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") ceiling_lights = hass_hue.states.get("light.ceiling_lights")
assert ceiling_lights.state == STATE_OFF assert ceiling_lights.state == STATE_OFF
ceiling_json = await perform_get_light_state( 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 # 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 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( bedroom_result = await perform_put_light_state(
hass_hue, hue_client, "light.bed_light", True 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 # Make sure we can't change the kitchen light state
kitchen_result = await perform_put_light_state( kitchen_result = await perform_put_light_state(
hass_hue, hue_client, "light.kitchen_lights", True 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. # Turn the ceiling lights on first and color temp.
await hass_hue.services.async_call( 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() 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 assert len(script_result_json) == 2
kitchen_light = hass_hue.states.get("light.kitchen_lights") 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() 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 assert len(hvac_result_json) == 2
hvac = hass_hue.states.get("climate.hvac") 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( ecobee_result = await perform_put_light_state(
hass_hue, hue_client, "climate.ecobee", True 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): 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() 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 assert len(humidifier_result_json) == 2
hvac = hass_hue.states.get("humidifier.humidifier") 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( hygrostat_result = await perform_put_light_state(
hass_hue, hue_client, "humidifier.hygrostat", True 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): 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() 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 assert len(mp_result_json) == 2
walkman = hass_hue.states.get("media_player.walkman") 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 # Go through the API to turn it on
cover_result = await perform_put_light_state(hass_hue, hue_client, cover_id, True) 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"] assert CONTENT_TYPE_JSON in cover_result.headers["content-type"]
for _ in range(11): 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 # Go through the API to turn it off
cover_result = await perform_put_light_state(hass_hue, hue_client, cover_id, False) 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"] assert CONTENT_TYPE_JSON in cover_result.headers["content-type"]
for _ in range(11): 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 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"] assert CONTENT_TYPE_JSON in cover_result.headers["content-type"]
cover_result_json = await cover_result.json() 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() 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 assert len(fan_result_json) == 2
living_room_fan = hass_hue.states.get("fan.living_room_fan") 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): with patch.object(hue_api, "STATE_CACHED_TIMEOUT", 0.000001):
await asyncio.sleep(0.000001) await asyncio.sleep(0.000001)
fan_json = await perform_get_light_state( 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 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): with patch.object(hue_api, "STATE_CACHED_TIMEOUT", 0.000001):
await asyncio.sleep(0.000001) await asyncio.sleep(0.000001)
fan_json = await perform_get_light_state( fan_json = await perform_get_light_state(
hue_client, "fan.living_room_fan", HTTP_OK hue_client, "fan.living_room_fan", HTTPStatus.OK
) )
assert ( assert (
round(fan_json["state"][HUE_API_STATE_BRI] * 100 / 254) == 67 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): with patch.object(hue_api, "STATE_CACHED_TIMEOUT", 0.000001):
await asyncio.sleep(0.000001) await asyncio.sleep(0.000001)
fan_json = await perform_get_light_state( 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 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, data=data,
) )
assert result.status == 400 assert result.status == HTTPStatus.BAD_REQUEST
async def test_entity_not_found(hue_client): async def test_entity_not_found(hue_client):
"""Test for entity which are not found.""" """Test for entity which are not found."""
result = await hue_client.get("/api/username/lights/98") 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") 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): 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" "/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( result = await hue_client.put(
"/api/username/lights/ENTITY_NUMBERS_BY_ID[light.ceiling_lights]" "/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") 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): 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}), data=json.dumps({HUE_API_STATE_ON: 1234}),
) )
assert result.status == 400 assert result.status == HTTPStatus.BAD_REQUEST
# Test proper brightness value parsing # Test proper brightness value parsing
result = await hue_client.put( 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!"}), 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): 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 # Test proper on value parsing
result = await hue_client.get("/api/username/groups") result = await hue_client.get("/api/username/groups")
assert result.status == HTTP_OK assert result.status == HTTPStatus.OK
result_json = await result.json() 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 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"] assert CONTENT_TYPE_JSON in office_result.headers["content-type"]
office_result_json = await office_result.json() 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 assert result.status == expected_status
if expected_status == HTTP_OK: if expected_status == HTTPStatus.OK:
assert CONTENT_TYPE_JSON in result.headers["content-type"] assert CONTENT_TYPE_JSON in result.headers["content-type"]
return await result.json() return await result.json()
@ -1305,15 +1307,15 @@ async def test_external_ip_blocked(hue_client):
): ):
for getUrl in getUrls: for getUrl in getUrls:
result = await hue_client.get(getUrl) result = await hue_client.get(getUrl)
assert result.status == HTTP_UNAUTHORIZED assert result.status == HTTPStatus.UNAUTHORIZED
for postUrl in postUrls: for postUrl in postUrls:
result = await hue_client.post(postUrl) result = await hue_client.post(postUrl)
assert result.status == HTTP_UNAUTHORIZED assert result.status == HTTPStatus.UNAUTHORIZED
for putUrl in putUrls: for putUrl in putUrls:
result = await hue_client.put(putUrl) result = await hue_client.put(putUrl)
assert result.status == HTTP_UNAUTHORIZED assert result.status == HTTPStatus.UNAUTHORIZED
async def test_unauthorized_user_blocked(hue_client): async def test_unauthorized_user_blocked(hue_client):
@ -1323,7 +1325,7 @@ async def test_unauthorized_user_blocked(hue_client):
] ]
for getUrl in getUrls: for getUrl in getUrls:
result = await hue_client.get(getUrl) result = await hue_client.get(getUrl)
assert result.status == HTTP_OK assert result.status == HTTPStatus.OK
result_json = await result.json() result_json = await result.json()
assert result_json[0]["error"]["description"] == "unauthorized user" 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. # 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( 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 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 # go through api to get the state back
ceiling_json = await perform_get_light_state( 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. # 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. # 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( 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. # 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. # go through api to get the state back, the value returned should now match the actual values.
ceiling_json = await perform_get_light_state( 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. # 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 # 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 # as the waiting to check the state change timed out
ceiling_json = await perform_get_light_state( 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 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.""" """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. # 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): 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() 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 len(scene_result_json) == 1
assert hass_hue.states.get("light.kitchen_lights").state == STATE_ON assert hass_hue.states.get("light.kitchen_lights").state == STATE_ON

View File

@ -1,4 +1,5 @@
"""The tests for the emulated Hue component.""" """The tests for the emulated Hue component."""
from http import HTTPStatus
import json import json
import unittest import unittest
@ -9,7 +10,7 @@ import pytest
from homeassistant import setup from homeassistant import setup
from homeassistant.components import emulated_hue from homeassistant.components import emulated_hue
from homeassistant.components.emulated_hue import upnp 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 from tests.common import get_test_instance_port
@ -149,7 +150,7 @@ async def test_description_xml(hass, hue_client):
client = await hue_client() client = await hue_client()
result = await client.get("/description.xml", timeout=5) 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"] assert "text/xml" in result.headers["content-type"]
try: 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) 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"] assert CONTENT_TYPE_JSON in result.headers["content-type"]
resp_json = await result.json() 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 "/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"] assert CONTENT_TYPE_JSON in result.headers["content-type"]
resp_json = await result.json() 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) result = await client.post("/api", data=json.dumps(request_json), timeout=5)
assert result.status == 400 assert result.status == HTTPStatus.BAD_REQUEST