def test_send_notification(mocker, user):
    """Tests send_notification"""
    ns = NotificationSettingsFactory.create(via_email=True, weekly=True)
    notifier = frontpage.FrontpageDigestNotifier(ns)
    post = PostFactory.create()
    send_messages_mock = mocker.patch("mail.api.send_messages")
    serializer_mock = mocker.patch("channels.serializers.posts.PostSerializer")
    serializer_mock.return_value.data = {
        "id": post.post_id,
        "title": "post's title",
        "slug": "a_slug",
        "channel_name": "micromasters",
        "channel_title": "MicroMasters",
        "created": now_in_utc().isoformat(),
        "author_id": user.username,
    }
    submission = mocker.Mock(id=post.post_id,
                             created=int(now_in_utc().timestamp()),
                             stickied=False)
    api_mock = mocker.patch("channels.api.Api")
    api_mock.return_value.front_page.return_value = [submission]
    note = EmailNotificationFactory.create(
        user=ns.user, notification_type=ns.notification_type, sending=True)

    notifier.send_notification(note)

    serializer_mock.assert_called_once_with(
        PostProxy(submission, post), context={"current_user": note.user})

    send_messages_mock.assert_called_once_with([any_instance_of(EmailMessage)])
def test_can_notify_invalid_frequency():
    """Verify it raises an error for an invalid frequency"""
    notification_settings = NotificationSettingsFactory.create(immediate=True,
                                                               via_email=True)
    notifier = frontpage.FrontpageDigestNotifier(notification_settings)
    with pytest.raises(InvalidTriggerFrequencyError):
        notifier.can_notify(None)
Exemple #3
0
def attempt_send_notification_batch(notification_settings_ids):
    """
    Attempts to send notification for the given batch of ids

    Args:
        notification_settings_ids (list of int): list of NotificationSettings.ids
    """
    notification_settings = NotificationSettings.objects.filter(
        id__in=notification_settings_ids)
    for notification_setting in notification_settings:
        try:
            notifier = frontpage.FrontpageDigestNotifier(notification_setting)
            notifier.attempt_notify()
        except:  # pylint: disable=bare-except
            log.exception("Error attempting notification for user %s",
                          notification_setting.user)
def test_send_notification_no_posts(mocker):
    """Tests send_notification if there are somehow no posts"""
    ns = NotificationSettingsFactory.create(via_email=True, weekly=True)
    notifier = frontpage.FrontpageDigestNotifier(ns)
    send_messages_mock = mocker.patch("mail.api.send_messages")
    serializer_mock = mocker.patch("channels.serializers.posts.PostSerializer")
    api_mock = mocker.patch("channels.api.Api")
    api_mock.return_value.front_page.return_value = []
    note = EmailNotificationFactory.create(
        user=ns.user, notification_type=ns.notification_type, sending=True)

    notifier.send_notification(note)

    serializer_mock.assert_not_called()
    send_messages_mock.assert_not_called()

    note.refresh_from_db()
    assert note.state == EmailNotification.STATE_CANCELED
def test_can_notify(
    settings,
    mocker,
    is_enabled,
    can_notify,
    has_posts,
    trigger_frequency,
    has_last_notification,
    has_posts_after,
):  # pylint: disable=too-many-arguments, too-many-locals
    """Test can_notify"""
    notification_settings = NotificationSettingsFactory.create(
        trigger_frequency=trigger_frequency)
    notification = (EmailNotificationFactory.create(
        user=notification_settings.user, frontpage_type=True, sent=True)
                    if has_last_notification else None)
    settings.FEATURES[features.FRONTPAGE_EMAIL_DIGESTS] = is_enabled
    can_notify_mock = mocker.patch(
        "notifications.notifiers.email.EmailNotifier.can_notify",
        return_value=can_notify,
    )
    created_on = notification.created_on if notification is not None else now_in_utc(
    )
    post = PostFactory.create()
    api_mock = mocker.patch("channels.api.Api")
    api_mock.return_value.front_page.return_value = ([
        mocker.Mock(
            id=post.post_id,
            created=int(
                (created_on +
                 timedelta(days=10 if has_posts_after else -10)).timestamp()),
            stickied=False,
        )
    ] if has_posts else [])
    notifier = frontpage.FrontpageDigestNotifier(notification_settings)

    expected = (is_enabled and can_notify and has_posts
                and (not has_last_notification or has_posts_after)
                and trigger_frequency in [FREQUENCY_DAILY, FREQUENCY_WEEKLY])
    assert notifier.can_notify(notification) is expected

    if is_enabled:
        can_notify_mock.assert_called_once_with(notification)
Exemple #6
0
def _get_notifier_for_notification(notification):
    """
    Get the notifier for the notification's type

    Args:
        notification (NotificationBase): the notification to get a notifier for

    Returns:
        Notifier: instance of the notifier to use
    """
    notification_settings = NotificationSettings.objects.get(
        user=notification.user,
        notification_type=notification.notification_type)

    if notification.notification_type == NOTIFICATION_TYPE_FRONTPAGE:
        return frontpage.FrontpageDigestNotifier(notification_settings)
    elif notification.notification_type == NOTIFICATION_TYPE_COMMENTS:
        return comments.CommentNotifier(notification_settings)
    else:
        raise UnsupportedNotificationTypeError(
            "Notification type '{}' is unsupported".format(
                notification.notification_type))
def test_can_notify_never():
    """Verify it returns False for notifications set to never"""
    notification_settings = NotificationSettingsFactory.create(never=True,
                                                               via_email=True)
    notifier = frontpage.FrontpageDigestNotifier(notification_settings)
    assert notifier.can_notify(None) is False