Use http.HTTPStatus in components/[ikl]* (#58248)

This commit is contained in:
Ville Skyttä 2021-10-23 00:06:18 +03:00 committed by GitHub
parent 1867d24b18
commit ce1eda9809
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 124 additions and 113 deletions

View File

@ -1,4 +1,5 @@
"""Support to trigger Maker IFTTT recipes.""" """Support to trigger Maker IFTTT recipes."""
from http import HTTPStatus
import json import json
import logging import logging
@ -6,7 +7,7 @@ import pyfttt
import requests import requests
import voluptuous as vol import voluptuous as vol
from homeassistant.const import CONF_WEBHOOK_ID, HTTP_OK from homeassistant.const import CONF_WEBHOOK_ID
from homeassistant.helpers import config_entry_flow from homeassistant.helpers import config_entry_flow
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -75,7 +76,7 @@ async def async_setup(hass, config):
for target, key in target_keys.items(): for target, key in target_keys.items():
res = pyfttt.send_event(key, event, value1, value2, value3) res = pyfttt.send_event(key, event, value1, value2, value3)
if res.status_code != HTTP_OK: if res.status_code != HTTPStatus.OK:
_LOGGER.error("IFTTT reported error sending event to %s", target) _LOGGER.error("IFTTT reported error sending event to %s", target)
except requests.exceptions.RequestException: except requests.exceptions.RequestException:
_LOGGER.exception("Error communicating with IFTTT") _LOGGER.exception("Error communicating with IFTTT")

View File

@ -1,4 +1,5 @@
"""Support for iOS push notifications.""" """Support for iOS push notifications."""
from http import HTTPStatus
import logging import logging
import requests import requests
@ -12,7 +13,6 @@ from homeassistant.components.notify import (
ATTR_TITLE_DEFAULT, ATTR_TITLE_DEFAULT,
BaseNotificationService, BaseNotificationService,
) )
from homeassistant.const import HTTP_CREATED, HTTP_TOO_MANY_REQUESTS
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -91,13 +91,13 @@ class iOSNotificationService(BaseNotificationService):
req = requests.post(PUSH_URL, json=data, timeout=10) req = requests.post(PUSH_URL, json=data, timeout=10)
if req.status_code != HTTP_CREATED: if req.status_code != HTTPStatus.CREATED:
fallback_error = req.json().get("errorMessage", "Unknown error") fallback_error = req.json().get("errorMessage", "Unknown error")
fallback_message = ( fallback_message = (
f"Internal server error, please try again later: {fallback_error}" f"Internal server error, please try again later: {fallback_error}"
) )
message = req.json().get("message", fallback_message) message = req.json().get("message", fallback_message)
if req.status_code == HTTP_TOO_MANY_REQUESTS: if req.status_code == HTTPStatus.TOO_MANY_REQUESTS:
_LOGGER.warning(message) _LOGGER.warning(message)
log_rate_limits(self.hass, target, req.json(), 30) log_rate_limits(self.hass, target, req.json(), 30)
else: else:

View File

@ -1,5 +1,6 @@
"""Support for LIFX Cloud scenes.""" """Support for LIFX Cloud scenes."""
import asyncio import asyncio
from http import HTTPStatus
import logging import logging
from typing import Any from typing import Any
@ -9,13 +10,7 @@ import async_timeout
import voluptuous as vol import voluptuous as vol
from homeassistant.components.scene import Scene from homeassistant.components.scene import Scene
from homeassistant.const import ( from homeassistant.const import CONF_PLATFORM, CONF_TIMEOUT, CONF_TOKEN
CONF_PLATFORM,
CONF_TIMEOUT,
CONF_TOKEN,
HTTP_OK,
HTTP_UNAUTHORIZED,
)
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -51,12 +46,12 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
return False return False
status = scenes_resp.status status = scenes_resp.status
if status == HTTP_OK: if status == HTTPStatus.OK:
data = await scenes_resp.json() data = await scenes_resp.json()
devices = [LifxCloudScene(hass, headers, timeout, scene) for scene in data] devices = [LifxCloudScene(hass, headers, timeout, scene) for scene in data]
async_add_entities(devices) async_add_entities(devices)
return True return True
if status == HTTP_UNAUTHORIZED: if status == HTTPStatus.UNAUTHORIZED:
_LOGGER.error("Unauthorized (bad token?) on %s", url) _LOGGER.error("Unauthorized (bad token?) on %s", url)
return False return False

View File

@ -1,4 +1,5 @@
"""Support for Linksys Smart Wifi routers.""" """Support for Linksys Smart Wifi routers."""
from http import HTTPStatus
import logging import logging
import requests import requests
@ -9,7 +10,7 @@ from homeassistant.components.device_tracker import (
PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA,
DeviceScanner, DeviceScanner,
) )
from homeassistant.const import CONF_HOST, HTTP_OK from homeassistant.const import CONF_HOST
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
DEFAULT_TIMEOUT = 10 DEFAULT_TIMEOUT = 10
@ -37,7 +38,7 @@ class LinksysSmartWifiDeviceScanner(DeviceScanner):
# Check if the access point is accessible # Check if the access point is accessible
response = self._make_request() response = self._make_request()
if not response.status_code == HTTP_OK: if response.status_code != HTTPStatus.OK:
raise ConnectionError("Cannot connect to Linksys Access Point") raise ConnectionError("Cannot connect to Linksys Access Point")
def scan_devices(self): def scan_devices(self):
@ -56,7 +57,7 @@ class LinksysSmartWifiDeviceScanner(DeviceScanner):
self.last_results = {} self.last_results = {}
response = self._make_request() response = self._make_request()
if response.status_code != HTTP_OK: if response.status_code != HTTPStatus.OK:
_LOGGER.error( _LOGGER.error(
"Got HTTP status code %d when getting device list", response.status_code "Got HTTP status code %d when getting device list", response.status_code
) )

View File

@ -1,4 +1,5 @@
"""LlamaLab Automate notification service.""" """LlamaLab Automate notification service."""
from http import HTTPStatus
import logging import logging
import requests import requests
@ -9,7 +10,7 @@ from homeassistant.components.notify import (
PLATFORM_SCHEMA, PLATFORM_SCHEMA,
BaseNotificationService, BaseNotificationService,
) )
from homeassistant.const import CONF_API_KEY, CONF_DEVICE, HTTP_OK from homeassistant.const import CONF_API_KEY, CONF_DEVICE
from homeassistant.helpers import config_validation as cv from homeassistant.helpers import config_validation as cv
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -66,5 +67,5 @@ class AutomateNotificationService(BaseNotificationService):
} }
response = requests.post(_RESOURCE, json=data) response = requests.post(_RESOURCE, json=data)
if response.status_code != HTTP_OK: if response.status_code != HTTPStatus.OK:
_LOGGER.error("Error sending message: %s", response) _LOGGER.error("Error sending message: %s", response)

View File

@ -1,12 +1,12 @@
"""Sensor for checking the status of London air.""" """Sensor for checking the status of London air."""
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
import logging import logging
import requests import requests
import voluptuous as vol import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import 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
@ -83,7 +83,7 @@ class APIData:
def update(self): def update(self):
"""Get the latest data from TFL.""" """Get the latest data from TFL."""
response = requests.get(URL, timeout=10) response = requests.get(URL, timeout=10)
if response.status_code != HTTP_OK: if response.status_code != HTTPStatus.OK:
_LOGGER.warning("Invalid response from API") _LOGGER.warning("Invalid response from API")
else: else:
self.data = parse_api_response(response.json()) self.data = parse_api_response(response.json())

View File

@ -1,6 +1,7 @@
"""The tests for the InfluxDB component.""" """The tests for the InfluxDB component."""
from dataclasses import dataclass from dataclasses import dataclass
import datetime import datetime
from http import HTTPStatus
from unittest.mock import MagicMock, Mock, call, patch from unittest.mock import MagicMock, Mock, call, patch
import pytest import pytest
@ -1640,14 +1641,16 @@ async def test_connection_failure_on_startup(
BASE_V1_CONFIG, BASE_V1_CONFIG,
_get_write_api_mock_v1, _get_write_api_mock_v1,
influxdb.DEFAULT_API_VERSION, influxdb.DEFAULT_API_VERSION,
influxdb.exceptions.InfluxDBClientError("fail", code=400), influxdb.exceptions.InfluxDBClientError(
"fail", code=HTTPStatus.BAD_REQUEST
),
), ),
( (
influxdb.API_VERSION_2, influxdb.API_VERSION_2,
BASE_V2_CONFIG, BASE_V2_CONFIG,
_get_write_api_mock_v2, _get_write_api_mock_v2,
influxdb.API_VERSION_2, influxdb.API_VERSION_2,
influxdb.ApiException(status=400), influxdb.ApiException(status=HTTPStatus.BAD_REQUEST),
), ),
], ],
indirect=["mock_client", "get_mock_call"], indirect=["mock_client", "get_mock_call"],

View File

@ -3,6 +3,7 @@ from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
from influxdb.exceptions import InfluxDBClientError, InfluxDBServerError from influxdb.exceptions import InfluxDBClientError, InfluxDBServerError
@ -423,7 +424,7 @@ async def test_state_for_no_results(
BASE_V2_CONFIG, BASE_V2_CONFIG,
BASE_V2_QUERY, BASE_V2_QUERY,
_set_query_mock_v2, _set_query_mock_v2,
ApiException(status=400), ApiException(status=HTTPStatus.BAD_REQUEST),
), ),
], ],
indirect=["mock_client"], indirect=["mock_client"],

View File

@ -1,4 +1,5 @@
"""Test the kmtronic config flow.""" """Test the kmtronic config flow."""
from http import HTTPStatus
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
from aiohttp import ClientConnectorError, ClientResponseError from aiohttp import ClientConnectorError, ClientResponseError
@ -91,7 +92,7 @@ async def test_form_invalid_auth(hass):
with patch( with patch(
"homeassistant.components.kmtronic.config_flow.KMTronicHubAPI.async_get_status", "homeassistant.components.kmtronic.config_flow.KMTronicHubAPI.async_get_status",
side_effect=ClientResponseError(None, None, status=401), side_effect=ClientResponseError(None, None, status=HTTPStatus.BAD_REQUEST),
): ):
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,6 +1,7 @@
"""The tests for the KMtronic switch platform.""" """The tests for the KMtronic switch platform."""
import asyncio import asyncio
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus
from homeassistant.components.kmtronic.const import DOMAIN from homeassistant.components.kmtronic.const import DOMAIN
from homeassistant.const import STATE_UNAVAILABLE from homeassistant.const import STATE_UNAVAILABLE
@ -128,7 +129,7 @@ async def test_failed_update(hass, aioclient_mock):
aioclient_mock.get( aioclient_mock.get(
"http://1.1.1.1/status.xml", "http://1.1.1.1/status.xml",
text="401 Unauthorized: Password required", text="401 Unauthorized: Password required",
status=401, status=HTTPStatus.UNAUTHORIZED,
) )
async_fire_time_changed(hass, future) async_fire_time_changed(hass, future)

View File

@ -1,4 +1,5 @@
"""Test Konnected setup process.""" """Test Konnected setup process."""
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
import pytest import pytest
@ -6,7 +7,6 @@ import pytest
from homeassistant.components import konnected from homeassistant.components import konnected
from homeassistant.components.konnected import config_flow from homeassistant.components.konnected import config_flow
from homeassistant.config import async_process_ha_core_config from homeassistant.config import async_process_ha_core_config
from homeassistant.const import HTTP_NOT_FOUND
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
@ -474,44 +474,44 @@ async def test_api(hass, hass_client_no_auth, mock_panel):
# Test the get endpoint for switch status polling # Test the get endpoint for switch status polling
resp = await client.get("/api/konnected") resp = await client.get("/api/konnected")
assert resp.status == HTTP_NOT_FOUND # no device provided assert resp.status == HTTPStatus.NOT_FOUND # no device provided
resp = await client.get("/api/konnected/223344556677") resp = await client.get("/api/konnected/223344556677")
assert resp.status == HTTP_NOT_FOUND # unknown device provided assert resp.status == HTTPStatus.NOT_FOUND # unknown device provided
resp = await client.get("/api/konnected/device/112233445566") resp = await client.get("/api/konnected/device/112233445566")
assert resp.status == HTTP_NOT_FOUND # no zone provided assert resp.status == HTTPStatus.NOT_FOUND # no zone provided
result = await resp.json() result = await resp.json()
assert result == {"message": "Switch on zone or pin unknown not configured"} assert result == {"message": "Switch on zone or pin unknown not configured"}
resp = await client.get("/api/konnected/device/112233445566?zone=8") resp = await client.get("/api/konnected/device/112233445566?zone=8")
assert resp.status == HTTP_NOT_FOUND # invalid zone assert resp.status == HTTPStatus.NOT_FOUND # invalid zone
result = await resp.json() result = await resp.json()
assert result == {"message": "Switch on zone or pin 8 not configured"} assert result == {"message": "Switch on zone or pin 8 not configured"}
resp = await client.get("/api/konnected/device/112233445566?pin=12") resp = await client.get("/api/konnected/device/112233445566?pin=12")
assert resp.status == HTTP_NOT_FOUND # invalid pin assert resp.status == HTTPStatus.NOT_FOUND # invalid pin
result = await resp.json() result = await resp.json()
assert result == {"message": "Switch on zone or pin 12 not configured"} assert result == {"message": "Switch on zone or pin 12 not configured"}
resp = await client.get("/api/konnected/device/112233445566?zone=out") resp = await client.get("/api/konnected/device/112233445566?zone=out")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"state": 1, "zone": "out"} assert result == {"state": 1, "zone": "out"}
resp = await client.get("/api/konnected/device/112233445566?pin=8") resp = await client.get("/api/konnected/device/112233445566?pin=8")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"state": 1, "pin": "8"} assert result == {"state": 1, "pin": "8"}
# Test the post endpoint for sensor updates # Test the post endpoint for sensor updates
resp = await client.post("/api/konnected/device", json={"zone": "1", "state": 1}) resp = await client.post("/api/konnected/device", json={"zone": "1", "state": 1})
assert resp.status == HTTP_NOT_FOUND assert resp.status == HTTPStatus.NOT_FOUND
resp = await client.post( resp = await client.post(
"/api/konnected/device/112233445566", json={"zone": "1", "state": 1} "/api/konnected/device/112233445566", json={"zone": "1", "state": 1}
) )
assert resp.status == 401 assert resp.status == HTTPStatus.UNAUTHORIZED
result = await resp.json() result = await resp.json()
assert result == {"message": "unauthorized"} assert result == {"message": "unauthorized"}
@ -520,14 +520,14 @@ async def test_api(hass, hass_client_no_auth, mock_panel):
headers={"Authorization": "Bearer abcdefgh"}, headers={"Authorization": "Bearer abcdefgh"},
json={"zone": "1", "state": 1}, json={"zone": "1", "state": 1},
) )
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
resp = await client.post( resp = await client.post(
"/api/konnected/device/112233445566", "/api/konnected/device/112233445566",
headers={"Authorization": "Bearer abcdefgh"}, headers={"Authorization": "Bearer abcdefgh"},
json={"zone": "15", "state": 1}, json={"zone": "15", "state": 1},
) )
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
result = await resp.json() result = await resp.json()
assert result == {"message": "unregistered sensor/actuator"} assert result == {"message": "unregistered sensor/actuator"}
@ -536,7 +536,7 @@ async def test_api(hass, hass_client_no_auth, mock_panel):
headers={"Authorization": "Bearer abcdefgh"}, headers={"Authorization": "Bearer abcdefgh"},
json={"zone": "1", "state": 1}, json={"zone": "1", "state": 1},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"message": "ok"} assert result == {"message": "ok"}
@ -545,7 +545,7 @@ async def test_api(hass, hass_client_no_auth, mock_panel):
headers={"Authorization": "Bearer globaltoken"}, headers={"Authorization": "Bearer globaltoken"},
json={"zone": "1", "state": 1}, json={"zone": "1", "state": 1},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"message": "ok"} assert result == {"message": "ok"}
@ -554,7 +554,7 @@ async def test_api(hass, hass_client_no_auth, mock_panel):
headers={"Authorization": "Bearer abcdefgh"}, headers={"Authorization": "Bearer abcdefgh"},
json={"zone": "4", "temp": 22, "humi": 20}, json={"zone": "4", "temp": 22, "humi": 20},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"message": "ok"} assert result == {"message": "ok"}
@ -564,7 +564,7 @@ async def test_api(hass, hass_client_no_auth, mock_panel):
headers={"Authorization": "Bearer abcdefgh"}, headers={"Authorization": "Bearer abcdefgh"},
json={"zone": "1", "state": 1}, json={"zone": "1", "state": 1},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"message": "ok"} assert result == {"message": "ok"}
@ -650,7 +650,7 @@ async def test_state_updates_zone(hass, hass_client_no_auth, mock_panel):
headers={"Authorization": "Bearer abcdefgh"}, headers={"Authorization": "Bearer abcdefgh"},
json={"zone": "1", "state": 0}, json={"zone": "1", "state": 0},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"message": "ok"} assert result == {"message": "ok"}
await hass.async_block_till_done() await hass.async_block_till_done()
@ -661,7 +661,7 @@ async def test_state_updates_zone(hass, hass_client_no_auth, mock_panel):
headers={"Authorization": "Bearer abcdefgh"}, headers={"Authorization": "Bearer abcdefgh"},
json={"zone": "1", "state": 1}, json={"zone": "1", "state": 1},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"message": "ok"} assert result == {"message": "ok"}
await hass.async_block_till_done() await hass.async_block_till_done()
@ -673,7 +673,7 @@ async def test_state_updates_zone(hass, hass_client_no_auth, mock_panel):
headers={"Authorization": "Bearer abcdefgh"}, headers={"Authorization": "Bearer abcdefgh"},
json={"zone": "4", "temp": 22, "humi": 20}, json={"zone": "4", "temp": 22, "humi": 20},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"message": "ok"} assert result == {"message": "ok"}
await hass.async_block_till_done() await hass.async_block_till_done()
@ -687,7 +687,7 @@ async def test_state_updates_zone(hass, hass_client_no_auth, mock_panel):
headers={"Authorization": "Bearer abcdefgh"}, headers={"Authorization": "Bearer abcdefgh"},
json={"zone": "4", "temp": 25, "humi": 23}, json={"zone": "4", "temp": 25, "humi": 23},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"message": "ok"} assert result == {"message": "ok"}
await hass.async_block_till_done() await hass.async_block_till_done()
@ -702,7 +702,7 @@ async def test_state_updates_zone(hass, hass_client_no_auth, mock_panel):
headers={"Authorization": "Bearer abcdefgh"}, headers={"Authorization": "Bearer abcdefgh"},
json={"zone": "5", "temp": 32, "addr": 1}, json={"zone": "5", "temp": 32, "addr": 1},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"message": "ok"} assert result == {"message": "ok"}
await hass.async_block_till_done() await hass.async_block_till_done()
@ -713,7 +713,7 @@ async def test_state_updates_zone(hass, hass_client_no_auth, mock_panel):
headers={"Authorization": "Bearer abcdefgh"}, headers={"Authorization": "Bearer abcdefgh"},
json={"zone": "5", "temp": 42, "addr": 1}, json={"zone": "5", "temp": 42, "addr": 1},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"message": "ok"} assert result == {"message": "ok"}
await hass.async_block_till_done() await hass.async_block_till_done()
@ -805,7 +805,7 @@ async def test_state_updates_pin(hass, hass_client_no_auth, mock_panel):
headers={"Authorization": "Bearer abcdefgh"}, headers={"Authorization": "Bearer abcdefgh"},
json={"pin": "1", "state": 0}, json={"pin": "1", "state": 0},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"message": "ok"} assert result == {"message": "ok"}
await hass.async_block_till_done() await hass.async_block_till_done()
@ -816,7 +816,7 @@ async def test_state_updates_pin(hass, hass_client_no_auth, mock_panel):
headers={"Authorization": "Bearer abcdefgh"}, headers={"Authorization": "Bearer abcdefgh"},
json={"pin": "1", "state": 1}, json={"pin": "1", "state": 1},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"message": "ok"} assert result == {"message": "ok"}
await hass.async_block_till_done() await hass.async_block_till_done()
@ -828,7 +828,7 @@ async def test_state_updates_pin(hass, hass_client_no_auth, mock_panel):
headers={"Authorization": "Bearer abcdefgh"}, headers={"Authorization": "Bearer abcdefgh"},
json={"pin": "6", "temp": 22, "humi": 20}, json={"pin": "6", "temp": 22, "humi": 20},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"message": "ok"} assert result == {"message": "ok"}
await hass.async_block_till_done() await hass.async_block_till_done()
@ -842,7 +842,7 @@ async def test_state_updates_pin(hass, hass_client_no_auth, mock_panel):
headers={"Authorization": "Bearer abcdefgh"}, headers={"Authorization": "Bearer abcdefgh"},
json={"pin": "6", "temp": 25, "humi": 23}, json={"pin": "6", "temp": 25, "humi": 23},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"message": "ok"} assert result == {"message": "ok"}
await hass.async_block_till_done() await hass.async_block_till_done()
@ -857,7 +857,7 @@ async def test_state_updates_pin(hass, hass_client_no_auth, mock_panel):
headers={"Authorization": "Bearer abcdefgh"}, headers={"Authorization": "Bearer abcdefgh"},
json={"pin": "7", "temp": 32, "addr": 1}, json={"pin": "7", "temp": 32, "addr": 1},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"message": "ok"} assert result == {"message": "ok"}
await hass.async_block_till_done() await hass.async_block_till_done()
@ -868,7 +868,7 @@ async def test_state_updates_pin(hass, hass_client_no_auth, mock_panel):
headers={"Authorization": "Bearer abcdefgh"}, headers={"Authorization": "Bearer abcdefgh"},
json={"pin": "7", "temp": 42, "addr": 1}, json={"pin": "7", "temp": 42, "addr": 1},
) )
assert resp.status == 200 assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result == {"message": "ok"} assert result == {"message": "ok"}
await hass.async_block_till_done() await hass.async_block_till_done()

View File

@ -1,4 +1,5 @@
"""The tests for local file camera component.""" """The tests for local file camera component."""
from http import HTTPStatus
from unittest import mock from unittest import mock
from homeassistant.components.local_file.const import DOMAIN, SERVICE_UPDATE_FILE_PATH from homeassistant.components.local_file.const import DOMAIN, SERVICE_UPDATE_FILE_PATH
@ -35,7 +36,7 @@ async def test_loading_file(hass, hass_client):
): ):
resp = await client.get("/api/camera_proxy/camera.config_test") resp = await client.get("/api/camera_proxy/camera.config_test")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
body = await resp.text() body = await resp.text()
assert body == "hello" assert body == "hello"
@ -107,23 +108,23 @@ async def test_camera_content_type(hass, hass_client):
resp_3 = await client.get("/api/camera_proxy/camera.test_svg") resp_3 = await client.get("/api/camera_proxy/camera.test_svg")
resp_4 = await client.get("/api/camera_proxy/camera.test_no_ext") resp_4 = await client.get("/api/camera_proxy/camera.test_no_ext")
assert resp_1.status == 200 assert resp_1.status == HTTPStatus.OK
assert resp_1.content_type == "image/jpeg" assert resp_1.content_type == "image/jpeg"
body = await resp_1.text() body = await resp_1.text()
assert body == image assert body == image
assert resp_2.status == 200 assert resp_2.status == HTTPStatus.OK
assert resp_2.content_type == "image/png" assert resp_2.content_type == "image/png"
body = await resp_2.text() body = await resp_2.text()
assert body == image assert body == image
assert resp_3.status == 200 assert resp_3.status == HTTPStatus.OK
assert resp_3.content_type == "image/svg+xml" assert resp_3.content_type == "image/svg+xml"
body = await resp_3.text() body = await resp_3.text()
assert body == image assert body == image
# default mime type # default mime type
assert resp_4.status == 200 assert resp_4.status == HTTPStatus.OK
assert resp_4.content_type == "image/jpeg" assert resp_4.content_type == "image/jpeg"
body = await resp_4.text() body = await resp_4.text()
assert body == image assert body == image

View File

@ -1,4 +1,5 @@
"""The tests the for Locative device tracker platform.""" """The tests the for Locative device tracker platform."""
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
import pytest import pytest
@ -8,7 +9,6 @@ from homeassistant.components import locative
from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER_DOMAIN from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER_DOMAIN
from homeassistant.components.locative import DOMAIN, TRACKER_UPDATE from homeassistant.components.locative import DOMAIN, TRACKER_UPDATE
from homeassistant.config import async_process_ha_core_config from homeassistant.config import async_process_ha_core_config
from homeassistant.const import HTTP_OK, HTTP_UNPROCESSABLE_ENTITY
from homeassistant.helpers.dispatcher import DATA_DISPATCHER from homeassistant.helpers.dispatcher import DATA_DISPATCHER
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -64,50 +64,50 @@ async def test_missing_data(locative_client, webhook_id):
# No data # No data
req = await locative_client.post(url) req = await locative_client.post(url)
assert req.status == HTTP_UNPROCESSABLE_ENTITY assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
# No latitude # No latitude
copy = data.copy() copy = data.copy()
del copy["latitude"] del copy["latitude"]
req = await locative_client.post(url, data=copy) req = await locative_client.post(url, data=copy)
assert req.status == HTTP_UNPROCESSABLE_ENTITY assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
# No device # No device
copy = data.copy() copy = data.copy()
del copy["device"] del copy["device"]
req = await locative_client.post(url, data=copy) req = await locative_client.post(url, data=copy)
assert req.status == HTTP_UNPROCESSABLE_ENTITY assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
# No location # No location
copy = data.copy() copy = data.copy()
del copy["id"] del copy["id"]
req = await locative_client.post(url, data=copy) req = await locative_client.post(url, data=copy)
assert req.status == HTTP_UNPROCESSABLE_ENTITY assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
# No trigger # No trigger
copy = data.copy() copy = data.copy()
del copy["trigger"] del copy["trigger"]
req = await locative_client.post(url, data=copy) req = await locative_client.post(url, data=copy)
assert req.status == HTTP_UNPROCESSABLE_ENTITY assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
# Test message # Test message
copy = data.copy() copy = data.copy()
copy["trigger"] = "test" copy["trigger"] = "test"
req = await locative_client.post(url, data=copy) req = await locative_client.post(url, data=copy)
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
# Test message, no location # Test message, no location
copy = data.copy() copy = data.copy()
copy["trigger"] = "test" copy["trigger"] = "test"
del copy["id"] del copy["id"]
req = await locative_client.post(url, data=copy) req = await locative_client.post(url, data=copy)
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
# Unknown trigger # Unknown trigger
copy = data.copy() copy = data.copy()
copy["trigger"] = "foobar" copy["trigger"] = "foobar"
req = await locative_client.post(url, data=copy) req = await locative_client.post(url, data=copy)
assert req.status == HTTP_UNPROCESSABLE_ENTITY assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
async def test_enter_and_exit(hass, locative_client, webhook_id): async def test_enter_and_exit(hass, locative_client, webhook_id):
@ -125,7 +125,7 @@ async def test_enter_and_exit(hass, locative_client, webhook_id):
# Enter the Home # Enter the Home
req = await locative_client.post(url, data=data) req = await locative_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state_name = hass.states.get( state_name = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]) "{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])
).state ).state
@ -137,7 +137,7 @@ async def test_enter_and_exit(hass, locative_client, webhook_id):
# Exit Home # Exit Home
req = await locative_client.post(url, data=data) req = await locative_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state_name = hass.states.get( state_name = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]) "{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])
).state ).state
@ -149,7 +149,7 @@ async def test_enter_and_exit(hass, locative_client, webhook_id):
# Enter Home again # Enter Home again
req = await locative_client.post(url, data=data) req = await locative_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state_name = hass.states.get( state_name = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]) "{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])
).state ).state
@ -160,7 +160,7 @@ async def test_enter_and_exit(hass, locative_client, webhook_id):
# Exit Home # Exit Home
req = await locative_client.post(url, data=data) req = await locative_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state_name = hass.states.get( state_name = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]) "{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])
).state ).state
@ -172,7 +172,7 @@ async def test_enter_and_exit(hass, locative_client, webhook_id):
# Enter Work # Enter Work
req = await locative_client.post(url, data=data) req = await locative_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state_name = hass.states.get( state_name = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]) "{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])
).state ).state
@ -194,7 +194,7 @@ async def test_exit_after_enter(hass, locative_client, webhook_id):
# Enter Home # Enter Home
req = await locative_client.post(url, data=data) req = await locative_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])) state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]))
assert state.state == "home" assert state.state == "home"
@ -204,7 +204,7 @@ async def test_exit_after_enter(hass, locative_client, webhook_id):
# Enter Work # Enter Work
req = await locative_client.post(url, data=data) req = await locative_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])) state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]))
assert state.state == "work" assert state.state == "work"
@ -215,7 +215,7 @@ async def test_exit_after_enter(hass, locative_client, webhook_id):
# Exit Home # Exit Home
req = await locative_client.post(url, data=data) req = await locative_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])) state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]))
assert state.state == "work" assert state.state == "work"
@ -236,7 +236,7 @@ async def test_exit_first(hass, locative_client, webhook_id):
# Exit Home # Exit Home
req = await locative_client.post(url, data=data) req = await locative_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])) state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]))
assert state.state == "not_home" assert state.state == "not_home"
@ -257,7 +257,7 @@ async def test_two_devices(hass, locative_client, webhook_id):
# Exit Home # Exit Home
req = await locative_client.post(url, data=data_device_1) req = await locative_client.post(url, data=data_device_1)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state = hass.states.get( state = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data_device_1["device"]) "{}.{}".format(DEVICE_TRACKER_DOMAIN, data_device_1["device"])
@ -270,7 +270,7 @@ async def test_two_devices(hass, locative_client, webhook_id):
data_device_2["trigger"] = "enter" data_device_2["trigger"] = "enter"
req = await locative_client.post(url, data=data_device_2) req = await locative_client.post(url, data=data_device_2)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state = hass.states.get( state = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data_device_2["device"]) "{}.{}".format(DEVICE_TRACKER_DOMAIN, data_device_2["device"])
@ -300,7 +300,7 @@ async def test_load_unload_entry(hass, locative_client, webhook_id):
# Exit Home # Exit Home
req = await locative_client.post(url, data=data) req = await locative_client.post(url, data=data)
await hass.async_block_till_done() await hass.async_block_till_done()
assert req.status == HTTP_OK assert req.status == HTTPStatus.OK
state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])) state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]))
assert state.state == "not_home" assert state.state == "not_home"

View File

@ -2,6 +2,7 @@
# pylint: disable=protected-access,invalid-name # pylint: disable=protected-access,invalid-name
import collections import collections
from datetime import datetime, timedelta from datetime import datetime, timedelta
from http import HTTPStatus
import json import json
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
@ -314,7 +315,7 @@ async def test_logbook_view(hass, hass_client):
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done) await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client() client = await hass_client()
response = await client.get(f"/api/logbook/{dt_util.utcnow().isoformat()}") response = await client.get(f"/api/logbook/{dt_util.utcnow().isoformat()}")
assert response.status == 200 assert response.status == HTTPStatus.OK
async def test_logbook_view_period_entity(hass, hass_client): async def test_logbook_view_period_entity(hass, hass_client):
@ -341,7 +342,7 @@ async def test_logbook_view_period_entity(hass, hass_client):
# Test today entries without filters # Test today entries without filters
response = await client.get(f"/api/logbook/{start_date.isoformat()}") response = await client.get(f"/api/logbook/{start_date.isoformat()}")
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 2 assert len(response_json) == 2
assert response_json[0]["entity_id"] == entity_id_test assert response_json[0]["entity_id"] == entity_id_test
@ -349,7 +350,7 @@ async def test_logbook_view_period_entity(hass, hass_client):
# Test today entries with filter by period # Test today entries with filter by period
response = await client.get(f"/api/logbook/{start_date.isoformat()}?period=1") response = await client.get(f"/api/logbook/{start_date.isoformat()}?period=1")
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 2 assert len(response_json) == 2
assert response_json[0]["entity_id"] == entity_id_test assert response_json[0]["entity_id"] == entity_id_test
@ -359,7 +360,7 @@ async def test_logbook_view_period_entity(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/logbook/{start_date.isoformat()}?entity=switch.test" f"/api/logbook/{start_date.isoformat()}?entity=switch.test"
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 1 assert len(response_json) == 1
assert response_json[0]["entity_id"] == entity_id_test assert response_json[0]["entity_id"] == entity_id_test
@ -368,7 +369,7 @@ async def test_logbook_view_period_entity(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/logbook/{start_date.isoformat()}?period=3&entity=switch.test" f"/api/logbook/{start_date.isoformat()}?period=3&entity=switch.test"
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 1 assert len(response_json) == 1
assert response_json[0]["entity_id"] == entity_id_test assert response_json[0]["entity_id"] == entity_id_test
@ -379,7 +380,7 @@ async def test_logbook_view_period_entity(hass, hass_client):
# Test tomorrow entries without filters # Test tomorrow entries without filters
response = await client.get(f"/api/logbook/{start_date.isoformat()}") response = await client.get(f"/api/logbook/{start_date.isoformat()}")
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 0 assert len(response_json) == 0
@ -387,7 +388,7 @@ async def test_logbook_view_period_entity(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/logbook/{start_date.isoformat()}?entity=switch.test" f"/api/logbook/{start_date.isoformat()}?entity=switch.test"
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 0 assert len(response_json) == 0
@ -395,7 +396,7 @@ async def test_logbook_view_period_entity(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/logbook/{start_date.isoformat()}?period=3&entity=switch.test" f"/api/logbook/{start_date.isoformat()}?period=3&entity=switch.test"
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 1 assert len(response_json) == 1
assert response_json[0]["entity_id"] == entity_id_test assert response_json[0]["entity_id"] == entity_id_test
@ -539,7 +540,7 @@ async def test_logbook_view_end_time_entity(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/logbook/{start_date.isoformat()}?end_time={end_time}" f"/api/logbook/{start_date.isoformat()}?end_time={end_time}"
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 2 assert len(response_json) == 2
assert response_json[0]["entity_id"] == entity_id_test assert response_json[0]["entity_id"] == entity_id_test
@ -550,7 +551,7 @@ async def test_logbook_view_end_time_entity(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/logbook/{start_date.isoformat()}?end_time={end_time}&entity=switch.test" f"/api/logbook/{start_date.isoformat()}?end_time={end_time}&entity=switch.test"
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 1 assert len(response_json) == 1
assert response_json[0]["entity_id"] == entity_id_test assert response_json[0]["entity_id"] == entity_id_test
@ -564,7 +565,7 @@ async def test_logbook_view_end_time_entity(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/logbook/{start_date.isoformat()}?end_time={end_time}&entity=switch.test" f"/api/logbook/{start_date.isoformat()}?end_time={end_time}&entity=switch.test"
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 1 assert len(response_json) == 1
assert response_json[0]["entity_id"] == entity_id_test assert response_json[0]["entity_id"] == entity_id_test
@ -611,7 +612,7 @@ async def test_logbook_entity_filter_with_automations(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/logbook/{start_date.isoformat()}?end_time={end_time}" f"/api/logbook/{start_date.isoformat()}?end_time={end_time}"
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
json_dict = await response.json() json_dict = await response.json()
assert json_dict[0]["entity_id"] == entity_id_test assert json_dict[0]["entity_id"] == entity_id_test
@ -625,7 +626,7 @@ async def test_logbook_entity_filter_with_automations(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/logbook/{start_date.isoformat()}?end_time={end_time}&entity=alarm_control_panel.area_001" f"/api/logbook/{start_date.isoformat()}?end_time={end_time}&entity=alarm_control_panel.area_001"
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
json_dict = await response.json() json_dict = await response.json()
assert len(json_dict) == 1 assert len(json_dict) == 1
assert json_dict[0]["entity_id"] == entity_id_test assert json_dict[0]["entity_id"] == entity_id_test
@ -639,7 +640,7 @@ async def test_logbook_entity_filter_with_automations(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/logbook/{start_date.isoformat()}?end_time={end_time}&entity=alarm_control_panel.area_002" f"/api/logbook/{start_date.isoformat()}?end_time={end_time}&entity=alarm_control_panel.area_002"
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
json_dict = await response.json() json_dict = await response.json()
assert len(json_dict) == 1 assert len(json_dict) == 1
assert json_dict[0]["entity_id"] == entity_id_second assert json_dict[0]["entity_id"] == entity_id_second
@ -673,7 +674,7 @@ async def test_filter_continuous_sensor_values(hass, hass_client):
# Test today entries without filters # Test today entries without filters
response = await client.get(f"/api/logbook/{start_date.isoformat()}") response = await client.get(f"/api/logbook/{start_date.isoformat()}")
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 2 assert len(response_json) == 2
@ -707,7 +708,7 @@ async def test_exclude_new_entities(hass, hass_client):
# Test today entries without filters # Test today entries without filters
response = await client.get(f"/api/logbook/{start_date.isoformat()}") response = await client.get(f"/api/logbook/{start_date.isoformat()}")
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 2 assert len(response_json) == 2
@ -748,7 +749,7 @@ async def test_exclude_removed_entities(hass, hass_client):
# Test today entries without filters # Test today entries without filters
response = await client.get(f"/api/logbook/{start_date.isoformat()}") response = await client.get(f"/api/logbook/{start_date.isoformat()}")
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 3 assert len(response_json) == 3
@ -787,7 +788,7 @@ async def test_exclude_attribute_changes(hass, hass_client):
# Test today entries without filters # Test today entries without filters
response = await client.get(f"/api/logbook/{start_date.isoformat()}") response = await client.get(f"/api/logbook/{start_date.isoformat()}")
assert response.status == 200 assert response.status == HTTPStatus.OK
response_json = await response.json() response_json = await response.json()
assert len(response_json) == 3 assert len(response_json) == 3
@ -904,7 +905,7 @@ async def test_logbook_entity_context_id(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/logbook/{start_date.isoformat()}?end_time={end_time}" f"/api/logbook/{start_date.isoformat()}?end_time={end_time}"
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
json_dict = await response.json() json_dict = await response.json()
assert json_dict[0]["entity_id"] == "automation.alarm" assert json_dict[0]["entity_id"] == "automation.alarm"
@ -1077,7 +1078,7 @@ async def test_logbook_entity_context_parent_id(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/logbook/{start_date.isoformat()}?end_time={end_time}" f"/api/logbook/{start_date.isoformat()}?end_time={end_time}"
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
json_dict = await response.json() json_dict = await response.json()
assert json_dict[0]["entity_id"] == "automation.alarm" assert json_dict[0]["entity_id"] == "automation.alarm"
@ -1192,7 +1193,7 @@ async def test_logbook_context_from_template(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/logbook/{start_date.isoformat()}?end_time={end_time}" f"/api/logbook/{start_date.isoformat()}?end_time={end_time}"
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
json_dict = await response.json() json_dict = await response.json()
assert json_dict[0]["domain"] == "homeassistant" assert json_dict[0]["domain"] == "homeassistant"
@ -1278,7 +1279,7 @@ async def test_logbook_entity_matches_only(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/logbook/{start_date.isoformat()}?end_time={end_time}&entity=switch.test_state&entity_matches_only" f"/api/logbook/{start_date.isoformat()}?end_time={end_time}&entity=switch.test_state&entity_matches_only"
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
json_dict = await response.json() json_dict = await response.json()
assert len(json_dict) == 2 assert len(json_dict) == 2
@ -1318,7 +1319,7 @@ async def test_custom_log_entry_discoverable_via_entity_matches_only(hass, hass_
response = await client.get( response = await client.get(
f"/api/logbook/{start_date.isoformat()}?end_time={end_time.isoformat()}&entity=switch.test_switch&entity_matches_only" f"/api/logbook/{start_date.isoformat()}?end_time={end_time.isoformat()}&entity=switch.test_switch&entity_matches_only"
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
json_dict = await response.json() json_dict = await response.json()
assert len(json_dict) == 1 assert len(json_dict) == 1
@ -1396,7 +1397,7 @@ async def test_logbook_entity_matches_only_multiple(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/logbook/{start_date.isoformat()}?end_time={end_time}&entity=switch.test_state,light.test_state&entity_matches_only" f"/api/logbook/{start_date.isoformat()}?end_time={end_time}&entity=switch.test_state,light.test_state&entity_matches_only"
) )
assert response.status == 200 assert response.status == HTTPStatus.OK
json_dict = await response.json() json_dict = await response.json()
assert len(json_dict) == 4 assert len(json_dict) == 4
@ -1428,7 +1429,7 @@ async def test_logbook_invalid_entity(hass, hass_client):
response = await client.get( response = await client.get(
f"/api/logbook/{start_date.isoformat()}?end_time={end_time}&entity=invalid&entity_matches_only" f"/api/logbook/{start_date.isoformat()}?end_time={end_time}&entity=invalid&entity_matches_only"
) )
assert response.status == 500 assert response.status == HTTPStatus.INTERNAL_SERVER_ERROR
async def test_icon_and_state(hass, hass_client): async def test_icon_and_state(hass, hass_client):
@ -1870,7 +1871,7 @@ async def test_context_filter(hass, hass_client):
response = await client.get( response = await client.get(
"/api/logbook", params={"context_id": context.id, "entity": entity_id} "/api/logbook", params={"context_id": context.id, "entity": entity_id}
) )
assert response.status == 400 assert response.status == HTTPStatus.BAD_REQUEST
async def _async_fetch_logbook(client, params=None): async def _async_fetch_logbook(client, params=None):
@ -1886,7 +1887,7 @@ async def _async_fetch_logbook(client, params=None):
# Test today entries without filters # Test today entries without filters
response = await client.get(f"/api/logbook/{start_date.isoformat()}", params=params) response = await client.get(f"/api/logbook/{start_date.isoformat()}", params=params)
assert response.status == 200 assert response.status == HTTPStatus.OK
return await response.json() return await response.json()

View File

@ -1,5 +1,6 @@
"""Tests for Logi Circle config flow.""" """Tests for Logi Circle config flow."""
import asyncio import asyncio
from http import HTTPStatus
from unittest.mock import AsyncMock, Mock, patch from unittest.mock import AsyncMock, Mock, patch
import pytest import pytest
@ -203,7 +204,7 @@ async def test_callback_view_rejects_missing_code(hass):
view = LogiCircleAuthCallbackView() view = LogiCircleAuthCallbackView()
resp = await view.get(MockRequest(hass, {})) resp = await view.get(MockRequest(hass, {}))
assert resp.status == 400 assert resp.status == HTTPStatus.BAD_REQUEST
async def test_callback_view_accepts_code( async def test_callback_view_accepts_code(
@ -214,7 +215,7 @@ async def test_callback_view_accepts_code(
view = LogiCircleAuthCallbackView() view = LogiCircleAuthCallbackView()
resp = await view.get(MockRequest(hass, {"code": "456"})) resp = await view.get(MockRequest(hass, {"code": "456"}))
assert resp.status == 200 assert resp.status == HTTPStatus.OK
await hass.async_block_till_done() await hass.async_block_till_done()
mock_logi_circle.authorize.assert_called_with("456") mock_logi_circle.authorize.assert_called_with("456")

View File

@ -1,6 +1,7 @@
"""The tests for the london_air platform.""" """The tests for the london_air platform."""
from http import HTTPStatus
from homeassistant.components.london_air.sensor import CONF_LOCATIONS, URL from homeassistant.components.london_air.sensor import CONF_LOCATIONS, URL
from homeassistant.const import HTTP_OK, HTTP_SERVICE_UNAVAILABLE
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import load_fixture from tests.common import load_fixture
@ -10,7 +11,9 @@ VALID_CONFIG = {"sensor": {"platform": "london_air", CONF_LOCATIONS: ["Merton"]}
async def test_valid_state(hass, requests_mock): async def test_valid_state(hass, requests_mock):
"""Test for operational london_air sensor with proper attributes.""" """Test for operational london_air sensor with proper attributes."""
requests_mock.get(URL, text=load_fixture("london_air.json"), status_code=HTTP_OK) requests_mock.get(
URL, text=load_fixture("london_air.json"), status_code=HTTPStatus.OK
)
assert await async_setup_component(hass, "sensor", VALID_CONFIG) assert await async_setup_component(hass, "sensor", VALID_CONFIG)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -41,7 +44,7 @@ async def test_valid_state(hass, requests_mock):
async def test_api_failure(hass, requests_mock): async def test_api_failure(hass, requests_mock):
"""Test for failure in the API.""" """Test for failure in the API."""
requests_mock.get(URL, status_code=HTTP_SERVICE_UNAVAILABLE) requests_mock.get(URL, status_code=HTTPStatus.SERVICE_UNAVAILABLE)
assert await async_setup_component(hass, "sensor", VALID_CONFIG) assert await async_setup_component(hass, "sensor", VALID_CONFIG)
await hass.async_block_till_done() await hass.async_block_till_done()

View File

@ -1,5 +1,6 @@
"""Test the Honeywell Lyric config flow.""" """Test the Honeywell Lyric config flow."""
import asyncio import asyncio
from http import HTTPStatus
from unittest.mock import patch from unittest.mock import patch
import pytest import pytest
@ -79,7 +80,7 @@ async def test_full_flow(
client = await hass_client_no_auth() client = await hass_client_no_auth()
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == 200 assert resp.status == HTTPStatus.OK
assert resp.headers["content-type"] == "text/html; charset=utf-8" assert resp.headers["content-type"] == "text/html; charset=utf-8"
aioclient_mock.post( aioclient_mock.post(