From fb8f8133a057cf403b522a9737e5588c50291c49 Mon Sep 17 00:00:00 2001 From: springstan <46536646+springstan@users.noreply.github.com> Date: Wed, 8 Apr 2020 23:20:03 +0200 Subject: [PATCH] Use HTTP_INTERNAL_SERVER_ERROR constant (#33832) --- homeassistant/components/cloud/http_api.py | 11 +++++++---- .../components/conversation/__init__.py | 3 ++- homeassistant/components/free_mobile/notify.py | 8 ++++++-- .../components/google_assistant/http.py | 6 +++--- homeassistant/components/hue/bridge.py | 3 ++- homeassistant/components/mailbox/__init__.py | 5 +++-- .../components/media_player/__init__.py | 3 ++- homeassistant/components/nexia/__init__.py | 12 +++++++----- homeassistant/components/nexia/config_flow.py | 7 +++++-- homeassistant/components/nuheat/__init__.py | 12 ++++++++++-- homeassistant/components/nuheat/config_flow.py | 7 +++++-- homeassistant/components/rest/notify.py | 11 +++++++++-- tests/components/abode/test_config_flow.py | 6 ++++-- tests/components/buienradar/test_camera.py | 3 ++- tests/components/cloud/test_http_api.py | 15 ++++++++------- tests/components/directv/__init__.py | 6 +++--- tests/components/foobot/test_sensor.py | 3 ++- tests/components/generic/test_camera.py | 3 ++- tests/components/hassio/test_auth.py | 3 ++- tests/components/html5/test_notify.py | 7 ++++--- tests/components/mailbox/test_init.py | 3 ++- tests/components/marytts/test_tts.py | 3 ++- tests/components/melcloud/test_config_flow.py | 18 ++++++++++-------- tests/components/nuheat/test_config_flow.py | 8 ++++---- tests/components/rest/test_switch.py | 7 ++++--- tests/components/smartthings/test_init.py | 9 +++++---- tests/components/yessssms/test_notify.py | 9 +++++++-- 27 files changed, 122 insertions(+), 69 deletions(-) diff --git a/homeassistant/components/cloud/http_api.py b/homeassistant/components/cloud/http_api.py index 09dae3efc24..8a30c4d9496 100644 --- a/homeassistant/components/cloud/http_api.py +++ b/homeassistant/components/cloud/http_api.py @@ -19,7 +19,7 @@ from homeassistant.components.google_assistant import helpers as google_helpers from homeassistant.components.http import HomeAssistantView from homeassistant.components.http.data_validator import RequestDataValidator from homeassistant.components.websocket_api import const as ws_const -from homeassistant.const import HTTP_OK +from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR, HTTP_OK from homeassistant.core import callback from .const import ( @@ -64,11 +64,11 @@ SCHEMA_WS_HOOK_DELETE = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend( _CLOUD_ERRORS = { InvalidTrustedNetworks: ( - 500, + HTTP_INTERNAL_SERVER_ERROR, "Remote UI not compatible with 127.0.0.1/::1 as a trusted network.", ), InvalidTrustedProxies: ( - 500, + HTTP_INTERNAL_SERVER_ERROR, "Remote UI not compatible with 127.0.0.1/::1 as trusted proxies.", ), } @@ -115,7 +115,10 @@ async def async_setup(hass): auth.Unauthenticated: (401, "Authentication failed."), auth.PasswordChangeRequired: (400, "Password change required."), asyncio.TimeoutError: (502, "Unable to reach the Home Assistant cloud."), - aiohttp.ClientError: (500, "Error making internal request"), + aiohttp.ClientError: ( + HTTP_INTERNAL_SERVER_ERROR, + "Error making internal request", + ), } ) diff --git a/homeassistant/components/conversation/__init__.py b/homeassistant/components/conversation/__init__.py index 91031c141dd..dd17eca6792 100644 --- a/homeassistant/components/conversation/__init__.py +++ b/homeassistant/components/conversation/__init__.py @@ -7,6 +7,7 @@ import voluptuous as vol from homeassistant import core from homeassistant.components import http, websocket_api from homeassistant.components.http.data_validator import RequestDataValidator +from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR from homeassistant.helpers import config_validation as cv, intent from homeassistant.loader import bind_hass @@ -145,7 +146,7 @@ class ConversationProcessView(http.HomeAssistantView): "message": str(err), }, }, - status_code=500, + status_code=HTTP_INTERNAL_SERVER_ERROR, ) return self.json(intent_result) diff --git a/homeassistant/components/free_mobile/notify.py b/homeassistant/components/free_mobile/notify.py index 8b5273f39d1..c28b56271b9 100644 --- a/homeassistant/components/free_mobile/notify.py +++ b/homeassistant/components/free_mobile/notify.py @@ -5,7 +5,11 @@ from freesms import FreeClient import voluptuous as vol from homeassistant.components.notify import PLATFORM_SCHEMA, BaseNotificationService -from homeassistant.const import CONF_ACCESS_TOKEN, CONF_USERNAME +from homeassistant.const import ( + CONF_ACCESS_TOKEN, + CONF_USERNAME, + HTTP_INTERNAL_SERVER_ERROR, +) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -37,5 +41,5 @@ class FreeSMSNotificationService(BaseNotificationService): _LOGGER.error("Too much SMS send in a few time") elif resp.status_code == 403: _LOGGER.error("Wrong Username/Password") - elif resp.status_code == 500: + elif resp.status_code == HTTP_INTERNAL_SERVER_ERROR: _LOGGER.error("Server error, try later") diff --git a/homeassistant/components/google_assistant/http.py b/homeassistant/components/google_assistant/http.py index 4c16e230e92..7b75a36f8bb 100644 --- a/homeassistant/components/google_assistant/http.py +++ b/homeassistant/components/google_assistant/http.py @@ -10,7 +10,7 @@ import jwt # Typing imports from homeassistant.components.http import HomeAssistantView -from homeassistant.const import CLOUD_NEVER_EXPOSED_ENTITIES +from homeassistant.const import CLOUD_NEVER_EXPOSED_ENTITIES, HTTP_INTERNAL_SERVER_ERROR from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.util import dt as dt_util @@ -177,7 +177,7 @@ class GoogleConfig(AbstractConfig): return error.status except (asyncio.TimeoutError, ClientError): _LOGGER.error("Could not contact %s", url) - return 500 + return HTTP_INTERNAL_SERVER_ERROR async def async_call_homegraph_api(self, url, data): """Call a homegraph api with authentication.""" @@ -212,7 +212,7 @@ class GoogleConfig(AbstractConfig): return error.status except (asyncio.TimeoutError, ClientError): _LOGGER.error("Could not contact %s", url) - return 500 + return HTTP_INTERNAL_SERVER_ERROR async def async_report_state(self, message, agent_user_id: str): """Send a state report to Google.""" diff --git a/homeassistant/components/hue/bridge.py b/homeassistant/components/hue/bridge.py index 37089e54b00..977a6717f1b 100644 --- a/homeassistant/components/hue/bridge.py +++ b/homeassistant/components/hue/bridge.py @@ -10,6 +10,7 @@ import slugify as unicode_slug import voluptuous as vol from homeassistant import core +from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import aiohttp_client, config_validation as cv @@ -134,7 +135,7 @@ class HueBridge: # We only retry if it's a server error. So raise on all 4XX errors. if ( isinstance(err, client_exceptions.ClientResponseError) - and err.status < 500 + and err.status < HTTP_INTERNAL_SERVER_ERROR ): raise diff --git a/homeassistant/components/mailbox/__init__.py b/homeassistant/components/mailbox/__init__.py index 2275c5eba48..c3a24fe9b02 100644 --- a/homeassistant/components/mailbox/__init__.py +++ b/homeassistant/components/mailbox/__init__.py @@ -9,6 +9,7 @@ from aiohttp.web_exceptions import HTTPNotFound import async_timeout from homeassistant.components.http import HomeAssistantView +from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR from homeassistant.core import callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import config_per_platform, discovery @@ -255,8 +256,8 @@ class MailboxMediaView(MailboxView): except StreamError as err: error_msg = "Error getting media: %s" % (err) _LOGGER.error(error_msg) - return web.Response(status=500) + return web.Response(status=HTTP_INTERNAL_SERVER_ERROR) if stream: return web.Response(body=stream, content_type=mailbox.media_type) - return web.Response(status=500) + return web.Response(status=HTTP_INTERNAL_SERVER_ERROR) diff --git a/homeassistant/components/media_player/__init__.py b/homeassistant/components/media_player/__init__.py index 86b5d758149..81f0fa010b0 100644 --- a/homeassistant/components/media_player/__init__.py +++ b/homeassistant/components/media_player/__init__.py @@ -18,6 +18,7 @@ import voluptuous as vol from homeassistant.components import websocket_api from homeassistant.components.http import KEY_AUTHENTICATED, HomeAssistantView from homeassistant.const import ( + HTTP_INTERNAL_SERVER_ERROR, HTTP_OK, SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PAUSE, @@ -878,7 +879,7 @@ class MediaPlayerImageView(HomeAssistantView): data, content_type = await player.async_get_media_image() if data is None: - return web.Response(status=500) + return web.Response(status=HTTP_INTERNAL_SERVER_ERROR) headers = {CACHE_CONTROL: "max-age=3600"} return web.Response(body=data, content_type=content_type, headers=headers) diff --git a/homeassistant/components/nexia/__init__.py b/homeassistant/components/nexia/__init__.py index 5c317794c2a..fd0b708576d 100644 --- a/homeassistant/components/nexia/__init__.py +++ b/homeassistant/components/nexia/__init__.py @@ -9,7 +9,7 @@ from requests.exceptions import ConnectTimeout, HTTPError import voluptuous as vol from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry -from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_INTERNAL_SERVER_ERROR from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady import homeassistant.helpers.config_validation as cv @@ -28,7 +28,7 @@ CONFIG_SCHEMA = vol.Schema( vol.Required(CONF_PASSWORD): cv.string, }, extra=vol.ALLOW_EXTRA, - ), + ) }, extra=vol.ALLOW_EXTRA, ) @@ -73,10 +73,12 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): _LOGGER.error("Unable to connect to Nexia service: %s", ex) raise ConfigEntryNotReady except HTTPError as http_ex: - if http_ex.response.status_code >= 400 and http_ex.response.status_code < 500: + if ( + http_ex.response.status_code >= 400 + and http_ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR + ): _LOGGER.error( - "Access error from Nexia service, please check credentials: %s", - http_ex, + "Access error from Nexia service, please check credentials: %s", http_ex ) return False _LOGGER.error("HTTP error from Nexia service: %s", http_ex) diff --git a/homeassistant/components/nexia/config_flow.py b/homeassistant/components/nexia/config_flow.py index 5844cb8da20..01d4dc406cf 100644 --- a/homeassistant/components/nexia/config_flow.py +++ b/homeassistant/components/nexia/config_flow.py @@ -6,7 +6,7 @@ from requests.exceptions import ConnectTimeout, HTTPError import voluptuous as vol from homeassistant import config_entries, core, exceptions -from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_INTERNAL_SERVER_ERROR from .const import DOMAIN # pylint:disable=unused-import @@ -34,7 +34,10 @@ async def validate_input(hass: core.HomeAssistant, data): raise CannotConnect except HTTPError as http_ex: _LOGGER.error("HTTP error from Nexia service: %s", http_ex) - if http_ex.response.status_code >= 400 and http_ex.response.status_code < 500: + if ( + http_ex.response.status_code >= 400 + and http_ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR + ): raise InvalidAuth raise CannotConnect diff --git a/homeassistant/components/nuheat/__init__.py b/homeassistant/components/nuheat/__init__.py index ca47f831370..6b49a3b975b 100644 --- a/homeassistant/components/nuheat/__init__.py +++ b/homeassistant/components/nuheat/__init__.py @@ -7,7 +7,12 @@ import requests import voluptuous as vol from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry -from homeassistant.const import CONF_DEVICES, CONF_PASSWORD, CONF_USERNAME +from homeassistant.const import ( + CONF_DEVICES, + CONF_PASSWORD, + CONF_USERNAME, + HTTP_INTERNAL_SERVER_ERROR, +) from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import config_validation as cv @@ -78,7 +83,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): except requests.exceptions.Timeout: raise ConfigEntryNotReady except requests.exceptions.HTTPError as ex: - if ex.response.status_code > 400 and ex.response.status_code < 500: + if ( + ex.response.status_code > 400 + and ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR + ): _LOGGER.error("Failed to login to nuheat: %s", ex) return False raise ConfigEntryNotReady diff --git a/homeassistant/components/nuheat/config_flow.py b/homeassistant/components/nuheat/config_flow.py index 4f12f590057..cf2f3398309 100644 --- a/homeassistant/components/nuheat/config_flow.py +++ b/homeassistant/components/nuheat/config_flow.py @@ -6,7 +6,7 @@ import requests.exceptions import voluptuous as vol from homeassistant import config_entries, core, exceptions -from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_INTERNAL_SERVER_ERROR from .const import CONF_SERIAL_NUMBER from .const import DOMAIN # pylint:disable=unused-import @@ -34,7 +34,10 @@ async def validate_input(hass: core.HomeAssistant, data): except requests.exceptions.Timeout: raise CannotConnect except requests.exceptions.HTTPError as ex: - if ex.response.status_code > 400 and ex.response.status_code < 500: + if ( + ex.response.status_code > 400 + and ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR + ): raise InvalidAuth raise CannotConnect # diff --git a/homeassistant/components/rest/notify.py b/homeassistant/components/rest/notify.py index b9739841130..60b000eae1e 100644 --- a/homeassistant/components/rest/notify.py +++ b/homeassistant/components/rest/notify.py @@ -23,6 +23,7 @@ from homeassistant.const import ( CONF_VERIFY_SSL, HTTP_BASIC_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION, + HTTP_INTERNAL_SERVER_ERROR, HTTP_OK, ) import homeassistant.helpers.config_validation as cv @@ -188,11 +189,17 @@ class RestNotificationService(BaseNotificationService): verify=self._verify_ssl, ) - if response.status_code >= 500 and response.status_code < 600: + if ( + response.status_code >= HTTP_INTERNAL_SERVER_ERROR + and response.status_code < 600 + ): _LOGGER.exception( "Server error. Response %d: %s:", response.status_code, response.reason ) - elif response.status_code >= 400 and response.status_code < 500: + elif ( + response.status_code >= 400 + and response.status_code < HTTP_INTERNAL_SERVER_ERROR + ): _LOGGER.exception( "Client error. Response %d: %s:", response.status_code, response.reason ) diff --git a/tests/components/abode/test_config_flow.py b/tests/components/abode/test_config_flow.py index 5e32c923245..d9762296e70 100644 --- a/tests/components/abode/test_config_flow.py +++ b/tests/components/abode/test_config_flow.py @@ -5,7 +5,7 @@ from abodepy.exceptions import AbodeAuthenticationException from homeassistant import data_entry_flow from homeassistant.components.abode import config_flow -from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_INTERNAL_SERVER_ERROR from tests.common import MockConfigEntry @@ -74,7 +74,9 @@ async def test_connection_error(hass): with patch( "homeassistant.components.abode.config_flow.Abode", - side_effect=AbodeAuthenticationException((500, "connection error")), + side_effect=AbodeAuthenticationException( + (HTTP_INTERNAL_SERVER_ERROR, "connection error") + ), ): result = await flow.async_step_user(user_input=conf) assert result["errors"] == {"base": "connection_error"} diff --git a/tests/components/buienradar/test_camera.py b/tests/components/buienradar/test_camera.py index 0a3c67d97d3..96c5d2ec67c 100644 --- a/tests/components/buienradar/test_camera.py +++ b/tests/components/buienradar/test_camera.py @@ -3,6 +3,7 @@ import asyncio from aiohttp.client_exceptions import ClientResponseError +from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR from homeassistant.setup import async_setup_component from homeassistant.util import dt as dt_util @@ -202,7 +203,7 @@ async def test_retries_after_error(aioclient_mock, hass, hass_client): client = await hass_client() - aioclient_mock.get(radar_map_url(), text=None, status=500) + aioclient_mock.get(radar_map_url(), text=None, status=HTTP_INTERNAL_SERVER_ERROR) # A 404 should not return data and throw: try: diff --git a/tests/components/cloud/test_http_api.py b/tests/components/cloud/test_http_api.py index 8bfa6185e9b..8cb4a0b9636 100644 --- a/tests/components/cloud/test_http_api.py +++ b/tests/components/cloud/test_http_api.py @@ -15,6 +15,7 @@ from homeassistant.components.alexa import errors as alexa_errors from homeassistant.components.alexa.entities import LightCapabilities from homeassistant.components.cloud.const import DOMAIN, RequireRelink from homeassistant.components.google_assistant.helpers import GoogleEntity +from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR from homeassistant.core import State from . import mock_cloud, mock_cloud_prefs @@ -99,10 +100,10 @@ async def test_google_actions_sync_fails(mock_cognito, mock_cloud_login, cloud_c """Test syncing Google Actions gone bad.""" with patch( "hass_nabucasa.cloud_api.async_google_actions_request_sync", - return_value=mock_coro(Mock(status=500)), + return_value=mock_coro(Mock(status=HTTP_INTERNAL_SERVER_ERROR)), ) as mock_request_sync: req = await cloud_client.post("/api/cloud/google_actions/sync") - assert req.status == 500 + assert req.status == HTTP_INTERNAL_SERVER_ERROR assert len(mock_request_sync.mock_calls) == 1 @@ -436,7 +437,7 @@ async def test_websocket_subscription_fail( hass, hass_ws_client, aioclient_mock, mock_auth, mock_cloud_login ): """Test querying the status.""" - aioclient_mock.get(SUBSCRIPTION_INFO_URL, status=500) + aioclient_mock.get(SUBSCRIPTION_INFO_URL, status=HTTP_INTERNAL_SERVER_ERROR) client = await hass_ws_client(hass) await client.send_json({"id": 5, "type": "cloud/subscription"}) response = await client.receive_json() @@ -611,7 +612,7 @@ async def test_enabling_remote_trusted_networks_local4( response = await client.receive_json() assert not response["success"] - assert response["error"]["code"] == 500 + assert response["error"]["code"] == HTTP_INTERNAL_SERVER_ERROR assert ( response["error"]["message"] == "Remote UI not compatible with 127.0.0.1/::1 as a trusted network." @@ -643,7 +644,7 @@ async def test_enabling_remote_trusted_networks_local6( response = await client.receive_json() assert not response["success"] - assert response["error"]["code"] == 500 + assert response["error"]["code"] == HTTP_INTERNAL_SERVER_ERROR assert ( response["error"]["message"] == "Remote UI not compatible with 127.0.0.1/::1 as a trusted network." @@ -744,7 +745,7 @@ async def test_enabling_remote_trusted_proxies_local4( response = await client.receive_json() assert not response["success"] - assert response["error"]["code"] == 500 + assert response["error"]["code"] == HTTP_INTERNAL_SERVER_ERROR assert ( response["error"]["message"] == "Remote UI not compatible with 127.0.0.1/::1 as trusted proxies." @@ -768,7 +769,7 @@ async def test_enabling_remote_trusted_proxies_local6( response = await client.receive_json() assert not response["success"] - assert response["error"]["code"] == 500 + assert response["error"]["code"] == HTTP_INTERNAL_SERVER_ERROR assert ( response["error"]["message"] == "Remote UI not compatible with 127.0.0.1/::1 as trusted proxies." diff --git a/tests/components/directv/__init__.py b/tests/components/directv/__init__.py index cd0f72307d8..d34ab0266af 100644 --- a/tests/components/directv/__init__.py +++ b/tests/components/directv/__init__.py @@ -1,7 +1,7 @@ """Tests for the DirecTV component.""" from homeassistant.components.directv.const import CONF_RECEIVER_ID, DOMAIN from homeassistant.components.ssdp import ATTR_SSDP_LOCATION -from homeassistant.const import CONF_HOST +from homeassistant.const import CONF_HOST, HTTP_INTERNAL_SERVER_ERROR from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry, load_fixture @@ -34,7 +34,7 @@ def mock_connection(aioclient_mock: AiohttpClientMocker) -> None: aioclient_mock.get( f"http://{HOST}:8080/info/mode", params={"clientAddr": "9XXXXXXXXXX9"}, - status=500, + status=HTTP_INTERNAL_SERVER_ERROR, text=load_fixture("directv/info-mode-error.json"), headers={"Content-Type": "application/json"}, ) @@ -80,7 +80,7 @@ async def setup_integration( """Set up the DirecTV integration in Home Assistant.""" if setup_error: aioclient_mock.get( - f"http://{HOST}:8080/info/getVersion", status=500, + f"http://{HOST}:8080/info/getVersion", status=HTTP_INTERNAL_SERVER_ERROR ) else: mock_connection(aioclient_mock) diff --git a/tests/components/foobot/test_sensor.py b/tests/components/foobot/test_sensor.py index f8cf38395f2..10cc3eb47b6 100644 --- a/tests/components/foobot/test_sensor.py +++ b/tests/components/foobot/test_sensor.py @@ -12,6 +12,7 @@ from homeassistant.const import ( CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONCENTRATION_PARTS_PER_BILLION, CONCENTRATION_PARTS_PER_MILLION, + HTTP_INTERNAL_SERVER_ERROR, TEMP_CELSIUS, UNIT_PERCENTAGE, ) @@ -83,7 +84,7 @@ async def test_setup_temporary_error(hass, aioclient_mock): """Expected failures caused by temporary errors in API response.""" fake_async_add_entities = MagicMock() - errors = [429, 500] + errors = [429, HTTP_INTERNAL_SERVER_ERROR] for error in errors: aioclient_mock.get(re.compile("api.foobot.io/v2/owner/.*"), status=error) with pytest.raises(PlatformNotReady): diff --git a/tests/components/generic/test_camera.py b/tests/components/generic/test_camera.py index 7f49d1b8979..9b0466dda93 100644 --- a/tests/components/generic/test_camera.py +++ b/tests/components/generic/test_camera.py @@ -2,6 +2,7 @@ import asyncio from unittest import mock +from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR from homeassistant.setup import async_setup_component @@ -117,7 +118,7 @@ async def test_limit_refetch(aioclient_mock, hass, hass_client): with mock.patch("async_timeout.timeout", side_effect=asyncio.TimeoutError()): resp = await client.get("/api/camera_proxy/camera.config_test") assert aioclient_mock.call_count == 0 - assert resp.status == 500 + assert resp.status == HTTP_INTERNAL_SERVER_ERROR hass.states.async_set("sensor.temp", "10") diff --git a/tests/components/hassio/test_auth.py b/tests/components/hassio/test_auth.py index 189273c5802..621efa1cb9e 100644 --- a/tests/components/hassio/test_auth.py +++ b/tests/components/hassio/test_auth.py @@ -1,6 +1,7 @@ """The tests for the hassio component.""" from unittest.mock import Mock, patch +from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR from homeassistant.exceptions import HomeAssistantError from tests.common import mock_coro @@ -186,5 +187,5 @@ async def test_password_no_user(hass, hassio_client_supervisor): ) # Check we got right response - assert resp.status == 500 + assert resp.status == HTTP_INTERNAL_SERVER_ERROR assert not mock_save.called diff --git a/tests/components/html5/test_notify.py b/tests/components/html5/test_notify.py index a9fd998f003..4a62eb76c27 100644 --- a/tests/components/html5/test_notify.py +++ b/tests/components/html5/test_notify.py @@ -5,6 +5,7 @@ from unittest.mock import MagicMock, mock_open, patch from aiohttp.hdrs import AUTHORIZATION import homeassistant.components.html5.notify as html5 +from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR from homeassistant.exceptions import HomeAssistantError from homeassistant.setup import async_setup_component @@ -335,7 +336,7 @@ async def test_registering_new_device_fails_view(hass, hass_client): ): resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4)) - assert resp.status == 500 + assert resp.status == HTTP_INTERNAL_SERVER_ERROR assert registrations == {} @@ -380,7 +381,7 @@ async def test_registering_existing_device_fails_view(hass, hass_client): mock_save.side_effect = HomeAssistantError resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4)) - assert resp.status == 500 + assert resp.status == HTTP_INTERNAL_SERVER_ERROR assert registrations == {"unnamed device": SUBSCRIPTION_1} @@ -451,7 +452,7 @@ async def test_unregistering_device_view_handles_save_error(hass, hass_client): data=json.dumps({"subscription": SUBSCRIPTION_1["subscription"]}), ) - assert resp.status == 500, resp.response + assert resp.status == HTTP_INTERNAL_SERVER_ERROR, resp.response assert registrations == { "some device": SUBSCRIPTION_1, "other device": SUBSCRIPTION_2, diff --git a/tests/components/mailbox/test_init.py b/tests/components/mailbox/test_init.py index ea52f98f70e..f35c763bf74 100644 --- a/tests/components/mailbox/test_init.py +++ b/tests/components/mailbox/test_init.py @@ -5,6 +5,7 @@ import pytest from homeassistant.bootstrap import async_setup_component import homeassistant.components.mailbox as mailbox +from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR @pytest.fixture @@ -90,7 +91,7 @@ async def test_get_media_from_invalid_msgid(mock_http_client): url = "/api/mailbox/media/DemoMailbox/%s" % (msgsha) req = await mock_http_client.get(url) - assert req.status == 500 + assert req.status == HTTP_INTERNAL_SERVER_ERROR async def test_delete_from_invalid_mailbox(mock_http_client): diff --git a/tests/components/marytts/test_tts.py b/tests/components/marytts/test_tts.py index d8a96b2db52..70a29fe11e1 100644 --- a/tests/components/marytts/test_tts.py +++ b/tests/components/marytts/test_tts.py @@ -11,6 +11,7 @@ from homeassistant.components.media_player.const import ( SERVICE_PLAY_MEDIA, ) import homeassistant.components.tts as tts +from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR from homeassistant.setup import setup_component from tests.common import assert_setup_component, get_test_home_assistant, mock_service @@ -122,7 +123,7 @@ class TestTTSMaryTTSPlatform: conn = Mock() response = Mock() conn.getresponse.return_value = response - response.status = 500 + response.status = HTTP_INTERNAL_SERVER_ERROR response.reason = "test" response.readline.return_value = "content" diff --git a/tests/components/melcloud/test_config_flow.py b/tests/components/melcloud/test_config_flow.py index 90c766f0831..4cd64afa053 100644 --- a/tests/components/melcloud/test_config_flow.py +++ b/tests/components/melcloud/test_config_flow.py @@ -8,6 +8,7 @@ import pytest from homeassistant import config_entries from homeassistant.components.melcloud.const import DOMAIN +from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR from tests.common import MockConfigEntry @@ -50,7 +51,7 @@ async def test_form(hass, mock_login, mock_get_devices): with patch( "homeassistant.components.melcloud.async_setup", return_value=True ) as mock_setup, patch( - "homeassistant.components.melcloud.async_setup_entry", return_value=True, + "homeassistant.components.melcloud.async_setup_entry", return_value=True ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], @@ -89,7 +90,11 @@ async def test_form_errors(hass, mock_login, mock_get_devices, error, reason): @pytest.mark.parametrize( "error,message", - [(401, "invalid_auth"), (403, "invalid_auth"), (500, "cannot_connect")], + [ + (401, "invalid_auth"), + (403, "invalid_auth"), + (HTTP_INTERNAL_SERVER_ERROR, "cannot_connect"), + ], ) async def test_form_response_errors( hass, mock_login, mock_get_devices, mock_request_info, error, message @@ -112,7 +117,7 @@ async def test_import_with_token(hass, mock_login, mock_get_devices): with patch( "homeassistant.components.melcloud.async_setup", return_value=True ) as mock_setup, patch( - "homeassistant.components.melcloud.async_setup_entry", return_value=True, + "homeassistant.components.melcloud.async_setup_entry", return_value=True ) as mock_setup_entry: result = await hass.config_entries.flow.async_init( DOMAIN, @@ -135,10 +140,7 @@ async def test_token_refresh(hass, mock_login, mock_get_devices): """Re-configuration with existing username should refresh token.""" mock_entry = MockConfigEntry( domain=DOMAIN, - data={ - "username": "test-email@test-domain.com", - "token": "test-original-token", - }, + data={"username": "test-email@test-domain.com", "token": "test-original-token"}, unique_id="test-email@test-domain.com", ) mock_entry.add_to_hass(hass) @@ -146,7 +148,7 @@ async def test_token_refresh(hass, mock_login, mock_get_devices): with patch( "homeassistant.components.melcloud.async_setup", return_value=True ) as mock_setup, patch( - "homeassistant.components.melcloud.async_setup_entry", return_value=True, + "homeassistant.components.melcloud.async_setup_entry", return_value=True ) as mock_setup_entry: result = await hass.config_entries.flow.async_init( DOMAIN, diff --git a/tests/components/nuheat/test_config_flow.py b/tests/components/nuheat/test_config_flow.py index d6e10e1dc7c..338509f09d1 100644 --- a/tests/components/nuheat/test_config_flow.py +++ b/tests/components/nuheat/test_config_flow.py @@ -4,7 +4,7 @@ import requests from homeassistant import config_entries, setup from homeassistant.components.nuheat.const import CONF_SERIAL_NUMBER, DOMAIN -from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_INTERNAL_SERVER_ERROR from .mocks import _get_mock_thermostat_run @@ -29,7 +29,7 @@ async def test_form_user(hass): ), patch( "homeassistant.components.nuheat.async_setup", return_value=True ) as mock_setup, patch( - "homeassistant.components.nuheat.async_setup_entry", return_value=True, + "homeassistant.components.nuheat.async_setup_entry", return_value=True ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], @@ -67,7 +67,7 @@ async def test_form_import(hass): ), patch( "homeassistant.components.nuheat.async_setup", return_value=True ) as mock_setup, patch( - "homeassistant.components.nuheat.async_setup_entry", return_value=True, + "homeassistant.components.nuheat.async_setup_entry", return_value=True ) as mock_setup_entry: result = await hass.config_entries.flow.async_init( DOMAIN, @@ -139,7 +139,7 @@ async def test_form_invalid_thermostat(hass): ) response_mock = MagicMock() - type(response_mock).status_code = 500 + type(response_mock).status_code = HTTP_INTERNAL_SERVER_ERROR with patch( "homeassistant.components.nuheat.config_flow.nuheat.NuHeat.authenticate", diff --git a/tests/components/rest/test_switch.py b/tests/components/rest/test_switch.py index d1e4ac05514..bba6ac3dc89 100644 --- a/tests/components/rest/test_switch.py +++ b/tests/components/rest/test_switch.py @@ -4,6 +4,7 @@ import asyncio import aiohttp import homeassistant.components.rest.switch as rest +from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR from homeassistant.helpers.template import Template from homeassistant.setup import setup_component @@ -140,7 +141,7 @@ class TestRestSwitch: def test_turn_on_status_not_ok(self, aioclient_mock): """Test turn_on when error status returned.""" - aioclient_mock.post(self.resource, status=500) + aioclient_mock.post(self.resource, status=HTTP_INTERNAL_SERVER_ERROR) asyncio.run_coroutine_threadsafe( self.switch.async_turn_on(), self.hass.loop ).result() @@ -150,7 +151,7 @@ class TestRestSwitch: def test_turn_on_timeout(self, aioclient_mock): """Test turn_on when timeout occurs.""" - aioclient_mock.post(self.resource, status=500) + aioclient_mock.post(self.resource, status=HTTP_INTERNAL_SERVER_ERROR) asyncio.run_coroutine_threadsafe( self.switch.async_turn_on(), self.hass.loop ).result() @@ -169,7 +170,7 @@ class TestRestSwitch: def test_turn_off_status_not_ok(self, aioclient_mock): """Test turn_off when error status returned.""" - aioclient_mock.post(self.resource, status=500) + aioclient_mock.post(self.resource, status=HTTP_INTERNAL_SERVER_ERROR) asyncio.run_coroutine_threadsafe( self.switch.async_turn_off(), self.hass.loop ).result() diff --git a/tests/components/smartthings/test_init.py b/tests/components/smartthings/test_init.py index 05ea832a81e..4093f3753f1 100644 --- a/tests/components/smartthings/test_init.py +++ b/tests/components/smartthings/test_init.py @@ -17,6 +17,7 @@ from homeassistant.components.smartthings.const import ( SIGNAL_SMARTTHINGS_UPDATE, SUPPORTED_PLATFORMS, ) +from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.setup import async_setup_component @@ -80,7 +81,7 @@ async def test_recoverable_api_errors_raise_not_ready( config_entry.add_to_hass(hass) request_info = Mock(real_url="http://example.com") smartthings_mock.app.side_effect = ClientResponseError( - request_info=request_info, history=None, status=500 + request_info=request_info, history=None, status=HTTP_INTERNAL_SERVER_ERROR ) with pytest.raises(ConfigEntryNotReady): @@ -96,7 +97,7 @@ async def test_scenes_api_errors_raise_not_ready( smartthings_mock.app.return_value = app smartthings_mock.installed_app.return_value = installed_app smartthings_mock.scenes.side_effect = ClientResponseError( - request_info=request_info, history=None, status=500 + request_info=request_info, history=None, status=HTTP_INTERNAL_SERVER_ERROR ) with pytest.raises(ConfigEntryNotReady): await smartthings.async_setup_entry(hass, config_entry) @@ -325,7 +326,7 @@ async def test_remove_entry_installedapp_api_error( request_info = Mock(real_url="http://example.com") # Arrange smartthings_mock.delete_installed_app.side_effect = ClientResponseError( - request_info=request_info, history=None, status=500 + request_info=request_info, history=None, status=HTTP_INTERNAL_SERVER_ERROR ) # Act with pytest.raises(ClientResponseError): @@ -354,7 +355,7 @@ async def test_remove_entry_app_api_error(hass, config_entry, smartthings_mock): # Arrange request_info = Mock(real_url="http://example.com") smartthings_mock.delete_app.side_effect = ClientResponseError( - request_info=request_info, history=None, status=500 + request_info=request_info, history=None, status=HTTP_INTERNAL_SERVER_ERROR ) # Act with pytest.raises(ClientResponseError): diff --git a/tests/components/yessssms/test_notify.py b/tests/components/yessssms/test_notify.py index 94f9c846d64..992185bf102 100644 --- a/tests/components/yessssms/test_notify.py +++ b/tests/components/yessssms/test_notify.py @@ -8,7 +8,12 @@ import requests_mock from homeassistant.components.yessssms.const import CONF_PROVIDER import homeassistant.components.yessssms.notify as yessssms -from homeassistant.const import CONF_PASSWORD, CONF_RECIPIENT, CONF_USERNAME +from homeassistant.const import ( + CONF_PASSWORD, + CONF_RECIPIENT, + CONF_USERNAME, + HTTP_INTERNAL_SERVER_ERROR, +) from homeassistant.setup import async_setup_component @@ -318,7 +323,7 @@ class TestNotifyYesssSMS(unittest.TestCase): "POST", # pylint: disable=protected-access self.yessssms.yesss._websms_url, - status_code=500, + status_code=HTTP_INTERNAL_SERVER_ERROR, ) message = "Testing YesssSMS platform :)"