Use http.HTTPStatus in components/[tuv]* (#58325)

This commit is contained in:
Ville Skyttä 2021-10-24 12:27:17 +03:00 committed by GitHub
parent 45a98aee10
commit cc0c79ac9a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 69 additions and 57 deletions

View file

@ -2,6 +2,7 @@
import asyncio import asyncio
from collections import namedtuple from collections import namedtuple
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
import logging import logging
import aiohttp import aiohttp
@ -13,7 +14,7 @@ from homeassistant.components.device_tracker import (
PLATFORM_SCHEMA, PLATFORM_SCHEMA,
DeviceScanner, DeviceScanner,
) )
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_OK from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers.aiohttp_client import async_create_clientsession from homeassistant.helpers.aiohttp_client import async_create_clientsession
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle from homeassistant.util import Throttle
@ -114,7 +115,7 @@ class TadoDeviceScanner(DeviceScanner):
response = await self.websession.get(url) response = await self.websession.get(url)
if response.status != HTTP_OK: if response.status != HTTPStatus.OK:
_LOGGER.warning("Error %d on %s", response.status, self.tadoapiurl) _LOGGER.warning("Error %d on %s", response.status, self.tadoapiurl)
return False return False

View file

@ -1,5 +1,6 @@
"""Support for The Things Network's Data storage integration.""" """Support for The Things Network's Data storage integration."""
import asyncio import asyncio
from http import HTTPStatus
import logging import logging
import aiohttp import aiohttp
@ -13,8 +14,6 @@ from homeassistant.const import (
ATTR_TIME, ATTR_TIME,
CONF_DEVICE_ID, CONF_DEVICE_ID,
CONTENT_TYPE_JSON, CONTENT_TYPE_JSON,
HTTP_NOT_FOUND,
HTTP_UNAUTHORIZED,
) )
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -134,15 +133,15 @@ class TtnDataStorage:
status = response.status status = response.status
if status == 204: if status == HTTPStatus.NO_CONTENT:
_LOGGER.error("The device is not available: %s", self._device_id) _LOGGER.error("The device is not available: %s", self._device_id)
return None return None
if status == HTTP_UNAUTHORIZED: if status == HTTPStatus.UNAUTHORIZED:
_LOGGER.error("Not authorized for Application ID: %s", self._app_id) _LOGGER.error("Not authorized for Application ID: %s", self._app_id)
return None return None
if status == HTTP_NOT_FOUND: if status == HTTPStatus.NOT_FOUND:
_LOGGER.error("Application ID is not available: %s", self._app_id) _LOGGER.error("Application ID is not available: %s", self._app_id)
return None return None

View file

@ -1,4 +1,5 @@
"""Support for Tomato routers.""" """Support for Tomato routers."""
from http import HTTPStatus
import json import json
import logging import logging
import re import re
@ -18,8 +19,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
@ -104,7 +103,7 @@ class TomatoDeviceScanner(DeviceScanner):
# Calling and parsing the Tomato api here. We only need the # Calling and parsing the Tomato api here. We only need the
# wldev and dhcpd_lease values. # wldev and dhcpd_lease values.
if response.status_code == HTTP_OK: if response.status_code == HTTPStatus.OK:
for param, value in self.parse_api_pattern.findall(response.text): for param, value in self.parse_api_pattern.findall(response.text):
@ -112,7 +111,7 @@ class TomatoDeviceScanner(DeviceScanner):
self.last_results[param] = json.loads(value.replace("'", '"')) self.last_results[param] = json.loads(value.replace("'", '"'))
return True return True
if response.status_code == HTTP_UNAUTHORIZED: if response.status_code == HTTPStatus.UNAUTHORIZED:
# Authentication error # Authentication error
_LOGGER.exception( _LOGGER.exception(
"Failed to authenticate, please check your username and password" "Failed to authenticate, please check your username and password"

View file

@ -1,6 +1,7 @@
"""Twitter platform for notify component.""" """Twitter platform for notify component."""
from datetime import datetime, timedelta from datetime import datetime, timedelta
from functools import partial from functools import partial
from http import HTTPStatus
import json import json
import logging import logging
import mimetypes import mimetypes
@ -14,7 +15,7 @@ from homeassistant.components.notify import (
PLATFORM_SCHEMA, PLATFORM_SCHEMA,
BaseNotificationService, BaseNotificationService,
) )
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_USERNAME, HTTP_OK from homeassistant.const import CONF_ACCESS_TOKEN, CONF_USERNAME
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_point_in_time from homeassistant.helpers.event import async_track_point_in_time
@ -88,7 +89,7 @@ class TwitterNotificationService(BaseNotificationService):
if self.user: if self.user:
user_resp = self.api.request("users/lookup", {"screen_name": self.user}) user_resp = self.api.request("users/lookup", {"screen_name": self.user})
user_id = user_resp.json()[0]["id"] user_id = user_resp.json()[0]["id"]
if user_resp.status_code != HTTP_OK: if user_resp.status_code != HTTPStatus.OK:
self.log_error_resp(user_resp) self.log_error_resp(user_resp)
else: else:
_LOGGER.debug("Message posted: %s", user_resp.json()) _LOGGER.debug("Message posted: %s", user_resp.json())
@ -108,7 +109,7 @@ class TwitterNotificationService(BaseNotificationService):
"statuses/update", {"status": message, "media_ids": media_id} "statuses/update", {"status": message, "media_ids": media_id}
) )
if resp.status_code != HTTP_OK: if resp.status_code != HTTPStatus.OK:
self.log_error_resp(resp) self.log_error_resp(resp)
else: else:
_LOGGER.debug("Message posted: %s", resp.json()) _LOGGER.debug("Message posted: %s", resp.json())
@ -171,7 +172,7 @@ class TwitterNotificationService(BaseNotificationService):
while bytes_sent < total_bytes: while bytes_sent < total_bytes:
chunk = file.read(4 * 1024 * 1024) chunk = file.read(4 * 1024 * 1024)
resp = self.upload_media_append(chunk, media_id, segment_id) resp = self.upload_media_append(chunk, media_id, segment_id)
if resp.status_code not in range(HTTP_OK, 299): if not HTTPStatus.OK <= resp.status_code < HTTPStatus.MULTIPLE_CHOICES:
self.log_error_resp_append(resp) self.log_error_resp_append(resp)
return None return None
segment_id = segment_id + 1 segment_id = segment_id + 1
@ -200,7 +201,7 @@ class TwitterNotificationService(BaseNotificationService):
{"command": "STATUS", "media_id": media_id}, {"command": "STATUS", "media_id": media_id},
method_override="GET", method_override="GET",
) )
if resp.status_code != HTTP_OK: if resp.status_code != HTTPStatus.OK:
_LOGGER.error("Media processing error: %s", resp.json()) _LOGGER.error("Media processing error: %s", resp.json())
processing_info = resp.json()["processing_info"] processing_info = resp.json()["processing_info"]

View file

@ -1,5 +1,6 @@
"""Support for UK public transport data provided by transportapi.com.""" """Support for UK public transport data provided by transportapi.com."""
from datetime import datetime, timedelta from datetime import datetime, timedelta
from http import HTTPStatus
import logging import logging
import re import re
@ -7,7 +8,7 @@ import requests
import voluptuous as vol import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_MODE, HTTP_OK, TIME_MINUTES from homeassistant.const import CONF_MODE, TIME_MINUTES
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle from homeassistant.util import Throttle
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
@ -121,7 +122,7 @@ class UkTransportSensor(SensorEntity):
) )
response = requests.get(self._url, params=request_params) response = requests.get(self._url, params=request_params)
if response.status_code != HTTP_OK: if response.status_code != HTTPStatus.OK:
_LOGGER.warning("Invalid response from API") _LOGGER.warning("Invalid response from API")
elif "error" in response.json(): elif "error" in response.json():
if "exceeded" in response.json()["error"]: if "exceeded" in response.json()["error"]:

View file

@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
from verisure import ( from verisure import (
Error as VerisureError, Error as VerisureError,
@ -10,7 +11,7 @@ from verisure import (
) )
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD, HTTP_SERVICE_UNAVAILABLE from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
from homeassistant.core import Event, HomeAssistant from homeassistant.core import Event, HomeAssistant
from homeassistant.helpers.storage import STORAGE_DIR from homeassistant.helpers.storage import STORAGE_DIR
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
@ -68,7 +69,7 @@ class VerisureDataUpdateCoordinator(DataUpdateCoordinator):
) )
except VerisureResponseError as ex: except VerisureResponseError as ex:
LOGGER.error("Could not read overview, %s", ex) LOGGER.error("Could not read overview, %s", ex)
if ex.status_code == HTTP_SERVICE_UNAVAILABLE: # Service unavailable if ex.status_code == HTTPStatus.SERVICE_UNAVAILABLE:
LOGGER.info("Trying to log in again") LOGGER.info("Trying to log in again")
await self.async_login() await self.async_login()
return {} return {}

View file

@ -1,5 +1,6 @@
"""Support for the Italian train system using ViaggiaTreno API.""" """Support for the Italian train system using ViaggiaTreno API."""
import asyncio import asyncio
from http import HTTPStatus
import logging import logging
import time import time
@ -8,7 +9,7 @@ import async_timeout
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, HTTP_OK, TIME_MINUTES from homeassistant.const import ATTR_ATTRIBUTION, TIME_MINUTES
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -71,7 +72,7 @@ async def async_http_request(hass, uri):
session = hass.helpers.aiohttp_client.async_get_clientsession(hass) session = hass.helpers.aiohttp_client.async_get_clientsession(hass)
with async_timeout.timeout(REQUEST_TIMEOUT): with async_timeout.timeout(REQUEST_TIMEOUT):
req = await session.get(uri) req = await session.get(uri)
if req.status != HTTP_OK: if req.status != HTTPStatus.OK:
return {"error": req.status} return {"error": req.status}
json_response = await req.json() json_response = await req.json()
return json_response return json_response

View file

@ -1,5 +1,6 @@
"""Support for the voicerss speech service.""" """Support for the voicerss speech service."""
import asyncio import asyncio
from http import HTTPStatus
import logging import logging
import aiohttp import aiohttp
@ -7,7 +8,7 @@ import async_timeout
import voluptuous as vol import voluptuous as vol
from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider
from homeassistant.const import CONF_API_KEY, HTTP_OK from homeassistant.const import CONF_API_KEY
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -198,7 +199,7 @@ class VoiceRSSProvider(Provider):
with async_timeout.timeout(10): with async_timeout.timeout(10):
request = await websession.post(VOICERSS_API_URL, data=form_data) request = await websession.post(VOICERSS_API_URL, data=form_data)
if request.status != HTTP_OK: if request.status != HTTPStatus.OK:
_LOGGER.error( _LOGGER.error(
"Error %d on load url %s", request.status, request.url "Error %d on load url %s", request.status, request.url
) )

View file

@ -1,4 +1,5 @@
"""Test the Tado config flow.""" """Test the Tado config flow."""
from http import HTTPStatus
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
import requests import requests
@ -59,7 +60,7 @@ async def test_form_invalid_auth(hass):
) )
response_mock = MagicMock() response_mock = MagicMock()
type(response_mock).status_code = 401 type(response_mock).status_code = HTTPStatus.UNAUTHORIZED
mock_tado_api = _get_mock_tado_api(getMe=requests.HTTPError(response=response_mock)) mock_tado_api = _get_mock_tado_api(getMe=requests.HTTPError(response=response_mock))
with patch( with patch(
@ -82,7 +83,7 @@ async def test_form_cannot_connect(hass):
) )
response_mock = MagicMock() response_mock = MagicMock()
type(response_mock).status_code = 500 type(response_mock).status_code = HTTPStatus.INTERNAL_SERVER_ERROR
mock_tado_api = _get_mock_tado_api(getMe=requests.HTTPError(response=response_mock)) mock_tado_api = _get_mock_tado_api(getMe=requests.HTTPError(response=response_mock))
with patch( with patch(

View file

@ -1,4 +1,5 @@
"""Tests for the Toon config flow.""" """Tests for the Toon config flow."""
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
from toonapi import Agreement, ToonError from toonapi import Agreement, ToonError
@ -77,7 +78,7 @@ async def test_full_flow_implementation(
client = await hass_client_no_auth() client = await hass_client_no_auth()
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert resp.headers["content-type"] == "text/html; charset=utf-8" assert resp.headers["content-type"] == "text/html; charset=utf-8"
aioclient_mock.post( aioclient_mock.post(

View file

@ -1,4 +1,5 @@
"""The tests the for Traccar device tracker platform.""" """The tests the for Traccar device tracker platform."""
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
import pytest import pytest
@ -8,12 +9,7 @@ from homeassistant.components import traccar, zone
from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER_DOMAIN from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER_DOMAIN
from homeassistant.components.traccar import DOMAIN, TRACKER_UPDATE from homeassistant.components.traccar import DOMAIN, TRACKER_UPDATE
from homeassistant.config import async_process_ha_core_config from homeassistant.config import async_process_ha_core_config
from homeassistant.const import ( from homeassistant.const import STATE_HOME, STATE_NOT_HOME
HTTP_OK,
HTTP_UNPROCESSABLE_ENTITY,
STATE_HOME,
STATE_NOT_HOME,
)
from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.dispatcher import DATA_DISPATCHER from homeassistant.helpers.dispatcher import DATA_DISPATCHER
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -84,21 +80,21 @@ async def test_missing_data(hass, client, webhook_id):
# No data # No data
req = await client.post(url) req = await client.post(url)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_UNPROCESSABLE_ENTITY assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
# No latitude # No latitude
copy = data.copy() copy = data.copy()
del copy["lat"] del copy["lat"]
req = await client.post(url, params=copy) req = await client.post(url, params=copy)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_UNPROCESSABLE_ENTITY assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
# No device # No device
copy = data.copy() copy = data.copy()
del copy["id"] del copy["id"]
req = await client.post(url, params=copy) req = await client.post(url, params=copy)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_UNPROCESSABLE_ENTITY assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
async def test_enter_and_exit(hass, client, webhook_id): async def test_enter_and_exit(hass, client, webhook_id):
@ -109,7 +105,7 @@ async def test_enter_and_exit(hass, client, webhook_id):
# Enter the Home # Enter the Home
req = await client.post(url, params=data) req = await client.post(url, params=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state_name = hass.states.get( state_name = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data["id"]) "{}.{}".format(DEVICE_TRACKER_DOMAIN, data["id"])
).state ).state
@ -118,7 +114,7 @@ async def test_enter_and_exit(hass, client, webhook_id):
# Enter Home again # Enter Home again
req = await client.post(url, params=data) req = await client.post(url, params=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state_name = hass.states.get( state_name = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data["id"]) "{}.{}".format(DEVICE_TRACKER_DOMAIN, data["id"])
).state ).state
@ -130,7 +126,7 @@ async def test_enter_and_exit(hass, client, webhook_id):
# Enter Somewhere else # Enter Somewhere else
req = await client.post(url, params=data) req = await client.post(url, params=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state_name = hass.states.get( state_name = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data["id"]) "{}.{}".format(DEVICE_TRACKER_DOMAIN, data["id"])
).state ).state
@ -160,7 +156,7 @@ async def test_enter_with_attrs(hass, client, webhook_id):
req = await client.post(url, params=data) req = await client.post(url, params=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["id"])) state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["id"]))
assert state.state == STATE_NOT_HOME assert state.state == STATE_NOT_HOME
assert state.attributes["gps_accuracy"] == 10.5 assert state.attributes["gps_accuracy"] == 10.5
@ -182,7 +178,7 @@ async def test_enter_with_attrs(hass, client, webhook_id):
req = await client.post(url, params=data) req = await client.post(url, params=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["id"])) state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["id"]))
assert state.state == STATE_HOME assert state.state == STATE_HOME
assert state.attributes["gps_accuracy"] == 123 assert state.attributes["gps_accuracy"] == 123
@ -201,7 +197,7 @@ async def test_two_devices(hass, client, webhook_id):
# Exit Home # Exit Home
req = await client.post(url, params=data_device_1) req = await client.post(url, params=data_device_1)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data_device_1["id"])) state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data_device_1["id"]))
assert state.state == "not_home" assert state.state == "not_home"
@ -213,7 +209,7 @@ async def test_two_devices(hass, client, webhook_id):
data_device_2["id"] = "device_2" data_device_2["id"] = "device_2"
req = await client.post(url, params=data_device_2) req = await client.post(url, params=data_device_2)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data_device_2["id"])) state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data_device_2["id"]))
assert state.state == "home" assert state.state == "home"
@ -232,7 +228,7 @@ async def test_load_unload_entry(hass, client, webhook_id):
# Enter the Home # Enter the Home
req = await client.post(url, params=data) req = await client.post(url, params=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state_name = hass.states.get( state_name = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data["id"]) "{}.{}".format(DEVICE_TRACKER_DOMAIN, data["id"])
).state ).state

View file

@ -1,4 +1,5 @@
"""The tests for the TTS component.""" """The tests for the TTS component."""
from http import HTTPStatus
from unittest.mock import PropertyMock, patch from unittest.mock import PropertyMock, patch
import pytest import pytest
@ -15,7 +16,6 @@ from homeassistant.components.media_player.const import (
import homeassistant.components.tts as tts import homeassistant.components.tts as tts
from homeassistant.components.tts import _get_cache_files from homeassistant.components.tts import _get_cache_files
from homeassistant.config import async_process_ha_core_config from homeassistant.config import async_process_ha_core_config
from homeassistant.const import HTTP_NOT_FOUND
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import assert_setup_component, async_mock_service from tests.common import assert_setup_component, async_mock_service
@ -486,7 +486,7 @@ async def test_setup_component_and_test_service_with_receive_voice(
"en", "en",
None, None,
) )
assert req.status == 200 assert req.status == HTTPStatus.OK
assert await req.read() == demo_data assert await req.read() == demo_data
@ -523,7 +523,7 @@ async def test_setup_component_and_test_service_with_receive_voice_german(
"de", "de",
None, None,
) )
assert req.status == 200 assert req.status == HTTPStatus.OK
assert await req.read() == demo_data assert await req.read() == demo_data
@ -539,7 +539,7 @@ async def test_setup_component_and_web_view_wrong_file(hass, hass_client):
url = "/api/tts_proxy/42f18378fd4393d18c8dd11d03fa9563c1e54491_en_-_demo.mp3" url = "/api/tts_proxy/42f18378fd4393d18c8dd11d03fa9563c1e54491_en_-_demo.mp3"
req = await client.get(url) req = await client.get(url)
assert req.status == HTTP_NOT_FOUND assert req.status == HTTPStatus.NOT_FOUND
async def test_setup_component_and_web_view_wrong_filename(hass, hass_client): async def test_setup_component_and_web_view_wrong_filename(hass, hass_client):
@ -554,7 +554,7 @@ async def test_setup_component_and_web_view_wrong_filename(hass, hass_client):
url = "/api/tts_proxy/265944dsk32c1b2a621be5930510bb2cd_en_-_demo.mp3" url = "/api/tts_proxy/265944dsk32c1b2a621be5930510bb2cd_en_-_demo.mp3"
req = await client.get(url) req = await client.get(url)
assert req.status == HTTP_NOT_FOUND assert req.status == HTTPStatus.NOT_FOUND
async def test_setup_component_test_without_cache(hass, empty_cache_dir): async def test_setup_component_test_without_cache(hass, empty_cache_dir):
@ -682,7 +682,7 @@ async def test_setup_component_load_cache_retrieve_without_mem_cache(
url = "/api/tts_proxy/42f18378fd4393d18c8dd11d03fa9563c1e54491_en_-_demo.mp3" url = "/api/tts_proxy/42f18378fd4393d18c8dd11d03fa9563c1e54491_en_-_demo.mp3"
req = await client.get(url) req = await client.get(url)
assert req.status == 200 assert req.status == HTTPStatus.OK
assert await req.read() == demo_data assert await req.read() == demo_data
@ -698,7 +698,7 @@ async def test_setup_component_and_web_get_url(hass, hass_client):
data = {"platform": "demo", "message": "There is someone at the door."} data = {"platform": "demo", "message": "There is someone at the door."}
req = await client.post(url, json=data) req = await client.post(url, json=data)
assert req.status == 200 assert req.status == HTTPStatus.OK
response = await req.json() response = await req.json()
assert response == { assert response == {
"url": "http://example.local:8123/api/tts_proxy/42f18378fd4393d18c8dd11d03fa9563c1e54491_en_-_demo.mp3", "url": "http://example.local:8123/api/tts_proxy/42f18378fd4393d18c8dd11d03fa9563c1e54491_en_-_demo.mp3",
@ -718,7 +718,7 @@ async def test_setup_component_and_web_get_url_bad_config(hass, hass_client):
data = {"message": "There is someone at the door."} data = {"message": "There is someone at the door."}
req = await client.post(url, json=data) req = await client.post(url, json=data)
assert req.status == 400 assert req.status == HTTPStatus.BAD_REQUEST
async def test_tags_with_wave(hass, demo_provider): async def test_tags_with_wave(hass, demo_provider):

View file

@ -3,6 +3,7 @@
import asyncio import asyncio
from copy import deepcopy from copy import deepcopy
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
import aiounifi import aiounifi
@ -404,7 +405,9 @@ async def test_reconnect_mechanism(hass, aioclient_mock, mock_unifi_websocket):
await setup_unifi_integration(hass, aioclient_mock) await setup_unifi_integration(hass, aioclient_mock)
aioclient_mock.clear_requests() aioclient_mock.clear_requests()
aioclient_mock.post(f"https://{DEFAULT_HOST}:1234/api/login", status=502) aioclient_mock.post(
f"https://{DEFAULT_HOST}:1234/api/login", status=HTTPStatus.BAD_GATEWAY
)
mock_unifi_websocket(state=STATE_DISCONNECTED) mock_unifi_websocket(state=STATE_DISCONNECTED)
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -1,5 +1,6 @@
"""The tests for the VoiceRSS speech platform.""" """The tests for the VoiceRSS speech platform."""
import asyncio import asyncio
from http import HTTPStatus
import os import os
import shutil import shutil
@ -65,7 +66,9 @@ class TestTTSVoiceRSSPlatform:
"""Test service call say.""" """Test service call say."""
calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA) calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA)
aioclient_mock.post(self.url, data=self.form_data, status=200, content=b"test") aioclient_mock.post(
self.url, data=self.form_data, status=HTTPStatus.OK, content=b"test"
)
config = {tts.DOMAIN: {"platform": "voicerss", "api_key": "1234567xx"}} config = {tts.DOMAIN: {"platform": "voicerss", "api_key": "1234567xx"}}
@ -92,7 +95,9 @@ class TestTTSVoiceRSSPlatform:
calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA) calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA)
self.form_data["hl"] = "de-de" self.form_data["hl"] = "de-de"
aioclient_mock.post(self.url, data=self.form_data, status=200, content=b"test") aioclient_mock.post(
self.url, data=self.form_data, status=HTTPStatus.OK, content=b"test"
)
config = { config = {
tts.DOMAIN: { tts.DOMAIN: {
@ -124,7 +129,9 @@ class TestTTSVoiceRSSPlatform:
calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA) calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA)
self.form_data["hl"] = "de-de" self.form_data["hl"] = "de-de"
aioclient_mock.post(self.url, data=self.form_data, status=200, content=b"test") aioclient_mock.post(
self.url, data=self.form_data, status=HTTPStatus.OK, content=b"test"
)
config = {tts.DOMAIN: {"platform": "voicerss", "api_key": "1234567xx"}} config = {tts.DOMAIN: {"platform": "voicerss", "api_key": "1234567xx"}}
@ -203,7 +210,7 @@ class TestTTSVoiceRSSPlatform:
aioclient_mock.post( aioclient_mock.post(
self.url, self.url,
data=self.form_data, data=self.form_data,
status=200, status=HTTPStatus.OK,
content=b"The subscription does not support SSML!", content=b"The subscription does not support SSML!",
) )