Skip to content

Commit

Permalink
feat(api): handle main unit disconnections (#147)
Browse files Browse the repository at this point in the history
  • Loading branch information
palazzem authored Mar 1, 2024
1 parent c1807d1 commit 5afd849
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/elmo/api/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
CodeError,
CommandError,
CredentialError,
DeviceDisconnectedError,
InvalidToken,
LockError,
ParseError,
Expand Down Expand Up @@ -622,8 +623,14 @@ def query(self, query):
# Bail-out if the query is not recognized
raise QueryNotValid()

response = self._session.post(endpoint, data={"sessionId": self._session_id})
response.raise_for_status()
try:
response = self._session.post(endpoint, data={"sessionId": self._session_id})
response.raise_for_status()
except HTTPError as err:
# Handle the case when the device is disconnected
if err.response.status_code == 403 and "Centrale non connessa" in err.response.text:
raise DeviceDisconnectedError
raise err

if query in [q.SECTORS, q.INPUTS, q.OUTPUTS]:
# Retrieve description or use the cache
Expand Down
6 changes: 6 additions & 0 deletions src/elmo/api/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,9 @@ class CommandError(APIException):
"""Exception raised when the API returns an error response after issuing a command."""

default_message = "An error occurred while executing the command."


class DeviceDisconnectedError(APIException):
"""Exception raised when the device is disconnected."""

default_message = "Unable to execute commands. Device is disconnected."
17 changes: 17 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
CodeError,
CommandError,
CredentialError,
DeviceDisconnectedError,
InvalidToken,
LockError,
LockNotAcquired,
Expand Down Expand Up @@ -2414,6 +2415,22 @@ def test_client_query_invalid_response(server, mocker):
client.query(query.SECTORS)


def test_client_query_unit_disconnected(server, mocker):
# Ensure that the client catches and raises an exception when the unit is disconnected
server.add(
responses.POST,
"https://example.com/api/areas",
body='"Centrale non connessa"',
status=403,
)
client = ElmoClient(base_url="https://example.com", domain="domain")
client._session_id = "test"
mocker.patch.object(client, "_get_descriptions")
# Test
with pytest.raises(DeviceDisconnectedError):
client.query(query.SECTORS)


def test_client_get_alerts_status(server):
"""Should query a Elmo system to retrieve alerts status."""
html = """
Expand Down

0 comments on commit 5afd849

Please sign in to comment.