Fix keyerror when no previous Picnic orders exist (#62870)

This commit is contained in:
corneyl 2021-12-27 20:31:35 +01:00 committed by GitHub
parent 1f425b1942
commit 7fc5605639
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 6 deletions

View file

@ -60,11 +60,11 @@ class PicnicUpdateCoordinator(DataUpdateCoordinator):
"""Fetch the data from the Picnic API and return a flat dict with only needed sensor data."""
# Fetch from the API and pre-process the data
cart = self.picnic_api_client.get_cart()
last_order = self._get_last_order()
if not cart or not last_order:
if not cart:
raise UpdateFailed("API response doesn't contain expected data.")
last_order = self._get_last_order()
slot_data = self._get_slot_data(cart)
return {
@ -102,11 +102,12 @@ class PicnicUpdateCoordinator(DataUpdateCoordinator):
"""Get data of the last order from the list of deliveries."""
# Get the deliveries
deliveries = self.picnic_api_client.get_deliveries(summary=True)
if not deliveries:
return {}
# Determine the last order
last_order = copy.deepcopy(deliveries[0])
# Determine the last order and return an empty dict if there is none
try:
last_order = copy.deepcopy(deliveries[0])
except KeyError:
return {}
# Get the position details if the order is not delivered yet
delivery_position = {}

View file

@ -387,6 +387,21 @@ class TestPicnicSensor(unittest.IsolatedAsyncioTestCase):
self._assert_sensor("sensor.picnic_last_order_eta_end", STATE_UNAVAILABLE)
self._assert_sensor("sensor.picnic_last_order_delivery_time", STATE_UNAVAILABLE)
async def test_sensors_malformed_delivery_data(self):
"""Test sensor states when the delivery api returns not a list."""
# Setup platform with default responses
await self._setup_platform(use_default_responses=True)
# Change mock responses to empty data and refresh the coordinator
self.picnic_mock().get_deliveries.return_value = {"error": "message"}
await self._coordinator.async_refresh()
# Assert all last-order sensors have STATE_UNAVAILABLE because the delivery info fetch failed
assert self._coordinator.last_update_success is True
self._assert_sensor("sensor.picnic_last_order_eta_start", STATE_UNKNOWN)
self._assert_sensor("sensor.picnic_last_order_eta_end", STATE_UNKNOWN)
self._assert_sensor("sensor.picnic_last_order_delivery_time", STATE_UNKNOWN)
async def test_sensors_malformed_response(self):
"""Test coordinator update fails when API yields ValueError."""
# Setup platform with default responses