"""test_signal_alert.""" from __future__ import annotations from os import environ from typing import TYPE_CHECKING import httpx from python.signal_alert import signal_alert if TYPE_CHECKING: from pytest_mock import MockerFixture def test_signal_alert(mocker: MockerFixture) -> None: """test_signal_alert.""" environ["SIGNAL_ALERT_FROM_PHONE"] = "1234567890" environ["SIGNAL_ALERT_TO_PHONE"] = "0987654321" mock_logger = mocker.patch("python.signal_alert.logger") mock_response = mocker.MagicMock(spec=httpx.Response, status_code=httpx.codes.CREATED) mock_post = mocker.patch("python.signal_alert.httpx.post", return_value=mock_response) signal_alert("test") mock_logger.info.assert_not_called() mock_post.assert_called_once_with( "http://localhost:8989/v2/send", json={ "message": "test", "number": "1234567890", "recipients": ["0987654321"], "text_mode": "normal", }, timeout=4.0, follow_redirects=True, ) def test_signal_alert_no_phones(mocker: MockerFixture) -> None: """test_signal_alert_no_phones.""" if "SIGNAL_ALERT_FROM_PHONE" in environ: del environ["SIGNAL_ALERT_FROM_PHONE"] if "SIGNAL_ALERT_TO_PHONE" in environ: del environ["SIGNAL_ALERT_TO_PHONE"] mock_logger = mocker.patch("python.signal_alert.logger") signal_alert("test") mock_logger.info.assert_called_once_with("SIGNAL_ALERT_FROM_PHONE or SIGNAL_ALERT_TO_PHONE not set") def test_signal_alert_http_error(mocker: MockerFixture) -> None: """HTTP errors are logged rather than propagated.""" environ["SIGNAL_ALERT_FROM_PHONE"] = "1234567890" environ["SIGNAL_ALERT_TO_PHONE"] = "0987654321" mock_logger = mocker.patch("python.signal_alert.logger") request = httpx.Request("POST", "http://localhost:8989/v2/send") mocker.patch( "python.signal_alert.httpx.post", side_effect=httpx.ConnectError("connection failed", request=request), ) signal_alert("test") mock_logger.exception.assert_called_once_with("Unable to contact the Signal API") def test_signal_alert_unsuccessful_response(mocker: MockerFixture) -> None: """Unexpected response statuses are logged.""" environ["SIGNAL_ALERT_FROM_PHONE"] = "1234567890" environ["SIGNAL_ALERT_TO_PHONE"] = "0987654321" mock_logger = mocker.patch("python.signal_alert.logger") mock_response = mocker.MagicMock(spec=httpx.Response, status_code=httpx.codes.BAD_GATEWAY) mocker.patch("python.signal_alert.httpx.post", return_value=mock_response) signal_alert("test") mock_logger.error.assert_called_once_with("Signal API returned HTTP status %d", httpx.codes.BAD_GATEWAY)