def test_send_fcm_retry_backoff_time(self):
        client = MobileClient(parent=ndb.Key(Account, 'user_id'),
                              user_id='user_id',
                              messaging_id='messaging_id',
                              client_type=ClientType.OS_IOS)
        client.put()

        import time

        batch_response = messaging.BatchResponse([
            messaging.SendResponse(None, QuotaExceededError('code', 'message'))
        ])
        for i in range(0, 6):
            with patch.object(
                    FCMRequest, 'send',
                    return_value=batch_response), patch('logging.error'):
                call_time = time.time()
                TBANSHelper._send_fcm([client], MockNotification(), i)

                # Check that we queue'd for a retry with the proper countdown time
                tasks = self.taskqueue_stub.get_filtered_tasks(
                    queue_names='push-notifications')
                if i > 0:
                    self.assertGreater(tasks[0].eta_posix - call_time, 0)

                # Make sure our taskqueue tasks execute what we expect
                with patch.object(TBANSHelper, '_send_fcm') as mock_send_fcm:
                    deferred.run(tasks[0].payload)
                    mock_send_fcm.assert_called_once_with([client], ANY, i + 1)

                self.taskqueue_stub.FlushQueue('push-notifications')
    def test_send_fcm_maximum_backoff(self):
        for i in range(0, 6):
            exit_code = TBANSHelper._send_fcm([],
                                              MockNotification(),
                                              backoff_iteration=i)
            self.assertEqual(exit_code, 0)

        # Backoff should start failing at 6
        exit_code = TBANSHelper._send_fcm([],
                                          MockNotification(),
                                          backoff_iteration=6)
        self.assertEqual(exit_code, 2)
    def test_send_fcm_unhandled_error(self):
        client = MobileClient(parent=ndb.Key(Account, 'user_id'),
                              user_id='user_id',
                              messaging_id='messaging_id',
                              client_type=ClientType.OS_IOS)
        client.put()

        # Sanity check
        self.assertEqual(fcm_messaging_ids('user_id'), ['messaging_id'])

        batch_response = messaging.BatchResponse(
            [messaging.SendResponse(None, FirebaseError('code', 'message'))])
        with patch.object(FCMRequest, 'send',
                          return_value=batch_response), patch(
                              'logging.error') as mock_error:
            exit_code = TBANSHelper._send_fcm([client], MockNotification())
            self.assertEqual(exit_code, 0)
            mock_error.assert_called_once_with(
                'Unhandled FCM error for messaging_id - code / message')

        # Sanity check
        self.assertEqual(fcm_messaging_ids('user_id'), ['messaging_id'])

        # Check that we didn't queue for a retry
        tasks = self.taskqueue_stub.get_filtered_tasks(
            queue_names='push-notifications')
        self.assertEqual(len(tasks), 0)
    def test_send_fcm_unavailable_error(self):
        client = MobileClient(parent=ndb.Key(Account, 'user_id'),
                              user_id='user_id',
                              messaging_id='messaging_id',
                              client_type=ClientType.OS_IOS)
        client.put()

        # Sanity check
        self.assertEqual(fcm_messaging_ids('user_id'), ['messaging_id'])

        batch_response = messaging.BatchResponse([
            messaging.SendResponse(None, UnavailableError('code', 'message'))
        ])
        with patch.object(FCMRequest, 'send',
                          return_value=batch_response), patch(
                              'logging.error') as mock_error:
            exit_code = TBANSHelper._send_fcm([client], MockNotification())
            self.assertEqual(exit_code, 0)
            mock_error.assert_called_once_with(
                'FCM unavailable - retrying client...')

        # Sanity check
        self.assertEqual(fcm_messaging_ids('user_id'), ['messaging_id'])

        # Check that we queue'd for a retry
        tasks = self.taskqueue_stub.get_filtered_tasks(
            queue_names='push-notifications')
        self.assertEqual(len(tasks), 1)

        # Make sure our taskqueue tasks execute what we expect
        with patch.object(TBANSHelper, '_send_fcm') as mock_send_fcm:
            deferred.run(tasks[0].payload)
            mock_send_fcm.assert_called_once_with([client], ANY, 1)
    def test_send_fcm_invalid_argument_error(self):
        client = MobileClient(parent=ndb.Key(Account, 'user_id'),
                              user_id='user_id',
                              messaging_id='messaging_id',
                              client_type=ClientType.OS_IOS)
        client.put()

        # Sanity check
        self.assertEqual(fcm_messaging_ids('user_id'), ['messaging_id'])

        batch_response = messaging.BatchResponse([
            messaging.SendResponse(None,
                                   InvalidArgumentError('code', 'message'))
        ])
        with patch.object(FCMRequest, 'send',
                          return_value=batch_response), patch(
                              'logging.critical') as mock_critical:
            exit_code = TBANSHelper._send_fcm([client], MockNotification())
            self.assertEqual(exit_code, 0)
            mock_critical.assert_called_once_with(
                'Invalid argument when sending to FCM - code')

        # Sanity check
        self.assertEqual(fcm_messaging_ids('user_id'), ['messaging_id'])

        # Make sure we haven't queued for a retry
        tasks = self.taskqueue_stub.get_filtered_tasks(
            queue_names='push-notifications')
        self.assertEqual(len(tasks), 0)
    def test_send_fcm_sender_id_mismatch_error(self):
        client = MobileClient(parent=ndb.Key(Account, 'user_id'),
                              user_id='user_id',
                              messaging_id='messaging_id',
                              client_type=ClientType.OS_IOS)
        client.put()

        # Sanity check
        self.assertEqual(fcm_messaging_ids('user_id'), ['messaging_id'])

        batch_response = messaging.BatchResponse([
            messaging.SendResponse(None,
                                   SenderIdMismatchError('code', 'message'))
        ])
        with patch.object(FCMRequest, 'send', return_value=batch_response), \
            patch.object(MobileClient, 'delete_for_messaging_id', wraps=MobileClient.delete_for_messaging_id) as mock_delete, \
                patch('logging.info') as mock_info:
            exit_code = TBANSHelper._send_fcm([client], MockNotification())
            mock_delete.assert_called_once_with('messaging_id')
            self.assertEqual(exit_code, 0)
            mock_info.assert_called_with(
                'Deleting mismatched client with ID: messaging_id')

        # Sanity check
        self.assertEqual(fcm_messaging_ids('user_id'), [])

        # Make sure we haven't queued for a retry
        tasks = self.taskqueue_stub.get_filtered_tasks(
            queue_names='push-notifications')
        self.assertEqual(len(tasks), 0)
    def test_send_fcm_disabled(self):
        from sitevars.notifications_enable import NotificationsEnable
        NotificationsEnable.enable_notifications(False)

        with patch.object(NotificationsEnable,
                          'notifications_enabled',
                          wraps=NotificationsEnable.notifications_enabled
                          ) as mock_check_enabled:
            exit_code = TBANSHelper._send_fcm([], MockNotification())
            mock_check_enabled.assert_called_once()
            self.assertEqual(exit_code, 1)
    def test_send_fcm_batch(self):
        clients = [
            MobileClient(parent=ndb.Key(Account, 'user_id'),
                         user_id='user_id',
                         messaging_id='{}'.format(i),
                         client_type=ClientType.OS_IOS) for i in range(3)
        ]

        batch_response = messaging.BatchResponse([])
        with patch('models.notifications.requests.fcm_request.MAXIMUM_TOKENS',
                   2), patch.object(FCMRequest,
                                    'send',
                                    return_value=batch_response) as mock_send:
            exit_code = TBANSHelper._send_fcm(clients, MockNotification())
            self.assertEqual(mock_send.call_count, 2)
            self.assertEqual(exit_code, 0)
    def test_send_fcm_filter_fcm_clients(self):
        expected = [
            'client_type_{}'.format(client_type)
            for client_type in ClientType.FCM_CLIENTS
        ]
        clients = [
            MobileClient(parent=ndb.Key(Account, 'user_id'),
                         user_id='user_id',
                         messaging_id='client_type_{}'.format(client_type),
                         client_type=client_type)
            for client_type in ClientType.names.keys()
        ]

        with patch('models.notifications.requests.fcm_request.FCMRequest',
                   autospec=True) as mock_init:
            exit_code = TBANSHelper._send_fcm(clients, MockNotification())
            mock_init.assert_called_once_with(ANY, ANY, expected)
            self.assertEqual(exit_code, 0)