Example #1
0
async def test_update_device(hass):
    """Test that update works."""
    host = "1.2.3.4"
    entry = MockConfigEntry(domain=dynalite.DOMAIN,
                            data={dynalite.CONF_HOST: host})
    entry.add_to_hass(hass)
    with patch("homeassistant.components.dynalite.bridge.DynaliteDevices"
               ) as mock_dyn_dev:
        mock_dyn_dev().async_setup = CoroutineMock(return_value=True)
        assert await hass.config_entries.async_setup(entry.entry_id)
        # Not waiting so it add the devices before registration
        update_device_func = mock_dyn_dev.mock_calls[1][2][
            "update_device_func"]
    device = Mock()
    device.unique_id = "abcdef"
    wide_func = Mock()
    async_dispatcher_connect(hass, f"dynalite-update-{host}", wide_func)
    specific_func = Mock()
    async_dispatcher_connect(hass,
                             f"dynalite-update-{host}-{device.unique_id}",
                             specific_func)
    update_device_func(CONF_ALL)
    await hass.async_block_till_done()
    wide_func.assert_called_once()
    specific_func.assert_not_called()
    update_device_func(device)
    await hass.async_block_till_done()
    wide_func.assert_called_once()
    specific_func.assert_called_once()
class TestValidateDecoratorTestCase(TestCase):
    def setUp(self):
        self.dummy_func = Mock()
        self.self_dummy = Mock(
            request=Mock(),
            _schemas={
                "post": Schema(
                    {"job_id": Coerce(int), "email": Email(), "template": str}
                )
            },
        )

    def test_validation_passed(self):
        self.self_dummy.request.method = "POST"
        self.self_dummy.request.body = (
            b'{"job_id": 12, "email": "*****@*****.**", "template": "Hello!"}'
        )

        validate_json(self.dummy_func)(self.self_dummy)

        self.dummy_func.assert_called_once_with(
            self.self_dummy,
            {"job_id": 12, "email": "*****@*****.**", "template": "Hello!"},
        )

    def test_validation_invalid(self):
        self.self_dummy.request.method = "POST"
        self.self_dummy.request.body = (
            b'{"job_id": "test", "email": "*****@*****.**", "template": "Hello!"}'
        )

        with self.assertRaises(ValidationError):
            validate_json(self.dummy_func)(self.self_dummy)

        self.dummy_func.assert_not_called()

    def test_schema_not_found(self):
        self.self_dummy.request.method = "PUT"
        self.self_dummy.request.body = (
            b'{"job_id": 12, "email": "*****@*****.**", "template": "Hello!"}'
        )

        with self.assertRaises(ValidationError):
            validate_json(self.dummy_func)(self.self_dummy)

        self.dummy_func.assert_not_called()

    def test_invalid_json(self):
        self.self_dummy.request.method = "POST"
        self.self_dummy.request.body = b"Hello"

        with self.assertRaises(UnsupportedFormatError):
            validate_json(self.dummy_func)(self.self_dummy)

        self.dummy_func.assert_not_called()
def test_maybe_init_is_not_main(cli_mock: Mock) -> None:
    """Test cli not called when file is not main."""
    cli_module.maybe_init()
    cli_mock.assert_not_called()
Example #4
0
class MockGateway:
    """Class to mock a TCP gateway."""
    def __init__(self, request, message_delay_zero):
        """Initialize the class."""
        request.addfinalizer(self.fin)
        self.reader = None
        self.writer = None
        self.server = None
        self.in_buffer = bytearray()
        self.new_dev_func = Mock()
        self.update_dev_func = Mock()
        self.exceptions = []
        if message_delay_zero:
            with patch("dynalite_devices_lib.dynalite.MESSAGE_DELAY", 0):
                self.dyn_dev = DynaliteDevices(
                    new_device_func=self.new_dev_func,
                    update_device_func=self.update_dev_func,
                )
        else:
            self.dyn_dev = DynaliteDevices(
                new_device_func=self.new_dev_func,
                update_device_func=self.update_dev_func,
            )

    async def run_server(self):
        """Run the actual server."""
        async def handle_connection(reader, writer):
            """Run a single session. Assumes only one for tests."""
            assert not self.reader and not self.writer
            self.reader = reader
            self.writer = writer
            while not reader.at_eof():
                data = await reader.read(100)
                addr = writer.get_extra_info("peername")
                dyn_const.LOGGER.debug("Received message from %s - %s", addr,
                                       [int(byte) for byte in data])
                for byte in data:
                    self.in_buffer.append(byte)
            self.reader = self.writer = None

        self.server = await asyncio.start_server(handle_connection,
                                                 "127.0.0.1", 12345)
        addr = self.server.sockets[0].getsockname()
        dyn_const.LOGGER.debug("Serving on %s", addr)
        async with self.server:
            await self.server.serve_forever()

    async def async_setup_server(self):
        """Start the server."""
        def exc_handle(loop, context):
            """Handle exceptions by rethrowing them, which will fail the test."""
            self.exceptions.append(context["exception"])

        asyncio.get_event_loop().set_exception_handler(exc_handle)
        asyncio.create_task(self.run_server())
        await asyncio.sleep(0.01)

    async def check_writes(self, packets):
        """Check that a set of packets was written."""
        await asyncio.sleep(0.01)
        assert len(self.in_buffer) == len(packets) * 8
        received = [
            self.in_buffer[i * 8:i * 8 + 8] for i in range(0, len(packets))
        ]
        for packet in packets:
            assert packet.msg in received
        self.reset()

    async def check_single_write(self, packet):
        """Check that there was only a single packet written."""
        await self.check_writes([packet])

    async def receive_message(self, message):
        """Fake a received message."""
        self.writer.write(message)
        await self.writer.drain()
        await asyncio.sleep(0.01)

    async def receive(self, packet):
        """Fake a received packet."""
        await self.receive_message(packet.msg)

    def configure_dyn_dev(self, config, num_devices=1):
        """Configure the DynaliteDevices."""
        self.new_dev_func.reset_mock()
        self.dyn_dev.configure(config)
        if num_devices == 0:
            self.new_dev_func.assert_not_called()
            return None
        self.new_dev_func.assert_called_once()
        assert len(self.new_dev_func.mock_calls[0][1][0]) == num_devices
        return self.new_dev_func.mock_calls[0][1][0]

    async def async_setup_dyn_dev(self):
        """Set up the internal DynaliteDevices."""
        return await self.dyn_dev.async_setup()

    def reset(self):
        """Reset the in buffer."""
        self.in_buffer = bytearray()

    def reset_connection(self):
        """Reset the current connection."""
        if self.writer:
            self.writer.close()

    async def shutdown(self):
        """Shut down the server."""
        self.reset_connection()
        self.server.close()
        await self.server.wait_closed()

    async def async_fin(self):
        """Shut the gateway down."""
        await self.shutdown()
        await self.dyn_dev.async_reset()

    def fin(self):
        """Run shutdown async."""
        asyncio.get_event_loop().run_until_complete(self.async_fin())
        for ex in self.exceptions:
            raise ex