def main(self):
        notifications_sent = False
        bug_notification_set = getUtility(IBugNotificationSet)
        deferred_notifications = \
            bug_notification_set.getDeferredNotifications()
        process_deferred_notifications(deferred_notifications)
        pending_notifications = get_email_notifications(
            bug_notification_set.getNotificationsToSend())
        for (bug_notifications,
             omitted_notifications,
             messages) in pending_notifications:
            for message in messages:
                self.logger.info("Notifying %s about bug %d." % (
                    message['To'], bug_notifications[0].bug.id))
                sendmail(message)
                self.logger.debug(message.as_string())
            for notification in bug_notifications:
                notification.date_emailed = UTC_NOW
                notification.status = BugNotificationStatus.SENT
            for notification in omitted_notifications:
                notification.date_emailed = UTC_NOW
                notification.status = BugNotificationStatus.OMITTED
            notifications_sent = True
            # Commit after each batch of email sent, so that we won't
            # re-mail the notifications in case of something going wrong
            # in the middle.
            self.txn.commit()

        if not notifications_sent:
            self.logger.debug("No notifications are pending to be sent.")
 def test_deferred_notifications(self):
     # Create some deferred notifications and show that processing them
     # puts then in the state where they are ready to send.
     num = 5
     for i in xrange(num):
         self._make_deferred_notification()
     deferred = self.notification_set.getDeferredNotifications()
     self.assertEqual(num, deferred.count())
     process_deferred_notifications(deferred)
     # Now that are all in the PENDING state.
     ready_to_send = self.notification_set.getNotificationsToSend()
     self.assertEqual(num, len(ready_to_send))
     # And there are no longer any deferred.
     deferred = self.notification_set.getDeferredNotifications()
     self.assertEqual(0, deferred.count())