async def test_init_params_assertion(self, mocker: MockFixture,
                                         fake_data_provider: BaseDataProvider):
        fake_get_many = CoroutineMock()
        fake_include_settings_data_provider = mocker.Mock(
            __name__='foo', return_value=mocker.Mock(get_many=fake_get_many))
        fake_item = mocker.Mock()
        fake_include_settings = {
            'relations': [{
                'included_entity_field_name': 'foo',
                'root_entity_field_name': 'bar',
            }],
            'data_provider_init_params': [{
                'param_name':
                'wrong_param_name',
                'attribute_name':
                'test_attribute_name',
            }],
            'data_provider_class':
            fake_include_settings_data_provider
        }
        fake_include_params = {'page': mocker.Mock(), 'fields': mocker.Mock()}

        with pytest.raises(AssertionError):
            await fake_data_provider.get_item_include_data(
                fake_item, fake_include_settings, fake_include_params)

        fake_item.get.assert_called_once_with('bar')
        fake_include_settings_data_provider.assert_not_called()
        fake_get_many.assert_not_called()
Exemplo n.º 2
0
    async def test_resolve_request_with_single_matcher(self):
        handler = CoroutineMock(return_value=sentinel.response)
        matcher = CoroutineMock(return_value=True)
        self.resolver.register_matcher(matcher, handler)

        request = Mock()
        response = await self.resolver.resolve(request, self.default_app)
        self.assertEqual(response, handler)

        matcher.assert_called_once_with(request)
        handler.assert_not_called()
    async def test_resolve_request_priority(self):
        matcher = CoroutineMock(side_effect=(True, True))
        handler1 = CoroutineMock(return_value=sentinel.response1)
        handler2 = CoroutineMock(return_value=sentinel.response2)
        self.resolver.register_matcher(matcher, handler1)
        self.resolver.register_matcher(matcher, handler2)

        request = Mock()
        response = await self.resolver.resolve(request, self.default_app)
        self.assertEqual(response, handler1)

        handler1.assert_not_called()
        handler2.assert_not_called()
        matcher.assert_called_once_with(request)
Exemplo n.º 4
0
    async def test_resolve_request_with_first_falsy_matcher(self):
        handler = CoroutineMock(return_value=sentinel.response)
        matcher1 = CoroutineMock(return_value=False)
        matcher2 = CoroutineMock(return_value=True)
        self.resolver.register_matcher(matcher1, handler)
        self.resolver.register_matcher(matcher2, handler)

        request = Mock()
        response = await self.resolver.resolve(request, self.default_app)
        self.assertEqual(response, self.default_handler)

        matcher1.assert_called_once_with(request)
        matcher2.assert_not_called()
        handler.assert_not_called()
    async def test_resolve_request_with_multiple_handlers(self):
        matcher = CoroutineMock(side_effect=(False, True))
        handler1 = CoroutineMock(return_value=sentinel.response1)
        handler2 = CoroutineMock(return_value=sentinel.response2)
        self.resolver.register_matcher(matcher, handler1)
        self.resolver.register_matcher(matcher, handler2)

        request = Mock()
        response = await self.resolver.resolve(request, self.default_app)
        self.assertEqual(response, handler2)

        handler1.assert_not_called()
        handler2.assert_not_called()
        matcher.assert_has_calls([call(request)] * 2)
        self.assertEqual(matcher.call_count, 2)
Exemplo n.º 6
0
    async def test_can_handle_message_with_no_subscription(self):
        frame = Frame("MESSAGE", {
            "subscription": "123",
            "message-id": "321"
        }, "blah")

        handler = CoroutineMock()

        frame_handler = Mock()
        frame_handler.get.return_value = None

        stomp = StompReader(frame_handler, self.loop)
        await stomp._handle_message(frame)

        handler.assert_not_called()
Exemplo n.º 7
0
    async def test_can_handle_message_with_no_subscription(self):
        frame = Frame('MESSAGE', {
            'subscription': '123',
            'message-id': '321'
        }, 'blah')

        handler = CoroutineMock()

        frame_handler = Mock()
        frame_handler.get.return_value = None

        stomp = StompReader(frame_handler, self.loop)
        await stomp._handle_message(frame)

        handler.assert_not_called()
    async def test_relations_assertion(self, mocker: MockFixture,
                                       fake_data_provider: BaseDataProvider):
        fake_get_many = CoroutineMock()
        fake_include_settings_data_provider = mocker.Mock(
            __name__='foo', return_value=mocker.Mock(get_many=fake_get_many))
        fake_item = mocker.Mock()
        fake_include_settings = {
            'data_provider_class': fake_include_settings_data_provider
        }
        fake_include_params = {'page': mocker.Mock(), 'fields': mocker.Mock()}

        with pytest.raises(AssertionError):
            await fake_data_provider.get_item_include_data(
                fake_item, fake_include_settings, fake_include_params)

        fake_item.get.assert_not_called()
        fake_include_settings_data_provider.assert_not_called()
        fake_get_many.assert_not_called()
Exemplo n.º 9
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()
Exemplo n.º 10
0
class Pick(CommandTestCase):
    def setup(self, state="A", inv=0):
        mock_command = Mock(spec=PickCommand, invocation="A")
        mock_message = Mock(spec=Message)
        mock_candy_value = Mock(spec=CandyValue,
                                candy=Mock(spec=Candy),
                                value=10)
        self.mock_candy_drop = Mock(spec=CandyDrop,
                                    candy_value=mock_candy_value,
                                    command=mock_command,
                                    message=mock_message)
        self.mock_state = {state: self.mock_candy_drop}
        self.patch("candybot.engine.STATE", self.mock_state)
        mock_get_inv = Mock(spec=database.get_inv,
                            return_value={
                                "A":
                                Mock(spec=CandyCollection,
                                     __getitem__=Mock(return_value=inv))
                            })
        self.mock_database = Mock(spec=database, get_inv=mock_get_inv)
        self.patch("candybot.commands.pick.database", self.mock_database)
        self.mock_send = CoroutineMock()
        self.patch("candybot.commands.Command.send", self.mock_send)

    def assert_action(self, expected_candy):
        self.assertFalse(self.mock_state)
        self.mock_candy_drop.message.delete.assert_called_once_with()
        self.mock_database.set_inv.assert_called_once_with(
            "A", "A", self.mock_candy_drop.candy_value, update=True)
        self.mock_send.assert_called_once_with(self.mock_candy_drop.pick_str)
        self.assertEqual(self.mock_candy_drop.candy_value.value,
                         expected_candy)

    def assert_no_action(self):
        self.assertTrue(self.mock_state)
        self.mock_candy_drop.message.delete.assert_not_called()
        self.mock_database.set_inv.assert_not_called()
        self.mock_send.assert_not_called()

    def test_invocation_default(self):
        command = PickCommand(None)
        self.assertEqual(command.invocation, "pick")

    def test_invocation_set(self):
        command = PickCommand(None, invocation="A")
        self.assertEqual(command.invocation, "A")

    async def test_ignore_if_no_state(self):
        self.setup(state="B")
        command = PickCommand(None, invocation="A")
        await command._run()
        self.assert_no_action()

    async def test_ignore_if_invocations_differ(self):
        self.setup()
        command = PickCommand(None, invocation="B")
        await command._run()
        self.assert_no_action()

    async def test_ignore_if_at_cap(self):
        self.setup(inv=20)
        command = PickCommand(Mock(spec=Settings, cap=20), invocation="A")
        await command._run()
        self.assert_no_action()

    async def test_successful_full_pick(self):
        self.setup()
        command = PickCommand(Mock(spec=Settings, cap=20), invocation="A")
        await command._run()
        self.assert_action(10)

    async def test_successful_partial_pick(self):
        self.setup(inv=15)
        command = PickCommand(Mock(spec=Settings, cap=20), invocation="A")
        await command._run()
        self.assert_action(5)