Update black to 22.1.0 (#65788)

This commit is contained in:
Franck Nijhof 2022-02-05 14:19:37 +01:00 committed by GitHub
parent 58409d0895
commit fa09cf663e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
42 changed files with 204 additions and 255 deletions

View file

@ -5,7 +5,7 @@ repos:
- id: pyupgrade
args: [--py39-plus]
- repo: https://github.com/psf/black
rev: 21.12b0
rev: 22.1.0
hooks:
- id: black
args:

View file

@ -242,7 +242,7 @@ class AppleTVManager:
backoff = min(
max(
BACKOFF_TIME_LOWER_LIMIT,
randrange(2 ** self._connection_attempts),
randrange(2**self._connection_attempts),
),
BACKOFF_TIME_UPPER_LIMIT,
)

View file

@ -260,7 +260,7 @@ CC_SENSOR_TYPES = (
name="Particulate Matter < 2.5 μm",
unit_imperial=CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT,
unit_metric=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
metric_conversion=3.2808399 ** 3,
metric_conversion=3.2808399**3,
is_metric_check=True,
),
ClimaCellSensorEntityDescription(
@ -268,7 +268,7 @@ CC_SENSOR_TYPES = (
name="Particulate Matter < 10 μm",
unit_imperial=CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT,
unit_metric=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
metric_conversion=3.2808399 ** 3,
metric_conversion=3.2808399**3,
is_metric_check=True,
),
ClimaCellSensorEntityDescription(
@ -424,7 +424,7 @@ CC_V3_SENSOR_TYPES = (
name="Particulate Matter < 2.5 μm",
unit_imperial=CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT,
unit_metric=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
metric_conversion=3.2808399 ** 3,
metric_conversion=3.2808399**3,
is_metric_check=False,
),
ClimaCellSensorEntityDescription(
@ -432,7 +432,7 @@ CC_V3_SENSOR_TYPES = (
name="Particulate Matter < 10 μm",
unit_imperial=CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT,
unit_metric=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
metric_conversion=3.2808399 ** 3,
metric_conversion=3.2808399**3,
is_metric_check=False,
),
ClimaCellSensorEntityDescription(

View file

@ -24,11 +24,11 @@ def create_matcher(utterance):
# Group part
if group_match is not None:
pattern.append(fr"(?P<{group_match.groups()[0]}>[\w ]+?)\s*")
pattern.append(rf"(?P<{group_match.groups()[0]}>[\w ]+?)\s*")
# Optional part
elif optional_match is not None:
pattern.append(fr"(?:{optional_match.groups()[0]} *)?")
pattern.append(rf"(?:{optional_match.groups()[0]} *)?")
pattern.append("$")
return re.compile("".join(pattern), re.I)

View file

@ -75,7 +75,7 @@ class CPUSpeedSensor(SensorEntity):
info = cpuinfo.get_cpu_info()
if info and HZ_ACTUAL in info:
self._attr_native_value = round(float(info[HZ_ACTUAL][0]) / 10 ** 9, 2)
self._attr_native_value = round(float(info[HZ_ACTUAL][0]) / 10**9, 2)
else:
self._attr_native_value = None
@ -86,5 +86,5 @@ class CPUSpeedSensor(SensorEntity):
}
if HZ_ADVERTISED in info:
self._attr_extra_state_attributes[ATTR_HZ] = round(
info[HZ_ADVERTISED][0] / 10 ** 9, 2
info[HZ_ADVERTISED][0] / 10**9, 2
)

View file

@ -168,7 +168,7 @@ class EnOceanPowerSensor(EnOceanSensor):
# this packet reports the current value
raw_val = packet.parsed["MR"]["raw_value"]
divisor = packet.parsed["DIV"]["raw_value"]
self._attr_native_value = raw_val / (10 ** divisor)
self._attr_native_value = raw_val / (10**divisor)
self.schedule_update_ha_state()

View file

@ -91,7 +91,7 @@ class EnOceanSwitch(EnOceanEntity, SwitchEntity):
if packet.parsed["DT"]["raw_value"] == 1:
raw_val = packet.parsed["MR"]["raw_value"]
divisor = packet.parsed["DIV"]["raw_value"]
watts = raw_val / (10 ** divisor)
watts = raw_val / (10**divisor)
if watts > 1:
self._on_state = True
self.schedule_update_ha_state()

View file

@ -65,7 +65,7 @@ class BanSensor(SensorEntity):
self.last_ban = None
self.log_parser = log_parser
self.log_parser.ip_regex[self.jail] = re.compile(
fr"\[{re.escape(self.jail)}\]\s*(Ban|Unban) (.*)"
rf"\[{re.escape(self.jail)}\]\s*(Ban|Unban) (.*)"
)
_LOGGER.debug("Setting up jail %s", self.jail)

View file

@ -158,12 +158,9 @@ def wifi_entities_list(
if network_info:
ssid = network_info["NewSSID"]
_LOGGER.debug("SSID from device: <%s>", ssid)
if (
slugify(
ssid,
)
in [slugify(v) for v in networks.values()]
):
if slugify(
ssid,
) in [slugify(v) for v in networks.values()]:
_LOGGER.debug("SSID duplicated, adding suffix")
networks[i] = f'{ssid} {std_table[network_info["NewStandard"]]}'
else:

View file

@ -19,7 +19,7 @@ DEFAULT_SCAN_INTERVAL = 60
DATA_UPDATED = "glances_data_updated"
SUPPORTED_VERSIONS = [2, 3]
if sys.maxsize > 2 ** 32:
if sys.maxsize > 2**32:
CPU_ICON = "mdi:cpu-64-bit"
else:
CPU_ICON = "mdi:cpu-32-bit"

View file

@ -129,14 +129,14 @@ class GlancesSensor(SensorEntity):
break
if self.entity_description.key == "disk_free":
try:
self._state = round(disk["free"] / 1024 ** 3, 1)
self._state = round(disk["free"] / 1024**3, 1)
except KeyError:
self._state = round(
(disk["size"] - disk["used"]) / 1024 ** 3,
(disk["size"] - disk["used"]) / 1024**3,
1,
)
elif self.entity_description.key == "disk_use":
self._state = round(disk["used"] / 1024 ** 3, 1)
self._state = round(disk["used"] / 1024**3, 1)
elif self.entity_description.key == "disk_use_percent":
self._state = disk["percent"]
elif self.entity_description.key == "battery":
@ -170,15 +170,15 @@ class GlancesSensor(SensorEntity):
elif self.entity_description.key == "memory_use_percent":
self._state = value["mem"]["percent"]
elif self.entity_description.key == "memory_use":
self._state = round(value["mem"]["used"] / 1024 ** 2, 1)
self._state = round(value["mem"]["used"] / 1024**2, 1)
elif self.entity_description.key == "memory_free":
self._state = round(value["mem"]["free"] / 1024 ** 2, 1)
self._state = round(value["mem"]["free"] / 1024**2, 1)
elif self.entity_description.key == "swap_use_percent":
self._state = value["memswap"]["percent"]
elif self.entity_description.key == "swap_use":
self._state = round(value["memswap"]["used"] / 1024 ** 3, 1)
self._state = round(value["memswap"]["used"] / 1024**3, 1)
elif self.entity_description.key == "swap_free":
self._state = round(value["memswap"]["free"] / 1024 ** 3, 1)
self._state = round(value["memswap"]["free"] / 1024**3, 1)
elif self.entity_description.key == "processor_load":
# Windows systems don't provide load details
try:
@ -219,7 +219,7 @@ class GlancesSensor(SensorEntity):
for container in value["docker"]["containers"]:
if container["Status"] == "running" or "Up" in container["Status"]:
mem_use += container["memory"]["usage"]
self._state = round(mem_use / 1024 ** 2, 1)
self._state = round(mem_use / 1024**2, 1)
except KeyError:
self._state = STATE_UNAVAILABLE
elif self.entity_description.type == "raid":

View file

@ -774,14 +774,10 @@ class StartStopTrait(_Trait):
"""Execute a StartStop command."""
if command == COMMAND_STARTSTOP:
if params["start"] is False:
if (
self.state.state
in (
cover.STATE_CLOSING,
cover.STATE_OPENING,
)
or self.state.attributes.get(ATTR_ASSUMED_STATE)
):
if self.state.state in (
cover.STATE_CLOSING,
cover.STATE_OPENING,
) or self.state.attributes.get(ATTR_ASSUMED_STATE):
await self.hass.services.async_call(
self.state.domain,
cover.SERVICE_STOP_COVER,

View file

@ -119,14 +119,10 @@ def get_accessory(hass, driver, state, aid, config): # noqa: C901
elif state.domain == "cover":
device_class = state.attributes.get(ATTR_DEVICE_CLASS)
if (
device_class
in (
cover.CoverDeviceClass.GARAGE,
cover.CoverDeviceClass.GATE,
)
and features & (cover.SUPPORT_OPEN | cover.SUPPORT_CLOSE)
):
if device_class in (
cover.CoverDeviceClass.GARAGE,
cover.CoverDeviceClass.GATE,
) and features & (cover.SUPPORT_OPEN | cover.SUPPORT_CLOSE):
a_type = "GarageDoorOpener"
elif (
device_class == cover.CoverDeviceClass.WINDOW

View file

@ -59,7 +59,7 @@ DEFAULT_DEVELOPMENT: Final = "0"
DEFAULT_CORS: Final[list[str]] = ["https://cast.home-assistant.io"]
NO_LOGIN_ATTEMPT_THRESHOLD: Final = -1
MAX_CLIENT_SIZE: Final = 1024 ** 2 * 16
MAX_CLIENT_SIZE: Final = 1024**2 * 16
STORAGE_KEY: Final = DOMAIN
STORAGE_VERSION: Final = 1

View file

@ -49,7 +49,7 @@ RIGHT_METHOD = "right"
INTEGRATION_METHOD = [TRAPEZOIDAL_METHOD, LEFT_METHOD, RIGHT_METHOD]
# SI Metric prefixes
UNIT_PREFIXES = {None: 1, "k": 10 ** 3, "M": 10 ** 6, "G": 10 ** 9, "T": 10 ** 12}
UNIT_PREFIXES = {None: 1, "k": 10**3, "M": 10**6, "G": 10**9, "T": 10**12}
# SI Time prefixes
UNIT_TIME = {

View file

@ -130,7 +130,7 @@ def numeric_type_validator(value: Any) -> str | int:
def _max_payload_value(payload_length: int) -> int:
if payload_length == 0:
return 0x3F
return int(256 ** payload_length) - 1
return int(256**payload_length) - 1
def button_payload_sub_validator(entity_config: OrderedDict) -> OrderedDict:

View file

@ -76,7 +76,7 @@ class UsageSensor(LTESensor):
@property
def native_value(self):
"""Return the state of the sensor."""
return round(self.modem_data.data.usage / 1024 ** 2, 1)
return round(self.modem_data.data.usage / 1024**2, 1)
class GenericSensor(LTESensor):

View file

@ -126,7 +126,7 @@ class NZBGetSensor(NZBGetEntity, SensorEntity):
if "DownloadRate" in sensor_type and value > 0:
# Convert download rate from Bytes/s to MBytes/s
return round(value / 2 ** 20, 2)
return round(value / 2**20, 2)
if "UpTimeSec" in sensor_type and value > 0:
uptime = utcnow() - timedelta(seconds=value)

View file

@ -253,7 +253,7 @@ class PandoraMediaPlayer(MediaPlayerEntity):
try:
match_idx = self._pianobar.expect(
[
br"(\d\d):(\d\d)/(\d\d):(\d\d)",
rb"(\d\d):(\d\d)/(\d\d):(\d\d)",
"No song playing",
"Select station",
"Receiving new playlist",

View file

@ -132,7 +132,7 @@ class PyLoadSensor(SensorEntity):
if "speed" in self.type and value > 0:
# Convert download rate from Bytes/s to MBytes/s
self._state = round(value / 2 ** 20, 2)
self._state = round(value / 2**20, 2)
else:
self._state = value

View file

@ -167,8 +167,8 @@ class SonarrSensor(SonarrEntity, SensorEntity):
if key == "diskspace":
for disk in self.sonarr.app.disks:
free = disk.free / 1024 ** 3
total = disk.total / 1024 ** 3
free = disk.free / 1024**3
total = disk.total / 1024**3
usage = free / total * 100
attrs[
@ -203,7 +203,7 @@ class SonarrSensor(SonarrEntity, SensorEntity):
if key == "diskspace":
total_free = sum(disk.free for disk in self.sonarr.app.disks)
free = total_free / 1024 ** 3
free = total_free / 1024**3
return f"{free:.2f}"
if key == "commands" and self.data.get(key) is not None:

View file

@ -36,14 +36,14 @@ SENSOR_TYPES: Final[tuple[SpeedtestSensorEntityDescription, ...]] = (
name="Download",
native_unit_of_measurement=DATA_RATE_MEGABITS_PER_SECOND,
state_class=SensorStateClass.MEASUREMENT,
value=lambda value: round(value / 10 ** 6, 2),
value=lambda value: round(value / 10**6, 2),
),
SpeedtestSensorEntityDescription(
key="upload",
name="Upload",
native_unit_of_measurement=DATA_RATE_MEGABITS_PER_SECOND,
state_class=SensorStateClass.MEASUREMENT,
value=lambda value: round(value / 10 ** 6, 2),
value=lambda value: round(value / 10**6, 2),
),
)

View file

@ -194,7 +194,7 @@ class StartcaData:
:param value: The value in bytes to convert to GB.
:return: Converted GB value
"""
return float(value) * 10 ** -9
return float(value) * 10**-9
@Throttle(MIN_TIME_BETWEEN_UPDATES)
async def async_update(self):

View file

@ -105,7 +105,7 @@ class SynoDSMUtilSensor(SynoDSMSensor):
# Data (RAM)
if self.native_unit_of_measurement == DATA_MEGABYTES:
return round(attr / 1024.0 ** 2, 1)
return round(attr / 1024.0**2, 1)
# Network
if self.native_unit_of_measurement == DATA_RATE_KILOBYTES_PER_SECOND:
@ -147,7 +147,7 @@ class SynoDSMStorageSensor(SynologyDSMDeviceEntity, SynoDSMSensor):
# Data (disk space)
if self.native_unit_of_measurement == DATA_TERABYTES:
return round(attr / 1024.0 ** 4, 2)
return round(attr / 1024.0**4, 2)
return attr

View file

@ -104,7 +104,7 @@ BASE_SENSOR_TYPES: tuple[SystemBridgeSensorEntityDescription, ...] = (
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=DATA_GIGABYTES,
icon="mdi:memory",
value=lambda bridge: round(bridge.memory.free / 1000 ** 3, 2),
value=lambda bridge: round(bridge.memory.free / 1000**3, 2),
),
SystemBridgeSensorEntityDescription(
key="memory_used_percentage",
@ -121,7 +121,7 @@ BASE_SENSOR_TYPES: tuple[SystemBridgeSensorEntityDescription, ...] = (
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=DATA_GIGABYTES,
icon="mdi:memory",
value=lambda bridge: round(bridge.memory.used / 1000 ** 3, 2),
value=lambda bridge: round(bridge.memory.used / 1000**3, 2),
),
SystemBridgeSensorEntityDescription(
key="os",
@ -324,7 +324,7 @@ async def async_setup_entry(
native_unit_of_measurement=DATA_GIGABYTES,
icon="mdi:memory",
value=lambda bridge, i=index: round(
bridge.graphics.controllers[i].memoryFree / 10 ** 3, 2
bridge.graphics.controllers[i].memoryFree / 10**3, 2
),
),
),
@ -356,7 +356,7 @@ async def async_setup_entry(
native_unit_of_measurement=DATA_GIGABYTES,
icon="mdi:memory",
value=lambda bridge, i=index: round(
bridge.graphics.controllers[i].memoryUsed / 10 ** 3, 2
bridge.graphics.controllers[i].memoryUsed / 10**3, 2
),
),
),

View file

@ -51,7 +51,7 @@ _LOGGER = logging.getLogger(__name__)
CONF_ARG = "arg"
if sys.maxsize > 2 ** 32:
if sys.maxsize > 2**32:
CPU_ICON = "mdi:cpu-64-bit"
else:
CPU_ICON = "mdi:cpu-32-bit"
@ -473,22 +473,22 @@ def _update( # noqa: C901
if type_ == "disk_use_percent":
state = _disk_usage(data.argument).percent
elif type_ == "disk_use":
state = round(_disk_usage(data.argument).used / 1024 ** 3, 1)
state = round(_disk_usage(data.argument).used / 1024**3, 1)
elif type_ == "disk_free":
state = round(_disk_usage(data.argument).free / 1024 ** 3, 1)
state = round(_disk_usage(data.argument).free / 1024**3, 1)
elif type_ == "memory_use_percent":
state = _virtual_memory().percent
elif type_ == "memory_use":
virtual_memory = _virtual_memory()
state = round((virtual_memory.total - virtual_memory.available) / 1024 ** 2, 1)
state = round((virtual_memory.total - virtual_memory.available) / 1024**2, 1)
elif type_ == "memory_free":
state = round(_virtual_memory().available / 1024 ** 2, 1)
state = round(_virtual_memory().available / 1024**2, 1)
elif type_ == "swap_use_percent":
state = _swap_memory().percent
elif type_ == "swap_use":
state = round(_swap_memory().used / 1024 ** 2, 1)
state = round(_swap_memory().used / 1024**2, 1)
elif type_ == "swap_free":
state = round(_swap_memory().free / 1024 ** 2, 1)
state = round(_swap_memory().free / 1024**2, 1)
elif type_ == "processor_use":
state = round(psutil.cpu_percent(interval=None))
elif type_ == "processor_temperature":
@ -510,7 +510,7 @@ def _update( # noqa: C901
counters = _net_io_counters()
if data.argument in counters:
counter = counters[data.argument][IO_COUNTER[type_]]
state = round(counter / 1024 ** 2, 1)
state = round(counter / 1024**2, 1)
else:
state = None
elif type_ in ("packets_out", "packets_in"):
@ -527,7 +527,7 @@ def _update( # noqa: C901
if data.value and data.value < counter:
state = round(
(counter - data.value)
/ 1000 ** 2
/ 1000**2
/ (now - (data.update_time or now)).total_seconds(),
3,
)

View file

@ -45,11 +45,11 @@ class IntegerTypeData:
def scale_value(self, value: float | int) -> float:
"""Scale a value."""
return value * 1.0 / (10 ** self.scale)
return value * 1.0 / (10**self.scale)
def scale_value_back(self, value: float | int) -> int:
"""Return raw value for scaled."""
return int(value * (10 ** self.scale))
return int(value * (10**self.scale))
def remap_value_to(
self,

View file

@ -91,15 +91,11 @@ async def async_setup_platform(
_LOGGER.debug("The following stations were returned: %s", stations)
for station in stations:
waqi_sensor = WaqiSensor(client, station)
if (
not station_filter
or {
waqi_sensor.uid,
waqi_sensor.url,
waqi_sensor.station_name,
}
& set(station_filter)
):
if not station_filter or {
waqi_sensor.uid,
waqi_sensor.url,
waqi_sensor.station_name,
} & set(station_filter):
dev.append(waqi_sensor)
except (
aiohttp.client_exceptions.ClientConnectorError,

View file

@ -431,14 +431,10 @@ class Thermostat(ZhaEntity, ClimateEntity):
self.debug("preset mode '%s' is not supported", preset_mode)
return
if (
self.preset_mode
not in (
preset_mode,
PRESET_NONE,
)
and not await self.async_preset_handler(self.preset_mode, enable=False)
):
if self.preset_mode not in (
preset_mode,
PRESET_NONE,
) and not await self.async_preset_handler(self.preset_mode, enable=False):
self.debug("Couldn't turn off '%s' preset", self.preset_mode)
return

View file

@ -1919,7 +1919,7 @@ def _async_create_timer(hass: HomeAssistant) -> None:
"""Schedule a timer tick when the next second rolls around."""
nonlocal handle
slp_seconds = 1 - (now.microsecond / 10 ** 6)
slp_seconds = 1 - (now.microsecond / 10**6)
target = monotonic() + slp_seconds
handle = hass.loop.call_later(slp_seconds, fire_time_event, target)

View file

@ -42,5 +42,5 @@ def extract_domain_configs(config: ConfigType, domain: str) -> Sequence[str]:
Async friendly.
"""
pattern = re.compile(fr"^{domain}(| .+)$")
pattern = re.compile(rf"^{domain}(| .+)$")
return [key for key in config.keys() if pattern.match(key)]

View file

@ -1302,7 +1302,7 @@ def forgiving_round(value, precision=0, method="common", default=_SENTINEL):
"""Filter to round a value."""
try:
# support rounding methods like jinja
multiplier = float(10 ** precision)
multiplier = float(10**precision)
if method == "ceil":
value = math.ceil(float(value) * multiplier) / multiplier
elif method == "floor":

View file

@ -65,7 +65,7 @@ async def fire_events(hass):
"""Fire a million events."""
count = 0
event_name = "benchmark_event"
events_to_fire = 10 ** 6
events_to_fire = 10**6
@core.callback
def listener(_):
@ -92,7 +92,7 @@ async def fire_events_with_filter(hass):
"""Fire a million events with a filter that rejects them."""
count = 0
event_name = "benchmark_event"
events_to_fire = 10 ** 6
events_to_fire = 10**6
@core.callback
def event_filter(event):
@ -131,13 +131,13 @@ async def time_changed_helper(hass):
nonlocal count
count += 1
if count == 10 ** 6:
if count == 10**6:
event.set()
hass.helpers.event.async_track_time_change(listener, minute=0, second=0)
event_data = {ATTR_NOW: datetime(2017, 10, 10, 15, 0, 0, tzinfo=dt_util.UTC)}
for _ in range(10 ** 6):
for _ in range(10**6):
hass.bus.async_fire(EVENT_TIME_CHANGED, event_data)
start = timer()
@ -160,7 +160,7 @@ async def state_changed_helper(hass):
nonlocal count
count += 1
if count == 10 ** 6:
if count == 10**6:
event.set()
for idx in range(1000):
@ -173,7 +173,7 @@ async def state_changed_helper(hass):
"new_state": core.State(entity_id, "on"),
}
for _ in range(10 ** 6):
for _ in range(10**6):
hass.bus.async_fire(EVENT_STATE_CHANGED, event_data)
start = timer()
@ -188,7 +188,7 @@ async def state_changed_event_helper(hass):
"""Run a million events through state changed event helper with 1000 entities."""
count = 0
entity_id = "light.kitchen"
events_to_fire = 10 ** 6
events_to_fire = 10**6
@core.callback
def listener(*args):
@ -223,7 +223,7 @@ async def state_changed_event_filter_helper(hass):
"""Run a million events through state changed event helper with 1000 entities that all get filtered."""
count = 0
entity_id = "light.kitchen"
events_to_fire = 10 ** 6
events_to_fire = 10**6
@core.callback
def listener(*args):
@ -292,7 +292,7 @@ async def _logbook_filtering(hass, last_changed, last_updated):
)
def yield_events(event):
for _ in range(10 ** 5):
for _ in range(10**5):
# pylint: disable=protected-access
if logbook._keep_event(hass, event, entities_filter):
yield event
@ -363,7 +363,7 @@ async def filtering_entity_id(hass):
start = timer()
for i in range(10 ** 5):
for i in range(10**5):
entities_filter(entity_ids[i % size])
return timer() - start
@ -373,7 +373,7 @@ async def filtering_entity_id(hass):
async def valid_entity_id(hass):
"""Run valid entity ID a million times."""
start = timer()
for _ in range(10 ** 6):
for _ in range(10**6):
core.valid_entity_id("light.kitchen")
return timer() - start
@ -383,7 +383,7 @@ async def json_serialize_states(hass):
"""Serialize million states with websocket default encoder."""
states = [
core.State("light.kitchen", "on", {"friendly_name": "Kitchen Lights"})
for _ in range(10 ** 6)
for _ in range(10**6)
]
start = timer()

View file

@ -115,7 +115,7 @@ def vincenty(
cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda
sigma = math.atan2(sinSigma, cosSigma)
sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma
cosSqAlpha = 1 - sinAlpha ** 2
cosSqAlpha = 1 - sinAlpha**2
try:
cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha
except ZeroDivisionError:
@ -124,14 +124,14 @@ def vincenty(
LambdaPrev = Lambda
Lambda = L + (1 - C) * FLATTENING * sinAlpha * (
sigma
+ C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM ** 2))
+ C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM**2))
)
if abs(Lambda - LambdaPrev) < CONVERGENCE_THRESHOLD:
break # successful convergence
else:
return None # failure to converge
uSq = cosSqAlpha * (AXIS_A ** 2 - AXIS_B ** 2) / (AXIS_B ** 2)
uSq = cosSqAlpha * (AXIS_A**2 - AXIS_B**2) / (AXIS_B**2)
A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)))
B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)))
deltaSigma = (
@ -142,12 +142,12 @@ def vincenty(
+ B
/ 4
* (
cosSigma * (-1 + 2 * cos2SigmaM ** 2)
cosSigma * (-1 + 2 * cos2SigmaM**2)
- B
/ 6
* cos2SigmaM
* (-3 + 4 * sinSigma ** 2)
* (-3 + 4 * cos2SigmaM ** 2)
* (-3 + 4 * sinSigma**2)
* (-3 + 4 * cos2SigmaM**2)
)
)
)

View file

@ -1,7 +1,7 @@
# Automatically generated from .pre-commit-config.yaml by gen_requirements_all.py, do not edit
bandit==1.7.0
black==21.12b0
black==22.1.0
codespell==2.1.0
flake8-comprehensions==3.7.0
flake8-docstrings==1.6.0

View file

@ -118,18 +118,15 @@ def test_blueprint_validate():
is None
)
assert (
models.Blueprint(
{
"blueprint": {
"name": "Hello",
"domain": "automation",
"homeassistant": {"min_version": "100000.0.0"},
},
}
).validate()
== ["Requires at least Home Assistant 100000.0.0"]
)
assert models.Blueprint(
{
"blueprint": {
"name": "Hello",
"domain": "automation",
"homeassistant": {"min_version": "100000.0.0"},
},
}
).validate() == ["Requires at least Home Assistant 100000.0.0"]
def test_blueprint_inputs(blueprint_2):

View file

@ -1810,54 +1810,51 @@ async def test_extract_entities():
async def test_extract_devices():
"""Test extracting devices."""
assert (
condition.async_extract_devices(
{
"condition": "and",
"conditions": [
{"condition": "device", "device_id": "abcd", "domain": "light"},
{"condition": "device", "device_id": "qwer", "domain": "switch"},
{
"condition": "state",
"entity_id": "sensor.not_a_device",
"state": "100",
},
{
"condition": "not",
"conditions": [
{
"condition": "device",
"device_id": "abcd_not",
"domain": "light",
},
{
"condition": "device",
"device_id": "qwer_not",
"domain": "switch",
},
],
},
{
"condition": "or",
"conditions": [
{
"condition": "device",
"device_id": "abcd_or",
"domain": "light",
},
{
"condition": "device",
"device_id": "qwer_or",
"domain": "switch",
},
],
},
Template("{{ is_state('light.example', 'on') }}"),
],
}
)
== {"abcd", "qwer", "abcd_not", "qwer_not", "abcd_or", "qwer_or"}
)
assert condition.async_extract_devices(
{
"condition": "and",
"conditions": [
{"condition": "device", "device_id": "abcd", "domain": "light"},
{"condition": "device", "device_id": "qwer", "domain": "switch"},
{
"condition": "state",
"entity_id": "sensor.not_a_device",
"state": "100",
},
{
"condition": "not",
"conditions": [
{
"condition": "device",
"device_id": "abcd_not",
"domain": "light",
},
{
"condition": "device",
"device_id": "qwer_not",
"domain": "switch",
},
],
},
{
"condition": "or",
"conditions": [
{
"condition": "device",
"device_id": "abcd_or",
"domain": "light",
},
{
"condition": "device",
"device_id": "qwer_or",
"domain": "switch",
},
],
},
Template("{{ is_state('light.example', 'on') }}"),
],
}
) == {"abcd", "qwer", "abcd_not", "qwer_not", "abcd_or", "qwer_or"}
async def test_condition_template_error(hass):

View file

@ -1050,23 +1050,20 @@ async def test_component_config_exceptions(hass, caplog):
# component.PLATFORM_SCHEMA
caplog.clear()
assert (
await config_util.async_process_component_config(
hass,
{"test_domain": {"platform": "test_platform"}},
integration=Mock(
domain="test_domain",
get_platform=Mock(return_value=None),
get_component=Mock(
return_value=Mock(
spec=["PLATFORM_SCHEMA_BASE"],
PLATFORM_SCHEMA_BASE=Mock(side_effect=ValueError("broken")),
)
),
assert await config_util.async_process_component_config(
hass,
{"test_domain": {"platform": "test_platform"}},
integration=Mock(
domain="test_domain",
get_platform=Mock(return_value=None),
get_component=Mock(
return_value=Mock(
spec=["PLATFORM_SCHEMA_BASE"],
PLATFORM_SCHEMA_BASE=Mock(side_effect=ValueError("broken")),
)
),
)
== {"test_domain": []}
)
),
) == {"test_domain": []}
assert "ValueError: broken" in caplog.text
assert (
"Unknown error validating test_platform platform config with test_domain component platform schema"
@ -1085,20 +1082,15 @@ async def test_component_config_exceptions(hass, caplog):
)
),
):
assert (
await config_util.async_process_component_config(
hass,
{"test_domain": {"platform": "test_platform"}},
integration=Mock(
domain="test_domain",
get_platform=Mock(return_value=None),
get_component=Mock(
return_value=Mock(spec=["PLATFORM_SCHEMA_BASE"])
),
),
)
== {"test_domain": []}
)
assert await config_util.async_process_component_config(
hass,
{"test_domain": {"platform": "test_platform"}},
integration=Mock(
domain="test_domain",
get_platform=Mock(return_value=None),
get_component=Mock(return_value=Mock(spec=["PLATFORM_SCHEMA_BASE"])),
),
) == {"test_domain": []}
assert "ValueError: broken" in caplog.text
assert (
"Unknown error validating config for test_platform platform for test_domain component with PLATFORM_SCHEMA"

View file

@ -21,7 +21,7 @@ RETYPE = type(re.compile(""))
def mock_stream(data):
"""Mock a stream with data."""
protocol = mock.Mock(_reading_paused=False)
stream = StreamReader(protocol, limit=2 ** 16)
stream = StreamReader(protocol, limit=2**16)
stream.feed_data(data)
stream.feed_eof()
return stream

View file

@ -461,20 +461,17 @@ def test_rgbww_to_color_temperature():
Temperature values must be in mireds
Home Assistant uses rgbcw for rgbww
"""
assert (
color_util.rgbww_to_color_temperature(
(
0,
0,
0,
255,
0,
),
153,
500,
)
== (153, 255)
)
assert color_util.rgbww_to_color_temperature(
(
0,
0,
0,
255,
0,
),
153,
500,
) == (153, 255)
assert color_util.rgbww_to_color_temperature((0, 0, 0, 128, 0), 153, 500) == (
153,
128,
@ -507,15 +504,12 @@ def test_white_levels_to_color_temperature():
Temperature values must be in mireds
Home Assistant uses rgbcw for rgbww
"""
assert (
color_util.while_levels_to_color_temperature(
255,
0,
153,
500,
)
== (153, 255)
)
assert color_util.while_levels_to_color_temperature(
255,
0,
153,
500,
) == (153, 255)
assert color_util.while_levels_to_color_temperature(128, 0, 153, 500) == (
153,
128,

View file

@ -143,21 +143,15 @@ def test_find_unserializable_data():
bad_data = object()
assert (
find_paths_unserializable_data(
[State("mock_domain.mock_entity", "on", {"bad": bad_data})],
dump=partial(dumps, cls=MockJSONEncoder),
)
== {"$[0](State: mock_domain.mock_entity).attributes.bad": bad_data}
)
assert find_paths_unserializable_data(
[State("mock_domain.mock_entity", "on", {"bad": bad_data})],
dump=partial(dumps, cls=MockJSONEncoder),
) == {"$[0](State: mock_domain.mock_entity).attributes.bad": bad_data}
assert (
find_paths_unserializable_data(
[Event("bad_event", {"bad_attribute": bad_data})],
dump=partial(dumps, cls=MockJSONEncoder),
)
== {"$[0](Event: bad_event).data.bad_attribute": bad_data}
)
assert find_paths_unserializable_data(
[Event("bad_event", {"bad_attribute": bad_data})],
dump=partial(dumps, cls=MockJSONEncoder),
) == {"$[0](Event: bad_event).data.bad_attribute": bad_data}
class BadData:
def __init__(self):
@ -166,10 +160,7 @@ def test_find_unserializable_data():
def as_dict(self):
return {"bla": self.bla}
assert (
find_paths_unserializable_data(
BadData(),
dump=partial(dumps, cls=MockJSONEncoder),
)
== {"$(BadData).bla": bad_data}
)
assert find_paths_unserializable_data(
BadData(),
dump=partial(dumps, cls=MockJSONEncoder),
) == {"$(BadData).bla": bad_data}

View file

@ -25,10 +25,7 @@ def test_substitute():
with pytest.raises(UndefinedSubstitution):
substitute(Input("hello"), {})
assert (
substitute(
{"info": [1, Input("hello"), 2, Input("world")]},
{"hello": 5, "world": 10},
)
== {"info": [1, 5, 2, 10]}
)
assert substitute(
{"info": [1, Input("hello"), 2, Input("world")]},
{"hello": 5, "world": 10},
) == {"info": [1, 5, 2, 10]}