def test_notify_channel_message_from_user_sends_notification(self):
        message = Message(sender_id=0,
                          receiver_id=1,
                          team_id=0,
                          content="Sarasa",
                          send_type=SendMessageType.DIRECT.value,
                          message_type=MessageType.TEXT.value)
        is_user_receiver = False
        '''Mocked outputs'''
        user_sender = PublicUser(user_id=0,
                                 username="******",
                                 first_name="Test0",
                                 last_name="Test0")
        channel = Channel(channel_id=0,
                          team_id=0,
                          name="Test-Channel",
                          creator=ChannelCreator(0, "Tester0", "Test0",
                                                 "Test0"))
        team = Team(team_id=0, name="Test-Team")

        def send_notification(topic_name, message_title, message_body,
                              data_message):
            from tests.test_services import test_notifications
            MockedNotificationServer.notification = Notification(
                topic_name, message_title, message_body, data_message)
            return {"failure": 0}

        sys.modules[
            "daos.teams"].TeamDatabaseClient.get_team_by_id.return_value = team
        sys.modules[
            "daos.users"].UserDatabaseClient.get_user_by_id.return_value = user_sender
        sys.modules[
            "daos.channels"].ChannelDatabaseClient.get_channel_by_id.return_value = channel
        sys.modules["pyfcm"].FCMNotification(
        ).notify_topic_subscribers = MagicMock(side_effect=send_notification)

        NotificationService.notify_message(message, is_user_receiver)
        self.assertEqual(1, MockedNotificationServer.notification.topic_name)
        self.assertEqual("Hypechat",
                         MockedNotificationServer.notification.message_title)
        self.assertEqual("You receive a channel message!",
                         MockedNotificationServer.notification.message_body)
        self.assertEqual(
            "Test-Team",
            MockedNotificationServer.notification.data_message.get(
                "team_name"))
        self.assertEqual(
            "Test-Channel",
            MockedNotificationServer.notification.data_message.get(
                "channel_name"))
        self.assertEqual(
            0,
            MockedNotificationServer.notification.data_message.get(
                "sender_id"))
        self.assertEqual(
            NotificationType.MESSAGE.value,
            MockedNotificationServer.notification.data_message.get(
                "notification_type"))
Exemplo n.º 2
0
    def send_message(cls, inbox_data):
        user = Authenticator.authenticate_team(inbox_data.authentication)

        if user.id == inbox_data.chat_id:
            raise WrongActionError("You cannot send a message to yourself!", MessageResponseStatus.ERROR.value)

        receiver = cls._determinate_message_receiver(inbox_data.chat_id, user.team_id)
        if receiver is None or receiver.team_id != user.team_id:
            cls.logger().info(f"Trying to send a message to client #{inbox_data.chat_id} who's not part of team "
                              f"{user.team_id}.")
            return BadRequestMessageSentResponse("The receiver it's not part of this team!",
                                                 TeamResponseStatus.USER_NOT_MEMBER.value)

        new_message = Message(
            sender_id=user.id,
            receiver_id=inbox_data.chat_id,
            team_id=user.team_id,
            content=inbox_data.content,
            send_type=SendMessageType.DIRECT.value if receiver.is_user else SendMessageType.CHANNEL.value,
            message_type=inbox_data.message_type
        )

        chat_sender, chat_receivers = cls._increase_chats_offset(user.id, inbox_data.chat_id, user.team_id, receiver.is_user)

        try:
            new_message = MessageDatabaseClient.add_message(new_message)
            if inbox_data.mentions is not None:
                MentionService.save_mentions(new_message, inbox_data.mentions)
            MessageDatabaseClient.add_or_update_chat(chat_sender)
            for chat_receiver in chat_receivers:
                MessageDatabaseClient.add_or_update_chat(chat_receiver)
            DatabaseClient.commit()
            NotificationService.notify_message(new_message, receiver.is_user)
            cls.logger().info(f"Message sent from user #{new_message.sender_id} to client #{new_message.receiver_id}.")
        except IntegrityError:
            DatabaseClient.rollback()
            if UserDatabaseClient.get_client_by_id(inbox_data.chat_id) is None:
                cls.logger().error(f"User #{new_message.sender_id} trying to sent a message to an nonexistent user.")
                raise UserNotFoundError("User not found.", UserResponseStatus.USER_NOT_FOUND.value)
            else:
                cls.logger().error(f"Failing to send message from user #{new_message.sender_id} to client"
                                   f" #{inbox_data.chat_id}.")
                return UnsuccessfulMessageSentResponse("Couldn't sent message.")
        except FlushError:
            cls.logger().error(
                f"Failing to send message from user #{new_message.sender_id} to client #{inbox_data.chat_id} "
                f"due to DB problems.")
            return UnsuccessfulMessageSentResponse("Couldn't sent message.")
        else:
            return SuccessfulMessageSentResponse("Message sent")
    def test_notify_direct_message_from_bot_sends_notification(self):
        message = Message(sender_id=0,
                          receiver_id=1,
                          team_id=0,
                          content="Sarasa",
                          send_type=SendMessageType.DIRECT.value,
                          message_type=MessageType.TEXT.value)
        is_user_receiver = True
        '''Mocked outputs'''
        bot_sender = Bot(bot_id=0, name="Test-Bot", callback=None, token=None)
        team = Team(team_id=0, name="Test-Team")

        def send_notification(topic_name, message_title, message_body,
                              data_message):
            from tests.test_services import test_notifications
            MockedNotificationServer.notification = Notification(
                topic_name, message_title, message_body, data_message)
            return {"failure": 0}

        sys.modules[
            "daos.teams"].TeamDatabaseClient.get_team_by_id.return_value = team
        sys.modules[
            "daos.users"].UserDatabaseClient.get_user_by_id.return_value = None
        sys.modules[
            "daos.bots"].BotDatabaseClient.get_bot_by_id.return_value = bot_sender
        sys.modules[
            "daos.channels"].ChannelDatabaseClient.get_channel_by_id.return_value = None
        sys.modules["pyfcm"].FCMNotification(
        ).notify_topic_subscribers = MagicMock(side_effect=send_notification)

        NotificationService.notify_message(message, is_user_receiver)
        self.assertEqual(1, MockedNotificationServer.notification.topic_name)
        self.assertEqual("Hypechat",
                         MockedNotificationServer.notification.message_title)
        self.assertEqual("You receive a direct message!",
                         MockedNotificationServer.notification.message_body)
        self.assertEqual(
            "Test-Team",
            MockedNotificationServer.notification.data_message.get(
                "team_name"))
        self.assertEqual(
            0,
            MockedNotificationServer.notification.data_message.get(
                "sender_id"))
        self.assertEqual(
            NotificationType.MESSAGE.value,
            MockedNotificationServer.notification.data_message.get(
                "notification_type"))
    def test_when_connection_error_is_raised_by_pyfcm_notification_is_not_send(
            self):
        def send_notification(topic_name, message_title, message_body,
                              data_message):
            raise ConnectionError

        sys.modules["pyfcm"].FCMNotification(
        ).notify_topic_subscribers = MagicMock(side_effect=send_notification)

        NotificationService.notify_team_invitation(mock, mock)
        self.assertIsNone(MockedNotificationServer.notification)
        NotificationService.notify_channel_invitation(mock, mock)
        self.assertIsNone(MockedNotificationServer.notification)
        NotificationService.notify_message(mock, mock)
        self.assertIsNone(MockedNotificationServer.notification)
        NotificationService.notify_mention(mock, mock)
        self.assertIsNone(MockedNotificationServer.notification)