From 51c3a5d11df7afe12d6c879b2b996ce123f78228 Mon Sep 17 00:00:00 2001 From: Ian Date: Sat, 4 Nov 2023 00:56:27 -0700 Subject: [PATCH] Nextbus: Listify directions (#103337) When a single value is returned, the list wrapper is not present in the json payload. This patch ensures that the result is always a list. --- .../components/nextbus/config_flow.py | 3 +- tests/components/nextbus/conftest.py | 39 +++++++++++++------ 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/homeassistant/components/nextbus/config_flow.py b/homeassistant/components/nextbus/config_flow.py index 000dd86eb52..84417a29c8d 100644 --- a/homeassistant/components/nextbus/config_flow.py +++ b/homeassistant/components/nextbus/config_flow.py @@ -16,6 +16,7 @@ from homeassistant.helpers.selector import ( ) from .const import CONF_AGENCY, CONF_ROUTE, CONF_STOP, DOMAIN +from .util import listify _LOGGER = logging.getLogger(__name__) @@ -51,7 +52,7 @@ def _get_stop_tags( title_counts = Counter(tags.values()) stop_directions: dict[str, str] = {} - for direction in route_config["route"]["direction"]: + for direction in listify(route_config["route"]["direction"]): for stop in direction["stop"]: stop_directions[stop["tag"]] = direction["name"] diff --git a/tests/components/nextbus/conftest.py b/tests/components/nextbus/conftest.py index 0940118c13a..4f6a6f22270 100644 --- a/tests/components/nextbus/conftest.py +++ b/tests/components/nextbus/conftest.py @@ -1,11 +1,37 @@ """Test helpers for NextBus tests.""" +from typing import Any from unittest.mock import MagicMock import pytest +@pytest.fixture( + params=[ + {"name": "Outbound", "stop": [{"tag": "5650"}]}, + [ + { + "name": "Outbound", + "stop": [{"tag": "5650"}], + }, + { + "name": "Inbound", + "stop": [{"tag": "5651"}], + }, + ], + ] +) +def route_config_direction(request: pytest.FixtureRequest) -> Any: + """Generate alternative directions values. + + When only on edirection is returned, it is not returned as a list, but instead an object. + """ + return request.param + + @pytest.fixture -def mock_nextbus_lists(mock_nextbus: MagicMock) -> MagicMock: +def mock_nextbus_lists( + mock_nextbus: MagicMock, route_config_direction: Any +) -> MagicMock: """Mock all list functions in nextbus to test validate logic.""" instance = mock_nextbus.return_value instance.get_agency_list.return_value = { @@ -22,16 +48,7 @@ def mock_nextbus_lists(mock_nextbus: MagicMock) -> MagicMock: # Error case test. Duplicate title with no unique direction {"tag": "5652", "title": "Market St & 7th St"}, ], - "direction": [ - { - "name": "Outbound", - "stop": [{"tag": "5650"}], - }, - { - "name": "Inbound", - "stop": [{"tag": "5651"}], - }, - ], + "direction": route_config_direction, } }