Rewrite signal_messenger unittest to pytest (#57777)

* convert signal messenger unittest to pytest

* more fixtures

* more assertions and fixed test attachment sending

* reverted unrelated changes

* fixed flake errors

* Flake8 related issues fixed

* HHTPStatus instead of int
This commit is contained in:
Antoni Różański 2021-11-06 23:36:59 +01:00 committed by GitHub
parent 3d0d038597
commit 9aec8f61d7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 111 additions and 95 deletions

View File

@ -0,0 +1,39 @@
"""Signal notification test helpers."""
from http import HTTPStatus
from pysignalclirestapi import SignalCliRestApi
import pytest
from homeassistant.components.signal_messenger.notify import SignalNotificationService
@pytest.fixture
def signal_notification_service():
"""Set up signal notification service."""
recipients = ["+435565656565"]
number = "+43443434343"
client = SignalCliRestApi("http://127.0.0.1:8080", number)
return SignalNotificationService(recipients, client)
SIGNAL_SEND_PATH_SUFIX = "/v2/send"
MESSAGE = "Testing Signal Messenger platform :)"
NUMBER_FROM = "+43443434343"
NUMBERS_TO = ["+435565656565"]
@pytest.fixture
def signal_requests_mock(requests_mock):
"""Prepare signal service mock."""
requests_mock.register_uri(
"POST",
"http://127.0.0.1:8080" + SIGNAL_SEND_PATH_SUFIX,
status_code=HTTPStatus.CREATED,
)
requests_mock.register_uri(
"GET",
"http://127.0.0.1:8080/v1/about",
status_code=HTTPStatus.OK,
json={"versions": ["v1", "v2"]},
)
return requests_mock

View File

@ -1,29 +1,31 @@
"""The tests for the signal_messenger platform.""" """The tests for the signal_messenger platform."""
from http import HTTPStatus import json
import logging
import os import os
import tempfile import tempfile
import unittest
from unittest.mock import patch from unittest.mock import patch
from pysignalclirestapi import SignalCliRestApi
import requests_mock
import homeassistant.components.signal_messenger.notify as signalmessenger
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.components.signal_messenger.conftest import (
MESSAGE,
NUMBER_FROM,
NUMBERS_TO,
SIGNAL_SEND_PATH_SUFIX,
)
BASE_COMPONENT = "notify" BASE_COMPONENT = "notify"
async def test_signal_messenger_init(hass): async def test_signal_messenger_init(hass):
"""Test that service loads successfully.""" """Test that service loads successfully."""
config = { config = {
BASE_COMPONENT: { BASE_COMPONENT: {
"name": "test", "name": "test",
"platform": "signal_messenger", "platform": "signal_messenger",
"url": "http://127.0.0.1:8080", "url": "http://127.0.0.1:8080",
"number": "+43443434343", "number": NUMBER_FROM,
"recipients": ["+435565656565"], "recipients": NUMBERS_TO,
} }
} }
@ -31,96 +33,71 @@ async def test_signal_messenger_init(hass):
assert await async_setup_component(hass, BASE_COMPONENT, config) assert await async_setup_component(hass, BASE_COMPONENT, config)
await hass.async_block_till_done() await hass.async_block_till_done()
# Test that service loads successfully
assert hass.services.has_service(BASE_COMPONENT, "test") assert hass.services.has_service(BASE_COMPONENT, "test")
class TestSignalMesssenger(unittest.TestCase): def test_send_message(signal_notification_service, signal_requests_mock, caplog):
"""Test the signal_messenger notify."""
def setUp(self):
"""Set up things to be run when tests are started."""
recipients = ["+435565656565"]
number = "+43443434343"
client = SignalCliRestApi("http://127.0.0.1:8080", number)
self._signalmessenger = signalmessenger.SignalNotificationService(
recipients, client
)
@requests_mock.Mocker()
def test_send_message(self, mock):
"""Test send message.""" """Test send message."""
message = "Testing Signal Messenger platform :)" with caplog.at_level(
mock.register_uri( logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"
"POST", ):
"http://127.0.0.1:8080/v2/send", signal_notification_service.send_message(MESSAGE)
status_code=HTTPStatus.CREATED, assert "Sending signal message" in caplog.text
) assert signal_requests_mock.called
mock.register_uri( assert signal_requests_mock.call_count == 2
"GET", assert_sending_requests(signal_requests_mock)
"http://127.0.0.1:8080/v1/about",
status_code=HTTPStatus.OK,
json={"versions": ["v1", "v2"]},
)
with self.assertLogs(
"homeassistant.components.signal_messenger.notify", level="DEBUG"
) as context:
self._signalmessenger.send_message(message)
self.assertIn("Sending signal message", context.output[0])
self.assertTrue(mock.called)
self.assertEqual(mock.call_count, 2)
@requests_mock.Mocker()
def test_send_message_should_show_deprecation_warning(self, mock): def test_send_message_should_show_deprecation_warning(
"""Test send message.""" signal_notification_service, signal_requests_mock, caplog
message = "Testing Signal Messenger platform with attachment :)" ):
mock.register_uri( """Test send message should show deprecation warning."""
"POST", with caplog.at_level(
"http://127.0.0.1:8080/v2/send", logging.WARNING, logger="homeassistant.components.signal_messenger.notify"
status_code=HTTPStatus.CREATED, ):
send_message_with_attachment(signal_notification_service, True)
assert (
"The 'attachment' option is deprecated, please replace it with 'attachments'. This option will become invalid in version 0.108"
in caplog.text
) )
mock.register_uri( assert signal_requests_mock.called
"GET", assert signal_requests_mock.call_count == 2
"http://127.0.0.1:8080/v1/about", assert_sending_requests(signal_requests_mock, 1)
status_code=HTTPStatus.OK,
json={"versions": ["v1", "v2"]},
) def test_send_message_with_attachment(
with self.assertLogs( signal_notification_service, signal_requests_mock, caplog
"homeassistant.components.signal_messenger.notify", level="WARNING" ):
) as context, tempfile.NamedTemporaryFile( """Test send message with attachment."""
suffix=".png", prefix=os.path.basename(__file__) with caplog.at_level(
logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"
):
send_message_with_attachment(signal_notification_service, False)
assert "Sending signal message" in caplog.text
assert signal_requests_mock.called
assert signal_requests_mock.call_count == 2
assert_sending_requests(signal_requests_mock, 1)
def send_message_with_attachment(signal_notification_service, deprecated=False):
"""Send message with attachment."""
with tempfile.NamedTemporaryFile(
mode="w", suffix=".png", prefix=os.path.basename(__file__)
) as tf: ) as tf:
data = {"data": {"attachment": tf.name}} tf.write("attachment_data")
self._signalmessenger.send_message(message, **data) data = {"attachment": tf.name} if deprecated else {"attachments": [tf.name]}
self.assertIn( signal_notification_service.send_message(MESSAGE, **{"data": data})
"The 'attachment' option is deprecated, please replace it with 'attachments'. This option will become invalid in version 0.108",
context.output[0],
)
self.assertTrue(mock.called)
self.assertEqual(mock.call_count, 2)
@requests_mock.Mocker()
def test_send_message_with_attachment(self, mock): def assert_sending_requests(signal_requests_mock, attachments_num=0):
"""Test send message.""" """Assert message was send with correct parameters."""
message = "Testing Signal Messenger platform :)" send_request = signal_requests_mock.request_history[-1]
mock.register_uri( assert send_request.path == SIGNAL_SEND_PATH_SUFIX
"POST",
"http://127.0.0.1:8080/v2/send", body_request = json.loads(send_request.text)
status_code=HTTPStatus.CREATED, assert body_request["message"] == MESSAGE
) assert body_request["number"] == NUMBER_FROM
mock.register_uri( assert body_request["recipients"] == NUMBERS_TO
"GET", assert len(body_request["base64_attachments"]) == attachments_num
"http://127.0.0.1:8080/v1/about",
status_code=HTTPStatus.OK,
json={"versions": ["v1", "v2"]},
)
with self.assertLogs(
"homeassistant.components.signal_messenger.notify", level="DEBUG"
) as context, tempfile.NamedTemporaryFile(
suffix=".png", prefix=os.path.basename(__file__)
) as tf:
data = {"data": {"attachments": [tf.name]}}
self._signalmessenger.send_message(message, **data)
self.assertIn("Sending signal message", context.output[0])
self.assertTrue(mock.called)
self.assertEqual(mock.call_count, 2)