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)])
Exemplo n.º 2
0
def test_mark_as_sent_or_canceled_already_sent():
    """Verify mark_as_sent_or_canceled doesn't try to send if it is already sent"""
    notification = EmailNotificationFactory.create(sent=True)

    with utils.mark_as_sent_or_canceled(notification) as will_send:
        assert will_send is False

    notification.refresh_from_db()
    assert notification.state == EmailNotification.STATE_SENT
Exemplo n.º 3
0
def test_mark_as_sent_or_canceled():
    """Verify mark_as_sent_or_canceled marks the notification sent if no errors"""
    notification = EmailNotificationFactory.create(sending=True)

    with utils.mark_as_sent_or_canceled(notification) as will_send:
        assert will_send is True

    notification.refresh_from_db()
    assert notification.state == EmailNotification.STATE_SENT
    assert notification.sent_at is not None
Exemplo n.º 4
0
def test_mark_as_sent_or_canceled_misc_error():
    """Verify mark_as_sent_or_canceled marks the task as pending if a non-send related error occurs"""
    notification = EmailNotificationFactory.create(sending=True)

    with utils.mark_as_sent_or_canceled(notification) as will_send:
        assert will_send is True
        raise Exception("some random error")

    notification.refresh_from_db()
    assert notification.state == EmailNotification.STATE_PENDING
    assert notification.sent_at is None
Exemplo n.º 5
0
def test_mark_as_sent_or_canceled_cancel_error():
    """Verify mark_as_sent_or_canceled marks the task as canceled"""
    notification = EmailNotificationFactory.create(sending=True)

    with utils.mark_as_sent_or_canceled(notification) as will_send:
        assert will_send is True
        raise CancelNotificationError()

    notification.refresh_from_db()
    assert notification.state == EmailNotification.STATE_CANCELED
    assert notification.sent_at is None
Exemplo n.º 6
0
def test_send_notification_already_sent(notifier, mocker):
    """Tests send_notification that it doesn't send a notification that has already been sent"""
    send_messages_mock = mocker.patch("mail.api.send_messages")
    note = EmailNotificationFactory.create(
        user=notifier.user,
        notification_type=notifier.notification_settings.notification_type,
        sent=True,
    )

    notifier.send_notification(note)

    send_messages_mock.assert_not_called()
Exemplo n.º 7
0
def test_send_notification(notifier, mocker):
    """Tests send_notification"""
    send_messages_mock = mocker.patch("mail.api.send_messages")
    note = EmailNotificationFactory.create(
        user=notifier.user,
        notification_type=notifier.notification_settings.notification_type,
        sending=True,
    )

    notifier.send_notification(note)

    send_messages_mock.assert_called_once_with([any_instance_of(EmailMessage)])
Exemplo n.º 8
0
def test_send_notification_no_user_mismatch(notifier, mocker):
    """Tests send_notification that it raises an error if the user mismatches"""
    send_messages_mock = mocker.patch("mail.api.send_messages")
    mocker.patch("mail.api.messages_for_recipients", return_value=[])
    note = EmailNotificationFactory.create(
        notification_type=notifier.notification_settings.notification_type,
        sending=True)

    notifier.send_notification(note)

    note.refresh_from_db()
    assert note.state == EmailNotification.STATE_PENDING

    send_messages_mock.assert_not_called()
Exemplo n.º 9
0
def test_send_notification_never(notifier, mocker):
    """Tests send_notification if trigger_frequency is never"""
    send_messages_mock = mocker.patch("mail.api.send_messages")
    notifier.notification_settings.trigger_frequency = FREQUENCY_NEVER
    note = EmailNotificationFactory.create(
        user=notifier.user,
        notification_type=notifier.notification_settings.notification_type,
        sending=True,
    )

    notifier.send_notification(note)
    note.refresh_from_db()
    assert note.state == EmailNotification.STATE_CANCELED

    send_messages_mock.assert_not_called()
Exemplo n.º 10
0
def test_send_notification_no_messages(notifier, mocker):
    """Tests send_notification that it cancels the notification if a message can't be sent"""
    send_messages_mock = mocker.patch("mail.api.send_messages")
    mocker.patch("mail.api.messages_for_recipients", return_value=[])
    note = EmailNotificationFactory.create(
        user=notifier.user,
        notification_type=notifier.notification_settings.notification_type,
        sending=True,
    )

    notifier.send_notification(note)

    note.refresh_from_db()
    assert note.state == EmailNotification.STATE_CANCELED

    send_messages_mock.assert_not_called()
Exemplo n.º 11
0
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
Exemplo n.º 12
0
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)
Exemplo n.º 13
0
def test_send_unsent_email_notifications(mocker, settings):
    """Tests that send_unsent_email_notifications triggers a task for each batch"""

    settings.NOTIFICATION_SEND_CHUNK_SIZE = 75

    notifications_ids = sorted(
        [note.id for note in EmailNotificationFactory.create_batch(150)])

    mock_task = mocker.patch(
        "notifications.tasks.send_email_notification_batch").delay
    assert (EmailNotification.objects.filter(
        state=EmailNotification.STATE_SENDING).count() == 0)

    api.send_unsent_email_notifications()

    assert mock_task.call_count == 2
    mock_task.assert_any_call(notifications_ids[:75])
    mock_task.assert_any_call(notifications_ids[75:])
    assert EmailNotification.objects.filter(
        state=EmailNotification.STATE_SENDING).count() == len(
            notifications_ids)
Exemplo n.º 14
0
def test_send_email_notification_batch(mocker, should_cancel,
                                       notification_type, notifier_fqn):
    """Verify send_email_notification_batch calls the notifier for each of the notifications it is given"""
    notifications = EmailNotificationFactory.create_batch(
        5, notification_type=notification_type)
    for notification in notifications:
        NotificationSettingsFactory.create(user=notification.user,
                                           notification_type=notification_type)

    mock_notifier = mocker.patch(notifier_fqn).return_value

    if should_cancel:
        mock_notifier.send_notification.side_effect = CancelNotificationError

    api.send_email_notification_batch([note.id for note in notifications])

    assert mock_notifier.send_notification.call_count == len(notifications)

    for notification in notifications:
        notification.refresh_from_db()
        mock_notifier.send_notification.assert_any_call(notification)

        if should_cancel:
            assert notification.state == EmailNotification.STATE_CANCELED