Esempio n. 1
0
def test_populate_posts_and_comments(mocker):
    """
    populate_posts_and_comments should call the backpopulate API for each post
    """

    post_ids = [1, 2, 3]

    ChannelFactory.create(name="exists")

    submission_mock = mocker.Mock(id="1",
                                  subreddit=mocker.Mock(display_name="exists"))

    mock_submissions = [
        submission_mock,
        mocker.Mock(id="2", subreddit=mocker.Mock(display_name="missing")),
    ]

    mock_api = mocker.patch("channels.api.Api", autospec=True)
    mock_api.return_value.get_submission.side_effect = mock_submissions

    mock_backpopulate_api = mocker.patch("channels.tasks.backpopulate_api")
    mock_backpopulate_api.backpopulate_comments.return_value = 15

    result = tasks.populate_posts_and_comments.delay(post_ids).get()

    assert mock_api.return_value.get_submission.call_count == len(post_ids)
    for post_id in post_ids:
        mock_api.return_value.get_submission.assert_any_call(
            base36.dumps(post_id))

    assert Post.objects.filter(post_id="1").exists()

    post = Post.objects.get(post_id="1")

    mock_backpopulate_api.backpopulate_post.assert_called_once_with(
        post=post, submission=submission_mock)
    mock_backpopulate_api.backpopulate_comments.assert_called_once_with(
        post=post, submission=submission_mock)

    for mock in mock_submissions:
        mock._fetch.assert_called_once_with()  # pylint: disable=protected-access

    assert result == {
        "posts":
        1,
        "comments":
        15,
        "failures": [{
            "thing_type": "post",
            "thing_id": "2",
            "reason": "unknown channel 'missing'",
        }],
    }
Esempio n. 2
0
def test_populate_channel_fields_batch(mocker):
    """
    populate_channel_fields should set fields from reddit
    """
    channels = ChannelFactory.create_batch(2)
    mock_api = mocker.patch("channels.api.Api", autospec=True)
    mock_subreddit = mock_api.return_value.get_subreddit.return_value
    mock_subreddit.submission_type = LINK_TYPE_ANY
    mock_subreddit.title = "A channel title"
    mock_subreddit.subreddit_type = CHANNEL_TYPE_PUBLIC

    updated_channel = channels[0]
    updated_channel.allowed_post_types = 0
    updated_channel.title = None
    updated_channel.channel_type = None
    updated_channel.save()

    tasks.populate_channel_fields_batch.delay(
        [channel.id for channel in channels])

    updated_channel.refresh_from_db()

    mock_api.return_value.get_subreddit.assert_called_once_with(
        updated_channel.name)

    assert int(updated_channel.allowed_post_types) == int(
        Channel.allowed_post_types.self | Channel.allowed_post_types.link)
    assert updated_channel.channel_type == CHANNEL_TYPE_PUBLIC
    assert updated_channel.title == "A channel title"
def test_update_channel(user, validated_data, expected_kwawrgs):
    """
    Test updating a channel
    """
    display_name = "subreddit"
    ChannelFactory.create(name=display_name)
    instance = Mock(display_name=display_name)
    request = Mock(user=user)
    api_mock = Mock()
    channel = ChannelSerializer(context={
        "channel_api": api_mock,
        "request": request
    }).update(instance, validated_data)
    api_mock.update_channel.assert_called_once_with(name=display_name,
                                                    **expected_kwawrgs)
    assert channel == api_mock.update_channel.return_value
def test_update_memberships_for_managed_channels(mocker):
    """
    Verify that update_memberships_for_managed_channels() calls
    update_memberships_for_managed_channel() with configured channels
    """
    # channels with no configs, shouldn't be used
    ChannelFactory.create(membership_is_managed=True)
    ChannelFactory.create(membership_is_managed=False)

    # channels with configs, only managed one should be used
    managed_channel1 = ChannelFactory.create(membership_is_managed=True)
    managed_channel1.channel_membership_configs.add(
        ChannelMembershipConfigFactory.create())
    managed_channel2 = ChannelFactory.create(membership_is_managed=True)
    managed_channel2.channel_membership_configs.add(
        ChannelMembershipConfigFactory.create())
    nonmanaged_channel = ChannelFactory.create(membership_is_managed=False)
    nonmanaged_channel.channel_membership_configs.add(
        ChannelMembershipConfigFactory.create())

    mock_update_memberships_for_managed_channel = mocker.patch(
        "channels.membership_api.update_memberships_for_managed_channel",
        autospec=True)

    update_memberships_for_managed_channels(channel_ids=[managed_channel1.id],
                                            user_ids=[1, 2, 3])

    mock_update_memberships_for_managed_channel.assert_called_once_with(
        managed_channel1, user_ids=[1, 2, 3])
Esempio n. 5
0
def test_get_channels(user):
    """
    Test that get_channels returns the correct list of channel names for a user
    """
    channels = ChannelFactory.create_batch(4)
    sync_channel_subscription_model(channels[0], user)
    add_user_role(channels[1], ROLE_CONTRIBUTORS, user)
    add_user_role(channels[2], ROLE_MODERATORS, user)
    assert get_channels(user) == {channel.name for channel in channels[:3]}
Esempio n. 6
0
def channels_and_users():
    """Channels and users for testing"""
    return (
        [
            ChannelFactory.create(name=channel_name)
            for channel_name in ["a", "b", "c"]
        ],
        UserFactory.create_batch(4),
    )
def test_list_invites_noauth(client, user, is_logged_in):
    """Test that the invite list returns all the invites for the channel"""
    channel = ChannelFactory.create()

    url = reverse("channel_invitation_api-list",
                  kwargs={"channel_name": channel.name})

    if is_logged_in:
        client.force_login(user)

    resp = client.get(url)
    assert resp.status_code == status.HTTP_403_FORBIDDEN
Esempio n. 8
0
def test_subscriber_create():
    """Adds a subscriber"""
    user = UserFactory.create()
    ChannelFactory.create(name="foo_channel")
    subscriber_user = UserFactory.create()
    api_mock = Mock(
        add_subscriber=Mock(
            side_effect=[
                sync_channel_subscription_model("foo_channel", subscriber_user)
            ]
        )
    )
    subscriber = SubscriberSerializer(
        context={
            "channel_api": api_mock,
            "request": Mock(user=user),
            "view": Mock(kwargs={"channel_name": "foo_channel"}),
        }
    ).create({"subscriber_name": subscriber_user.username})
    assert subscriber.id == subscriber_user.id
    api_mock.add_subscriber.assert_called_once_with(
        subscriber_user.username, "foo_channel"
    )
def test_invite_create_email_error(user, mocker):
    """Rolls back invite record if the celert task fails to queue"""
    mock_tasks = mocker.patch("channels.serializers.invites.tasks")
    mock_tasks.send_invitation_email.delay.side_effect = Exception()
    channel = ChannelFactory.create()
    email = "*****@*****.**"

    with pytest.raises(Exception):
        ChannelInvitationSerializer(context={
            "channel": channel,
            "inviter": user
        }).create({"email": email})

    assert not ChannelInvitation.objects.filter(channel=channel,
                                                email=email).exists()
Esempio n. 10
0
def test_get_channel_join_dates(user):
    """
    Test out the get_channel_join_dates function
    """
    channels = ChannelFactory.create_batch(4)
    sync_channel_subscription_model(channels[0], user)
    sync_channel_subscription_model(channels[1], user)
    add_user_role(channels[2], "moderators", user)
    add_user_role(channels[3], "contributors", user)
    assert sorted(get_channel_join_dates(user)) == sorted(
        [
            (obj.channel.name, obj.created_on)
            for obj in list(user.channelsubscription_set.all())
            + list(ChannelGroupRole.objects.filter(group__in=user.groups.all()))
        ]
    )
def test_update_memberships_for_managed_channel_empty_queries(mocker):
    """Verifies that update_memberships_for_managed_channel() bails if the queries would return all users"""
    mock_api = mocker.patch("channels.api.Api", autospec=True).return_value
    channel = ChannelFactory.create(membership_is_managed=True)
    channel.channel_membership_configs.add(
        ChannelMembershipConfigFactory.create(
            query={}  # an empty query should match all users
        ))

    UserFactory.create(
        is_active=True)  # this user will match the `active_users` query

    update_memberships_for_managed_channel(channel)

    mock_api.add_subscriber.assert_not_called()
    mock_api.add_contributor.assert_not_called()
Esempio n. 12
0
def test_channel_membership_config_save(mocker, settings, query,
                                        moira_enabled):
    """Test that update_moira_list_users is called for every moira list in the config"""
    settings.FEATURES[features.MOIRA] = moira_enabled
    mock_update_moira = mocker.patch(
        "moira_lists.tasks.update_moira_list_users.delay")
    channel = ChannelFactory.create(membership_is_managed=True)
    config = ChannelMembershipConfigFactory.create()
    channel.channel_membership_configs.add(config)
    config.query = query
    config.save()
    if moira_enabled and "moira_lists" in query:
        mock_update_moira.assert_called_once_with(query["moira_lists"],
                                                  channel_ids=[channel.id])
    else:
        mock_update_moira.assert_not_called()
Esempio n. 13
0
def test_create_invite_noauth(client, user, mocker, is_logged_in):
    """Test that the invite list creates an invite for the channel"""
    channel = ChannelFactory.create()
    mock_tasks = mocker.patch("channels.serializers.invites.tasks")
    email = "*****@*****.**"
    url = reverse("channel_invitation_api-list",
                  kwargs={"channel_name": channel.name})

    if is_logged_in:
        client.force_login(user)

    resp = client.post(url, data={"email": email}, format="json")

    assert resp.status_code == status.HTTP_403_FORBIDDEN
    assert ChannelInvitation.objects.count() == 0
    mock_tasks.send_invitation_email.delay.assert_not_called()
def test_update_channel_about(user, about):
    """
    Test updating the channel about field
    """
    channel = ChannelFactory.create(about=None)
    instance = Mock(display_name=channel.name)
    request = Mock(user=user)
    api_mock = Mock()
    api_mock.update_channel.return_value._self_channel = (  # pylint: disable=protected-access
        channel)
    ChannelSerializer(context={
        "channel_api": api_mock,
        "request": request
    }).update(instance, {"about": about})
    channel.refresh_from_db()
    assert channel.about == about
Esempio n. 15
0
def test_create_invite(staff_client, mocker):
    """Test that the invite list creates an invite for the channel"""
    channel = ChannelFactory.create()
    mocker.patch("channels.serializers.invites.tasks")
    email = "*****@*****.**"
    url = reverse("channel_invitation_api-list",
                  kwargs={"channel_name": channel.name})

    resp = staff_client.post(url, data={"email": email}, format="json")
    invite = ChannelInvitation.objects.first()

    assert resp.status_code == status.HTTP_201_CREATED
    assert resp.json() == {
        "id": invite.id,
        "email": invite.email,
        "created_on": drf_datetime(invite.created_on),
        "updated_on": drf_datetime(invite.updated_on),
    }
Esempio n. 16
0
def test_invite_create_email(user, mocker):
    """Invites a user by email"""
    mock_tasks = mocker.patch("channels.serializers.invites.tasks")
    channel = ChannelFactory.create()
    email = "*****@*****.**"
    result = ChannelInvitationSerializer(context={
        "channel": channel,
        "inviter": user
    }).create({"email": email})

    invite = ChannelInvitation.objects.get(channel=channel, email=email)

    mock_tasks.send_invitation_email.delay.assert_called_once_with(invite.id)

    assert result == invite
    assert result.email == email
    assert result.inviter == user
    assert result.channel == channel
Esempio n. 17
0
def test_list_invites(staff_client):
    """Test that the invite list returns all the invites for the channel"""
    channel = ChannelFactory.create()
    invites = ChannelInvitationFactory.create_batch(5, channel=channel)
    ChannelInvitationFactory.create_batch(5)  # these should not show up

    url = reverse("channel_invitation_api-list",
                  kwargs={"channel_name": channel.name})

    resp = staff_client.get(url)
    assert resp.status_code == status.HTTP_200_OK
    assert resp.json() == [{
        "id": invite.id,
        "email": invite.email,
        "created_on": drf_datetime(invite.created_on),
        "updated_on": drf_datetime(invite.updated_on),
    } for invite in sorted(invites, key=attrgetter("created_on"), reverse=True)
                           ]
def test_update_memberships_for_managed_channel_missing_profile(mocker):
    """Verify that an exception is logged if a profile is missing for a user"""
    mock_api = mocker.patch("channels.api.Api", autospec=True).return_value
    mock_api.add_contributor.side_effect = Profile.DoesNotExist
    user = UserFactory.create(email="*****@*****.**",
                              is_active=True,
                              profile=None)
    channel = ChannelFactory.create(membership_is_managed=True)
    channel.channel_membership_configs.add(
        ChannelMembershipConfigFactory.create(
            query={"email__endswith": "@matching.email"}))

    update_memberships_for_managed_channel(channel, user_ids=[user.id])

    mock_log = mocker.patch("channels.membership_api.log.exception")
    update_memberships_for_managed_channel(channel, user_ids=[user.id])
    mock_log.assert_called_once_with(
        "Channel %s membership update failed due to missing user profile: %s",
        channel.name,
        user.username,
    )
def test_update_memberships_for_managed_channel(mocker, is_managed,
                                                has_configs):
    """"Verifies that update_memberships_for_managed_channel() adds matching users as members to a channel"""
    mock_api = mocker.patch("channels.api.Api", autospec=True).return_value
    channel = ChannelFactory.create(membership_is_managed=is_managed)
    if has_configs:
        channel.channel_membership_configs.add(
            ChannelMembershipConfigFactory.create(
                query={"email__endswith": "@matching.email"}))

    user = UserFactory.create(email="*****@*****.**", is_active=True)
    UserFactory.create(email="*****@*****.**", is_active=True)
    UserFactory.create(email="*****@*****.**", is_active=False)

    update_memberships_for_managed_channel(channel, user_ids=[user.id])

    if is_managed and has_configs:
        mock_api.add_subscriber.assert_called_once_with(
            user.username, channel.name)
        mock_api.add_contributor.assert_called_once_with(
            user.username, channel.name)
    else:
        mock_api.add_subscriber.assert_not_called()
        mock_api.add_contributor.assert_not_called()