Exemplo n.º 1
0
    async def test_logger_handlers_are_not_initialized_twice(self):
        condition = asyncio.Condition()
        initialize_meta = {'count': 0}

        async def create_handlers():
            async with condition:
                await condition.wait_for(
                    predicate=lambda: initialize_meta['count'] == 4)

            return await Logger._create_default_handlers()

        handlers_factory = CoroutineMock(side_effect=create_handlers)

        logger = Logger(handler_factory=handlers_factory)

        original_initialize = logger._initialize

        async def initialize():
            async with condition:
                initialize_meta['count'] += 1
                condition.notify_all()
            await original_initialize()

        patch.object(logger, '_initialize', initialize).start()

        await asyncio.gather(
            logger.info('sardinha'),
            logger.info('tilápia'),
            logger.info('xerelete'),
            logger.error('fraldinha'),
        )

        handlers_factory.assert_called_once()
        await logger.shutdown()
async def test_connect(mocker):
    connection = StunIPConnection(site_id="home",
                                  email="*****@*****.**",
                                  panel_serial="0584b067",
                                  password="******")

    protocol = mocker.Mock()
    protocol.is_active.return_value = True

    create_connection_mock = CoroutineMock(return_value=(None, protocol))
    mocker.patch.object(connection.loop, "create_connection",
                        create_connection_mock)
    connect_command_execute = mocker.patch.object(IPModuleConnectCommand,
                                                  "execute", CoroutineMock())

    stun_session_connect = mocker.patch.object(StunSession, "connect",
                                               CoroutineMock())
    stun_session_get_socket = mocker.patch.object(StunSession,
                                                  "get_socket",
                                                  return_value=mocker.Mock())

    assert connection.connected is False

    await connection.connect()

    create_connection_mock.assert_called_once()
    stun_session_connect.assert_called_once()
    connect_command_execute.assert_called_once()
    stun_session_get_socket.assert_called_once()

    assert connection.connected is True
Exemplo n.º 3
0
async def test_watchdog_firing():
    """Test that the watchdog expiring fires the provided coroutine."""
    mock_coro = CoroutineMock()
    mock_coro.__name__ = "mock_coro"

    watchdog = WebsocketWatchdog(mock_coro)

    await watchdog.on_expire()
    mock_coro.assert_called_once()
async def test_gather_without_exceptions_subclass():
    completes_correctly = CoroutineMock()

    await gather_without_exceptions([
        raises_connection_error(),
        raises_connection_reset_error(),
        completes_correctly()
    ], ConnectionError)

    completes_correctly.assert_called_once()
Exemplo n.º 5
0
    async def test_ok(self, model_manager: BaseModelManager, mocker: MockFixture):
        fake_fetch = CoroutineMock()
        fake_proxy_result = mocker.Mock(fake_fetch=fake_fetch)

        compared_result = await model_manager.fetch_from_result_proxy(fake_proxy_result, 'fake_fetch')
        expected_result = fake_fetch.return_value

        assert compared_result == expected_result

        fake_fetch.assert_called_once()
async def test_gather_without_exceptions():
    completes_correctly = CoroutineMock()

    with pytest.raises(CustomError):
        await gather_without_exceptions([
            raises_connection_error(),
            raises_custom_error(),
            completes_correctly()
        ], ConnectionError)

    completes_correctly.assert_called_once()
Exemplo n.º 7
0
async def test_callbacks():
    """Test detection and handling of both sync and async callbacks."""
    callback = Mock()
    async_callback = CoroutineMock()

    with patch("pysqueezebox.discovery._unpack_discovery_response",
               return_value=RESPONSE):
        protocol = pysqueezebox.discovery.ServerDiscoveryProtocol(callback)
        async_protocol = pysqueezebox.discovery.ServerDiscoveryProtocol(
            async_callback)
        protocol.datagram_received(ADDR, DATA)
        async_protocol.datagram_received(ADDR, DATA)

    callback.assert_called_once()
    async_callback.assert_called_once()
Exemplo n.º 8
0
async def test_connect(mocker):
    connection = BareIPConnection(host="localhost", port=1000)

    protocol = mocker.Mock(spec=ConnectionProtocol)
    protocol.is_active.return_value = True

    create_connection_mock = CoroutineMock(return_value=(None, protocol))
    mocker.patch.object(connection.loop, "create_connection",
                        create_connection_mock)

    assert connection.connected is False

    await connection.connect()

    create_connection_mock.assert_called_once()

    assert connection.connected is True
Exemplo n.º 9
0
async def test_reconnect(event_loop):
    """Test that reconnecting to the websocket does the right thing."""
    async with aiohttp.ClientSession(loop=event_loop) as session:
        client = Client(TEST_API_KEY, TEST_APP_KEY, session=session)
        client.websocket._sio.eio._trigger_event = CoroutineMock()
        client.websocket._sio.eio.connect = CoroutineMock()

        async_on_connect = CoroutineMock()
        async_on_disconnect = CoroutineMock()

        client.websocket.async_on_connect(async_on_connect)
        client.websocket.async_on_disconnect(async_on_disconnect)

        await client.websocket.reconnect()
        await client.websocket._sio._trigger_event("disconnect", "/")
        async_on_disconnect.assert_called_once()
        await client.websocket._sio._trigger_event("connect", "/")
        async_on_connect.assert_called_once()
Exemplo n.º 10
0
async def test_connect_sync_success(event_loop):
    """Test connecting to the socket with a sync handler."""
    async with aiohttp.ClientSession(loop=event_loop) as session:
        client = Client(TEST_API_KEY, TEST_APP_KEY, session=session)
        client.websocket._sio.eio._trigger_event = CoroutineMock()
        client.websocket._sio.eio.connect = CoroutineMock()

        async_on_connect = CoroutineMock()
        client.websocket.async_on_connect(async_on_connect)

        await client.websocket.connect()
        client.websocket._sio.eio.connect.assert_called_once_with(
            f"https://api.ambientweather.net/?api=1&applicationKey={TEST_APP_KEY}",
            engineio_path="socket.io",
            headers={},
            transports=["websocket"],
        )

        await client.websocket._sio._trigger_event("connect", "/")
        async_on_connect.assert_called_once()
Exemplo n.º 11
0
async def test_connect(mocker):
    connection = LocalIPConnection(host="localhost",
                                   port=1000,
                                   password="******")

    protocol = mocker.Mock(spec=ConnectionProtocol)
    protocol.is_active.return_value = True

    create_connection_mock = CoroutineMock(return_value=(None, protocol))
    mocker.patch.object(connection.loop, "create_connection",
                        create_connection_mock)
    connect_command_execute = mocker.patch.object(IPModuleConnectCommand,
                                                  "execute", CoroutineMock())

    assert connection.connected is False

    await connection.connect()

    create_connection_mock.assert_called_once()
    connect_command_execute.assert_called_once()

    assert connection.connected is True
Exemplo n.º 12
0
async def test_data_async(event_loop):
    """Test data and subscription with async handlers."""
    async with aiohttp.ClientSession(loop=event_loop) as session:
        client = Client(TEST_API_KEY, TEST_APP_KEY, session=session)
        client.websocket._sio.eio._trigger_event = CoroutineMock()
        client.websocket._sio.eio.connect = CoroutineMock()
        client.websocket._sio.eio.disconnect = CoroutineMock()

        async_on_connect = CoroutineMock()
        async_on_data = CoroutineMock()
        async_on_disconnect = CoroutineMock()
        async_on_subscribed = CoroutineMock()

        client.websocket.async_on_connect(async_on_connect)
        client.websocket.async_on_data(async_on_data)
        client.websocket.async_on_disconnect(async_on_disconnect)
        client.websocket.async_on_subscribed(async_on_subscribed)

        await client.websocket.connect()
        client.websocket._sio.eio.connect.assert_called_once_with(
            f"https://api.ambientweather.net/?api=1&applicationKey={TEST_APP_KEY}",
            engineio_path="socket.io",
            headers={},
            transports=["websocket"],
        )

        await client.websocket._sio._trigger_event("connect", "/")
        async_on_connect.assert_called_once()

        await client.websocket._sio._trigger_event("data", "/", {"foo": "bar"})
        async_on_data.assert_called_once()

        await client.websocket._sio._trigger_event("subscribed", "/",
                                                   {"foo": "bar"})
        async_on_subscribed.assert_called()

        await client.websocket.disconnect()
        await client.websocket._sio._trigger_event("disconnect", "/")
        async_on_disconnect.assert_called_once()
        client.websocket._sio.eio.disconnect.assert_called_once_with(
            abort=True)
Exemplo n.º 13
0
class TestBarterDude(TestCase):
    @patch("barterdude.App")
    @patch("barterdude.AMQPConnection")
    def setUp(self, AMQPConnection, App):
        self.monitor = Mock()
        self.monitor.dispatch_before_consume = CoroutineMock()
        self.monitor.dispatch_on_success = CoroutineMock()
        self.monitor.dispatch_on_fail = CoroutineMock()
        self.callback = CoroutineMock()
        self.messages = [Mock(value=i) for i in range(10)]
        self.calls = [call(message) for message in self.messages]

        self.AMQPConnection = AMQPConnection
        self.connection = self.AMQPConnection.return_value
        self.App = App
        self.app = self.App.return_value
        self.app.startup = CoroutineMock()
        self.app.shutdown = CoroutineMock()
        self.decorator = self.app.route.return_value
        self.schema = load_fixture("schema.json")
        self.barterdude = BarterDude()

    def test_should_create_connection(self):
        self.AMQPConnection.assert_called_once_with(  # nosec
            hostname="127.0.0.1",
            username="******",
            password="******",
            prefetch=10,
            name="default",
        )
        self.App.assert_called_once_with(connections=[self.connection])

    def test_should_call_route_when_created(self):
        monitor = Mock()
        self.barterdude.consume_amqp(["queue"],
                                     monitor=monitor)(CoroutineMock())
        self.app.route.assert_called_once_with(
            ["queue"],
            type=RouteTypes.AMQP_RABBITMQ,
            options={
                Options.BULK_SIZE:
                10,
                Options.BULK_FLUSH_INTERVAL:
                60,
                Options.CONNECTION_FAIL_CALLBACK:
                monitor.dispatch_on_connection_fail,
            })

    def test_should_call_route_when_adding_endpoint(self):
        hook = Mock()
        self.barterdude.add_endpoint(['/my_route'], ['GET'], hook)
        self.app.route.assert_called_once_with(routes=['/my_route'],
                                               methods=['GET'],
                                               type=RouteTypes.HTTP)
        self.decorator.assert_called_once_with(hook)

    async def test_should_call_callback_for_each_message(self):
        self.barterdude.consume_amqp(["queue"], self.monitor)(self.callback)
        self.decorator.assert_called_once()
        wrapper = self.decorator.call_args[0][0]
        await wrapper(self.messages)
        messages = []
        for message in self.callback.mock_calls:
            self.assertEqual(Message, type(message[1][0]))
            messages.append(message[1][0]._message)
        self.assertListEqual(sorted(messages, key=lambda x: x.value),
                             sorted(self.messages, key=lambda x: x.value))

    async def test_should_call_reject_when_callback_fail(self):
        self.callback.side_effect = Exception('Boom!')
        self.barterdude.consume_amqp(["queue"], self.monitor)(self.callback)
        wrapper = self.decorator.call_args[0][0]
        await wrapper(self.messages)
        for message in self.messages:
            message.reject.assert_called_once()

    async def test_should_call_monitor_for_each_success_message(self):
        self.barterdude.consume_amqp(["queue"], self.monitor)(self.callback)
        wrapper = self.decorator.call_args[0][0]
        await wrapper(self.messages)
        self.monitor.dispatch_before_consume.assert_has_calls(self.calls,
                                                              any_order=True)
        self.monitor.dispatch_on_success.assert_has_calls(self.calls,
                                                          any_order=True)
        self.monitor.dispatch_on_fail.assert_not_called()

    async def test_should_call_callback_for_valid_message(self):
        self.barterdude.consume_amqp(["queue"],
                                     self.monitor,
                                     validation_schema=self.schema)(
                                         self.callback)
        self.decorator.assert_called_once()
        wrapper = self.decorator.call_args[0][0]
        message = Mock(Message)
        message.body = {"key": 'ok'}
        await wrapper([message])
        self.callback.assert_called_once()
        self.assertEqual(self.callback.await_args[0][0].body["key"],
                         message.body["key"])

    async def test_should_not_call_callback_for_valid_message(self):
        self.barterdude.consume_amqp(["queue"],
                                     self.monitor,
                                     validation_schema=self.schema)(
                                         self.callback)
        self.decorator.assert_called_once()
        wrapper = self.decorator.call_args[0][0]
        message = Mock(Message)
        message.body = {"wrong": 'ok'}
        await wrapper([message])
        self.callback.assert_not_called()

    async def test_should_call_monitor_for_each_fail_message(self):
        error = Exception('Boom!')
        self.callback.side_effect = error
        self.barterdude.consume_amqp(["queue"], self.monitor)(self.callback)
        wrapper = self.decorator.call_args[0][0]
        await wrapper(self.messages)
        self.monitor.dispatch_before_consume.assert_has_calls(self.calls,
                                                              any_order=True)
        error_calls = [call(message, error) for message in self.messages]
        self.monitor.dispatch_on_fail.assert_has_calls(error_calls,
                                                       any_order=True)
        self.monitor.dispatch_on_success.assert_not_called()

    async def test_should_call_put_when_publish(self):
        data = Mock()
        self.connection.put = CoroutineMock()
        await self.barterdude.publish_amqp('exchange',
                                           data,
                                           vhost="vhost",
                                           routing_key="routing_key")
        self.connection.put.assert_called_once_with(exchange='exchange',
                                                    data=data,
                                                    vhost="vhost",
                                                    routing_key="routing_key",
                                                    properties=None)

    async def test_should_call_startup_and_shutdown(self):
        await self.barterdude.startup()
        self.app.startup.assert_called_once_with()
        await self.barterdude.shutdown()
        self.app.shutdown.assert_called_once_with()

    def test_should_call_run(self):
        self.barterdude.run()
        self.app.run.assert_called_once_with()