Python 3.10 support cleanups (#98640)

This commit is contained in:
Ville Skyttä 2023-08-21 20:14:07 +03:00 committed by GitHub
parent faf0f5f19b
commit 2399cd283a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
31 changed files with 75 additions and 103 deletions

View file

@ -2,7 +2,7 @@
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from datetime import UTC, datetime, timedelta
import logging
from typing import final
@ -110,7 +110,7 @@ class DateTimeEntity(Entity):
"which is missing timezone information"
)
return value.astimezone(timezone.utc).isoformat(timespec="seconds")
return value.astimezone(UTC).isoformat(timespec="seconds")
@property
def native_value(self) -> datetime | None:

View file

@ -1,7 +1,7 @@
"""Demo platform that offers a fake date/time entity."""
from __future__ import annotations
from datetime import datetime, timezone
from datetime import UTC, datetime
from homeassistant.components.datetime import DateTimeEntity
from homeassistant.config_entries import ConfigEntry
@ -23,7 +23,7 @@ async def async_setup_entry(
DemoDateTime(
"datetime",
"Date and Time",
datetime(2020, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
datetime(2020, 1, 1, 12, 0, 0, tzinfo=UTC),
"mdi:calendar-clock",
False,
),

View file

@ -2,7 +2,7 @@
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from datetime import UTC, datetime, timedelta
from gardena_bluetooth.const import Battery, Valve
from gardena_bluetooth.parse import Characteristic
@ -106,7 +106,7 @@ class GardenaBluetoothRemainSensor(GardenaBluetoothEntity, SensorEntity):
super()._handle_coordinator_update()
return
time = datetime.now(timezone.utc) + timedelta(seconds=value)
time = datetime.now(UTC) + timedelta(seconds=value)
if not self._attr_native_value:
self._attr_native_value = time
super()._handle_coordinator_update()

View file

@ -1,7 +1,7 @@
"""Support for Google Mail Sensors."""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from datetime import UTC, datetime, timedelta
from googleapiclient.http import HttpRequest
@ -46,7 +46,7 @@ class GoogleMailSensor(GoogleMailEntity, SensorEntity):
data: dict = await self.hass.async_add_executor_job(settings.execute)
if data["enableAutoReply"] and (end := data.get("endTime")):
value = datetime.fromtimestamp(int(end) / 1000, tz=timezone.utc)
value = datetime.fromtimestamp(int(end) / 1000, tz=UTC)
else:
value = None
self._attr_native_value = value

View file

@ -4,7 +4,7 @@ from __future__ import annotations
from collections.abc import Callable
from copy import deepcopy
from dataclasses import dataclass
from datetime import datetime, timezone
from datetime import UTC, datetime
from typing import Any, Generic
from aiopyarr import Diskspace, RootFolder, SystemStatus
@ -88,7 +88,7 @@ SENSOR_TYPES: dict[str, RadarrSensorEntityDescription[Any]] = {
device_class=SensorDeviceClass.TIMESTAMP,
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
value_fn=lambda data, _: data.startTime.replace(tzinfo=timezone.utc),
value_fn=lambda data, _: data.startTime.replace(tzinfo=UTC),
),
}

View file

@ -5,12 +5,10 @@ import asyncio
from collections.abc import Mapping
from contextlib import suppress
from dataclasses import dataclass
from datetime import date, datetime, timedelta, timezone
from datetime import UTC, date, datetime, timedelta
from decimal import Decimal, InvalidOperation as DecimalInvalidOperation
import logging
from math import ceil, floor, log10
import re
import sys
from typing import Any, Final, Self, cast, final
from homeassistant.config_entries import ConfigEntry
@ -89,10 +87,6 @@ _LOGGER: Final = logging.getLogger(__name__)
ENTITY_ID_FORMAT: Final = DOMAIN + ".{}"
NEGATIVE_ZERO_PATTERN = re.compile(r"^-(0\.?0*)$")
PY_311 = sys.version_info >= (3, 11, 0)
SCAN_INTERVAL: Final = timedelta(seconds=30)
__all__ = [
@ -534,8 +528,8 @@ class SensorEntity(Entity):
"which is missing timezone information"
)
if value.tzinfo != timezone.utc:
value = value.astimezone(timezone.utc)
if value.tzinfo != UTC:
value = value.astimezone(UTC)
return value.isoformat(timespec="seconds")
except (AttributeError, OverflowError, TypeError) as err:
@ -636,12 +630,7 @@ class SensorEntity(Entity):
)
precision = precision + floor(ratio_log)
if PY_311:
value = f"{converted_numerical_value:z.{precision}f}"
else:
value = f"{converted_numerical_value:.{precision}f}"
if value.startswith("-0") and NEGATIVE_ZERO_PATTERN.match(value):
value = value[1:]
value = f"{converted_numerical_value:z.{precision}f}"
else:
value = converted_numerical_value
@ -903,11 +892,6 @@ def async_rounded_state(hass: HomeAssistant, entity_id: str, state: State) -> st
with suppress(TypeError, ValueError):
numerical_value = float(value)
if PY_311:
value = f"{numerical_value:z.{precision}f}"
else:
value = f"{numerical_value:.{precision}f}"
if value.startswith("-0") and NEGATIVE_ZERO_PATTERN.match(value):
value = value[1:]
value = f"{numerical_value:z.{precision}f}"
return value

View file

@ -3,7 +3,7 @@ from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from datetime import UTC, datetime, timedelta
from typing import Final, cast
from homeassistant.components.sensor import (
@ -146,9 +146,7 @@ BASE_SENSOR_TYPES: tuple[SystemBridgeSensorEntityDescription, ...] = (
name="Boot time",
device_class=SensorDeviceClass.TIMESTAMP,
icon="mdi:av-timer",
value=lambda data: datetime.fromtimestamp(
data.system.boot_time, tz=timezone.utc
),
value=lambda data: datetime.fromtimestamp(data.system.boot_time, tz=UTC),
),
SystemBridgeSensorEntityDescription(
key="cpu_power_package",

View file

@ -3,7 +3,7 @@ from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime, timezone
from datetime import UTC, datetime
from typing import cast
from whois import Domain
@ -55,7 +55,7 @@ def _ensure_timezone(timestamp: datetime | None) -> datetime | None:
# If timezone info isn't provided by the Whois, assume UTC.
if timestamp.tzinfo is None:
return timestamp.replace(tzinfo=timezone.utc)
return timestamp.replace(tzinfo=UTC)
return timestamp

View file

@ -4,7 +4,6 @@ from __future__ import annotations
import enum
import functools
import numbers
import sys
from typing import TYPE_CHECKING, Any, Self
from zigpy import types
@ -485,7 +484,7 @@ class SmartEnergyMetering(Sensor):
if self._cluster_handler.device_type is not None:
attrs["device_type"] = self._cluster_handler.device_type
if (status := self._cluster_handler.status) is not None:
if isinstance(status, enum.IntFlag) and sys.version_info >= (3, 11):
if isinstance(status, enum.IntFlag):
attrs["status"] = str(
status.name if status.name is not None else status.value
)

View file

@ -21,9 +21,7 @@ _P = ParamSpec("_P")
def cancelling(task: Future[Any]) -> bool:
"""Return True if task is done or cancelling."""
# https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancelling
# is new in Python 3.11
"""Return True if task is cancelling."""
return bool((cancelling_ := getattr(task, "cancelling", None)) and cancelling_())

View file

@ -14,8 +14,8 @@ import zoneinfo
import ciso8601
DATE_STR_FORMAT = "%Y-%m-%d"
UTC = dt.timezone.utc
DEFAULT_TIME_ZONE: dt.tzinfo = dt.timezone.utc
UTC = dt.UTC
DEFAULT_TIME_ZONE: dt.tzinfo = dt.UTC
CLOCK_MONOTONIC_COARSE = 6
# EPOCHORDINAL is not exposed as a constant

View file

@ -521,8 +521,6 @@ filterwarnings = [
]
[tool.ruff]
target-version = "py310"
select = [
"B002", # Python does not support the unary prefix increment
"B007", # Loop control variable {name} not used within loop body

View file

@ -9,9 +9,8 @@ from pathlib import Path
import pkgutil
import re
import sys
from typing import Any
import tomllib
from typing import Any
from homeassistant.util.yaml.loader import load_yaml
from script.hassfest.model import Integration

View file

@ -5,7 +5,7 @@ import asyncio
from collections import OrderedDict
from collections.abc import Generator, Mapping, Sequence
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
from datetime import UTC, datetime, timedelta
import functools as ft
from functools import lru_cache
from io import StringIO
@ -384,7 +384,7 @@ def async_fire_time_changed_exact(
approach, as this is only for testing.
"""
if datetime_ is None:
utc_datetime = datetime.now(timezone.utc)
utc_datetime = datetime.now(UTC)
else:
utc_datetime = dt_util.as_utc(datetime_)
@ -406,7 +406,7 @@ def async_fire_time_changed(
for an exact microsecond, use async_fire_time_changed_exact.
"""
if datetime_ is None:
utc_datetime = datetime.now(timezone.utc)
utc_datetime = datetime.now(UTC)
else:
utc_datetime = dt_util.as_utc(datetime_)

View file

@ -1,5 +1,5 @@
"""The tests for the datetime component."""
from datetime import datetime, timezone
from datetime import UTC, datetime
from zoneinfo import ZoneInfo
import pytest
@ -14,7 +14,7 @@ from homeassistant.const import ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, CONF_PLATFOR
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
DEFAULT_VALUE = datetime(2020, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
DEFAULT_VALUE = datetime(2020, 1, 1, 12, 0, 0, tzinfo=UTC)
class MockDateTimeEntity(DateTimeEntity):

View file

@ -1,5 +1,5 @@
"""Test Environment Canada diagnostics."""
from datetime import datetime, timezone
from datetime import UTC, datetime
import json
from unittest.mock import AsyncMock, MagicMock, patch
@ -43,7 +43,7 @@ async def init_integration(hass: HomeAssistant) -> MockConfigEntry:
)
weather_mock = mock_ec()
ec_data["metadata"]["timestamp"] = datetime(2022, 10, 4, tzinfo=timezone.utc)
ec_data["metadata"]["timestamp"] = datetime(2022, 10, 4, tzinfo=UTC)
weather_mock.conditions = ec_data["conditions"]
weather_mock.alerts = ec_data["alerts"]
weather_mock.daily_forecasts = ec_data["daily_forecasts"]
@ -51,7 +51,7 @@ async def init_integration(hass: HomeAssistant) -> MockConfigEntry:
radar_mock = mock_ec()
radar_mock.image = b"GIF..."
radar_mock.timestamp = datetime(2022, 10, 4, tzinfo=timezone.utc)
radar_mock.timestamp = datetime(2022, 10, 4, tzinfo=UTC)
with patch(
"homeassistant.components.environment_canada.ECWeather",

View file

@ -1,5 +1,5 @@
"""Test forecast solar energy platform."""
from datetime import datetime, timezone
from datetime import UTC, datetime
from unittest.mock import MagicMock
from homeassistant.components.forecast_solar import energy
@ -16,8 +16,8 @@ async def test_energy_solar_forecast(
) -> None:
"""Test the Forecast.Solar energy platform solar forecast."""
mock_forecast_solar.estimate.return_value.wh_period = {
datetime(2021, 6, 27, 13, 0, tzinfo=timezone.utc): 12,
datetime(2021, 6, 27, 14, 0, tzinfo=timezone.utc): 8,
datetime(2021, 6, 27, 13, 0, tzinfo=UTC): 12,
datetime(2021, 6, 27, 14, 0, tzinfo=UTC): 8,
}
mock_config_entry.add_to_hass(hass)

View file

@ -1,5 +1,5 @@
"""Test Google http services."""
from datetime import datetime, timedelta, timezone
from datetime import UTC, datetime, timedelta
from http import HTTPStatus
from typing import Any
from unittest.mock import ANY, patch
@ -51,7 +51,7 @@ async def test_get_jwt(hass: HomeAssistant) -> None:
jwt = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJkdW1teUBkdW1teS5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbSIsInNjb3BlIjoiaHR0cHM6Ly93d3cuZ29vZ2xlYXBpcy5jb20vYXV0aC9ob21lZ3JhcGgiLCJhdWQiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20vby9vYXV0aDIvdG9rZW4iLCJpYXQiOjE1NzEwMTEyMDAsImV4cCI6MTU3MTAxNDgwMH0.akHbMhOflXdIDHVvUVwO0AoJONVOPUdCghN6hAdVz4gxjarrQeGYc_Qn2r84bEvCU7t6EvimKKr0fyupyzBAzfvKULs5mTHO3h2CwSgvOBMv8LnILboJmbO4JcgdnRV7d9G3ktQs7wWSCXJsI5i5jUr1Wfi9zWwxn2ebaAAgrp8"
res = _get_homegraph_jwt(
datetime(2019, 10, 14, tzinfo=timezone.utc),
datetime(2019, 10, 14, tzinfo=UTC),
DUMMY_CONFIG["service_account"]["client_email"],
DUMMY_CONFIG["service_account"]["private_key"],
)
@ -85,7 +85,7 @@ async def test_update_access_token(hass: HomeAssistant) -> None:
config = GoogleConfig(hass, DUMMY_CONFIG)
await config.async_initialize()
base_time = datetime(2019, 10, 14, tzinfo=timezone.utc)
base_time = datetime(2019, 10, 14, tzinfo=UTC)
with patch(
"homeassistant.components.google_assistant.http._get_homegraph_token"
) as mock_get_token, patch(

View file

@ -143,7 +143,7 @@ async def test_plant_topology_reduction_change(
return_value=mock_modules,
) as mock_check:
async_fire_time_changed(
hass, dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=400)
hass, dt.datetime.now(dt.UTC) + dt.timedelta(seconds=400)
)
await hass.async_block_till_done()
assert len(mock_check.mock_calls) == 1
@ -205,7 +205,7 @@ async def test_plant_topology_increase_change(
return_value=mock_modules,
) as mock_check:
async_fire_time_changed(
hass, dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=400)
hass, dt.datetime.now(dt.UTC) + dt.timedelta(seconds=400)
)
await hass.async_block_till_done()
assert len(mock_check.mock_calls) == 1
@ -267,7 +267,7 @@ async def test_module_status_unavailable(
return_value=mock_modules,
) as mock_check:
async_fire_time_changed(
hass, dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=400)
hass, dt.datetime.now(dt.UTC) + dt.timedelta(seconds=400)
)
await hass.async_block_till_done()
assert len(mock_check.mock_calls) == 1
@ -338,7 +338,7 @@ async def test_module_status_available(
return_value=mock_modules,
) as mock_check:
async_fire_time_changed(
hass, dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=400)
hass, dt.datetime.now(dt.UTC) + dt.timedelta(seconds=400)
)
await hass.async_block_till_done()
assert len(mock_check.mock_calls) == 1
@ -442,7 +442,7 @@ async def test_update_with_api_error(
side_effect=HomePlusControlApiError,
) as mock_check:
async_fire_time_changed(
hass, dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=400)
hass, dt.datetime.now(dt.UTC) + dt.timedelta(seconds=400)
)
await hass.async_block_till_done()
assert len(mock_check.mock_calls) == 1

View file

@ -1,6 +1,6 @@
"""Tests for the IPMA component."""
from collections import namedtuple
from datetime import datetime, timezone
from datetime import UTC, datetime
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_MODE, CONF_NAME
@ -87,7 +87,7 @@ class MockLocation:
return [
Forecast(
"7.7",
datetime(2020, 1, 15, 1, 0, 0, tzinfo=timezone.utc),
datetime(2020, 1, 15, 1, 0, 0, tzinfo=UTC),
1,
"86.9",
12.0,
@ -101,7 +101,7 @@ class MockLocation:
),
Forecast(
"5.7",
datetime(2020, 1, 15, 2, 0, 0, tzinfo=timezone.utc),
datetime(2020, 1, 15, 2, 0, 0, tzinfo=UTC),
1,
"86.9",
12.0,

View file

@ -2,7 +2,7 @@
from __future__ import annotations
from collections.abc import Generator
from datetime import datetime, time, timedelta, timezone
from datetime import UTC, datetime, time, timedelta
from unittest.mock import AsyncMock, patch
from melnor_bluetooth.device import Device
@ -73,7 +73,7 @@ class MockFrequency:
self._interval = 0
self._is_watering = False
self._start_time = time(12, 0)
self._next_run_time = datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc)
self._next_run_time = datetime(2021, 1, 1, 12, 0, tzinfo=UTC)
@property
def duration_minutes(self) -> int:

View file

@ -1,5 +1,5 @@
"""The tests for Octoptint binary sensor module."""
from datetime import datetime, timezone
from datetime import UTC, datetime
from unittest.mock import patch
from homeassistant.core import HomeAssistant
@ -24,7 +24,7 @@ async def test_sensors(hass: HomeAssistant) -> None:
}
with patch(
"homeassistant.util.dt.utcnow",
return_value=datetime(2020, 2, 20, 9, 10, 13, 543, tzinfo=timezone.utc),
return_value=datetime(2020, 2, 20, 9, 10, 13, 543, tzinfo=UTC),
):
await init_integration(hass, "sensor", printer=printer, job=job)

View file

@ -1,6 +1,6 @@
"""Test Prusalink sensors."""
from datetime import datetime, timezone
from datetime import UTC, datetime
from unittest.mock import PropertyMock, patch
import pytest
@ -125,7 +125,7 @@ async def test_sensors_active_job(
"""Test sensors while active job."""
with patch(
"homeassistant.components.prusalink.sensor.utcnow",
return_value=datetime(2022, 8, 27, 14, 0, 0, tzinfo=timezone.utc),
return_value=datetime(2022, 8, 27, 14, 0, 0, tzinfo=UTC),
):
assert await async_setup_component(hass, "prusalink", {})

View file

@ -1,6 +1,6 @@
"""Test util methods."""
from collections.abc import Callable
from datetime import datetime, timedelta, timezone
from datetime import UTC, datetime, timedelta
import os
from pathlib import Path
import sqlite3
@ -948,7 +948,7 @@ def test_execute_stmt_lambda_element(
assert rows == ["mock_row"]
@pytest.mark.freeze_time(datetime(2022, 10, 21, 7, 25, tzinfo=timezone.utc))
@pytest.mark.freeze_time(datetime(2022, 10, 21, 7, 25, tzinfo=UTC))
async def test_resolve_period(hass: HomeAssistant) -> None:
"""Test statistic_during_period."""

View file

@ -2,7 +2,7 @@
from __future__ import annotations
from collections.abc import Generator
from datetime import date, datetime, timezone
from datetime import UTC, date, datetime
from decimal import Decimal
from typing import Any
@ -177,7 +177,7 @@ async def test_datetime_conversion(
enable_custom_integrations: None,
) -> None:
"""Test conversion of datetime."""
test_timestamp = datetime(2017, 12, 19, 18, 29, 42, tzinfo=timezone.utc)
test_timestamp = datetime(2017, 12, 19, 18, 29, 42, tzinfo=UTC)
test_local_timestamp = test_timestamp.astimezone(
dt_util.get_time_zone("Europe/Amsterdam")
)
@ -233,7 +233,7 @@ async def test_a_sensor_with_a_non_numeric_device_class(
A non numeric sensor with a valid device class should never be
handled as numeric because it has a device class.
"""
test_timestamp = datetime(2017, 12, 19, 18, 29, 42, tzinfo=timezone.utc)
test_timestamp = datetime(2017, 12, 19, 18, 29, 42, tzinfo=UTC)
test_local_timestamp = test_timestamp.astimezone(
dt_util.get_time_zone("Europe/Amsterdam")
)
@ -334,7 +334,7 @@ RESTORE_DATA = {
"native_unit_of_measurement": None,
"native_value": {
"__type": "<class 'datetime.datetime'>",
"isoformat": datetime(2020, 2, 8, 15, tzinfo=timezone.utc).isoformat(),
"isoformat": datetime(2020, 2, 8, 15, tzinfo=UTC).isoformat(),
},
},
"Decimal": {
@ -375,7 +375,7 @@ RESTORE_DATA = {
),
(date(2020, 2, 8), dict, RESTORE_DATA["date"], SensorDeviceClass.DATE, None),
(
datetime(2020, 2, 8, 15, tzinfo=timezone.utc),
datetime(2020, 2, 8, 15, tzinfo=UTC),
dict,
RESTORE_DATA["datetime"],
SensorDeviceClass.TIMESTAMP,
@ -433,7 +433,7 @@ async def test_restore_sensor_save_state(
(123.0, float, RESTORE_DATA["float"], SensorDeviceClass.TEMPERATURE, "°F"),
(date(2020, 2, 8), date, RESTORE_DATA["date"], SensorDeviceClass.DATE, None),
(
datetime(2020, 2, 8, 15, tzinfo=timezone.utc),
datetime(2020, 2, 8, 15, tzinfo=UTC),
datetime,
RESTORE_DATA["datetime"],
SensorDeviceClass.TIMESTAMP,

View file

@ -1,6 +1,6 @@
"""Sample API response data for tests."""
from datetime import datetime, timezone
from datetime import UTC, datetime
from homeassistant.components.subaru.const import (
API_GEN_1,
@ -58,7 +58,7 @@ VEHICLE_DATA = {
},
}
MOCK_DATETIME = datetime.fromtimestamp(1595560000, timezone.utc)
MOCK_DATETIME = datetime.fromtimestamp(1595560000, UTC)
VEHICLE_STATUS_EV = {
VEHICLE_STATUS: {

View file

@ -1,5 +1,5 @@
"""The tests for the Template Binary sensor platform."""
from datetime import datetime, timedelta, timezone
from datetime import UTC, datetime, timedelta
import logging
from unittest.mock import patch
@ -1276,9 +1276,7 @@ async def test_trigger_entity_restore_state_auto_off(
fake_extra_data = {
"auto_off_time": {
"__type": "<class 'datetime.datetime'>",
"isoformat": datetime(
2022, 2, 2, 12, 2, 2, tzinfo=timezone.utc
).isoformat(),
"isoformat": datetime(2022, 2, 2, 12, 2, 2, tzinfo=UTC).isoformat(),
},
}
mock_restore_cache_with_extra_data(hass, ((fake_state, fake_extra_data),))
@ -1336,9 +1334,7 @@ async def test_trigger_entity_restore_state_auto_off_expired(
fake_extra_data = {
"auto_off_time": {
"__type": "<class 'datetime.datetime'>",
"isoformat": datetime(
2022, 2, 2, 12, 2, 0, tzinfo=timezone.utc
).isoformat(),
"isoformat": datetime(2022, 2, 2, 12, 2, 0, tzinfo=UTC).isoformat(),
},
}
mock_restore_cache_with_extra_data(hass, ((fake_state, fake_extra_data),))

View file

@ -97,7 +97,7 @@ async def test_all_optional_config(hass: HomeAssistant, calls) -> None:
_TEST_OPTIONS_BUTTON,
)
now = dt.datetime.now(dt.timezone.utc)
now = dt.datetime.now(dt.UTC)
with patch("homeassistant.util.dt.utcnow", return_value=now):
await hass.services.async_call(

View file

@ -1,5 +1,5 @@
"""The tests for UVC camera module."""
from datetime import datetime, timedelta, timezone
from datetime import UTC, datetime, timedelta
from unittest.mock import call, patch
import pytest
@ -368,7 +368,7 @@ async def test_motion_recording_mode_properties(
assert state
assert state.state != STATE_RECORDING
assert state.attributes["last_recording_start_time"] == datetime(
2021, 1, 8, 1, 56, 32, 367000, tzinfo=timezone.utc
2021, 1, 8, 1, 56, 32, 367000, tzinfo=UTC
)
mock_remote.return_value.get_camera.return_value["recordingIndicator"] = "DISABLED"

View file

@ -1,5 +1,5 @@
"""Test the Whirlpool Sensor domain."""
from datetime import datetime, timezone
from datetime import UTC, datetime
from unittest.mock import MagicMock
import pytest
@ -50,7 +50,7 @@ async def test_dryer_sensor_values(
) -> None:
"""Test the sensor value callbacks."""
hass.state = CoreState.not_running
thetimestamp: datetime = datetime(2022, 11, 29, 00, 00, 00, 00, timezone.utc)
thetimestamp: datetime = datetime(2022, 11, 29, 00, 00, 00, 00, UTC)
mock_restore_cache_with_extra_data(
hass,
(
@ -114,7 +114,7 @@ async def test_washer_sensor_values(
) -> None:
"""Test the sensor value callbacks."""
hass.state = CoreState.not_running
thetimestamp: datetime = datetime(2022, 11, 29, 00, 00, 00, 00, timezone.utc)
thetimestamp: datetime = datetime(2022, 11, 29, 00, 00, 00, 00, UTC)
mock_restore_cache_with_extra_data(
hass,
(
@ -281,7 +281,7 @@ async def test_restore_state(
"""Test sensor restore state."""
# Home assistant is not running yet
hass.state = CoreState.not_running
thetimestamp: datetime = datetime(2022, 11, 29, 00, 00, 00, 00, timezone.utc)
thetimestamp: datetime = datetime(2022, 11, 29, 00, 00, 00, 00, UTC)
mock_restore_cache_with_extra_data(
hass,
(
@ -334,7 +334,7 @@ async def test_callback(
) -> None:
"""Test callback timestamp callback function."""
hass.state = CoreState.not_running
thetimestamp: datetime = datetime(2022, 11, 29, 00, 00, 00, 00, timezone.utc)
thetimestamp: datetime = datetime(2022, 11, 29, 00, 00, 00, 00, UTC)
mock_restore_cache_with_extra_data(
hass,
(

View file

@ -2,7 +2,7 @@
Call init before using it in your tests to ensure clean test data.
"""
from datetime import datetime, timezone
from datetime import UTC, datetime
from homeassistant.components.datetime import DateTimeEntity
@ -37,7 +37,7 @@ def init(empty=False):
MockDateTimeEntity(
name="test",
unique_id=UNIQUE_DATETIME,
native_value=datetime(2020, 1, 1, 1, 2, 3, tzinfo=timezone.utc),
native_value=datetime(2020, 1, 1, 1, 2, 3, tzinfo=UTC),
),
]
)