Skip to content

Commit

Permalink
fix: handle battery range attributes NoneType (#453)
Browse files Browse the repository at this point in the history
closes #450
  • Loading branch information
InTheDaylight14 authored Dec 21, 2022
1 parent ae8d389 commit 90f7d0d
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 12 deletions.
9 changes: 6 additions & 3 deletions custom_components/tesla_custom/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,9 +325,12 @@ def extra_state_attributes(self):
est_battery_range = self._car._vehicle_data.get("charge_state", {}).get(
"est_battery_range"
)
est_battery_range_km = DistanceConverter.convert(
est_battery_range, LENGTH_MILES, LENGTH_KILOMETERS
)
if est_battery_range is not None:
est_battery_range_km = DistanceConverter.convert(
est_battery_range, LENGTH_MILES, LENGTH_KILOMETERS
)
else:
est_battery_range_km = None

return {
"est_battery_range_miles": est_battery_range,
Expand Down
45 changes: 36 additions & 9 deletions tests/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,15 +387,42 @@ async def test_range_value(hass: HomeAssistant) -> None:
assert state.attributes.get(ATTR_DEVICE_CLASS) == SensorDeviceClass.DISTANCE
assert state.attributes.get(ATTR_STATE_CLASS) == SensorStateClass.MEASUREMENT

assert (
state.attributes.get("est_battery_range_miles")
== car_mock_data.VEHICLE_DATA["charge_state"]["est_battery_range"]
)
est_range_km = DistanceConverter.convert(
car_mock_data.VEHICLE_DATA["charge_state"]["est_battery_range"],
LENGTH_MILES,
LENGTH_KILOMETERS,
)
est_range_miles = car_mock_data.VEHICLE_DATA["charge_state"]["est_battery_range"]

assert state.attributes.get("est_battery_range_miles") == est_range_miles

if est_range_miles is not None:
est_range_km = DistanceConverter.convert(
car_mock_data.VEHICLE_DATA["charge_state"]["est_battery_range"],
LENGTH_MILES,
LENGTH_KILOMETERS,
)
else:
est_range_km = None

assert state.attributes.get("est_battery_range_km") == est_range_km


async def test_range_attributes_not_available(hass: HomeAssistant) -> None:
"""Tests range attributes handle None correctly."""
car_mock_data.VEHICLE_DATA["charge_state"]["est_battery_range"] = None

await setup_platform(hass, SENSOR_DOMAIN)

state = hass.states.get("sensor.my_model_s_range")

est_range_miles = car_mock_data.VEHICLE_DATA["charge_state"]["est_battery_range"]

assert state.attributes.get("est_battery_range_miles") == est_range_miles

if est_range_miles is not None:
est_range_km = DistanceConverter.convert(
car_mock_data.VEHICLE_DATA["charge_state"]["est_battery_range"],
LENGTH_MILES,
LENGTH_KILOMETERS,
)
else:
est_range_km = None

assert state.attributes.get("est_battery_range_km") == est_range_km

Expand Down

0 comments on commit 90f7d0d

Please sign in to comment.