Use HTTPStatus instead of HTTP_* constants in various test mocks (#56543)

This commit is contained in:
Ville Skyttä 2021-10-02 01:52:45 +03:00 committed by GitHub
parent e5b0bbcca6
commit 2730a27fd0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 59 additions and 59 deletions

View file

@ -2,15 +2,12 @@
import asyncio import asyncio
from contextlib import suppress from contextlib import suppress
import copy import copy
from http import HTTPStatus
from aiohttp.client_exceptions import ClientResponseError from aiohttp.client_exceptions import ClientResponseError
from homeassistant.components.buienradar.const import CONF_COUNTRY, CONF_DELTA, DOMAIN from homeassistant.components.buienradar.const import CONF_COUNTRY, CONF_DELTA, DOMAIN
from homeassistant.const import ( from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE
CONF_LATITUDE,
CONF_LONGITUDE,
HTTP_INTERNAL_SERVER_ERROR,
)
from homeassistant.helpers.entity_registry import async_get from homeassistant.helpers.entity_registry import async_get
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
@ -216,7 +213,9 @@ async def test_retries_after_error(aioclient_mock, hass, hass_client):
client = await hass_client() client = await hass_client()
aioclient_mock.get(radar_map_url(), text=None, status=HTTP_INTERNAL_SERVER_ERROR) aioclient_mock.get(
radar_map_url(), text=None, status=HTTPStatus.INTERNAL_SERVER_ERROR
)
# A 404 should not return data and throw: # A 404 should not return data and throw:
with suppress(ClientResponseError): with suppress(ClientResponseError):

View file

@ -1,5 +1,6 @@
"""Tests for the HTTP API for the cloud component.""" """Tests for the HTTP API for the cloud component."""
import asyncio import asyncio
from http import HTTPStatus
from ipaddress import ip_network from ipaddress import ip_network
from unittest.mock import AsyncMock, MagicMock, Mock, patch from unittest.mock import AsyncMock, MagicMock, Mock, patch
@ -412,7 +413,7 @@ async def test_websocket_subscription_fail(
hass, hass_ws_client, aioclient_mock, mock_auth, mock_cloud_login hass, hass_ws_client, aioclient_mock, mock_auth, mock_cloud_login
): ):
"""Test querying the status.""" """Test querying the status."""
aioclient_mock.get(SUBSCRIPTION_INFO_URL, status=HTTP_INTERNAL_SERVER_ERROR) aioclient_mock.get(SUBSCRIPTION_INFO_URL, status=HTTPStatus.INTERNAL_SERVER_ERROR)
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
await client.send_json({"id": 5, "type": "cloud/subscription"}) await client.send_json({"id": 5, "type": "cloud/subscription"})
response = await client.receive_json() response = await client.receive_json()

View file

@ -1,12 +1,9 @@
"""Tests for the DirecTV component.""" """Tests for the DirecTV component."""
from http import HTTPStatus
from homeassistant.components.directv.const import CONF_RECEIVER_ID, DOMAIN from homeassistant.components.directv.const import CONF_RECEIVER_ID, DOMAIN
from homeassistant.components.ssdp import ATTR_SSDP_LOCATION from homeassistant.components.ssdp import ATTR_SSDP_LOCATION
from homeassistant.const import ( from homeassistant.const import CONF_HOST, CONTENT_TYPE_JSON
CONF_HOST,
CONTENT_TYPE_JSON,
HTTP_FORBIDDEN,
HTTP_INTERNAL_SERVER_ERROR,
)
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry, load_fixture from tests.common import MockConfigEntry, load_fixture
@ -46,7 +43,7 @@ def mock_connection(aioclient_mock: AiohttpClientMocker) -> None:
aioclient_mock.get( aioclient_mock.get(
f"http://{HOST}:8080/info/mode", f"http://{HOST}:8080/info/mode",
params={"clientAddr": "9XXXXXXXXXX9"}, params={"clientAddr": "9XXXXXXXXXX9"},
status=HTTP_INTERNAL_SERVER_ERROR, status=HTTPStatus.INTERNAL_SERVER_ERROR,
text=load_fixture("directv/info-mode-error.json"), text=load_fixture("directv/info-mode-error.json"),
headers={"Content-Type": CONTENT_TYPE_JSON}, headers={"Content-Type": CONTENT_TYPE_JSON},
) )
@ -86,7 +83,7 @@ def mock_connection(aioclient_mock: AiohttpClientMocker) -> None:
aioclient_mock.get( aioclient_mock.get(
f"http://{HOST}:8080/tv/getTuned", f"http://{HOST}:8080/tv/getTuned",
params={"clientAddr": "C01234567890"}, params={"clientAddr": "C01234567890"},
status=HTTP_FORBIDDEN, status=HTTPStatus.FORBIDDEN,
text=load_fixture("directv/tv-get-tuned-restricted.json"), text=load_fixture("directv/tv-get-tuned-restricted.json"),
headers={"Content-Type": CONTENT_TYPE_JSON}, headers={"Content-Type": CONTENT_TYPE_JSON},
) )
@ -107,7 +104,8 @@ async def setup_integration(
"""Set up the DirecTV integration in Home Assistant.""" """Set up the DirecTV integration in Home Assistant."""
if setup_error: if setup_error:
aioclient_mock.get( aioclient_mock.get(
f"http://{HOST}:8080/info/getVersion", status=HTTP_INTERNAL_SERVER_ERROR f"http://{HOST}:8080/info/getVersion",
status=HTTPStatus.INTERNAL_SERVER_ERROR,
) )
else: else:
mock_connection(aioclient_mock) mock_connection(aioclient_mock)

View file

@ -1,5 +1,6 @@
"""The tests for the REST switch platform.""" """The tests for the REST switch platform."""
import asyncio import asyncio
from http import HTTPStatus
import aiohttp import aiohttp
@ -13,9 +14,6 @@ from homeassistant.const import (
CONF_PLATFORM, CONF_PLATFORM,
CONF_RESOURCE, CONF_RESOURCE,
CONTENT_TYPE_JSON, CONTENT_TYPE_JSON,
HTTP_INTERNAL_SERVER_ERROR,
HTTP_NOT_FOUND,
HTTP_OK,
) )
from homeassistant.helpers.template import Template from homeassistant.helpers.template import Template
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -69,7 +67,7 @@ async def test_setup_timeout(hass, aioclient_mock):
async def test_setup_minimum(hass, aioclient_mock): async def test_setup_minimum(hass, aioclient_mock):
"""Test setup with minimum configuration.""" """Test setup with minimum configuration."""
aioclient_mock.get("http://localhost", status=HTTP_OK) aioclient_mock.get("http://localhost", status=HTTPStatus.OK)
with assert_setup_component(1, SWITCH_DOMAIN): with assert_setup_component(1, SWITCH_DOMAIN):
assert await async_setup_component( assert await async_setup_component(
hass, hass,
@ -87,7 +85,7 @@ async def test_setup_minimum(hass, aioclient_mock):
async def test_setup_query_params(hass, aioclient_mock): async def test_setup_query_params(hass, aioclient_mock):
"""Test setup with query params.""" """Test setup with query params."""
aioclient_mock.get("http://localhost/?search=something", status=HTTP_OK) aioclient_mock.get("http://localhost/?search=something", status=HTTPStatus.OK)
with assert_setup_component(1, SWITCH_DOMAIN): with assert_setup_component(1, SWITCH_DOMAIN):
assert await async_setup_component( assert await async_setup_component(
hass, hass,
@ -108,7 +106,7 @@ async def test_setup_query_params(hass, aioclient_mock):
async def test_setup(hass, aioclient_mock): async def test_setup(hass, aioclient_mock):
"""Test setup with valid configuration.""" """Test setup with valid configuration."""
aioclient_mock.get("http://localhost", status=HTTP_OK) aioclient_mock.get("http://localhost", status=HTTPStatus.OK)
assert await async_setup_component( assert await async_setup_component(
hass, hass,
SWITCH_DOMAIN, SWITCH_DOMAIN,
@ -130,8 +128,8 @@ async def test_setup(hass, aioclient_mock):
async def test_setup_with_state_resource(hass, aioclient_mock): async def test_setup_with_state_resource(hass, aioclient_mock):
"""Test setup with valid configuration.""" """Test setup with valid configuration."""
aioclient_mock.get("http://localhost", status=HTTP_NOT_FOUND) aioclient_mock.get("http://localhost", status=HTTPStatus.NOT_FOUND)
aioclient_mock.get("http://localhost/state", status=HTTP_OK) aioclient_mock.get("http://localhost/state", status=HTTPStatus.OK)
assert await async_setup_component( assert await async_setup_component(
hass, hass,
SWITCH_DOMAIN, SWITCH_DOMAIN,
@ -190,7 +188,7 @@ def test_is_on_before_update(hass):
async def test_turn_on_success(hass, aioclient_mock): async def test_turn_on_success(hass, aioclient_mock):
"""Test turn_on.""" """Test turn_on."""
aioclient_mock.post(RESOURCE, status=HTTP_OK) aioclient_mock.post(RESOURCE, status=HTTPStatus.OK)
switch, body_on, body_off = _setup_test_switch(hass) switch, body_on, body_off = _setup_test_switch(hass)
await switch.async_turn_on() await switch.async_turn_on()
@ -200,7 +198,7 @@ async def test_turn_on_success(hass, aioclient_mock):
async def test_turn_on_status_not_ok(hass, aioclient_mock): async def test_turn_on_status_not_ok(hass, aioclient_mock):
"""Test turn_on when error status returned.""" """Test turn_on when error status returned."""
aioclient_mock.post(RESOURCE, status=HTTP_INTERNAL_SERVER_ERROR) aioclient_mock.post(RESOURCE, status=HTTPStatus.INTERNAL_SERVER_ERROR)
switch, body_on, body_off = _setup_test_switch(hass) switch, body_on, body_off = _setup_test_switch(hass)
await switch.async_turn_on() await switch.async_turn_on()
@ -210,7 +208,7 @@ async def test_turn_on_status_not_ok(hass, aioclient_mock):
async def test_turn_on_timeout(hass, aioclient_mock): async def test_turn_on_timeout(hass, aioclient_mock):
"""Test turn_on when timeout occurs.""" """Test turn_on when timeout occurs."""
aioclient_mock.post(RESOURCE, status=HTTP_INTERNAL_SERVER_ERROR) aioclient_mock.post(RESOURCE, status=HTTPStatus.INTERNAL_SERVER_ERROR)
switch, body_on, body_off = _setup_test_switch(hass) switch, body_on, body_off = _setup_test_switch(hass)
await switch.async_turn_on() await switch.async_turn_on()
@ -219,7 +217,7 @@ async def test_turn_on_timeout(hass, aioclient_mock):
async def test_turn_off_success(hass, aioclient_mock): async def test_turn_off_success(hass, aioclient_mock):
"""Test turn_off.""" """Test turn_off."""
aioclient_mock.post(RESOURCE, status=HTTP_OK) aioclient_mock.post(RESOURCE, status=HTTPStatus.OK)
switch, body_on, body_off = _setup_test_switch(hass) switch, body_on, body_off = _setup_test_switch(hass)
await switch.async_turn_off() await switch.async_turn_off()
@ -229,7 +227,7 @@ async def test_turn_off_success(hass, aioclient_mock):
async def test_turn_off_status_not_ok(hass, aioclient_mock): async def test_turn_off_status_not_ok(hass, aioclient_mock):
"""Test turn_off when error status returned.""" """Test turn_off when error status returned."""
aioclient_mock.post(RESOURCE, status=HTTP_INTERNAL_SERVER_ERROR) aioclient_mock.post(RESOURCE, status=HTTPStatus.INTERNAL_SERVER_ERROR)
switch, body_on, body_off = _setup_test_switch(hass) switch, body_on, body_off = _setup_test_switch(hass)
await switch.async_turn_off() await switch.async_turn_off()

View file

@ -1,4 +1,5 @@
"""Tests for the SmartThings config flow module.""" """Tests for the SmartThings config flow module."""
from http import HTTPStatus
from unittest.mock import AsyncMock, Mock, patch from unittest.mock import AsyncMock, Mock, patch
from uuid import uuid4 from uuid import uuid4
@ -15,14 +16,7 @@ from homeassistant.components.smartthings.const import (
DOMAIN, DOMAIN,
) )
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 CONF_ACCESS_TOKEN, CONF_CLIENT_ID, CONF_CLIENT_SECRET
CONF_ACCESS_TOKEN,
CONF_CLIENT_ID,
CONF_CLIENT_SECRET,
HTTP_FORBIDDEN,
HTTP_NOT_FOUND,
HTTP_UNAUTHORIZED,
)
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
@ -482,7 +476,7 @@ async def test_unauthorized_token_shows_error(hass, smartthings_mock):
token = str(uuid4()) token = str(uuid4())
request_info = Mock(real_url="http://example.com") request_info = Mock(real_url="http://example.com")
smartthings_mock.apps.side_effect = ClientResponseError( smartthings_mock.apps.side_effect = ClientResponseError(
request_info=request_info, history=None, status=HTTP_UNAUTHORIZED request_info=request_info, history=None, status=HTTPStatus.UNAUTHORIZED
) )
# Webhook confirmation shown # Webhook confirmation shown
@ -519,7 +513,7 @@ async def test_forbidden_token_shows_error(hass, smartthings_mock):
token = str(uuid4()) token = str(uuid4())
request_info = Mock(real_url="http://example.com") request_info = Mock(real_url="http://example.com")
smartthings_mock.apps.side_effect = ClientResponseError( smartthings_mock.apps.side_effect = ClientResponseError(
request_info=request_info, history=None, status=HTTP_FORBIDDEN request_info=request_info, history=None, status=HTTPStatus.FORBIDDEN
) )
# Webhook confirmation shown # Webhook confirmation shown
@ -635,7 +629,7 @@ async def test_unknown_response_error_shows_error(hass, smartthings_mock):
token = str(uuid4()) token = str(uuid4())
request_info = Mock(real_url="http://example.com") request_info = Mock(real_url="http://example.com")
error = ClientResponseError( error = ClientResponseError(
request_info=request_info, history=None, status=HTTP_NOT_FOUND request_info=request_info, history=None, status=HTTPStatus.NOT_FOUND
) )
smartthings_mock.apps.side_effect = error smartthings_mock.apps.side_effect = error

View file

@ -1,4 +1,5 @@
"""Tests for the SmartThings component init module.""" """Tests for the SmartThings component init module."""
from http import HTTPStatus
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
from uuid import uuid4 from uuid import uuid4
@ -19,7 +20,6 @@ from homeassistant.components.smartthings.const import (
SIGNAL_SMARTTHINGS_UPDATE, SIGNAL_SMARTTHINGS_UPDATE,
) )
from homeassistant.config import async_process_ha_core_config from homeassistant.config import async_process_ha_core_config
from homeassistant.const import HTTP_FORBIDDEN, HTTP_INTERNAL_SERVER_ERROR
from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -83,7 +83,9 @@ async def test_recoverable_api_errors_raise_not_ready(
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
request_info = Mock(real_url="http://example.com") request_info = Mock(real_url="http://example.com")
smartthings_mock.app.side_effect = ClientResponseError( smartthings_mock.app.side_effect = ClientResponseError(
request_info=request_info, history=None, status=HTTP_INTERNAL_SERVER_ERROR request_info=request_info,
history=None,
status=HTTPStatus.INTERNAL_SERVER_ERROR,
) )
with pytest.raises(ConfigEntryNotReady): with pytest.raises(ConfigEntryNotReady):
@ -99,7 +101,9 @@ async def test_scenes_api_errors_raise_not_ready(
smartthings_mock.app.return_value = app smartthings_mock.app.return_value = app
smartthings_mock.installed_app.return_value = installed_app smartthings_mock.installed_app.return_value = installed_app
smartthings_mock.scenes.side_effect = ClientResponseError( smartthings_mock.scenes.side_effect = ClientResponseError(
request_info=request_info, history=None, status=HTTP_INTERNAL_SERVER_ERROR request_info=request_info,
history=None,
status=HTTPStatus.INTERNAL_SERVER_ERROR,
) )
with pytest.raises(ConfigEntryNotReady): with pytest.raises(ConfigEntryNotReady):
await smartthings.async_setup_entry(hass, config_entry) await smartthings.async_setup_entry(hass, config_entry)
@ -160,7 +164,7 @@ async def test_scenes_unauthorized_loads_platforms(
smartthings_mock.installed_app.return_value = installed_app smartthings_mock.installed_app.return_value = installed_app
smartthings_mock.devices.return_value = [device] smartthings_mock.devices.return_value = [device]
smartthings_mock.scenes.side_effect = ClientResponseError( smartthings_mock.scenes.side_effect = ClientResponseError(
request_info=request_info, history=None, status=HTTP_FORBIDDEN request_info=request_info, history=None, status=HTTPStatus.FORBIDDEN
) )
mock_token = Mock() mock_token = Mock()
mock_token.access_token = str(uuid4()) mock_token.access_token = str(uuid4())
@ -311,10 +315,10 @@ async def test_remove_entry_already_deleted(hass, config_entry, smartthings_mock
request_info = Mock(real_url="http://example.com") request_info = Mock(real_url="http://example.com")
# Arrange # Arrange
smartthings_mock.delete_installed_app.side_effect = ClientResponseError( smartthings_mock.delete_installed_app.side_effect = ClientResponseError(
request_info=request_info, history=None, status=HTTP_FORBIDDEN request_info=request_info, history=None, status=HTTPStatus.FORBIDDEN
) )
smartthings_mock.delete_app.side_effect = ClientResponseError( smartthings_mock.delete_app.side_effect = ClientResponseError(
request_info=request_info, history=None, status=HTTP_FORBIDDEN request_info=request_info, history=None, status=HTTPStatus.FORBIDDEN
) )
# Act # Act
await smartthings.async_remove_entry(hass, config_entry) await smartthings.async_remove_entry(hass, config_entry)
@ -330,7 +334,9 @@ async def test_remove_entry_installedapp_api_error(
request_info = Mock(real_url="http://example.com") request_info = Mock(real_url="http://example.com")
# Arrange # Arrange
smartthings_mock.delete_installed_app.side_effect = ClientResponseError( smartthings_mock.delete_installed_app.side_effect = ClientResponseError(
request_info=request_info, history=None, status=HTTP_INTERNAL_SERVER_ERROR request_info=request_info,
history=None,
status=HTTPStatus.INTERNAL_SERVER_ERROR,
) )
# Act # Act
with pytest.raises(ClientResponseError): with pytest.raises(ClientResponseError):
@ -359,7 +365,9 @@ async def test_remove_entry_app_api_error(hass, config_entry, smartthings_mock):
# Arrange # Arrange
request_info = Mock(real_url="http://example.com") request_info = Mock(real_url="http://example.com")
smartthings_mock.delete_app.side_effect = ClientResponseError( smartthings_mock.delete_app.side_effect = ClientResponseError(
request_info=request_info, history=None, status=HTTP_INTERNAL_SERVER_ERROR request_info=request_info,
history=None,
status=HTTPStatus.INTERNAL_SERVER_ERROR,
) )
# Act # Act
with pytest.raises(ClientResponseError): with pytest.raises(ClientResponseError):

View file

@ -1,12 +1,9 @@
"""Tests for the Start.ca sensor platform.""" """Tests for the Start.ca sensor platform."""
from http import HTTPStatus
from homeassistant.bootstrap import async_setup_component from homeassistant.bootstrap import async_setup_component
from homeassistant.components.startca.sensor import StartcaData from homeassistant.components.startca.sensor import StartcaData
from homeassistant.const import ( from homeassistant.const import ATTR_UNIT_OF_MEASUREMENT, DATA_GIGABYTES, PERCENTAGE
ATTR_UNIT_OF_MEASUREMENT,
DATA_GIGABYTES,
HTTP_NOT_FOUND,
PERCENTAGE,
)
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
@ -205,7 +202,8 @@ async def test_unlimited_setup(hass, aioclient_mock):
async def test_bad_return_code(hass, aioclient_mock): async def test_bad_return_code(hass, aioclient_mock):
"""Test handling a return code that isn't HTTP OK.""" """Test handling a return code that isn't HTTP OK."""
aioclient_mock.get( aioclient_mock.get(
"https://www.start.ca/support/usage/api?key=NOTAKEY", status=HTTP_NOT_FOUND "https://www.start.ca/support/usage/api?key=NOTAKEY",
status=HTTPStatus.NOT_FOUND,
) )
scd = StartcaData(hass.loop, async_get_clientsession(hass), "NOTAKEY", 400) scd = StartcaData(hass.loop, async_get_clientsession(hass), "NOTAKEY", 400)

View file

@ -1,5 +1,6 @@
"""The tests for the Yandex SpeechKit speech platform.""" """The tests for the Yandex SpeechKit speech platform."""
import asyncio import asyncio
from http import HTTPStatus
import os import os
import shutil import shutil
@ -9,7 +10,6 @@ from homeassistant.components.media_player.const import (
) )
import homeassistant.components.tts as tts import homeassistant.components.tts as tts
from homeassistant.config import async_process_ha_core_config from homeassistant.config import async_process_ha_core_config
from homeassistant.const import HTTP_FORBIDDEN
from homeassistant.setup import setup_component from homeassistant.setup import setup_component
from tests.common import assert_setup_component, get_test_home_assistant, mock_service from tests.common import assert_setup_component, get_test_home_assistant, mock_service
@ -207,7 +207,10 @@ class TestTTSYandexPlatform:
"speed": 1, "speed": 1,
} }
aioclient_mock.get( aioclient_mock.get(
self._base_url, status=HTTP_FORBIDDEN, content=b"test", params=url_param self._base_url,
status=HTTPStatus.FORBIDDEN,
content=b"test",
params=url_param,
) )
config = {tts.DOMAIN: {"platform": "yandextts", "api_key": "1234567xx"}} config = {tts.DOMAIN: {"platform": "yandextts", "api_key": "1234567xx"}}

View file

@ -1,6 +1,7 @@
"""Aiohttp test utils.""" """Aiohttp test utils."""
import asyncio import asyncio
from contextlib import contextmanager from contextlib import contextmanager
from http import HTTPStatus
import json as _json import json as _json
import re import re
from unittest import mock from unittest import mock
@ -41,7 +42,7 @@ class AiohttpClientMocker:
url, url,
*, *,
auth=None, auth=None,
status=200, status=HTTPStatus.OK,
text=None, text=None,
data=None, data=None,
content=None, content=None,
@ -157,7 +158,7 @@ class AiohttpClientMockResponse:
self, self,
method, method,
url, url,
status=200, status=HTTPStatus.OK,
response=None, response=None,
json=None, json=None,
text=None, text=None,