Example #1
0
    def test_generatereviews(self):
        PROFILES_TO_CREATE = 20

        ProfileFactory.create_batch(PROFILES_TO_CREATE)
        call_command('generatereviews', reviews_count=self.REVIEWS_TO_CREATE)
        review_count = Review.objects.count()
        self.assertEqual(review_count, self.REVIEWS_TO_CREATE)
    def test_patch_own_profile(self):
        """
        A user PATCHes their own profile
        """
        with mute_signals(post_save):
            ProfileFactory.create(user=self.user1,
                                  filled_out=False,
                                  agreed_to_terms_of_service=False)
        self.client.force_login(self.user1)

        with mute_signals(post_save):
            new_profile = ProfileFactory.create(filled_out=False)
        new_profile.user.social_auth.create(provider=EdxOrgOAuth2.name,
                                            uid="{}_edx".format(
                                                new_profile.user.username))
        patch_data = ProfileSerializer().to_representation(new_profile)

        resp = self.client.patch(self.url1,
                                 content_type="application/json",
                                 data=json.dumps(patch_data))
        assert resp.status_code == 200

        old_profile = Profile.objects.get(user__username=self.user1.username)
        for key, value in patch_data.items():
            field = ProfileSerializer().fields[key]

            if isinstance(field, (ListSerializer, SerializerMethodField,
                                  ReadOnlyField)) or field.read_only is True:
                # these fields are readonly
                continue
            elif isinstance(field, DateField):
                assert getattr(old_profile, key) == parse(value).date()
            else:
                assert getattr(old_profile, key) == value
Example #3
0
 def setUpTestData(cls):
     super().setUpTestData()
     with mute_signals(post_save):
         staff_profile = ProfileFactory.create(user__email='*****@*****.**')
         recipient_profile = ProfileFactory.create(
             user__email='*****@*****.**',
             email_optin=True,
         )
     cls.staff_user = staff_profile.user
     cls.recipient_user = recipient_profile.user
     cls.program = ProgramFactory.create(financial_aid_availability=False)
     ProgramEnrollmentFactory.create(
         user=cls.recipient_user,
         program=cls.program
     )
     Role.objects.create(
         user=cls.staff_user,
         program=cls.program,
         role=Staff.ROLE_ID
     )
     cls.url_name = 'learner_mail_api'
     cls.request_data = {
         'email_subject': 'email subject',
         'email_body': 'email body'
     }
Example #4
0
    def test_staff_sees_entire_profile(self):
        """
        Staff should be able to see the entire profile despite the account privacy
        """
        with mute_signals(post_save):
            profile = ProfileFactory.create(user=self.user2,
                                            account_privacy=Profile.PRIVATE)
            ProfileFactory.create(user=self.user1,
                                  verified_micromaster_user=False)

        program = ProgramFactory.create()
        ProgramEnrollment.objects.create(
            program=program,
            user=profile.user,
        )
        Role.objects.create(
            program=program,
            role=Staff.ROLE_ID,
            user=self.user1,
        )

        self.client.force_login(self.user1)
        resp = self.client.get(self.url2)
        profile_data = ProfileSerializer(profile).data
        assert resp.json() == format_image_expectation(profile_data)
Example #5
0
    def test_redirects_to_itself_when_submitted_second_time(self):
        self.user.passport_photo = ProfileFactory.create_passport_photo()
        self.user.bar_license_photo = ProfileFactory.create_bar_license_photo()
        self.user.save()

        response = self.client.post(self.VIEW_URL, data=self.data_payload)
        self.assertRedirects(response, self.VIEW_URL)
Example #6
0
    def test_patch_own_profile(self):
        """
        A user PATCHes their own profile
        """
        with mute_signals(post_save):
            ProfileFactory.create(user=self.user1, filled_out=False, agreed_to_terms_of_service=False)
        self.client.force_login(self.user1)

        with mute_signals(post_save):
            new_profile = ProfileFactory.create(filled_out=False)
        new_profile.user.social_auth.create(
            provider=EdxOrgOAuth2.name,
            uid="{}_edx".format(new_profile.user.username)
        )
        patch_data = ProfileSerializer(new_profile).data
        del patch_data['image']

        resp = self.client.patch(self.url1, content_type="application/json", data=json.dumps(patch_data))
        assert resp.status_code == 200

        old_profile = Profile.objects.get(user__username=self.user1.username)
        for key, value in patch_data.items():
            field = ProfileSerializer().fields[key]

            if isinstance(field, (ListSerializer, SerializerMethodField, ReadOnlyField)) or field.read_only is True:
                # these fields are readonly
                continue
            elif isinstance(field, DateField):
                assert getattr(old_profile, key) == parse(value).date()
            else:
                assert getattr(old_profile, key) == value
Example #7
0
    def test_is_attorney_proof_submitted(self):
        profile = ProfileFactory(no_attorney_proof=True)
        self.assertFalse(profile.is_attorney_proof_submitted())

        profile.passport_photo = ProfileFactory.create_passport_photo()
        profile.bar_license_photo = ProfileFactory.create_bar_license_photo()
        profile.save()
        self.assertTrue(profile.is_attorney_proof_submitted())
Example #8
0
 def setUp(self):
     self.data_payload = {
         "passport_photo": ProfileFactory.create_passport_photo(),
         "bar_license_photo": ProfileFactory.create_bar_license_photo(),
         "attorney_confirm": "on",
     }
     self.user = ProfileFactory(no_attorney_proof=True)
     self.client.force_login(self.user)
Example #9
0
 def test_forbidden_methods(self):
     """
     POST is not implemented.
     """
     with mute_signals(post_save):
         ProfileFactory.create(user=self.user1)
     self.client.force_login(self.user1)
     assert self.client.post(self.url1).status_code == HTTP_405_METHOD_NOT_ALLOWED
Example #10
0
 def test_anonym_user_get_private_profile(self):
     """
     An anonymous user gets user's private profile
     """
     with mute_signals(post_save):
         ProfileFactory.create(user=self.user2, account_privacy=Profile.PRIVATE)
     self.client.logout()
     resp = self.client.get(self.url2)
     assert resp.status_code == HTTP_404_NOT_FOUND
Example #11
0
    def test_generatetransactions(self):
        PROFILES_TO_CREATE = 10

        ProfileFactory.create_batch(size=PROFILES_TO_CREATE)
        call_command('generatetransactions',
                     transactions_count=self.TRANSACTIONS_TO_CREATE)
        transaction_count = Transaction.objects.count()

        self.assertEqual(transaction_count, self.TRANSACTIONS_TO_CREATE)
Example #12
0
 def handle(self, *args, **options):
     try:
         ProfileFactory.create_batch(options['profile_count'])
     except IntegrityError as ie:
         raise CommandError(
             'Unable to generate dummy profiles, truncate your database and try again.',
             ie)
     except Exception as ex:
         raise CommandError('Unable to generate dummy profiles.', ex)
Example #13
0
 def test_forbidden_methods(self):
     """
     POST is not implemented.
     """
     with mute_signals(post_save):
         ProfileFactory.create(user=self.user1)
     self.client.force_login(self.user1)
     assert self.client.post(
         self.url1).status_code == HTTP_405_METHOD_NOT_ALLOWED
Example #14
0
 def test_weird_privacy_get_private_profile(self):
     """
     If a user profile has a weird profile setting, it defaults to private
     """
     with mute_signals(post_save):
         ProfileFactory.create(user=self.user2, account_privacy='weird_setting')
         ProfileFactory.create(user=self.user1, verified_micromaster_user=True)
     self.client.force_login(self.user1)
     resp = self.client.get(self.url2)
     assert resp.status_code == HTTP_404_NOT_FOUND
Example #15
0
 def test_vermm_user_get_private_profile(self):
     """
     A verified mm user gets user's private profile
     """
     with mute_signals(post_save):
         ProfileFactory.create(user=self.user2, account_privacy=Profile.PRIVATE)
         ProfileFactory.create(user=self.user1, verified_micromaster_user=True)
     self.client.force_login(self.user1)
     resp = self.client.get(self.url2)
     assert resp.status_code == HTTP_404_NOT_FOUND
Example #16
0
 def test_mm_user_get_public_to_mm_profile(self):
     """
     An unverified mm user gets user's public_to_mm profile.
     """
     with mute_signals(post_save):
         ProfileFactory.create(user=self.user2, account_privacy=Profile.PUBLIC_TO_MM)
         ProfileFactory.create(user=self.user1, verified_micromaster_user=False)
     self.client.force_login(self.user1)
     resp = self.client.get(self.url2)
     assert resp.status_code == HTTP_404_NOT_FOUND
Example #17
0
 def test_anonym_user_get_private_profile(self):
     """
     An anonymous user gets user's private profile
     """
     with mute_signals(post_save):
         ProfileFactory.create(user=self.user2,
                               account_privacy=Profile.PRIVATE)
     self.client.logout()
     resp = self.client.get(self.url2)
     assert resp.status_code == HTTP_404_NOT_FOUND
Example #18
0
    def setUpTestData(cls):
        cls.created_by = ProfileFactory()
        cls.sent_to = ProfileFactory()

        cls.data_payload = {
            'date': timezone.now(),
            'amount': 1234,
            'currency': 'USD',
            'is_requester_principal': True
        }
Example #19
0
 def test_vermm_user_get_public_profile(self):
     """
     A verified mm user gets another user's public profile.
     """
     with mute_signals(post_save):
         profile = ProfileFactory.create(user=self.user2, account_privacy=Profile.PUBLIC)
         ProfileFactory.create(user=self.user1, verified_micromaster_user=True)
     profile_data = ProfileLimitedSerializer(profile).data
     self.client.force_login(self.user1)
     resp = self.client.get(self.url2)
     assert resp.json() == format_image_expectation(profile_data)
Example #20
0
    def test_check_object_permissions(self):
        """
        Make sure check_object_permissions is called at some point so the permissions work correctly
        """
        with mute_signals(post_save):
            ProfileFactory.create(user=self.user1, account_privacy=Profile.PUBLIC)
        self.client.force_login(self.user1)

        with patch.object(ProfileViewSet, 'check_object_permissions', autospec=True) as check_object_permissions:
            self.client.get(self.url1)
        assert check_object_permissions.called
Example #21
0
    def test_generate_profiles_working(self):
        GENERATED_MODELS_COUNT = 25

        existing_profiles_count = Profile.objects.count()

        ProfileFactory.create_batch(GENERATED_MODELS_COUNT)

        new_profiles_count = Profile.objects.count()

        self.assertEqual(new_profiles_count,
                         existing_profiles_count + GENERATED_MODELS_COUNT)
Example #22
0
 def test_weird_privacy_get_private_profile(self):
     """
     If a user profile has a weird profile setting, it defaults to private
     """
     with mute_signals(post_save):
         ProfileFactory.create(user=self.user2,
                               account_privacy='weird_setting')
         ProfileFactory.create(user=self.user1,
                               verified_micromaster_user=True)
     self.client.force_login(self.user1)
     resp = self.client.get(self.url2)
     assert resp.status_code == HTTP_404_NOT_FOUND
Example #23
0
 def test_mm_user_get_public_to_mm_profile(self):
     """
     An unverified mm user gets user's public_to_mm profile.
     """
     with mute_signals(post_save):
         ProfileFactory.create(user=self.user2,
                               account_privacy=Profile.PUBLIC_TO_MM)
         ProfileFactory.create(user=self.user1,
                               verified_micromaster_user=False)
     self.client.force_login(self.user1)
     resp = self.client.get(self.url2)
     assert resp.status_code == HTTP_404_NOT_FOUND
    def test_users_can_view_public_profile(self):
        """
        Users are allowed to view public profile.
        """
        perm = CanSeeIfNotPrivate()
        with mute_signals(post_save):
            ProfileFactory.create(user=self.profile_user,
                                  account_privacy=Profile.PUBLIC)

        request = Mock(user=self.other_user)
        view = Mock(kwargs={'user': self.profile_user_id})
        assert perm.has_permission(request, view) is True
Example #25
0
 def test_vermm_user_get_private_profile(self):
     """
     A verified mm user gets user's private profile
     """
     with mute_signals(post_save):
         ProfileFactory.create(user=self.user2,
                               account_privacy=Profile.PRIVATE)
         ProfileFactory.create(user=self.user1,
                               verified_micromaster_user=True)
     self.client.force_login(self.user1)
     resp = self.client.get(self.url2)
     assert resp.status_code == HTTP_404_NOT_FOUND
Example #26
0
 def test_vermm_user_get_public_profile(self):
     """
     A verified mm user gets another user's public profile.
     """
     with mute_signals(post_save):
         profile = ProfileFactory.create(user=self.user2,
                                         account_privacy=Profile.PUBLIC)
         ProfileFactory.create(user=self.user1,
                               verified_micromaster_user=True)
     profile_data = ProfileLimitedSerializer(profile).data
     self.client.force_login(self.user1)
     resp = self.client.get(self.url2)
     assert resp.json() == format_image_expectation(profile_data)
Example #27
0
 def test_vermm_user_get_public_to_mm_profile(self):
     """
     A verified mm user gets  user's public_to_mm profile.
     """
     with mute_signals(post_save):
         profile = ProfileFactory.create(
             user=self.user2, account_privacy=Profile.PUBLIC_TO_MM)
         ProfileFactory.create(user=self.user1,
                               verified_micromaster_user=True)
     self.client.force_login(self.user1)
     resp = self.client.get(self.url2)
     assert resp.json() == ProfileLimitedSerializer().to_representation(
         profile)
    def test_cant_view_public_if_anonymous_user(self):
        """
        Anonymous are not supposed to view private profiles.
        """
        perm = CanSeeIfNotPrivate()
        with mute_signals(post_save):
            ProfileFactory.create(user=self.profile_user,
                                  account_privacy=Profile.PUBLIC)

        request = Mock(user=Mock(is_anonymous=Mock(return_value=True)))
        view = Mock(kwargs={'user': self.profile_user_id})

        assert perm.has_permission(request, view) is True
    def test_cant_view_if_non_verified_mm_user(self):
        """
        Non verified micromaster users are not supposed to view public_to_mm profiles.
        """
        perm = CanSeeIfNotPrivate()
        with mute_signals(post_save):
            ProfileFactory.create(user=self.profile_user,
                                  account_privacy=Profile.PUBLIC_TO_MM)

        request = Mock(user=self.other_user)
        view = Mock(kwargs={'user': self.profile_user_id})

        with self.assertRaises(Http404):
            perm.has_permission(request, view)
    def test_cant_view_if_privacy_weird(self):
        """
        Users can not open profiles with ambiguous account_privacy settings.
        """
        perm = CanSeeIfNotPrivate()
        with mute_signals(post_save):
            ProfileFactory.create(user=self.profile_user,
                                  account_privacy='weird_setting')

        request = Mock(user=self.other_user)
        view = Mock(kwargs={'user': self.profile_user_id})

        with self.assertRaises(Http404):
            perm.has_permission(request, view)
Example #31
0
    def test_check_object_permissions(self):
        """
        Make sure check_object_permissions is called at some point so the permissions work correctly
        """
        with mute_signals(post_save):
            ProfileFactory.create(user=self.user1,
                                  account_privacy=Profile.PUBLIC)
        self.client.force_login(self.user1)

        with patch.object(ProfileViewSet,
                          'check_object_permissions',
                          autospec=True) as check_object_permissions:
            self.client.get(self.url1)
        assert check_object_permissions.called
    def test_cant_view_if_privacy_is_private(self):
        """
        Users are not supposed to view private profiles.
        """
        perm = CanSeeIfNotPrivate()

        with mute_signals(post_save):
            ProfileFactory.create(user=self.profile_user,
                                  account_privacy=Profile.PRIVATE)

        request = Mock(user=self.other_user)
        view = Mock(kwargs={'user': self.profile_user_id})

        with self.assertRaises(Http404):
            perm.has_permission(request, view)
 def test_verified_enroll_factory_fa_create(self):
     """
     Tests that CachedEnrollmentFactory creates additional data for a FA-enabled course run
     """
     assert Line.objects.count() == 0
     with mute_signals(post_save):
         user = UserFactory.create()
         ProfileFactory.create(user=user)
     fa_program = FullProgramFactory.create(financial_aid_availability=True)
     CachedEnrollmentFactory.create(user=user,
                                    course_run__course__program=fa_program,
                                    verified=True)
     lines = Line.objects.all()
     assert len(lines) == 1
     assert lines[0].order.status == Order.FULFILLED
Example #34
0
    def test_index_program_enrolled_users(self, mock_on_commit):
        """
        Test that index_program_enrolled_users indexes an iterable of program-enrolled users
        """
        num_enrollments = 10
        chunk_size = 4
        with mute_signals(post_save):
            program_enrollments = [
                ProgramEnrollmentFactory.create() for _ in range(num_enrollments)
            ]
            for enrollment in program_enrollments:
                ProfileFactory.create(user=enrollment.user)

        private = [serialize_program_enrolled_user(enrollment) for enrollment in program_enrollments]
        private_dicts = {serialized['id']: serialized for serialized in private}
        public = [serialize_public_enrolled_user(serialized) for serialized in private]
        public_dicts = {serialized['id']: serialized for serialized in public}

        with patch(
            'search.indexing_api._index_chunk', autospec=True, return_value=0
        ) as index_chunk, patch(
            'search.indexing_api.serialize_program_enrolled_user', autospec=True,
            side_effect=lambda x: private_dicts[x.id]
        ) as serialize_mock, patch(
            'search.indexing_api.serialize_public_enrolled_user', autospec=True,
            side_effect=lambda x: public_dicts[x['id']]
        ) as serialize_public_mock:
            index_program_enrolled_users(program_enrollments, chunk_size=chunk_size)
            assert index_chunk.call_count == 6  # 10 enrollments divided in chunks of 4, times the number of types (2)

            public_index = make_alias_name(PUBLIC_ENROLLMENT_INDEX_TYPE, is_reindexing=False)
            private_index = make_alias_name(PRIVATE_ENROLLMENT_INDEX_TYPE, is_reindexing=False)
            for offset in range(0, num_enrollments, chunk_size):
                # each enrollment should get yielded twice to account for each doctype
                index_chunk.assert_any_call(
                    public[offset:offset+4],  # ordered dicts FTW
                    index=public_index
                )
                index_chunk.assert_any_call(
                    private[offset:offset+4],
                    index=private_index
                )

            assert serialize_mock.call_count == len(program_enrollments)
            assert serialize_public_mock.call_count == len(program_enrollments)
            for enrollment in program_enrollments:
                serialize_mock.assert_any_call(enrollment)
                serialize_public_mock.assert_any_call(private_dicts[enrollment.id])
Example #35
0
 def setUpTestData(cls):
     with mute_signals(post_save):
         profile = ProfileFactory.create()
     cls.user = profile.user
     cls.program = ProgramFactory.create()
     cls.program_enrollment = ProgramEnrollment.objects.create(
         user=cls.user, program=cls.program)
Example #36
0
def test_add_moderators_to_channel(mocker, patched_users_api):
    """add_moderators_to_channel should add staff or instructors as moderators and subscribers"""
    channel = ChannelFactory.create()
    mods = []
    for _ in range(3):
        program = ChannelProgramFactory.create(channel=channel).program
        with mute_signals(post_save):
            mods += [
                RoleFactory.create(
                    program=program,
                    user=ProfileFactory.create().user
                ).user for _ in range(5)
            ]

        for __ in range(5):
            # Add some users to the channel to show that being part of the channel is not enough to be added as a mod
            ProgramEnrollmentFactory.create(program=program)

    create_stub, _ = patched_users_api
    create_stub.reset_mock()
    add_subscriber_stub = mocker.patch('discussions.api.add_subscriber_to_channel', autospec=True)
    add_moderator_stub = mocker.patch('discussions.api.add_moderator_to_channel', autospec=True)
    api.add_moderators_to_channel(channel.name)

    for mod in mods:
        add_subscriber_stub.assert_any_call(channel.name, mod.discussion_user.username)
        add_moderator_stub.assert_any_call(channel.name, mod.discussion_user.username)
        create_stub.assert_any_call(mod.discussion_user)

    assert add_subscriber_stub.call_count == len(mods)
    assert add_moderator_stub.call_count == len(mods)
    assert create_stub.call_count == len(mods)
Example #37
0
def test_update_discussion_user_no_update(mock_staff_client):
    """Verify update_discussion_user makes the correct API calls"""
    with mute_signals(post_save):
        profile = ProfileFactory.create()
    discussion_user = DiscussionUser.objects.create(user=profile.user, username='******', last_sync=profile.updated_on)
    api.update_discussion_user(discussion_user)
    assert mock_staff_client.users.update.call_count == 0
Example #38
0
 def test_post_redirects(self):
     """Test that POST redirects to same URL"""
     with mute_signals(post_save):
         profile = ProfileFactory.create(agreed_to_terms_of_service=True, filled_out=True)
     self.client.force_login(profile.user)
     resp = self.client.post("/dashboard/", follow=True)
     assert resp.redirect_chain == [('http://testserver/dashboard/', 302)]
Example #39
0
 def test_save_and_log(self):
     """
     Tests that FinancialAid.save_and_log() creates an audit record with the correct information.
     """
     with mute_signals(post_save):
         profile = ProfileFactory.create()
     acting_user = profile.user
     financial_aid = FinancialAidFactory.create()
     original_before_json = serialize_model_object(financial_aid)
     # Make sure audit object is created
     assert FinancialAidAudit.objects.count() == 0
     financial_aid.status = FinancialAidStatus.AUTO_APPROVED
     financial_aid.save_and_log(acting_user)
     assert FinancialAidAudit.objects.count() == 1
     # Make sure the before and after data are correct
     financial_aid.refresh_from_db()
     original_after_json = serialize_model_object(financial_aid)
     financial_aid_audit = FinancialAidAudit.objects.first()
     before_json = financial_aid_audit.data_before
     after_json = financial_aid_audit.data_after
     for field, value in before_json.items():
         # Data before
         if isinstance(value, float):
             # JSON serialization of FloatField is precise, so we need to do almost equal
             self.assertAlmostEqual(value, original_before_json[field])
         else:
             assert value == original_before_json[field]
     for field, value in after_json.items():
         # Data after
         if isinstance(value, float):
             # JSON serialization of FloatField is precise, so we need to do almost equal
             self.assertAlmostEqual(value, original_after_json[field])
         else:
             assert value == original_after_json[field]
Example #40
0
def test_sync_user_profile_save_enabled(mocker, patched_users_api):
    """Test that sync_user_profile calls the task if enabled on save"""
    mock_task = mocker.patch('discussions.tasks.sync_discussion_user')
    with mute_signals(post_save):
        profile = ProfileFactory.create()
    profile.save()
    mock_task.delay.assert_called_once_with(profile.user_id)
Example #41
0
    def setUpTestData(cls):
        super(SearchTests, cls).setUpTestData()
        # create some students
        with mute_signals(post_save):
            cls.students = [(ProfileFactory.create(filled_out=True)).user for _ in range(30)]
        # create the programs
        cls.program1 = ProgramFactory.create(live=True)
        cls.program2 = ProgramFactory.create(live=True)
        cls.program3 = ProgramFactory.create(live=True)

        # enroll the users in the programs
        for num, student in enumerate(cls.students):
            if num % 3 == 0:
                program = cls.program1
            elif num % 3 == 1:
                program = cls.program2
            else:
                program = cls.program3
            ProgramEnrollmentFactory.create(
                user=student,
                program=program
            )

        # create an user with a role for one program
        cls.staff = UserFactory.create()
        Role.objects.create(
            user=cls.staff,
            program=cls.program1,
            role=Staff.ROLE_ID
        )

        # search URL
        cls.search_url = reverse('search_api', kwargs={'elastic_url': ''})
Example #42
0
    def test_register_status_correct(self):
        profile = ProfileFactory(empty_profile=True)
        self.assertEqual(profile.register_status,
                         Profile.REGISTER_STATUS_EMPTY_PROFILE)

        profile = ProfileFactory(no_attorney_proof=True)
        self.assertEqual(profile.register_status,
                         Profile.REGISTER_STATUS_NO_ATTORNEY_PROOF)

        profile = ProfileFactory(email_not_confirmed=True)
        self.assertEqual(profile.register_status,
                         Profile.REGISTER_STATUS_EMAIL_NOT_CONFIRMED)

        profile = ProfileFactory()
        self.assertEqual(profile.register_status,
                         Profile.REGISTER_STATUS_COMPLETE)
Example #43
0
    def test_update_percolate_memberships(self, source_type, is_member, query_matches, mock_on_commit):
        """
        Tests that existing memberships are updated where appropriate
        """
        with mute_signals(post_save):
            query = PercolateQueryFactory.create(source_type=source_type)
            profile = ProfileFactory.create(filled_out=True)
            program_enrollment = ProgramEnrollmentFactory.create(user=profile.user)
        membership = PercolateQueryMembershipFactory.create(
            user=profile.user,
            query=query,
            is_member=is_member,
            needs_update=False
        )

        with patch(
            'search.api._search_percolate_queries',
            return_value=[query.id] if query_matches else []
        ) as search_percolate_queries_mock:
            update_percolate_memberships(profile.user, source_type)

        search_percolate_queries_mock.assert_called_once_with(program_enrollment)

        membership.refresh_from_db()
        assert membership.needs_update is (is_member is not query_matches)
Example #44
0
 def setUpTestData(cls):
     """
     Create a profile
     """
     super().setUpTestData()
     with mute_signals(post_save):
         cls.profile = ProfileFactory.create()
Example #45
0
 def test_display_name_no_last_name(self):
     """Test the profile display name with a blank last name"""
     with mute_signals(post_save):
         profile = ProfileFactory(first_name='First',
                                  last_name=None,
                                  preferred_name=None)
     assert profile.display_name == 'First'
Example #46
0
    def test_index_context_logged_in_staff(self, role):
        """
        Assert context values when logged in as staff for a program
        """
        program = ProgramFactory.create(live=True)
        with mute_signals(post_save):
            profile = ProfileFactory.create()
        Role.objects.create(
            role=role,
            program=program,
            user=profile.user,
        )
        self.client.force_login(profile.user)

        ga_tracking_id = FuzzyText().fuzz()
        with self.settings(
            GA_TRACKING_ID=ga_tracking_id,
        ):
            response = self.client.get('/')
            assert response.context['authenticated'] is True
            assert response.context['username'] is None
            assert response.context['title'] == HomePage.objects.first().title
            assert response.context['is_public'] is True
            assert response.context['has_zendesk_widget'] is True
            assert response.context['is_staff'] is True
            assert response.context['programs'] == [
                (program, None),
            ]
            self.assertContains(response, 'Share this page')
            js_settings = json.loads(response.context['js_settings_json'])
            assert js_settings['gaTrackingID'] == ga_tracking_id
Example #47
0
    def test_learner_view_needs_paid_learner(self, mock_mailgun_client):
        """
        Test that a learner attempting to email another learner will only succeed if the sender
        has paid for a course run in a program that the recipient is enrolled in
        """
        mock_mailgun_client.send_individual_email.return_value = Mock(
            spec=Response,
            status_code=status.HTTP_200_OK,
            json=mocked_json()
        )
        with mute_signals(post_save):
            learner_profile = ProfileFactory.create(
                user__email='*****@*****.**',
                email_optin=True,
            )
        learner_user = learner_profile.user
        ProgramEnrollmentFactory.create(user=learner_user, program=self.program)
        CachedEnrollment.objects.filter(user=learner_user).delete()

        self.client.force_login(learner_user)
        url = reverse(self.url_name, kwargs={'student_id': self.recipient_user.profile.student_id})
        resp_post = self.client.post(url, data=self.request_data, format='json')
        assert resp_post.status_code == status.HTTP_403_FORBIDDEN
        CachedEnrollmentFactory.create(user=learner_user, course_run__course__program=self.program, verified=True)
        resp_post = self.client.post(url, data=self.request_data, format='json')
        assert resp_post.status_code == status.HTTP_200_OK
Example #48
0
    def test_view_with_search(self, staff_client, program_data):
        """
        Tests that ReviewFinancialAidView returns the expected results with search
        """
        fin_aid_status = FinancialAidStatus.AUTO_APPROVED
        profiles = ProfileFactory.create_batch(
            4,
            first_name=factory.Iterator(['match_name', 'x', 'y', 'z']),
            last_name=factory.Iterator(['x', 'y', 'z', 'match_name']),
        )
        FinancialAidFactory.create_batch(
            4,
            tier_program=program_data.tier_programs["0k"],
            status=fin_aid_status,
            user=factory.Iterator([p.user for p in profiles])
        )
        name_query = 'match_name'
        url = self.review_url(program_data.program.id, status=fin_aid_status, search_param=name_query)
        resp = staff_client.get(url)
        assert resp.status_code == status.HTTP_200_OK
        financial_aid_objects = resp.context_data["financial_aid_objects"]

        # Two users should match the search term - one for first_name, one for last_name
        assert len(financial_aid_objects) == 2
        assert all(
            fin_aid.user.profile.first_name == name_query or fin_aid.user.profile.last_name == name_query
            for fin_aid in financial_aid_objects
        )
Example #49
0
def create_enrolled_profile(program, role=None, **profile_kwargs):
    """
    Helper function to create a profile and some related models

    Args:
        program (courses.models.Program):
            A program
        role (str or None):
            A role, or no role if None
    Returns:
        profiles.models.Profile: A new profile
    """
    with mute_signals(post_save):
        profile = ProfileFactory.create(**profile_kwargs)

    ProgramEnrollment.objects.create(
        user=profile.user,
        program=program
    )
    if role is not None:
        Role.objects.create(
            user=profile.user,
            program=program,
            role=role,
        )

    return profile
Example #50
0
 def setUpTestData(cls):
     """
     Create a profile
     """
     super().setUpTestData()
     with mute_signals(post_save):
         cls.profile = ProfileFactory.create()
Example #51
0
    def test_upload_image_creates_thumbnail(self, image_already_exists, thumb_already_exists):
        """
        An image upload should cause the thumbnail to be updated
        """
        with mute_signals(post_save):
            profile = ProfileFactory.create(user=self.user1, filled_out=False, agreed_to_terms_of_service=False)
            if image_already_exists is False:
                profile.image = None
            if thumb_already_exists is False:
                profile.image_small = None
                profile.image_medium = None
            profile.save()
        self.client.force_login(self.user1)

        patch_data = ProfileSerializer(profile).data
        del patch_data['image']
        del patch_data['image_small']
        del patch_data['image_medium']

        # create a dummy image file in memory for upload
        with make_temp_image_file() as image_file:
            # format patch using multipart upload
            resp = self.client.patch(self.url1, data={
                'image': image_file
            }, format='multipart')
        assert resp.status_code == 200, resp.content.decode('utf-8')

        profile.refresh_from_db()
        assert profile.image.height == 500
        assert profile.image.width == 500
        assert profile.image_small.height == 64
        assert profile.image_small.width == 64
        assert profile.image_medium.height == 128
        assert profile.image_medium.width == 128
Example #52
0
    def test_no_thumbnail_change_if_image_upload(self, image_already_exists, thumb_already_exists):
        """
        A patch without an image upload should not touch the image or the thumbnail
        """
        with mute_signals(post_save):
            profile = ProfileFactory.create(user=self.user1, filled_out=False, agreed_to_terms_of_service=False)
            if image_already_exists is False:
                profile.image = None
            if thumb_already_exists is False:
                profile.image_small = None
                profile.image_medium = None
            profile.save()
        self.client.force_login(self.user1)

        patch_data = ProfileSerializer(profile).data
        del patch_data['image']
        del patch_data['image_small']
        del patch_data['image_medium']

        resp = self.client.patch(self.url1, content_type="application/json", data=json.dumps(patch_data))
        assert resp.status_code == 200

        profile.refresh_from_db()
        assert bool(profile.image) == image_already_exists
        assert bool(profile.image_small) == thumb_already_exists
        assert bool(profile.image_medium) == thumb_already_exists
Example #53
0
    def test_readonly_resized_images(self, image_key):
        """
        Users should not be able to modify image_small or image_medium directly
        """

        with mute_signals(post_save):
            profile = ProfileFactory.create(user=self.user1)
        self.client.force_login(self.user1)

        # create a dummy image file in memory for upload
        with make_temp_image_file() as image_file:

            # save old thumbnail
            resized_image_file = getattr(profile, image_key).file
            backup_thumb_bytes = resized_image_file.read()
            resized_image_file.seek(0)

            # format patch using multipart upload
            resp = self.client.patch(self.url1, data={
                image_key: image_file
            }, format='multipart')
        assert resp.status_code == 200, resp.content.decode('utf-8')

        profile.refresh_from_db()
        # resized image should not have changed
        thumb_bytes = getattr(profile, image_key).file.read()
        assert thumb_bytes == backup_thumb_bytes
Example #54
0
 def test_unset_address(self):
     """Test splitting an unset address"""
     with mute_signals(post_save):
         profile = ProfileFactory(address=None)
     assert profile.address1 is None
     assert profile.address2 is None
     assert profile.address3 is None
Example #55
0
    def test_financial_aid_with_application_with_full_profile(self):
        """
        Test that financialAid request serializer works when profile is filled out.
        """
        with mute_signals(post_save):
            profile = ProfileFactory.create()

        ProgramEnrollmentFactory.create(user=profile.user, program=self.program)
        original_currency = 'USD'
        original_income = 1000.0
        serializer = FinancialAidRequestSerializer(
            data={
                'program_id': self.program.id,
                'tier_program': self.min_tier_program,
                'date_documents_sent': None,
                'original_currency': original_currency,
                'original_income': original_income
            },
            context={
                'request': MagicMock(user=profile.user)
            }
        )
        serializer.is_valid(raise_exception=True)
        serializer.save()
        assert serializer.data == {
            'original_currency': original_currency,
            'original_income': original_income,
            'program_id': self.program.id
        }
Example #56
0
    def test_index_context_logged_in_no_social_auth(self):
        """
        Assert context values when logged in without a social_auth account
        """
        with mute_signals(post_save):
            profile = ProfileFactory.create()
            self.client.force_login(profile.user)

        ga_tracking_id = FuzzyText().fuzz()
        with self.settings(
            GA_TRACKING_ID=ga_tracking_id,
        ), patch('ui.templatetags.render_bundle._get_bundle') as get_bundle:
            response = self.client.get('/')

            bundles = [bundle[0][1] for bundle in get_bundle.call_args_list]
            assert set(bundles) == {
                'common',
                'public',
                'sentry_client',
                'style',
                'style_public',
                'zendesk_widget',
            }

            assert response.context['authenticated'] is True
            assert response.context['username'] is None
            assert response.context['title'] == HomePage.objects.first().title
            assert response.context['is_public'] is True
            assert response.context['has_zendesk_widget'] is True
            assert response.context['is_staff'] is False
            assert response.context['programs'] == []
            self.assertContains(response, 'Share this page')
            js_settings = json.loads(response.context['js_settings_json'])
            assert js_settings['gaTrackingID'] == ga_tracking_id
Example #57
0
 def test_user_with_no_program_access(self):
     """
     Test that a user with no program permissions will raise an exception
     """
     with mute_signals(post_save):
         profile = ProfileFactory.create()
     with self.assertRaises(NoProgramAccessException):
         create_search_obj(profile.user)
Example #58
0
def test_delete_staff_as_moderator_enabled(mocker, patched_users_api):
    """Test that remove_user_as_moderator_to_channel calls the task if enabled on save"""
    mock_task = mocker.patch('discussions.tasks.remove_user_as_moderator_from_channel')
    with mute_signals(post_save):
        profile = ProfileFactory.create()
        role = RoleFactory.create(user=profile.user)
    role.delete()
    mock_task.delay.assert_called_once_with(role.user_id, role.program_id)
Example #59
0
def test_sync_user_profile_disabled(settings, mocker):
    """Test that sync_user_profile doesn't call the api if disabled"""
    settings.FEATURES['OPEN_DISCUSSIONS_USER_SYNC'] = False
    mock_task = mocker.patch('discussions.tasks.sync_discussion_user')
    with mute_signals(post_save):
        profile = ProfileFactory.create()
    profile.save()
    assert mock_task.delay.called is False
Example #60
0
    def test_missing_profile(self):
        """get_mail_vars should skip User objects without a Profile"""
        with mute_signals(post_save):
            profile = ProfileFactory.create()
        user = profile.user
        profile.delete()

        assert list(get_mail_vars([user.email])) == []