diff --git a/omnikinverter/omnikinverter.py b/omnikinverter/omnikinverter.py index 9ed3526c..de47c9fa 100644 --- a/omnikinverter/omnikinverter.py +++ b/omnikinverter/omnikinverter.py @@ -12,7 +12,11 @@ from aiohttp.hdrs import METH_GET from yarl import URL -from .exceptions import OmnikInverterConnectionError, OmnikInverterError +from .exceptions import ( + OmnikInverterAuthError, + OmnikInverterConnectionError, + OmnikInverterError, +) from .models import Device, Inverter @@ -50,6 +54,7 @@ async def request( Raises: OmnikInverterConnectionError: An error occurred while communicating with the Omnik Inverter. + OmnikInverterAuthError: Authentication failed with the Omnik Inverter. OmnikInverterError: Received an unexpected response from the Omnik Inverter. """ url = URL.build(scheme="http", host=self.host, path="/").join(URL(uri)) @@ -62,6 +67,12 @@ async def request( self.session = ClientSession() self._close_session = True + if self.source_type == "html" and ( + self.username is None or self.password is None + ): + raise OmnikInverterAuthError( + "A username and/or password is missing from the request" + ) auth = None if self.username and self.password: auth = aiohttp.BasicAuth(self.username, self.password) diff --git a/tests/test_omnik.py b/tests/test_omnik.py index c4551fc0..9ae92666 100644 --- a/tests/test_omnik.py +++ b/tests/test_omnik.py @@ -10,7 +10,7 @@ OmnikInverterConnectionError, OmnikInverterWrongSourceError, ) -from omnikinverter.exceptions import OmnikInverterError +from omnikinverter.exceptions import OmnikInverterAuthError, OmnikInverterError from . import load_fixtures @@ -97,6 +97,25 @@ async def test_wrong_html_source(aresponses): assert await client.inverter() +@pytest.mark.asyncio +async def test_html_no_auth(aresponses): + """Test on html request without auth.""" + aresponses.add( + "example.com", + "/status.html", + "GET", + aresponses.Response( + status=200, + headers={"Content-Type": "text/html"}, + ), + ) + + async with aiohttp.ClientSession() as session: + client = OmnikInverter(host="example.com", source_type="html", session=session) + with pytest.raises(OmnikInverterAuthError): + assert await client.inverter() + + @pytest.mark.asyncio async def test_timeout(aresponses): """Test request timeout from Omnik Inverter."""