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.""" """Test send message."""
with caplog.at_level(
logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"
):
signal_notification_service.send_message(MESSAGE)
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)
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_should_show_deprecation_warning(
def test_send_message(self, mock): signal_notification_service, signal_requests_mock, caplog
"""Test send message.""" ):
message = "Testing Signal Messenger platform :)" """Test send message should show deprecation warning."""
mock.register_uri( with caplog.at_level(
"POST", logging.WARNING, logger="homeassistant.components.signal_messenger.notify"
"http://127.0.0.1:8080/v2/send", ):
status_code=HTTPStatus.CREATED, send_message_with_attachment(signal_notification_service, True)
)
mock.register_uri(
"GET",
"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() assert (
def test_send_message_should_show_deprecation_warning(self, mock): "The 'attachment' option is deprecated, please replace it with 'attachments'. This option will become invalid in version 0.108"
"""Test send message.""" in caplog.text
message = "Testing Signal Messenger platform with attachment :)" )
mock.register_uri( assert signal_requests_mock.called
"POST", assert signal_requests_mock.call_count == 2
"http://127.0.0.1:8080/v2/send", assert_sending_requests(signal_requests_mock, 1)
status_code=HTTPStatus.CREATED,
)
mock.register_uri(
"GET",
"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="WARNING"
) as context, tempfile.NamedTemporaryFile(
suffix=".png", prefix=os.path.basename(__file__)
) as tf:
data = {"data": {"attachment": tf.name}}
self._signalmessenger.send_message(message, **data)
self.assertIn(
"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 test_send_message_with_attachment(
"""Test send message.""" signal_notification_service, signal_requests_mock, caplog
message = "Testing Signal Messenger platform :)" ):
mock.register_uri( """Test send message with attachment."""
"POST", with caplog.at_level(
"http://127.0.0.1:8080/v2/send", logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"
status_code=HTTPStatus.CREATED, ):
) send_message_with_attachment(signal_notification_service, False)
mock.register_uri(
"GET", assert "Sending signal message" in caplog.text
"http://127.0.0.1:8080/v1/about", assert signal_requests_mock.called
status_code=HTTPStatus.OK, assert signal_requests_mock.call_count == 2
json={"versions": ["v1", "v2"]}, assert_sending_requests(signal_requests_mock, 1)
)
with self.assertLogs(
"homeassistant.components.signal_messenger.notify", level="DEBUG" def send_message_with_attachment(signal_notification_service, deprecated=False):
) as context, tempfile.NamedTemporaryFile( """Send message with attachment."""
suffix=".png", prefix=os.path.basename(__file__) with tempfile.NamedTemporaryFile(
) as tf: mode="w", suffix=".png", prefix=os.path.basename(__file__)
data = {"data": {"attachments": [tf.name]}} ) as tf:
self._signalmessenger.send_message(message, **data) tf.write("attachment_data")
self.assertIn("Sending signal message", context.output[0]) data = {"attachment": tf.name} if deprecated else {"attachments": [tf.name]}
self.assertTrue(mock.called) signal_notification_service.send_message(MESSAGE, **{"data": data})
self.assertEqual(mock.call_count, 2)
def assert_sending_requests(signal_requests_mock, attachments_num=0):
"""Assert message was send with correct parameters."""
send_request = signal_requests_mock.request_history[-1]
assert send_request.path == SIGNAL_SEND_PATH_SUFIX
body_request = json.loads(send_request.text)
assert body_request["message"] == MESSAGE
assert body_request["number"] == NUMBER_FROM
assert body_request["recipients"] == NUMBERS_TO
assert len(body_request["base64_attachments"]) == attachments_num