Use http.HTTPStatus in components/f* (#58244)

This commit is contained in:
Ville Skyttä 2021-10-22 23:10:47 +03:00 committed by GitHub
parent 4369b0b8be
commit b1360ffafb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 61 additions and 63 deletions

View file

@ -1,4 +1,5 @@
"""Facebook platform for notify component."""
from http import HTTPStatus
import json
import logging
@ -12,7 +13,7 @@ from homeassistant.components.notify import (
PLATFORM_SCHEMA,
BaseNotificationService,
)
from homeassistant.const import CONTENT_TYPE_JSON, HTTP_OK
from homeassistant.const import CONTENT_TYPE_JSON
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
@ -76,7 +77,7 @@ class FacebookNotificationService(BaseNotificationService):
headers={CONTENT_TYPE: CONTENT_TYPE_JSON},
timeout=10,
)
if resp.status_code != HTTP_OK:
if resp.status_code != HTTPStatus.OK:
log_error(resp)

View file

@ -1,5 +1,6 @@
"""Component for facial detection and identification via facebox."""
import base64
from http import HTTPStatus
import logging
import requests
@ -21,9 +22,6 @@ from homeassistant.const import (
CONF_PASSWORD,
CONF_PORT,
CONF_USERNAME,
HTTP_BAD_REQUEST,
HTTP_OK,
HTTP_UNAUTHORIZED,
)
from homeassistant.core import split_entity_id
import homeassistant.helpers.config_validation as cv
@ -67,10 +65,10 @@ def check_box_health(url, username, password):
kwargs["auth"] = requests.auth.HTTPBasicAuth(username, password)
try:
response = requests.get(url, **kwargs)
if response.status_code == HTTP_UNAUTHORIZED:
if response.status_code == HTTPStatus.UNAUTHORIZED:
_LOGGER.error("AuthenticationError on %s", CLASSIFIER)
return None
if response.status_code == HTTP_OK:
if response.status_code == HTTPStatus.OK:
return response.json()["hostname"]
except requests.exceptions.ConnectionError:
_LOGGER.error("ConnectionError: Is %s running?", CLASSIFIER)
@ -115,7 +113,7 @@ def post_image(url, image, username, password):
kwargs["auth"] = requests.auth.HTTPBasicAuth(username, password)
try:
response = requests.post(url, json={"base64": encode_image(image)}, **kwargs)
if response.status_code == HTTP_UNAUTHORIZED:
if response.status_code == HTTPStatus.UNAUTHORIZED:
_LOGGER.error("AuthenticationError on %s", CLASSIFIER)
return None
return response
@ -137,9 +135,9 @@ def teach_file(url, name, file_path, username, password):
files={"file": open_file},
**kwargs,
)
if response.status_code == HTTP_UNAUTHORIZED:
if response.status_code == HTTPStatus.UNAUTHORIZED:
_LOGGER.error("AuthenticationError on %s", CLASSIFIER)
elif response.status_code == HTTP_BAD_REQUEST:
elif response.status_code == HTTPStatus.BAD_REQUEST:
_LOGGER.error(
"%s teaching of file %s failed with message:%s",
CLASSIFIER,

View file

@ -1,12 +1,13 @@
"""Flock platform for notify component."""
import asyncio
from http import HTTPStatus
import logging
import async_timeout
import voluptuous as vol
from homeassistant.components.notify import PLATFORM_SCHEMA, BaseNotificationService
from homeassistant.const import CONF_ACCESS_TOKEN, HTTP_OK
from homeassistant.const import CONF_ACCESS_TOKEN
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
@ -44,7 +45,7 @@ class FlockNotificationService(BaseNotificationService):
response = await self._session.post(self._url, json=payload)
result = await response.json()
if response.status != HTTP_OK or "error" in result:
if response.status != HTTPStatus.OK or "error" in result:
_LOGGER.error(
"Flock service returned HTTP status %d, response %s",
response.status,

View file

@ -6,7 +6,7 @@ import requests
import voluptuous as vol
from homeassistant.components.http import HomeAssistantView
from homeassistant.const import CONF_ACCESS_TOKEN, HTTP_CREATED, HTTP_OK
from homeassistant.const import CONF_ACCESS_TOKEN
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
@ -56,7 +56,7 @@ def setup(hass, config):
url = f"https://api.foursquare.com/v2/checkins/add?oauth_token={config[CONF_ACCESS_TOKEN]}&v=20160802&m=swarm"
response = requests.post(url, data=call.data, timeout=10)
if response.status_code not in (HTTP_OK, HTTP_CREATED):
if response.status_code not in (HTTPStatus.OK, HTTPStatus.CREATED):
_LOGGER.exception(
"Error checking in user. Response %d: %s:",
response.status_code,

View file

@ -1,17 +1,12 @@
"""Support for Free Mobile SMS platform."""
from http import HTTPStatus
import logging
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,
HTTP_BAD_REQUEST,
HTTP_FORBIDDEN,
HTTP_INTERNAL_SERVER_ERROR,
)
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_USERNAME
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
@ -37,11 +32,11 @@ class FreeSMSNotificationService(BaseNotificationService):
"""Send a message to the Free Mobile user cell."""
resp = self.free_client.send_sms(message)
if resp.status_code == HTTP_BAD_REQUEST:
if resp.status_code == HTTPStatus.BAD_REQUEST:
_LOGGER.error("At least one parameter is missing")
elif resp.status_code == 402:
elif resp.status_code == HTTPStatus.PAYMENT_REQUIRED:
_LOGGER.error("Too much SMS send in a few time")
elif resp.status_code == HTTP_FORBIDDEN:
elif resp.status_code == HTTPStatus.FORBIDDEN:
_LOGGER.error("Wrong Username/Password")
elif resp.status_code == HTTP_INTERNAL_SERVER_ERROR:
elif resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR:
_LOGGER.error("Server error, try later")

View file

@ -1,4 +1,6 @@
"""The test for the Facebook notify module."""
from http import HTTPStatus
import pytest
import requests_mock
@ -15,7 +17,7 @@ def facebook():
async def test_send_simple_message(hass, facebook):
"""Test sending a simple message with success."""
with requests_mock.Mocker() as mock:
mock.register_uri(requests_mock.POST, fb.BASE_URL, status_code=200)
mock.register_uri(requests_mock.POST, fb.BASE_URL, status_code=HTTPStatus.OK)
message = "This is just a test"
target = ["+15555551234"]
@ -39,7 +41,7 @@ async def test_send_simple_message(hass, facebook):
async def test_send_multiple_message(hass, facebook):
"""Test sending a message to multiple targets."""
with requests_mock.Mocker() as mock:
mock.register_uri(requests_mock.POST, fb.BASE_URL, status_code=200)
mock.register_uri(requests_mock.POST, fb.BASE_URL, status_code=HTTPStatus.OK)
message = "This is just a test"
targets = ["+15555551234", "+15555551235"]
@ -65,7 +67,7 @@ async def test_send_multiple_message(hass, facebook):
async def test_send_message_attachment(hass, facebook):
"""Test sending a message with a remote attachment."""
with requests_mock.Mocker() as mock:
mock.register_uri(requests_mock.POST, fb.BASE_URL, status_code=200)
mock.register_uri(requests_mock.POST, fb.BASE_URL, status_code=HTTPStatus.OK)
message = "This will be thrown away."
data = {
@ -94,7 +96,9 @@ async def test_send_message_attachment(hass, facebook):
async def test_send_targetless_message(hass, facebook):
"""Test sending a message without a target."""
with requests_mock.Mocker() as mock:
mock.register_uri(requests_mock.POST, fb.BASE_URL, status_code=200)
mock.register_uri(
requests_mock.POST, fb.BASE_URL, status_code=HTTPStatus.OK
)
facebook.send_message(message="going nowhere")
assert not mock.called
@ -105,7 +109,7 @@ async def test_send_message_attachment(hass, facebook):
mock.register_uri(
requests_mock.POST,
fb.BASE_URL,
status_code=400,
status_code=HTTPStatus.BAD_REQUEST,
json={
"error": {
"message": "Invalid OAuth access token.",

View file

@ -1,4 +1,5 @@
"""The tests for the facebox component."""
from http import HTTPStatus
from unittest.mock import Mock, mock_open, patch
import pytest
@ -15,9 +16,6 @@ from homeassistant.const import (
CONF_PASSWORD,
CONF_PORT,
CONF_USERNAME,
HTTP_BAD_REQUEST,
HTTP_OK,
HTTP_UNAUTHORIZED,
STATE_UNKNOWN,
)
from homeassistant.core import callback
@ -120,10 +118,10 @@ def test_check_box_health(caplog):
"""Test check box health."""
with requests_mock.Mocker() as mock_req:
url = f"http://{MOCK_IP}:{MOCK_PORT}/healthz"
mock_req.get(url, status_code=HTTP_OK, json=MOCK_HEALTH)
mock_req.get(url, status_code=HTTPStatus.OK, json=MOCK_HEALTH)
assert fb.check_box_health(url, "user", "pass") == MOCK_BOX_ID
mock_req.get(url, status_code=HTTP_UNAUTHORIZED)
mock_req.get(url, status_code=HTTPStatus.UNAUTHORIZED)
assert fb.check_box_health(url, None, None) is None
assert "AuthenticationError on facebox" in caplog.text
@ -238,7 +236,7 @@ async def test_process_image_errors(hass, mock_healthybox, mock_image, caplog):
# Now test with bad auth.
with requests_mock.Mocker() as mock_req:
url = f"http://{MOCK_IP}:{MOCK_PORT}/facebox/check"
mock_req.register_uri("POST", url, status_code=HTTP_UNAUTHORIZED)
mock_req.register_uri("POST", url, status_code=HTTPStatus.UNAUTHORIZED)
data = {ATTR_ENTITY_ID: VALID_ENTITY_ID}
await hass.services.async_call(ip.DOMAIN, ip.SERVICE_SCAN, service_data=data)
await hass.async_block_till_done()
@ -259,7 +257,7 @@ async def test_teach_service(
# Test successful teach.
with requests_mock.Mocker() as mock_req:
url = f"http://{MOCK_IP}:{MOCK_PORT}/facebox/teach"
mock_req.post(url, status_code=HTTP_OK)
mock_req.post(url, status_code=HTTPStatus.OK)
data = {
ATTR_ENTITY_ID: VALID_ENTITY_ID,
ATTR_NAME: MOCK_NAME,
@ -273,7 +271,7 @@ async def test_teach_service(
# Now test with bad auth.
with requests_mock.Mocker() as mock_req:
url = f"http://{MOCK_IP}:{MOCK_PORT}/facebox/teach"
mock_req.post(url, status_code=HTTP_UNAUTHORIZED)
mock_req.post(url, status_code=HTTPStatus.UNAUTHORIZED)
data = {
ATTR_ENTITY_ID: VALID_ENTITY_ID,
ATTR_NAME: MOCK_NAME,
@ -288,7 +286,7 @@ async def test_teach_service(
# Now test the failed teaching.
with requests_mock.Mocker() as mock_req:
url = f"http://{MOCK_IP}:{MOCK_PORT}/facebox/teach"
mock_req.post(url, status_code=HTTP_BAD_REQUEST, text=MOCK_ERROR_NO_FACE)
mock_req.post(url, status_code=HTTPStatus.BAD_REQUEST, text=MOCK_ERROR_NO_FACE)
data = {
ATTR_ENTITY_ID: VALID_ENTITY_ID,
ATTR_NAME: MOCK_NAME,

View file

@ -1,4 +1,5 @@
"""Define fixtures available for all tests."""
from http import HTTPStatus
import json
import time
@ -41,40 +42,40 @@ def aioclient_mock_fixture(aioclient_mock):
}
),
headers={"Content-Type": CONTENT_TYPE_JSON},
status=200,
status=HTTPStatus.OK,
)
# Mocks the devices for flo.
aioclient_mock.get(
"https://api-gw.meetflo.com/api/v2/devices/98765",
text=load_fixture("flo/device_info_response.json"),
status=200,
status=HTTPStatus.OK,
headers={"Content-Type": CONTENT_TYPE_JSON},
)
aioclient_mock.get(
"https://api-gw.meetflo.com/api/v2/devices/32839",
text=load_fixture("flo/device_info_response_detector.json"),
status=200,
status=HTTPStatus.OK,
headers={"Content-Type": CONTENT_TYPE_JSON},
)
# Mocks the water consumption for flo.
aioclient_mock.get(
"https://api-gw.meetflo.com/api/v2/water/consumption",
text=load_fixture("flo/water_consumption_info_response.json"),
status=200,
status=HTTPStatus.OK,
headers={"Content-Type": CONTENT_TYPE_JSON},
)
# Mocks the location info for flo.
aioclient_mock.get(
"https://api-gw.meetflo.com/api/v2/locations/mmnnoopp",
text=load_fixture("flo/location_info_expand_devices_response.json"),
status=200,
status=HTTPStatus.OK,
headers={"Content-Type": CONTENT_TYPE_JSON},
)
# Mocks the user info for flo.
aioclient_mock.get(
"https://api-gw.meetflo.com/api/v2/users/12345abcde",
text=load_fixture("flo/user_info_expand_locations_response.json"),
status=200,
status=HTTPStatus.OK,
headers={"Content-Type": CONTENT_TYPE_JSON},
params={"expand": "locations"},
)
@ -82,14 +83,14 @@ def aioclient_mock_fixture(aioclient_mock):
aioclient_mock.get(
"https://api-gw.meetflo.com/api/v2/users/12345abcde",
text=load_fixture("flo/user_info_expand_locations_response.json"),
status=200,
status=HTTPStatus.OK,
headers={"Content-Type": CONTENT_TYPE_JSON},
)
# Mocks the valve open call for flo.
aioclient_mock.post(
"https://api-gw.meetflo.com/api/v2/devices/98765",
text=load_fixture("flo/device_info_response.json"),
status=200,
status=HTTPStatus.OK,
headers={"Content-Type": CONTENT_TYPE_JSON},
json={"valve": {"target": "open"}},
)
@ -97,7 +98,7 @@ def aioclient_mock_fixture(aioclient_mock):
aioclient_mock.post(
"https://api-gw.meetflo.com/api/v2/devices/98765",
text=load_fixture("flo/device_info_response_closed.json"),
status=200,
status=HTTPStatus.OK,
headers={"Content-Type": CONTENT_TYPE_JSON},
json={"valve": {"target": "closed"}},
)
@ -105,14 +106,14 @@ def aioclient_mock_fixture(aioclient_mock):
aioclient_mock.post(
"https://api-gw.meetflo.com/api/v2/devices/98765/healthTest/run",
text=load_fixture("flo/user_info_expand_locations_response.json"),
status=200,
status=HTTPStatus.OK,
headers={"Content-Type": CONTENT_TYPE_JSON},
)
# Mocks the health test call for flo.
aioclient_mock.post(
"https://api-gw.meetflo.com/api/v2/locations/mmnnoopp/systemMode",
text=load_fixture("flo/user_info_expand_locations_response.json"),
status=200,
status=HTTPStatus.OK,
headers={"Content-Type": CONTENT_TYPE_JSON},
json={"systemMode": {"target": "home"}},
)
@ -120,7 +121,7 @@ def aioclient_mock_fixture(aioclient_mock):
aioclient_mock.post(
"https://api-gw.meetflo.com/api/v2/locations/mmnnoopp/systemMode",
text=load_fixture("flo/user_info_expand_locations_response.json"),
status=200,
status=HTTPStatus.OK,
headers={"Content-Type": CONTENT_TYPE_JSON},
json={"systemMode": {"target": "away"}},
)
@ -128,7 +129,7 @@ def aioclient_mock_fixture(aioclient_mock):
aioclient_mock.post(
"https://api-gw.meetflo.com/api/v2/locations/mmnnoopp/systemMode",
text=load_fixture("flo/user_info_expand_locations_response.json"),
status=200,
status=HTTPStatus.OK,
headers={"Content-Type": CONTENT_TYPE_JSON},
json={
"systemMode": {

View file

@ -1,4 +1,5 @@
"""Test the flo config flow."""
from http import HTTPStatus
import json
import time
from unittest.mock import patch
@ -51,7 +52,7 @@ async def test_form_cannot_connect(hass, aioclient_mock):
}
),
headers={"Content-Type": CONTENT_TYPE_JSON},
status=400,
status=HTTPStatus.BAD_REQUEST,
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}

View file

@ -1,6 +1,7 @@
"""The tests for the Foobot sensor platform."""
import asyncio
from http import HTTPStatus
import re
from unittest.mock import MagicMock
@ -12,8 +13,6 @@ from homeassistant.const import (
CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
CONCENTRATION_PARTS_PER_BILLION,
CONCENTRATION_PARTS_PER_MILLION,
HTTP_FORBIDDEN,
HTTP_INTERNAL_SERVER_ERROR,
PERCENTAGE,
TEMP_CELSIUS,
)
@ -73,7 +72,7 @@ async def test_setup_permanent_error(hass, aioclient_mock):
"""Expected failures caused by permanent errors in API response."""
fake_async_add_entities = MagicMock()
errors = [400, 401, HTTP_FORBIDDEN]
errors = [HTTPStatus.BAD_REQUEST, HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN]
for error in errors:
aioclient_mock.get(re.compile("api.foobot.io/v2/owner/.*"), status=error)
result = await foobot.async_setup_platform(
@ -86,7 +85,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, HTTP_INTERNAL_SERVER_ERROR]
errors = [HTTPStatus.TOO_MANY_REQUESTS, HTTPStatus.INTERNAL_SERVER_ERROR]
for error in errors:
aioclient_mock.get(re.compile("api.foobot.io/v2/owner/.*"), status=error)
with pytest.raises(PlatformNotReady):

View file

@ -1,5 +1,6 @@
"""The tests for Home Assistant frontend."""
from datetime import timedelta
from http import HTTPStatus
import re
from unittest.mock import patch
@ -16,7 +17,6 @@ from homeassistant.components.frontend import (
THEMES_STORAGE_KEY,
)
from homeassistant.components.websocket_api.const import TYPE_RESULT
from homeassistant.const import HTTP_NOT_FOUND, HTTP_OK
from homeassistant.loader import async_get_integration
from homeassistant.setup import async_setup_component
from homeassistant.util import dt
@ -156,7 +156,7 @@ async def test_dont_cache_service_worker(mock_http_client):
async def test_404(mock_http_client):
"""Test for HTTP 404 error."""
resp = await mock_http_client.get("/not-existing")
assert resp.status == HTTP_NOT_FOUND
assert resp.status == HTTPStatus.NOT_FOUND
async def test_we_cannot_POST_to_root(mock_http_client):
@ -365,7 +365,7 @@ async def test_get_panels(hass, hass_ws_client, mock_http_client):
events = async_capture_events(hass, EVENT_PANELS_UPDATED)
resp = await mock_http_client.get("/map")
assert resp.status == HTTP_NOT_FOUND
assert resp.status == HTTPStatus.NOT_FOUND
hass.components.frontend.async_register_built_in_panel(
"map", "Map", "mdi:tooltip-account", require_admin=True
@ -393,7 +393,7 @@ async def test_get_panels(hass, hass_ws_client, mock_http_client):
hass.components.frontend.async_remove_panel("map")
resp = await mock_http_client.get("/map")
assert resp.status == HTTP_NOT_FOUND
assert resp.status == HTTPStatus.NOT_FOUND
assert len(events) == 2
@ -509,7 +509,7 @@ async def test_static_paths(hass, mock_http_client):
async def test_manifest_json(hass, frontend_themes, mock_http_client):
"""Test for fetching manifest.json."""
resp = await mock_http_client.get("/manifest.json")
assert resp.status == HTTP_OK
assert resp.status == HTTPStatus.OK
assert "cache-control" not in resp.headers
json = await resp.json()
@ -521,7 +521,7 @@ async def test_manifest_json(hass, frontend_themes, mock_http_client):
await hass.async_block_till_done()
resp = await mock_http_client.get("/manifest.json")
assert resp.status == HTTP_OK
assert resp.status == HTTPStatus.OK
assert "cache-control" not in resp.headers
json = await resp.json()