Use HTTPStatus in components/[nop]* (#58279)

This commit is contained in:
Ville Skyttä 2021-10-23 21:56:30 +03:00 committed by GitHub
parent 5626cc4524
commit 380cff167e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
25 changed files with 92 additions and 70 deletions

View file

@ -1,10 +1,10 @@
"""Local Nest authentication for the legacy api.""" """Local Nest authentication for the legacy api."""
import asyncio import asyncio
from functools import partial from functools import partial
from http import HTTPStatus
from nest.nest import AUTHORIZE_URL, AuthorizationError, NestAuth from nest.nest import AUTHORIZE_URL, AuthorizationError, NestAuth
from homeassistant.const import HTTP_UNAUTHORIZED
from homeassistant.core import callback from homeassistant.core import callback
from ..config_flow import CodeInvalid, NestAuthError, register_flow_implementation from ..config_flow import CodeInvalid, NestAuthError, register_flow_implementation
@ -43,7 +43,7 @@ async def resolve_auth_code(hass, client_id, client_secret, code):
await hass.async_add_executor_job(auth.login) await hass.async_add_executor_job(auth.login)
return await result return await result
except AuthorizationError as err: except AuthorizationError as err:
if err.response.status_code == HTTP_UNAUTHORIZED: if err.response.status_code == HTTPStatus.UNAUTHORIZED:
raise CodeInvalid() from err raise CodeInvalid() from err
raise NestAuthError( raise NestAuthError(
f"Unknown error: {err} ({err.response.status_code})" f"Unknown error: {err} ({err.response.status_code})"

View file

@ -1,11 +1,11 @@
"""Utils for Nexia / Trane XL Thermostats.""" """Utils for Nexia / Trane XL Thermostats."""
from homeassistant.const import HTTP_FORBIDDEN, HTTP_UNAUTHORIZED from http import HTTPStatus
def is_invalid_auth_code(http_status_code): def is_invalid_auth_code(http_status_code):
"""HTTP status codes that mean invalid auth.""" """HTTP status codes that mean invalid auth."""
if http_status_code in (HTTP_UNAUTHORIZED, HTTP_FORBIDDEN): if http_status_code in (HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN):
return True return True
return False return False

View file

@ -1,13 +1,14 @@
"""Support for the Nissan Leaf Carwings/Nissan Connect API.""" """Support for the Nissan Leaf Carwings/Nissan Connect API."""
import asyncio import asyncio
from datetime import datetime, timedelta from datetime import datetime, timedelta
from http import HTTPStatus
import logging import logging
import sys import sys
from pycarwings2 import CarwingsError, Session from pycarwings2 import CarwingsError, Session
import voluptuous as vol import voluptuous as vol
from homeassistant.const import CONF_PASSWORD, CONF_REGION, CONF_USERNAME, HTTP_OK from homeassistant.const import CONF_PASSWORD, CONF_REGION, CONF_USERNAME
from homeassistant.core import callback from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.discovery import load_platform from homeassistant.helpers.discovery import load_platform
@ -293,7 +294,7 @@ class LeafDataStore:
if server_response is not None: if server_response is not None:
_LOGGER.debug("Server Response: %s", server_response.__dict__) _LOGGER.debug("Server Response: %s", server_response.__dict__)
if server_response.answer["status"] == HTTP_OK: if server_response.answer["status"] == HTTPStatus.OK:
self.data[DATA_BATTERY] = server_response.battery_percent self.data[DATA_BATTERY] = server_response.battery_percent
# pycarwings2 library doesn't always provide cruising rnages # pycarwings2 library doesn't always provide cruising rnages

View file

@ -1,17 +1,13 @@
"""Support for NuHeat thermostats.""" """Support for NuHeat thermostats."""
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
import logging import logging
import nuheat import nuheat
import requests import requests
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
CONF_PASSWORD,
CONF_USERNAME,
HTTP_BAD_REQUEST,
HTTP_INTERNAL_SERVER_ERROR,
)
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import config_validation as cv from homeassistant.helpers import config_validation as cv
@ -49,8 +45,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
raise ConfigEntryNotReady from ex raise ConfigEntryNotReady from ex
except requests.exceptions.HTTPError as ex: except requests.exceptions.HTTPError as ex:
if ( if (
ex.response.status_code > HTTP_BAD_REQUEST ex.response.status_code > HTTPStatus.BAD_REQUEST
and ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR and ex.response.status_code < HTTPStatus.INTERNAL_SERVER_ERROR
): ):
_LOGGER.error("Failed to login to nuheat: %s", ex) _LOGGER.error("Failed to login to nuheat: %s", ex)
return False return False

View file

@ -1,4 +1,5 @@
"""Config flow for NuHeat integration.""" """Config flow for NuHeat integration."""
from http import HTTPStatus
import logging import logging
import nuheat import nuheat
@ -6,12 +7,7 @@ import requests.exceptions
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_PASSWORD, CONF_USERNAME
CONF_PASSWORD,
CONF_USERNAME,
HTTP_BAD_REQUEST,
HTTP_INTERNAL_SERVER_ERROR,
)
from .const import CONF_SERIAL_NUMBER, DOMAIN from .const import CONF_SERIAL_NUMBER, DOMAIN
@ -39,8 +35,8 @@ async def validate_input(hass: core.HomeAssistant, data):
raise CannotConnect from ex raise CannotConnect from ex
except requests.exceptions.HTTPError as ex: except requests.exceptions.HTTPError as ex:
if ( if (
ex.response.status_code > HTTP_BAD_REQUEST ex.response.status_code > HTTPStatus.BAD_REQUEST
and ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR and ex.response.status_code < HTTPStatus.INTERNAL_SERVER_ERROR
): ):
raise InvalidAuth from ex raise InvalidAuth from ex
raise CannotConnect from ex raise CannotConnect from ex

View file

@ -1,6 +1,7 @@
"""Component that will help set the OpenALPR cloud for ALPR processing.""" """Component that will help set the OpenALPR cloud for ALPR processing."""
import asyncio import asyncio
from base64 import b64encode from base64 import b64encode
from http import HTTPStatus
import logging import logging
import aiohttp import aiohttp
@ -17,7 +18,7 @@ from homeassistant.components.image_processing import (
from homeassistant.components.openalpr_local.image_processing import ( from homeassistant.components.openalpr_local.image_processing import (
ImageProcessingAlprEntity, ImageProcessingAlprEntity,
) )
from homeassistant.const import CONF_API_KEY, CONF_REGION, HTTP_OK from homeassistant.const import CONF_API_KEY, CONF_REGION
from homeassistant.core import split_entity_id from homeassistant.core import split_entity_id
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
@ -119,7 +120,7 @@ class OpenAlprCloudEntity(ImageProcessingAlprEntity):
data = await request.json() data = await request.json()
if request.status != HTTP_OK: if request.status != HTTPStatus.OK:
_LOGGER.error("Error %d -> %s", request.status, data.get("error")) _LOGGER.error("Error %d -> %s", request.status, data.get("error"))
return return

View file

@ -1,5 +1,6 @@
"""Support for openexchangerates.org exchange rates service.""" """Support for openexchangerates.org exchange rates service."""
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
import logging import logging
import requests import requests
@ -12,7 +13,6 @@ from homeassistant.const import (
CONF_BASE, CONF_BASE,
CONF_NAME, CONF_NAME,
CONF_QUOTE, CONF_QUOTE,
HTTP_OK,
) )
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle from homeassistant.util import Throttle
@ -49,7 +49,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
rest = OpenexchangeratesData(_RESOURCE, parameters, quote) rest = OpenexchangeratesData(_RESOURCE, parameters, quote)
response = requests.get(_RESOURCE, params=parameters, timeout=10) response = requests.get(_RESOURCE, params=parameters, timeout=10)
if response.status_code != HTTP_OK: if response.status_code != HTTPStatus.OK:
_LOGGER.error("Check your OpenExchangeRates API key") _LOGGER.error("Check your OpenExchangeRates API key")
return False return False

View file

@ -1,5 +1,6 @@
"""Prowl notification service.""" """Prowl notification service."""
import asyncio import asyncio
from http import HTTPStatus
import logging import logging
import async_timeout import async_timeout
@ -12,7 +13,7 @@ from homeassistant.components.notify import (
PLATFORM_SCHEMA, PLATFORM_SCHEMA,
BaseNotificationService, BaseNotificationService,
) )
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
@ -59,7 +60,7 @@ class ProwlNotificationService(BaseNotificationService):
response = await session.post(url, data=payload) response = await session.post(url, data=payload)
result = await response.text() result = await response.text()
if response.status != HTTP_OK or "error" in result: if response.status != HTTPStatus.OK or "error" in result:
_LOGGER.error( _LOGGER.error(
"Prowl service returned http status %d, response %s", "Prowl service returned http status %d, response %s",
response.status, response.status,

View file

@ -1,5 +1,6 @@
"""Pushsafer platform for notify component.""" """Pushsafer platform for notify component."""
import base64 import base64
from http import HTTPStatus
import logging import logging
import mimetypes import mimetypes
@ -15,7 +16,7 @@ from homeassistant.components.notify import (
PLATFORM_SCHEMA, PLATFORM_SCHEMA,
BaseNotificationService, BaseNotificationService,
) )
from homeassistant.const import ATTR_ICON, HTTP_OK from homeassistant.const import ATTR_ICON
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -118,7 +119,7 @@ class PushsaferNotificationService(BaseNotificationService):
for target in targets: for target in targets:
payload["d"] = target payload["d"] = target
response = requests.post(_RESOURCE, data=payload, timeout=CONF_TIMEOUT) response = requests.post(_RESOURCE, data=payload, timeout=CONF_TIMEOUT)
if response.status_code != HTTP_OK: if response.status_code != HTTPStatus.OK:
_LOGGER.error("Pushsafer failed with: %s", response.text) _LOGGER.error("Pushsafer failed with: %s", response.text)
else: else:
_LOGGER.debug("Push send: %s", response.json()) _LOGGER.debug("Push send: %s", response.json())

View file

@ -6,6 +6,7 @@ pubsub subscriber.
""" """
import datetime import datetime
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
import aiohttp import aiohttp
@ -237,7 +238,7 @@ async def test_camera_ws_stream(hass, auth, hass_ws_client):
async def test_camera_ws_stream_failure(hass, auth, hass_ws_client): async def test_camera_ws_stream_failure(hass, auth, hass_ws_client):
"""Test a basic camera that supports web rtc.""" """Test a basic camera that supports web rtc."""
auth.responses = [aiohttp.web.Response(status=400)] auth.responses = [aiohttp.web.Response(status=HTTPStatus.BAD_REQUEST)]
await async_setup_camera(hass, DEVICE_TRAITS, auth=auth) await async_setup_camera(hass, DEVICE_TRAITS, auth=auth)
assert len(hass.states.async_all()) == 1 assert len(hass.states.async_all()) == 1
@ -438,7 +439,7 @@ async def test_refresh_expired_stream_failure(hass, auth):
auth.responses = [ auth.responses = [
make_stream_url_response(expiration=stream_1_expiration, token_num=1), make_stream_url_response(expiration=stream_1_expiration, token_num=1),
# Extending the stream fails with arbitrary error # Extending the stream fails with arbitrary error
aiohttp.web.Response(status=500), aiohttp.web.Response(status=HTTPStatus.INTERNAL_SERVER_ERROR),
# Next attempt to get a stream fetches a new url # Next attempt to get a stream fetches a new url
make_stream_url_response(expiration=stream_2_expiration, token_num=2), make_stream_url_response(expiration=stream_2_expiration, token_num=2),
] ]
@ -544,7 +545,7 @@ async def test_generate_event_image_url_failure(hass, auth):
auth.responses = [ auth.responses = [
# Fail to generate the image url # Fail to generate the image url
aiohttp.web.Response(status=500), aiohttp.web.Response(status=HTTPStatus.INTERNAL_SERVER_ERROR),
# Camera fetches a stream url as a fallback # Camera fetches a stream url as a fallback
make_stream_url_response(), make_stream_url_response(),
] ]
@ -566,7 +567,7 @@ async def test_fetch_event_image_failure(hass, auth):
# Fake response from API that returns url image # Fake response from API that returns url image
aiohttp.web.json_response(GENERATE_IMAGE_URL_RESPONSE), aiohttp.web.json_response(GENERATE_IMAGE_URL_RESPONSE),
# Fail to download the image # Fail to download the image
aiohttp.web.Response(status=500), aiohttp.web.Response(status=HTTPStatus.INTERNAL_SERVER_ERROR),
# Camera fetches a stream url as a fallback # Camera fetches a stream url as a fallback
make_stream_url_response(), make_stream_url_response(),
] ]
@ -756,7 +757,7 @@ async def test_camera_web_rtc_unsupported(hass, auth, hass_ws_client):
async def test_camera_web_rtc_offer_failure(hass, auth, hass_ws_client): async def test_camera_web_rtc_offer_failure(hass, auth, hass_ws_client):
"""Test a basic camera that supports web rtc.""" """Test a basic camera that supports web rtc."""
auth.responses = [ auth.responses = [
aiohttp.web.Response(status=400), aiohttp.web.Response(status=HTTPStatus.BAD_REQUEST),
] ]
device_traits = { device_traits = {
"sdm.devices.traits.Info": { "sdm.devices.traits.Info": {

View file

@ -1,16 +1,16 @@
"""The sensor tests for the nexia platform.""" """The sensor tests for the nexia platform."""
from http import HTTPStatus
from homeassistant.components.nexia import util from homeassistant.components.nexia import util
from homeassistant.const import HTTP_FORBIDDEN, HTTP_NOT_FOUND, HTTP_UNAUTHORIZED
async def test_is_invalid_auth_code(): async def test_is_invalid_auth_code():
"""Test for invalid auth.""" """Test for invalid auth."""
assert util.is_invalid_auth_code(HTTP_UNAUTHORIZED) is True assert util.is_invalid_auth_code(HTTPStatus.UNAUTHORIZED) is True
assert util.is_invalid_auth_code(HTTP_FORBIDDEN) is True assert util.is_invalid_auth_code(HTTPStatus.FORBIDDEN) is True
assert util.is_invalid_auth_code(HTTP_NOT_FOUND) is False assert util.is_invalid_auth_code(HTTPStatus.NOT_FOUND) is False
async def test_percent_conv(): async def test_percent_conv():

View file

@ -1,4 +1,5 @@
"""Test the Nightscout config flow.""" """Test the Nightscout config flow."""
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
from aiohttp import ClientConnectionError, ClientResponseError from aiohttp import ClientConnectionError, ClientResponseError
@ -70,7 +71,7 @@ async def test_user_form_api_key_required(hass):
return_value=SERVER_STATUS_STATUS_ONLY, return_value=SERVER_STATUS_STATUS_ONLY,
), patch( ), patch(
"homeassistant.components.nightscout.NightscoutAPI.get_sgvs", "homeassistant.components.nightscout.NightscoutAPI.get_sgvs",
side_effect=ClientResponseError(None, None, status=401), side_effect=ClientResponseError(None, None, status=HTTPStatus.UNAUTHORIZED),
): ):
result2 = await hass.config_entries.flow.async_configure( result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], result["flow_id"],

View file

@ -1,11 +1,12 @@
"""Test the NuHeat config flow.""" """Test the NuHeat config flow."""
from http import HTTPStatus
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
import requests import requests
from homeassistant import config_entries from homeassistant import config_entries
from homeassistant.components.nuheat.const import CONF_SERIAL_NUMBER, DOMAIN from homeassistant.components.nuheat.const import CONF_SERIAL_NUMBER, DOMAIN
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_INTERNAL_SERVER_ERROR from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from .mocks import _get_mock_thermostat_run from .mocks import _get_mock_thermostat_run
@ -98,7 +99,7 @@ async def test_form_invalid_thermostat(hass):
) )
response_mock = MagicMock() response_mock = MagicMock()
type(response_mock).status_code = HTTP_INTERNAL_SERVER_ERROR type(response_mock).status_code = HTTPStatus.INTERNAL_SERVER_ERROR
with patch( with patch(
"homeassistant.components.nuheat.config_flow.nuheat.NuHeat.authenticate", "homeassistant.components.nuheat.config_flow.nuheat.NuHeat.authenticate",

View file

@ -1,5 +1,6 @@
"""Test the onboarding views.""" """Test the onboarding views."""
import asyncio import asyncio
from http import HTTPStatus
import os import os
from unittest.mock import patch from unittest.mock import patch
@ -7,7 +8,6 @@ import pytest
from homeassistant.components import onboarding from homeassistant.components import onboarding
from homeassistant.components.onboarding import const, views from homeassistant.components.onboarding import const, views
from homeassistant.const import HTTP_FORBIDDEN
from homeassistant.helpers import area_registry as ar from homeassistant.helpers import area_registry as ar
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -130,7 +130,7 @@ async def test_onboarding_user_already_done(hass, hass_storage, hass_client_no_a
}, },
) )
assert resp.status == HTTP_FORBIDDEN assert resp.status == HTTPStatus.FORBIDDEN
async def test_onboarding_user(hass, hass_storage, hass_client_no_auth): async def test_onboarding_user(hass, hass_storage, hass_client_no_auth):
@ -247,7 +247,7 @@ async def test_onboarding_user_race(hass, hass_storage, hass_client_no_auth):
res1, res2 = await asyncio.gather(resp1, resp2) res1, res2 = await asyncio.gather(resp1, resp2)
assert sorted([res1.status, res2.status]) == [200, HTTP_FORBIDDEN] assert sorted([res1.status, res2.status]) == [HTTPStatus.OK, HTTPStatus.FORBIDDEN]
async def test_onboarding_integration(hass, hass_storage, hass_client, hass_admin_user): async def test_onboarding_integration(hass, hass_storage, hass_client, hass_admin_user):

View file

@ -1,4 +1,5 @@
"""Tests for Plex media browser.""" """Tests for Plex media browser."""
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
from homeassistant.components.media_player.const import ( from homeassistant.components.media_player.const import (
@ -359,7 +360,8 @@ async def test_browse_media(
# Browse into a non-existent TV season # Browse into a non-existent TV season
unknown_key = 99999999999999 unknown_key = 99999999999999
requests_mock.get( requests_mock.get(
f"{mock_plex_server.url_in_use}/library/metadata/{unknown_key}", status_code=404 f"{mock_plex_server.url_in_use}/library/metadata/{unknown_key}",
status_code=HTTPStatus.NOT_FOUND,
) )
msg_id += 1 msg_id += 1

View file

@ -1,5 +1,6 @@
"""Tests for Plex config flow.""" """Tests for Plex config flow."""
import copy import copy
from http import HTTPStatus
import ssl import ssl
from unittest.mock import patch from unittest.mock import patch
@ -528,7 +529,7 @@ async def test_callback_view(hass, hass_client_no_auth, current_request_with_hos
forward_url = f'{config_flow.AUTH_CALLBACK_PATH}?flow_id={result["flow_id"]}' forward_url = f'{config_flow.AUTH_CALLBACK_PATH}?flow_id={result["flow_id"]}'
resp = await client.get(forward_url) resp = await client.get(forward_url)
assert resp.status == 200 assert resp.status == HTTPStatus.OK
async def test_manual_config(hass, mock_plex_calls, current_request_with_host): async def test_manual_config(hass, mock_plex_calls, current_request_with_host):

View file

@ -1,6 +1,7 @@
"""Tests for Plex setup.""" """Tests for Plex setup."""
import copy import copy
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
import ssl import ssl
from unittest.mock import patch from unittest.mock import patch
@ -212,7 +213,9 @@ async def test_setup_when_certificate_changed(
requests_mock.get(old_url, exc=WrongCertHostnameException) requests_mock.get(old_url, exc=WrongCertHostnameException)
# Test with account failure # Test with account failure
requests_mock.get("https://plex.tv/users/account", status_code=401) requests_mock.get(
"https://plex.tv/users/account", status_code=HTTPStatus.UNAUTHORIZED
)
old_entry.add_to_hass(hass) old_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(old_entry.entry_id) is False assert await hass.config_entries.async_setup(old_entry.entry_id) is False
await hass.async_block_till_done() await hass.async_block_till_done()
@ -262,7 +265,9 @@ async def test_bad_token_with_tokenless_server(
hass, entry, mock_websocket, setup_plex_server, requests_mock hass, entry, mock_websocket, setup_plex_server, requests_mock
): ):
"""Test setup with a bad token and a server with token auth disabled.""" """Test setup with a bad token and a server with token auth disabled."""
requests_mock.get("https://plex.tv/users/account", status_code=401) requests_mock.get(
"https://plex.tv/users/account", status_code=HTTPStatus.UNAUTHORIZED
)
await setup_plex_server() await setup_plex_server()

View file

@ -1,4 +1,5 @@
"""Tests for Plex player playback methods/services.""" """Tests for Plex player playback methods/services."""
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
from homeassistant.components.media_player.const import ( from homeassistant.components.media_player.const import (
@ -23,7 +24,7 @@ async def test_media_player_playback(
media_player = "media_player.plex_plex_web_chrome" media_player = "media_player.plex_plex_web_chrome"
requests_mock.post("/playqueues", text=playqueue_created) requests_mock.post("/playqueues", text=playqueue_created)
requests_mock.get("/player/playback/playMedia", status_code=200) requests_mock.get("/player/playback/playMedia", status_code=HTTPStatus.OK)
# Test movie success # Test movie success
assert await hass.services.async_call( assert await hass.services.async_call(
@ -111,7 +112,7 @@ async def test_media_player_playback(
) )
# Test media lookup failure by key # Test media lookup failure by key
requests_mock.get("/library/metadata/999", status_code=404) requests_mock.get("/library/metadata/999", status_code=HTTPStatus.NOT_FOUND)
assert await hass.services.async_call( assert await hass.services.async_call(
MP_DOMAIN, MP_DOMAIN,
SERVICE_PLAY_MEDIA, SERVICE_PLAY_MEDIA,

View file

@ -1,5 +1,6 @@
"""Tests for Plex sensors.""" """Tests for Plex sensors."""
from datetime import datetime, timedelta from datetime import datetime, timedelta
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
import requests.exceptions import requests.exceptions
@ -165,7 +166,8 @@ async def test_library_sensor_values(
# Handle library deletion # Handle library deletion
requests_mock.get( requests_mock.get(
"/library/sections/2/all?includeCollections=0&type=2", status_code=404 "/library/sections/2/all?includeCollections=0&type=2",
status_code=HTTPStatus.NOT_FOUND,
) )
trigger_plex_update( trigger_plex_update(
mock_websocket, msgtype="status", payload=LIBRARY_UPDATE_PAYLOAD mock_websocket, msgtype="status", payload=LIBRARY_UPDATE_PAYLOAD

View file

@ -1,5 +1,6 @@
"""Tests for Plex server.""" """Tests for Plex server."""
import copy import copy
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
from plexapi.exceptions import BadRequest, NotFound from plexapi.exceptions import BadRequest, NotFound
@ -188,7 +189,7 @@ async def test_media_lookups(hass, mock_plex_server, requests_mock, playqueue_cr
# Plex Key searches # Plex Key searches
media_player_id = hass.states.async_entity_ids("media_player")[0] media_player_id = hass.states.async_entity_ids("media_player")[0]
requests_mock.post("/playqueues", text=playqueue_created) requests_mock.post("/playqueues", text=playqueue_created)
requests_mock.get("/player/playback/playMedia", status_code=200) requests_mock.get("/player/playback/playMedia", status_code=HTTPStatus.OK)
assert await hass.services.async_call( assert await hass.services.async_call(
MP_DOMAIN, MP_DOMAIN,
SERVICE_PLAY_MEDIA, SERVICE_PLAY_MEDIA,

View file

@ -1,4 +1,5 @@
"""Tests for various Plex services.""" """Tests for various Plex services."""
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
from plexapi.exceptions import NotFound from plexapi.exceptions import NotFound
@ -33,7 +34,9 @@ async def test_refresh_library(
): ):
"""Test refresh_library service call.""" """Test refresh_library service call."""
url = mock_plex_server.url_in_use url = mock_plex_server.url_in_use
refresh = requests_mock.get(f"{url}/library/sections/1/refresh", status_code=200) refresh = requests_mock.get(
f"{url}/library/sections/1/refresh", status_code=HTTPStatus.OK
)
# Test with non-existent server # Test with non-existent server
with pytest.raises(HomeAssistantError): with pytest.raises(HomeAssistantError):
@ -126,7 +129,9 @@ async def test_sonos_play_media(
requests_mock.get("https://plex.tv/users/account", text=plextv_account) requests_mock.get("https://plex.tv/users/account", text=plextv_account)
requests_mock.post("/playqueues", text=playqueue_created) requests_mock.post("/playqueues", text=playqueue_created)
playback_mock = requests_mock.get("/player/playback/playMedia", status_code=200) playback_mock = requests_mock.get(
"/player/playback/playMedia", status_code=HTTPStatus.OK
)
# Test with no Plex integration available # Test with no Plex integration available
with pytest.raises(HomeAssistantError) as excinfo: with pytest.raises(HomeAssistantError) as excinfo:
@ -187,7 +192,9 @@ async def test_sonos_play_media(
assert playback_mock.call_count == 4 assert playback_mock.call_count == 4
# Test with speakers available and invalid playqueue # Test with speakers available and invalid playqueue
requests_mock.get("https://1.2.3.4:32400/playQueues/1235", status_code=404) requests_mock.get(
"https://1.2.3.4:32400/playQueues/1235", status_code=HTTPStatus.NOT_FOUND
)
content_id_with_playqueue = '{"playqueue_id": 1235}' content_id_with_playqueue = '{"playqueue_id": 1235}'
with pytest.raises(HomeAssistantError) as excinfo: with pytest.raises(HomeAssistantError) as excinfo:
play_on_sonos( play_on_sonos(

View file

@ -1,6 +1,7 @@
"""Setup mocks for the Plugwise integration tests.""" """Setup mocks for the Plugwise integration tests."""
from functools import partial from functools import partial
from http import HTTPStatus
import re import re
from unittest.mock import AsyncMock, Mock, patch from unittest.mock import AsyncMock, Mock, patch
@ -38,15 +39,15 @@ def mock_smile():
@pytest.fixture(name="mock_smile_unauth") @pytest.fixture(name="mock_smile_unauth")
def mock_smile_unauth(aioclient_mock: AiohttpClientMocker) -> None: def mock_smile_unauth(aioclient_mock: AiohttpClientMocker) -> None:
"""Mock the Plugwise Smile unauthorized for Home Assistant.""" """Mock the Plugwise Smile unauthorized for Home Assistant."""
aioclient_mock.get(re.compile(".*"), status=401) aioclient_mock.get(re.compile(".*"), status=HTTPStatus.UNAUTHORIZED)
aioclient_mock.put(re.compile(".*"), status=401) aioclient_mock.put(re.compile(".*"), status=HTTPStatus.UNAUTHORIZED)
@pytest.fixture(name="mock_smile_error") @pytest.fixture(name="mock_smile_error")
def mock_smile_error(aioclient_mock: AiohttpClientMocker) -> None: def mock_smile_error(aioclient_mock: AiohttpClientMocker) -> None:
"""Mock the Plugwise Smile server failure for Home Assistant.""" """Mock the Plugwise Smile server failure for Home Assistant."""
aioclient_mock.get(re.compile(".*"), status=500) aioclient_mock.get(re.compile(".*"), status=HTTPStatus.INTERNAL_SERVER_ERROR)
aioclient_mock.put(re.compile(".*"), status=500) aioclient_mock.put(re.compile(".*"), status=HTTPStatus.INTERNAL_SERVER_ERROR)
@pytest.fixture(name="mock_smile_notconnect") @pytest.fixture(name="mock_smile_notconnect")

View file

@ -1,6 +1,7 @@
"""The tests for the Prometheus exporter.""" """The tests for the Prometheus exporter."""
from dataclasses import dataclass from dataclasses import dataclass
import datetime import datetime
from http import HTTPStatus
import unittest.mock as mock import unittest.mock as mock
import pytest import pytest
@ -106,7 +107,7 @@ async def test_view_empty_namespace(hass, hass_client):
client = await prometheus_client(hass, hass_client, "") client = await prometheus_client(hass, hass_client, "")
resp = await client.get(prometheus.API_ENDPOINT) resp = await client.get(prometheus.API_ENDPOINT)
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert resp.headers["content-type"] == CONTENT_TYPE_TEXT_PLAIN assert resp.headers["content-type"] == CONTENT_TYPE_TEXT_PLAIN
body = await resp.text() body = await resp.text()
body = body.split("\n") body = body.split("\n")
@ -234,7 +235,7 @@ async def test_view_default_namespace(hass, hass_client):
client = await prometheus_client(hass, hass_client, None) client = await prometheus_client(hass, hass_client, None)
resp = await client.get(prometheus.API_ENDPOINT) resp = await client.get(prometheus.API_ENDPOINT)
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert resp.headers["content-type"] == CONTENT_TYPE_TEXT_PLAIN assert resp.headers["content-type"] == CONTENT_TYPE_TEXT_PLAIN
body = await resp.text() body = await resp.text()
body = body.split("\n") body = body.split("\n")

View file

@ -1,5 +1,6 @@
"""The tests for generic camera component.""" """The tests for generic camera component."""
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
import io import io
from homeassistant.config import async_process_ha_core_config from homeassistant.config import async_process_ha_core_config
@ -34,7 +35,7 @@ async def test_bad_posting(hass, hass_client_no_auth):
# missing file # missing file
async with client.post("/api/webhook/camera.config_test") as resp: async with client.post("/api/webhook/camera.config_test") as resp:
assert resp.status == 200 # webhooks always return 200 assert resp.status == HTTPStatus.OK # webhooks always return OK
camera_state = hass.states.get("camera.config_test") camera_state = hass.states.get("camera.config_test")
assert camera_state.state == "idle" # no file supplied we are still idle assert camera_state.state == "idle" # no file supplied we are still idle
@ -69,7 +70,7 @@ async def test_posting_url(hass, hass_client_no_auth):
# post image # post image
resp = await client.post("/api/webhook/camera.config_test", data=files) resp = await client.post("/api/webhook/camera.config_test", data=files)
assert resp.status == 200 assert resp.status == HTTPStatus.OK
# state recording # state recording
camera_state = hass.states.get("camera.config_test") camera_state = hass.states.get("camera.config_test")

View file

@ -1,4 +1,5 @@
"""The tests for the pushbullet notification platform.""" """The tests for the pushbullet notification platform."""
from http import HTTPStatus
import json import json
from unittest.mock import patch from unittest.mock import patch
@ -62,7 +63,7 @@ async def test_pushbullet_push_default(hass, requests_mock, mock_pushbullet):
requests_mock.register_uri( requests_mock.register_uri(
"POST", "POST",
"https://api.pushbullet.com/v2/pushes", "https://api.pushbullet.com/v2/pushes",
status_code=200, status_code=HTTPStatus.OK,
json={"mock_response": "Ok"}, json={"mock_response": "Ok"},
) )
data = {"title": "Test Title", "message": "Test Message"} data = {"title": "Test Title", "message": "Test Message"}
@ -91,7 +92,7 @@ async def test_pushbullet_push_device(hass, requests_mock, mock_pushbullet):
requests_mock.register_uri( requests_mock.register_uri(
"POST", "POST",
"https://api.pushbullet.com/v2/pushes", "https://api.pushbullet.com/v2/pushes",
status_code=200, status_code=HTTPStatus.OK,
json={"mock_response": "Ok"}, json={"mock_response": "Ok"},
) )
data = { data = {
@ -129,7 +130,7 @@ async def test_pushbullet_push_devices(hass, requests_mock, mock_pushbullet):
requests_mock.register_uri( requests_mock.register_uri(
"POST", "POST",
"https://api.pushbullet.com/v2/pushes", "https://api.pushbullet.com/v2/pushes",
status_code=200, status_code=HTTPStatus.OK,
json={"mock_response": "Ok"}, json={"mock_response": "Ok"},
) )
data = { data = {
@ -175,7 +176,7 @@ async def test_pushbullet_push_email(hass, requests_mock, mock_pushbullet):
requests_mock.register_uri( requests_mock.register_uri(
"POST", "POST",
"https://api.pushbullet.com/v2/pushes", "https://api.pushbullet.com/v2/pushes",
status_code=200, status_code=HTTPStatus.OK,
json={"mock_response": "Ok"}, json={"mock_response": "Ok"},
) )
data = { data = {
@ -214,7 +215,7 @@ async def test_pushbullet_push_mixed(hass, requests_mock, mock_pushbullet):
requests_mock.register_uri( requests_mock.register_uri(
"POST", "POST",
"https://api.pushbullet.com/v2/pushes", "https://api.pushbullet.com/v2/pushes",
status_code=200, status_code=HTTPStatus.OK,
json={"mock_response": "Ok"}, json={"mock_response": "Ok"},
) )
data = { data = {
@ -260,7 +261,7 @@ async def test_pushbullet_push_no_file(hass, requests_mock, mock_pushbullet):
requests_mock.register_uri( requests_mock.register_uri(
"POST", "POST",
"https://api.pushbullet.com/v2/pushes", "https://api.pushbullet.com/v2/pushes",
status_code=200, status_code=HTTPStatus.OK,
json={"mock_response": "Ok"}, json={"mock_response": "Ok"},
) )
data = { data = {