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

View File

@ -1,7 +1,7 @@
"""Demo platform that offers a fake date/time entity.""" """Demo platform that offers a fake date/time entity."""
from __future__ import annotations from __future__ import annotations
from datetime import datetime, timezone from datetime import UTC, datetime
from homeassistant.components.datetime import DateTimeEntity from homeassistant.components.datetime import DateTimeEntity
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
@ -23,7 +23,7 @@ async def async_setup_entry(
DemoDateTime( DemoDateTime(
"datetime", "datetime",
"Date and Time", "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", "mdi:calendar-clock",
False, False,
), ),

View File

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

View File

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

View File

@ -4,7 +4,7 @@ from __future__ import annotations
from collections.abc import Callable from collections.abc import Callable
from copy import deepcopy from copy import deepcopy
from dataclasses import dataclass from dataclasses import dataclass
from datetime import datetime, timezone from datetime import UTC, datetime
from typing import Any, Generic from typing import Any, Generic
from aiopyarr import Diskspace, RootFolder, SystemStatus from aiopyarr import Diskspace, RootFolder, SystemStatus
@ -88,7 +88,7 @@ SENSOR_TYPES: dict[str, RadarrSensorEntityDescription[Any]] = {
device_class=SensorDeviceClass.TIMESTAMP, device_class=SensorDeviceClass.TIMESTAMP,
entity_category=EntityCategory.DIAGNOSTIC, entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False, 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 collections.abc import Mapping
from contextlib import suppress from contextlib import suppress
from dataclasses import dataclass 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 from decimal import Decimal, InvalidOperation as DecimalInvalidOperation
import logging import logging
from math import ceil, floor, log10 from math import ceil, floor, log10
import re
import sys
from typing import Any, Final, Self, cast, final from typing import Any, Final, Self, cast, final
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
@ -89,10 +87,6 @@ _LOGGER: Final = logging.getLogger(__name__)
ENTITY_ID_FORMAT: Final = DOMAIN + ".{}" 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) SCAN_INTERVAL: Final = timedelta(seconds=30)
__all__ = [ __all__ = [
@ -534,8 +528,8 @@ class SensorEntity(Entity):
"which is missing timezone information" "which is missing timezone information"
) )
if value.tzinfo != timezone.utc: if value.tzinfo != UTC:
value = value.astimezone(timezone.utc) value = value.astimezone(UTC)
return value.isoformat(timespec="seconds") return value.isoformat(timespec="seconds")
except (AttributeError, OverflowError, TypeError) as err: except (AttributeError, OverflowError, TypeError) as err:
@ -636,12 +630,7 @@ class SensorEntity(Entity):
) )
precision = precision + floor(ratio_log) precision = precision + floor(ratio_log)
if PY_311:
value = f"{converted_numerical_value:z.{precision}f}" 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:]
else: else:
value = converted_numerical_value value = converted_numerical_value
@ -903,11 +892,6 @@ def async_rounded_state(hass: HomeAssistant, entity_id: str, state: State) -> st
with suppress(TypeError, ValueError): with suppress(TypeError, ValueError):
numerical_value = float(value) numerical_value = float(value)
if PY_311:
value = f"{numerical_value:z.{precision}f}" 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:]
return value return value

View File

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

View File

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

View File

@ -4,7 +4,6 @@ from __future__ import annotations
import enum import enum
import functools import functools
import numbers import numbers
import sys
from typing import TYPE_CHECKING, Any, Self from typing import TYPE_CHECKING, Any, Self
from zigpy import types from zigpy import types
@ -485,7 +484,7 @@ class SmartEnergyMetering(Sensor):
if self._cluster_handler.device_type is not None: if self._cluster_handler.device_type is not None:
attrs["device_type"] = self._cluster_handler.device_type attrs["device_type"] = self._cluster_handler.device_type
if (status := self._cluster_handler.status) is not None: 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( attrs["status"] = str(
status.name if status.name is not None else status.value 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: def cancelling(task: Future[Any]) -> bool:
"""Return True if task is done or cancelling.""" """Return True if task is cancelling."""
# https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancelling
# is new in Python 3.11
return bool((cancelling_ := getattr(task, "cancelling", None)) and cancelling_()) return bool((cancelling_ := getattr(task, "cancelling", None)) and cancelling_())

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,5 @@
"""The tests for the datetime component.""" """The tests for the datetime component."""
from datetime import datetime, timezone from datetime import UTC, datetime
from zoneinfo import ZoneInfo from zoneinfo import ZoneInfo
import pytest 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.core import HomeAssistant
from homeassistant.setup import async_setup_component 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): class MockDateTimeEntity(DateTimeEntity):

View File

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

View File

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

View File

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

View File

@ -143,7 +143,7 @@ async def test_plant_topology_reduction_change(
return_value=mock_modules, return_value=mock_modules,
) as mock_check: ) as mock_check:
async_fire_time_changed( 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() await hass.async_block_till_done()
assert len(mock_check.mock_calls) == 1 assert len(mock_check.mock_calls) == 1
@ -205,7 +205,7 @@ async def test_plant_topology_increase_change(
return_value=mock_modules, return_value=mock_modules,
) as mock_check: ) as mock_check:
async_fire_time_changed( 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() await hass.async_block_till_done()
assert len(mock_check.mock_calls) == 1 assert len(mock_check.mock_calls) == 1
@ -267,7 +267,7 @@ async def test_module_status_unavailable(
return_value=mock_modules, return_value=mock_modules,
) as mock_check: ) as mock_check:
async_fire_time_changed( 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() await hass.async_block_till_done()
assert len(mock_check.mock_calls) == 1 assert len(mock_check.mock_calls) == 1
@ -338,7 +338,7 @@ async def test_module_status_available(
return_value=mock_modules, return_value=mock_modules,
) as mock_check: ) as mock_check:
async_fire_time_changed( 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() await hass.async_block_till_done()
assert len(mock_check.mock_calls) == 1 assert len(mock_check.mock_calls) == 1
@ -442,7 +442,7 @@ async def test_update_with_api_error(
side_effect=HomePlusControlApiError, side_effect=HomePlusControlApiError,
) as mock_check: ) as mock_check:
async_fire_time_changed( 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() await hass.async_block_till_done()
assert len(mock_check.mock_calls) == 1 assert len(mock_check.mock_calls) == 1

View File

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

View File

@ -2,7 +2,7 @@
from __future__ import annotations from __future__ import annotations
from collections.abc import Generator 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 unittest.mock import AsyncMock, patch
from melnor_bluetooth.device import Device from melnor_bluetooth.device import Device
@ -73,7 +73,7 @@ class MockFrequency:
self._interval = 0 self._interval = 0
self._is_watering = False self._is_watering = False
self._start_time = time(12, 0) 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 @property
def duration_minutes(self) -> int: def duration_minutes(self) -> int:

View File

@ -1,5 +1,5 @@
"""The tests for Octoptint binary sensor module.""" """The tests for Octoptint binary sensor module."""
from datetime import datetime, timezone from datetime import UTC, datetime
from unittest.mock import patch from unittest.mock import patch
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
@ -24,7 +24,7 @@ async def test_sensors(hass: HomeAssistant) -> None:
} }
with patch( with patch(
"homeassistant.util.dt.utcnow", "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) await init_integration(hass, "sensor", printer=printer, job=job)

View File

@ -1,6 +1,6 @@
"""Test Prusalink sensors.""" """Test Prusalink sensors."""
from datetime import datetime, timezone from datetime import UTC, datetime
from unittest.mock import PropertyMock, patch from unittest.mock import PropertyMock, patch
import pytest import pytest
@ -125,7 +125,7 @@ async def test_sensors_active_job(
"""Test sensors while active job.""" """Test sensors while active job."""
with patch( with patch(
"homeassistant.components.prusalink.sensor.utcnow", "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", {}) assert await async_setup_component(hass, "prusalink", {})

View File

@ -1,6 +1,6 @@
"""Test util methods.""" """Test util methods."""
from collections.abc import Callable from collections.abc import Callable
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
import os import os
from pathlib import Path from pathlib import Path
import sqlite3 import sqlite3
@ -948,7 +948,7 @@ def test_execute_stmt_lambda_element(
assert rows == ["mock_row"] 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: async def test_resolve_period(hass: HomeAssistant) -> None:
"""Test statistic_during_period.""" """Test statistic_during_period."""

View File

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

View File

@ -1,6 +1,6 @@
"""Sample API response data for tests.""" """Sample API response data for tests."""
from datetime import datetime, timezone from datetime import UTC, datetime
from homeassistant.components.subaru.const import ( from homeassistant.components.subaru.const import (
API_GEN_1, 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_EV = {
VEHICLE_STATUS: { VEHICLE_STATUS: {

View File

@ -1,5 +1,5 @@
"""The tests for the Template Binary sensor platform.""" """The tests for the Template Binary sensor platform."""
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
import logging import logging
from unittest.mock import patch from unittest.mock import patch
@ -1276,9 +1276,7 @@ async def test_trigger_entity_restore_state_auto_off(
fake_extra_data = { fake_extra_data = {
"auto_off_time": { "auto_off_time": {
"__type": "<class 'datetime.datetime'>", "__type": "<class 'datetime.datetime'>",
"isoformat": datetime( "isoformat": datetime(2022, 2, 2, 12, 2, 2, tzinfo=UTC).isoformat(),
2022, 2, 2, 12, 2, 2, tzinfo=timezone.utc
).isoformat(),
}, },
} }
mock_restore_cache_with_extra_data(hass, ((fake_state, fake_extra_data),)) 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 = { fake_extra_data = {
"auto_off_time": { "auto_off_time": {
"__type": "<class 'datetime.datetime'>", "__type": "<class 'datetime.datetime'>",
"isoformat": datetime( "isoformat": datetime(2022, 2, 2, 12, 2, 0, tzinfo=UTC).isoformat(),
2022, 2, 2, 12, 2, 0, tzinfo=timezone.utc
).isoformat(),
}, },
} }
mock_restore_cache_with_extra_data(hass, ((fake_state, fake_extra_data),)) 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, _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): with patch("homeassistant.util.dt.utcnow", return_value=now):
await hass.services.async_call( await hass.services.async_call(

View File

@ -1,5 +1,5 @@
"""The tests for UVC camera module.""" """The tests for UVC camera module."""
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
from unittest.mock import call, patch from unittest.mock import call, patch
import pytest import pytest
@ -368,7 +368,7 @@ async def test_motion_recording_mode_properties(
assert state assert state
assert state.state != STATE_RECORDING assert state.state != STATE_RECORDING
assert state.attributes["last_recording_start_time"] == datetime( 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" mock_remote.return_value.get_camera.return_value["recordingIndicator"] = "DISABLED"

View File

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

View File

@ -2,7 +2,7 @@
Call init before using it in your tests to ensure clean test data. 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 from homeassistant.components.datetime import DateTimeEntity
@ -37,7 +37,7 @@ def init(empty=False):
MockDateTimeEntity( MockDateTimeEntity(
name="test", name="test",
unique_id=UNIQUE_DATETIME, 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),
), ),
] ]
) )