diff --git a/homeassistant/components/history/__init__.py b/homeassistant/components/history/__init__.py index 3b751b86c73..d402aceaa40 100644 --- a/homeassistant/components/history/__init__.py +++ b/homeassistant/components/history/__init__.py @@ -234,6 +234,7 @@ def states_to_json( axis correctly. """ result = defaultdict(list) + # Set all entity IDs to empty lists in result set to maintain the order if entity_ids is not None: for ent_id in entity_ids: result[ent_id] = [] @@ -253,7 +254,9 @@ def states_to_json( # Append all changes to it for ent_id, group in groupby(states, lambda state: state.entity_id): result[ent_id].extend(group) - return result + + # Filter out the empty lists if some states had 0 results. + return {key: val for key, val in result.items() if val} def get_state(hass, utc_point_in_time, entity_id, run=None): @@ -348,7 +351,6 @@ class HistoryPeriodView(HomeAssistantView): # Optionally reorder the result to respect the ordering given # by any entities explicitly included in the configuration. - if self.use_include_order: sorted_result = [] for order_entity in self.filters.included_entities: diff --git a/tests/components/history/test_init.py b/tests/components/history/test_init.py index ebd5991235d..68bc9c5371f 100644 --- a/tests/components/history/test_init.py +++ b/tests/components/history/test_init.py @@ -628,3 +628,25 @@ async def test_fetch_period_api(hass, hass_client): "/api/history/period/{}".format(dt_util.utcnow().isoformat()) ) assert response.status == 200 + + +async def test_fetch_period_api_with_include_order(hass, hass_client): + """Test the fetch period view for history.""" + await hass.async_add_job(init_recorder_component, hass) + await async_setup_component( + hass, + "history", + { + "history": { + "use_include_order": True, + "include": {"entities": ["light.kitchen"]}, + } + }, + ) + await hass.async_add_job(hass.data[recorder.DATA_INSTANCE].block_till_done) + client = await hass_client() + response = await client.get( + "/api/history/period/{}".format(dt_util.utcnow().isoformat()), + params={"filter_entity_id": "non.existing,something.else"}, + ) + assert response.status == 200