diff --git a/homeassistant/components/wallbox/__init__.py b/homeassistant/components/wallbox/__init__.py index 63fe37732dc..aeacee9b943 100644 --- a/homeassistant/components/wallbox/__init__.py +++ b/homeassistant/components/wallbox/__init__.py @@ -121,19 +121,5 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry): return unload_ok -class CannotConnect(exceptions.HomeAssistantError): - """Error to indicate we cannot connect.""" - - def __init__(self, msg=""): - """Create a log record.""" - super().__init__() - _LOGGER.error("Cannot connect to Wallbox API. %s", msg) - - class InvalidAuth(exceptions.HomeAssistantError): """Error to indicate there is invalid auth.""" - - def __init__(self, msg=""): - """Create a log record.""" - super().__init__() - _LOGGER.error("Cannot authenticate with Wallbox API. %s", msg) diff --git a/homeassistant/components/wallbox/config_flow.py b/homeassistant/components/wallbox/config_flow.py index 69b01d96c40..f9fdef3c5af 100644 --- a/homeassistant/components/wallbox/config_flow.py +++ b/homeassistant/components/wallbox/config_flow.py @@ -4,7 +4,7 @@ import voluptuous as vol from homeassistant import config_entries, core from homeassistant.const import CONF_PASSWORD, CONF_USERNAME -from . import CannotConnect, InvalidAuth, WallboxHub +from . import InvalidAuth, WallboxHub from .const import CONF_STATION, DOMAIN COMPONENT_DOMAIN = DOMAIN @@ -46,7 +46,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=COMPONENT_DOMAIN): try: info = await validate_input(self.hass, user_input) - except CannotConnect: + except ConnectionError: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" diff --git a/tests/components/wallbox/__init__.py b/tests/components/wallbox/__init__.py index 35bf3cee242..21554cc4456 100644 --- a/tests/components/wallbox/__init__.py +++ b/tests/components/wallbox/__init__.py @@ -1 +1,44 @@ """Tests for the Wallbox integration.""" + +import json + +import requests_mock + +from homeassistant.components.wallbox.const import CONF_STATION, DOMAIN +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME + +from tests.common import MockConfigEntry + +test_response = json.loads( + '{"charging_power": 0,"max_available_power": "xx","charging_speed": 0,"added_range": "xx","added_energy": "44.697"}' +) + + +async def setup_integration(hass): + """Test wallbox sensor class setup.""" + + entry = MockConfigEntry( + domain=DOMAIN, + data={ + CONF_USERNAME: "test_username", + CONF_PASSWORD: "test_password", + CONF_STATION: "12345", + }, + entry_id="testEntry", + ) + + entry.add_to_hass(hass) + + with requests_mock.Mocker() as mock_request: + mock_request.get( + "https://api.wall-box.com/auth/token/user", + text='{"jwt":"fakekeyhere","user_id":12345,"ttl":145656758,"error":false,"status":200}', + status_code=200, + ) + mock_request.get( + "https://api.wall-box.com/chargers/status/12345", + json=test_response, + status_code=200, + ) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() diff --git a/tests/components/wallbox/test_config_flow.py b/tests/components/wallbox/test_config_flow.py index 074f67abe2c..6b5a05a3486 100644 --- a/tests/components/wallbox/test_config_flow.py +++ b/tests/components/wallbox/test_config_flow.py @@ -1,13 +1,18 @@ """Test the Wallbox config flow.""" +import json from unittest.mock import patch -from voluptuous.schema_builder import raises +import requests_mock from homeassistant import config_entries, data_entry_flow -from homeassistant.components.wallbox import CannotConnect, InvalidAuth, config_flow +from homeassistant.components.wallbox import InvalidAuth, config_flow from homeassistant.components.wallbox.const import DOMAIN from homeassistant.core import HomeAssistant +test_response = json.loads( + '{"charging_power": 0,"max_available_power": 25,"charging_speed": 0,"added_range": 372,"added_energy": 44.697}' +) + async def test_show_set_form(hass: HomeAssistant) -> None: """Test that the setup form is served.""" @@ -42,16 +47,31 @@ async def test_form_invalid_auth(hass): assert result2["errors"] == {"base": "invalid_auth"} -async def test_form_cannot_connect(hass): +async def test_form_cannot_authenticate(hass): """Test we handle cannot connect error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) - with patch( - "homeassistant.components.wallbox.config_flow.WallboxHub.async_authenticate", - side_effect=CannotConnect, - ): + with requests_mock.Mocker() as mock_request: + mock_request.get( + "https://api.wall-box.com/auth/token/user", + text='{"jwt":"fakekeyhere","user_id":12345,"ttl":145656758,"error":false,"status":200}', + status_code=403, + ) + mock_request.get( + "https://api.wall-box.com/chargers/status/12345", + text='{"Temperature": 100, "Location": "Toronto", "Datetime": "2020-07-23", "Units": "Celsius"}', + status_code=403, + ) + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + "station": "12345", + "username": "test-username", + "password": "test-password", + }, + ) result2 = await hass.config_entries.flow.async_configure( result["flow_id"], { @@ -65,64 +85,61 @@ async def test_form_cannot_connect(hass): assert result2["errors"] == {"base": "invalid_auth"} -async def test_validate_input(hass): - """Test we can validate input.""" - data = { - "station": "12345", - "username": "test-username", - "password": "test-password", - } +async def test_form_cannot_connect(hass): + """Test we handle cannot connect error.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) - def alternate_authenticate_method(): - return None + with requests_mock.Mocker() as mock_request: + mock_request.get( + "https://api.wall-box.com/auth/token/user", + text='{"jwt":"fakekeyhere","user_id":12345,"ttl":145656758,"error":false,"status":200}', + status_code=200, + ) + mock_request.get( + "https://api.wall-box.com/chargers/status/12345", + text='{"Temperature": 100, "Location": "Toronto", "Datetime": "2020-07-23", "Units": "Celsius"}', + status_code=404, + ) + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + "station": "12345", + "username": "test-username", + "password": "test-password", + }, + ) - def alternate_get_charger_status_method(station): - data = '{"Temperature": 100, "Location": "Toronto", "Datetime": "2020-07-23", "Units": "Celsius"}' - return data - - with patch( - "wallbox.Wallbox.authenticate", - side_effect=alternate_authenticate_method, - ), patch( - "wallbox.Wallbox.getChargerStatus", - side_effect=alternate_get_charger_status_method, - ): - - result = await config_flow.validate_input(hass, data) - - assert result == {"title": "Wallbox Portal"} + assert result2["type"] == "form" + assert result2["errors"] == {"base": "cannot_connect"} -async def test_configflow_class(): - """Test configFlow class.""" - configflow = config_flow.ConfigFlow() - assert configflow +async def test_form_validate_input(hass): + """Test we handle cannot connect error.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) - with patch( - "homeassistant.components.wallbox.config_flow.validate_input", - side_effect=TypeError, - ), raises(Exception): - assert await configflow.async_step_user(True) + with requests_mock.Mocker() as mock_request: + mock_request.get( + "https://api.wall-box.com/auth/token/user", + text='{"jwt":"fakekeyhere","user_id":12345,"ttl":145656758,"error":false,"status":200}', + status_code=200, + ) + mock_request.get( + "https://api.wall-box.com/chargers/status/12345", + text='{"Temperature": 100, "Location": "Toronto", "Datetime": "2020-07-23", "Units": "Celsius"}', + status_code=200, + ) + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + "station": "12345", + "username": "test-username", + "password": "test-password", + }, + ) - with patch( - "homeassistant.components.wallbox.config_flow.validate_input", - side_effect=CannotConnect, - ), raises(Exception): - assert await configflow.async_step_user(True) - - with patch( - "homeassistant.components.wallbox.config_flow.validate_input", - ), raises(Exception): - assert await configflow.async_step_user(True) - - -def test_cannot_connect_class(): - """Test cannot Connect class.""" - cannot_connect = CannotConnect - assert cannot_connect - - -def test_invalid_auth_class(): - """Test invalid auth class.""" - invalid_auth = InvalidAuth - assert invalid_auth + assert result2["title"] == "Wallbox Portal" + assert result2["data"]["station"] == "12345" diff --git a/tests/components/wallbox/test_init.py b/tests/components/wallbox/test_init.py index d03974d1dfe..874629bac3e 100644 --- a/tests/components/wallbox/test_init.py +++ b/tests/components/wallbox/test_init.py @@ -1,16 +1,12 @@ """Test Wallbox Init Component.""" import json -import pytest -import requests_mock -from voluptuous.schema_builder import raises - -from homeassistant.components import wallbox from homeassistant.components.wallbox.const import CONF_STATION, DOMAIN from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant from tests.common import MockConfigEntry +from tests.components.wallbox import setup_integration entry = MockConfigEntry( domain=DOMAIN, @@ -31,135 +27,9 @@ test_response_rounding_error = json.loads( ) -async def test_wallbox_setup_entry(hass: HomeAssistant): - """Test Wallbox Setup.""" - with requests_mock.Mocker() as m: - m.get( - "https://api.wall-box.com/auth/token/user", - text='{"jwt":"fakekeyhere","user_id":12345,"ttl":145656758,"error":false,"status":200}', - status_code=200, - ) - m.get( - "https://api.wall-box.com/chargers/status/12345", - text='{"Temperature": 100, "Location": "Toronto", "Datetime": "2020-07-23", "Units": "Celsius"}', - status_code=200, - ) - assert await wallbox.async_setup_entry(hass, entry) - - with requests_mock.Mocker() as m, raises(ConnectionError): - m.get( - "https://api.wall-box.com/auth/token/user", - text='{"jwt":"fakekeyhere","user_id":12345,"ttl":145656758,"error":false,"status":404}', - status_code=404, - ) - assert await wallbox.async_setup_entry(hass, entry) is False - - async def test_wallbox_unload_entry(hass: HomeAssistant): """Test Wallbox Unload.""" - hass.data[DOMAIN] = {"connections": {entry.entry_id: entry}} - assert await wallbox.async_unload_entry(hass, entry) + await setup_integration(hass) - hass.data[DOMAIN] = {"fail_entry": entry} - - with pytest.raises(KeyError): - await wallbox.async_unload_entry(hass, entry) - - -async def test_get_data(hass: HomeAssistant): - """Test hub class, get_data.""" - - station = ("12345",) - username = ("test-username",) - password = "test-password" - - hub = wallbox.WallboxHub(station, username, password, hass) - - with requests_mock.Mocker() as m: - m.get( - "https://api.wall-box.com/auth/token/user", - text='{"jwt":"fakekeyhere","user_id":12345,"ttl":145656758,"error":false,"status":200}', - status_code=200, - ) - m.get( - "https://api.wall-box.com/chargers/status/('12345',)", - json=test_response, - status_code=200, - ) - assert await hub.async_get_data() - - -async def test_get_data_rounding_error(hass: HomeAssistant): - """Test hub class, get_data with rounding error.""" - - station = ("12345",) - username = ("test-username",) - password = "test-password" - - hub = wallbox.WallboxHub(station, username, password, hass) - - with requests_mock.Mocker() as m: - m.get( - "https://api.wall-box.com/auth/token/user", - text='{"jwt":"fakekeyhere","user_id":12345,"ttl":145656758,"error":false,"status":200}', - status_code=200, - ) - m.get( - "https://api.wall-box.com/chargers/status/('12345',)", - json=test_response_rounding_error, - status_code=200, - ) - assert await hub.async_get_data() - - -async def test_authentication_exception(hass: HomeAssistant): - """Test hub class, authentication raises exception.""" - - station = ("12345",) - username = ("test-username",) - password = "test-password" - - hub = wallbox.WallboxHub(station, username, password, hass) - - with requests_mock.Mocker() as m, raises(wallbox.InvalidAuth): - m.get("https://api.wall-box.com/auth/token/user", text="data", status_code=403) - - assert await hub.async_authenticate() - - with requests_mock.Mocker() as m, raises(ConnectionError): - m.get("https://api.wall-box.com/auth/token/user", text="data", status_code=404) - - assert await hub.async_authenticate() - - with requests_mock.Mocker() as m, raises(wallbox.InvalidAuth): - m.get("https://api.wall-box.com/auth/token/user", text="data", status_code=403) - m.get( - "https://api.wall-box.com/chargers/status/test", - json=test_response, - status_code=403, - ) - assert await hub.async_get_data() - - -async def test_get_data_exception(hass: HomeAssistant): - """Test hub class, authentication raises exception.""" - - station = ("12345",) - username = ("test-username",) - password = "test-password" - - hub = wallbox.WallboxHub(station, username, password, hass) - - with requests_mock.Mocker() as m, raises(ConnectionError): - m.get( - "https://api.wall-box.com/auth/token/user", - text='{"jwt":"fakekeyhere","user_id":12345,"ttl":145656758,"error":false,"status":200}', - status_code=200, - ) - m.get( - "https://api.wall-box.com/chargers/status/('12345',)", - text="data", - status_code=404, - ) - assert await hub.async_get_data() + assert await hass.config_entries.async_unload(entry.entry_id) diff --git a/tests/components/wallbox/test_sensor.py b/tests/components/wallbox/test_sensor.py index 5c0c3511a30..b88ed094fda 100644 --- a/tests/components/wallbox/test_sensor.py +++ b/tests/components/wallbox/test_sensor.py @@ -1,13 +1,10 @@ """Test Wallbox Switch component.""" -import json -from unittest.mock import MagicMock - -from homeassistant.components.wallbox import sensor from homeassistant.components.wallbox.const import CONF_STATION, DOMAIN from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from tests.common import MockConfigEntry +from tests.components.wallbox import setup_integration entry = MockConfigEntry( domain=DOMAIN, @@ -19,63 +16,17 @@ entry = MockConfigEntry( entry_id="testEntry", ) -test_response = json.loads( - '{"charging_power": 0,"max_available_power": 25,"charging_speed": 0,"added_range": 372,"added_energy": 44.697}' -) -test_response_rounding_error = json.loads( - '{"charging_power": "XX","max_available_power": "xx","charging_speed": 0,"added_range": "xx","added_energy": "XX"}' -) - -CONF_STATION = ("12345",) -CONF_USERNAME = ("test-username",) -CONF_PASSWORD = "test-password" - -# wallbox = WallboxHub(CONF_STATION, CONF_USERNAME, CONF_PASSWORD, hass) - - -async def test_wallbox_sensor_class(): +async def test_wallbox_sensor_class(hass): """Test wallbox sensor class.""" - coordinator = MagicMock(return_value="connected") - idx = 1 - ent = "charging_power" + await setup_integration(hass) - wallboxSensor = sensor.WallboxSensor(coordinator, idx, ent, entry) + state = hass.states.get("sensor.mock_title_charging_power") + assert state.attributes["unit_of_measurement"] == "kW" + assert state.attributes["icon"] == "mdi:ev-station" + assert state.name == "Mock Title Charging Power" - assert wallboxSensor.icon == "mdi:ev-station" - assert wallboxSensor.unit_of_measurement == "kW" - assert wallboxSensor.name == "Mock Title Charging Power" - assert wallboxSensor.state - - -# async def test_wallbox_updater(hass: HomeAssistantType): -# """Test wallbox updater.""" -# with requests_mock.Mocker() as m: -# m.get( -# "https://api.wall-box.com/auth/token/user", -# text='{"jwt":"fakekeyhere","user_id":12345,"ttl":145656758,"error":false,"status":200}', -# status_code=200, -# ) -# m.get( -# "https://api.wall-box.com/chargers/status/('12345',)", -# json=test_response, -# status_code=200, -# ) -# await sensor.wallbox_updater(wallbox, hass) - - -# async def test_wallbox_updater_rounding_error(hass: HomeAssistantType): -# """Test wallbox updater rounding error.""" -# with requests_mock.Mocker() as m: -# m.get( -# "https://api.wall-box.com/auth/token/user", -# text='{"jwt":"fakekeyhere","user_id":12345,"ttl":145656758,"error":false,"status":200}', -# status_code=200, -# ) -# m.get( -# "https://api.wall-box.com/chargers/status/('12345',)", -# json=test_response_rounding_error, -# status_code=200, -# ) -# await sensor.wallbox_updater(wallbox, hass) + state = hass.states.get("sensor.mock_title_charging_speed") + assert state.attributes["icon"] == "mdi:speedometer" + assert state.name == "Mock Title Charging Speed"