factory.django.mute_signals - python examples

Here are the examples of the python api factory.django.mute_signals taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

3 View Complete Implementation : views_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    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)
        astert resp.status_code == HTTP_404_NOT_FOUND

3 View Complete Implementation : views_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    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)
        astert resp.status_code == HTTP_404_NOT_FOUND

3 View Complete Implementation : serializers_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_update_education(self):
        """
        Test that we handle updating an Education correctly
        """
        with mute_signals(post_save):
            education = EducationFactory.create()
        education_data = EducationSerializer(education).data
        education_data['degree_name'] = BACHELORS

        serializer = ProfileSerializer(instance=education.profile, data={
            'education': [education_data], 'work_history': []
        })
        serializer.is_valid(raise_exception=True)
        serializer.save()

        astert education.profile.education.count() == 1
        education = education.profile.education.first()
        astert EducationSerializer(education).data == education_data

3 View Complete Implementation : permissions_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_allow_nonedit(self):
        """
        Users are allowed to use safe methods without owning the profile.
        """
        perm = CanEditIfOwner()
        for method in ('GET', 'HEAD', 'OPTIONS'):
            request = Mock(method=method)
            with mute_signals(post_save):
                profile = ProfileFactory.create()
            astert perm.has_object_permission(request, None, profile)

3 View Complete Implementation : api_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_percolate_failure_user_unenroll_program(self, mock_on_commit):
        """
        If search_percolate fails we should raise an Exception with some useful information for Sentry
        Case when there is not program enrollment.
        """
        with mute_signals(post_save):
            profile = ProfileFactory.create(filled_out=True)
        program_enrollment = ProgramEnrollmentFactory.create(user=profile.user)
        program_enrollment_id = program_enrollment.id
        program_enrollment.delete()
        with self.astertRaises(ProgramEnrollment.DoesNotExist):
            search_percolate_queries(program_enrollment_id, "doesnt_matter")

3 View Complete Implementation : models_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    @data(
        (None, (None, None)),
        ('MA', (None, None)),
        ('US-MA', ('US', 'MA')),
        ('US-MA-BS', (None, None)),  # non a valid code
    )
    @unpack
    def test_country_subdivision(self, state, expected_result):
        """Test country_subdivision against a range of values"""
        with mute_signals(post_save):
            profile = ProfileFactory(state_or_territory=state)

        astert profile.country_subdivision == expected_result

3 View Complete Implementation : views_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    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)
        astert resp.status_code == HTTP_404_NOT_FOUND

3 View Complete Implementation : api_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_successful_program_letter_generation(self):
        """
        Test happy scenario
        """
        self.program.financial_aid_availability = False
        self.program.save()
        with mute_signals(post_save):
            FinalGradeFactory.create(
                user=self.user,
                course_run=self.run_1,
                pasted=True,
                status='complete',
                grade=0.8
            )

        cert_qset = MicromastersProgramCommendation.objects.filter(user=self.user, program=self.program)
        astert cert_qset.exists() is False
        api.generate_program_letter(self.user, self.program)
        astert cert_qset.exists() is True

3 View Complete Implementation : signals_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_update(self, mock_on_commit):
        """
        Tests that the database is reindexed when a ProgramEnrollment is created
        """
        with mute_signals(post_save):
            enrollment = ProgramEnrollment.objects.create(user=self.user, program=self.program)
        enrollment.save()
        astert list(self.index_program_enrolled_users_mock.call_args[0][0].values_list('id', flat=True)) == [
            enrollment.id
        ]

3 View Complete Implementation : writers_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    @ddt.data(
        ("Jekyll", None, "Jekyll"),
        (None, "Hyde", "Hyde"),
        ("Jekyll", "Hyde", "Hyde"),
    )
    @ddt.unpack
    def test_last_name(self, unromanized, romanized, expected):
        """
        Test that the `last_name` method prefers the `romanized_last_name`
        field, and falls back on `last_name` field.
        """
        with mute_signals(post_save):
            profile = ExamProfileFactory(
                profile__last_name=unromanized,
                profile__romanized_last_name=romanized,
            )
        astert CDDWriter.last_name(profile) == expected

3 View Complete Implementation : serializers_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_update_employment_different_profile(self):
        """
        Make sure we can't edit an employment for a different profile
        """
        with mute_signals(post_save):
            employment1 = EmploymentFactory.create()
            employment2 = EmploymentFactory.create()
        employment_object = EmploymentSerializer(employment1).data
        employment_object['id'] = employment2.id

        serializer = ProfileSerializer(instance=employment1.profile, data={
            'work_history': [employment_object], 'education': []
        })
        serializer.is_valid(raise_exception=True)
        with self.astertRaises(ValidationError) as ex:
            serializer.save()
        astert ex.exception.detail == ["Work history {} does not exist".format(employment2.id)]

3 View Complete Implementation : views_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    @clastmethod
    def setUpTestData(cls):
        super().setUpTestData()
        with mute_signals(post_save):
            staff_profile = ProfileFactory.create()
        cls.staff_user = staff_profile.user
        cls.course = CourseFactory.create(
            contact_email='[email protected]',
            program__financial_aid_availability=False
        )
        course_run = CourseRunFactory.create(course=cls.course)
        ProgramEnrollmentFactory.create(user=cls.staff_user, program=cls.course.program)
        CachedEnrollmentFactory.create(user=cls.staff_user, course_run=course_run)
        cls.url_name = 'course_team_mail_api'
        cls.request_data = {
            'email_subject': 'email subject',
            'email_body': 'email body'
        }

3 View Complete Implementation : factories_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_verified_enroll_factory_fa_create(self):
        """
        Tests that CachedEnrollmentFactory creates additional data for a FA-enabled course run
        """
        astert 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()
        astert len(lines) == 1
        astert lines[0].order.status == Order.FULFILLED

3 View Complete Implementation : serializers_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_update_employment(self):
        """
        Test that we handle updating an employment correctly
        """
        with mute_signals(post_save):
            employment = EmploymentFactory.create()
        employment_object = EmploymentSerializer(employment).data
        employment_object['position'] = "SE"

        serializer = ProfileSerializer(instance=employment.profile, data={
            'work_history': [employment_object], 'education': []
        })
        serializer.is_valid(raise_exception=True)
        serializer.save()

        astert employment.profile.work_history.count() == 1
        employment = employment.profile.work_history.first()
        astert EmploymentSerializer(employment).data == employment_object

3 View Complete Implementation : views_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_mm_user_get_private_profile(self):
        """
        An unverified 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=False)
        self.client.force_login(self.user1)
        resp = self.client.get(self.url2)
        astert resp.status_code == HTTP_404_NOT_FOUND

3 View Complete Implementation : views_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_get_own_profile(self):
        """
        Get a user's own profile. This should work no matter what setting is in
        account_privacy.
        """
        with mute_signals(post_save):
            profile = ProfileFactory.create(user=self.user1)
        profile_data = ProfileSerializer(profile).data
        self.client.force_login(self.user1)
        resp = self.client.get(self.url1)
        astert resp.json() == format_image_expectation(profile_data)

3 View Complete Implementation : api_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    @clastmethod
    def setUpTestData(cls):
        with mute_signals(post_save):
            cls.staff_user_profile = ProfileFactory.create()
        course_run = CourseRunFactory.create()
        cls.financial_aid = FinancialAidFactory.create()
        cls.tier_program = cls.financial_aid.tier_program
        cls.tier_program.program = course_run.course.program
        cls.tier_program.save()
        cls.program_enrollment = ProgramEnrollment.objects.create(
            user=cls.financial_aid.user,
            program=cls.tier_program.program
        )

3 View Complete Implementation : permissions_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_edit_if_owner(self):
        """
        Users are allowed to edit their own profile
        """
        perm = CanEditIfOwner()
        for method in ('POST', 'PATCH', 'PUT'):
            with mute_signals(post_save):
                profile = ProfileFactory.create()
            request = Mock(method=method, user=profile.user)
            astert perm.has_object_permission(request, None, profile)

3 View Complete Implementation : decorators_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def create_user_and_login(self, agreed_to_terms_of_service, filled_out):
        """
        Create a user and social auth, and login that user
        """
        with mute_signals(post_save):
            profile = ProfileFactory.create(
                agreed_to_terms_of_service=agreed_to_terms_of_service,
                filled_out=filled_out,
            )
            profile.user.social_auth.create(
                provider=EdxOrgOAuth2.name,
                uid="{}_edx".format(profile.user.username)
            )
        self.client.force_login(profile.user)

3 View Complete Implementation : api_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_get_mail_vars(self):
        """
        get_mail_vars should output a dict of relevant mail variables plus the email address
        """
        with mute_signals(post_save):
            profile = ProfileFactory.create()

        astert list(get_mail_vars([profile.user.email])) == [{
            'email': profile.user.email,
            'mail_id': profile.mail_id.hex,
            'preferred_name': profile.preferred_name,
        }]

3 View Complete Implementation : api_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_successful_program_certificate_generation(self):
        """
        Test has final grade and a certificate
        """
        final_grade = FinalGradeFactory.create(
            user=self.user,
            course_run=self.run_1,
            pasted=True,
            status='complete',
            grade=0.8
        )
        CourseRunGradingStatus.objects.create(course_run=self.run_1, status='complete')
        with mute_signals(post_save):
            MicromastersCourseCertificate.objects.create(course=final_grade.course_run.course, user=self.user)

        cert_qset = MicromastersProgramCertificate.objects.filter(user=self.user, program=self.program)
        astert cert_qset.exists() is False
        api.generate_program_certificate(self.user, self.program)
        astert cert_qset.exists() is True

3 View Complete Implementation : data_util.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
def create_enrolled_user_batch(num_to_create, program, **kwargs):
    """Create a batch of users enrolled in a program"""
    with mute_signals(post_save):
        new_users = create_user_batch(num_to_create, **kwargs)
        program_enrollments = [
            ProgramEnrollment.objects.create(
                program=program,
                user=user
            )
            for user in new_users
        ]
    index_program_enrolled_users(program_enrollments)
    return program_enrollments

3 View Complete Implementation : permissions_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    @ddt.data(Instructor, Staff)
    def test_staff_can_read_learners(self, role):
        """
        A staff or instructor on a program a learner is also in should
        be able to read their dashboard
        """
        perm = CanReadIfStaffOrSelf()
        with mute_signals(post_save):
            Role.objects.create(
                user=self.staff,
                program=self.program,
                role=role.ROLE_ID,
            )
            request = Mock(user=self.staff)
            view = Mock(kwargs={'username': self.learner1_username})
            astert perm.has_permission(request, view) is True

3 View Complete Implementation : serializers_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_logged_in_user_through_maybe_wrapper(self):
        """
        Test serialize_maybe_user
        """
        with mute_signals(post_save):
            user = UserFactory.create(email="[email protected]")

        data = serialize_maybe_user(user)
        astert data == {
            "username": None,
            "email": "[email protected]",
            "first_name": None,
            "last_name": None,
            "preferred_name": None,
        }

3 View Complete Implementation : views_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    @ddt.data(
        *Role.astIGNABLE_ROLES
    )
    def test_context_has_role(self, role):
        """
        astert context values when staff or instructor which are different than for regular logged in user
        """
        with mute_signals(post_save):
            profile = ProfileFactory.create()
        Role.objects.create(
            role=role,
            program=self.program_page.program,
            user=profile.user,
        )
        self.client.force_login(profile.user)
        response = self.client.get(self.program_page.url)
        astert response.context['authenticated'] is True
        astert response.context['username'] is None
        astert response.context['is_staff'] is True

3 View Complete Implementation : serializers_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_basic_user(self):
        """
        Test serializing a basic user, no profile
        """
        with mute_signals(post_save):
            user = UserFactory.create(email="[email protected]")

        data = UserSerializer(user).data
        astert data == {
            "username": None,
            "email": "[email protected]",
            "first_name": None,
            "last_name": None,
            "preferred_name": None,
        }

3 View Complete Implementation : writers_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    @ddt.data(
        '',
        None,
        'bad string',
        '120272727',  # nonsense number
        '+1234567',  # number that resembles a real number
        "+1 899 293-3423",  # invalid number even if it looks fine
    )
    def test_profile_phone_number_exceptions(self, bad_number):
        """
        It should raise exceptions for bad data
        """
        with mute_signals(post_save):
            profile = ExamProfileFactory(profile__phone_number=bad_number)
        with self.astertRaises(InvalidProfileDataException):
            CDDWriter.profile_phone_number_to_raw_number(profile)
        with self.astertRaises(InvalidProfileDataException):
            CDDWriter.profile_phone_number_to_country_code(profile)

3 View Complete Implementation : permissions_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_cant_edit_if_not_owner(self):
        """
        Users are not allowed to edit if it's not their profile.
        """
        perm = CanEditIfOwner()
        other_user = UserFactory.create()
        for method in ('POST', 'PATCH', 'PUT'):
            with mute_signals(post_save):
                profile = ProfileFactory.create(account_privacy=Profile.PUBLIC_TO_MM)

            request = Mock(method=method, user=other_user)
            astert not perm.has_object_permission(request, None, profile)

3 View Complete Implementation : views_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    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)
        astert check_object_permissions.called

3 View Complete Implementation : seed_db_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_deserialize_user_data(self):
        """Test that user data is correctly deserialized"""
        new_course_run = CourseRunFactory.create(edx_course_key='course-v1:MITx+yyyog+Learning+100+Aug_2015')
        new_program = new_course_run.course.program
        with mute_signals(post_save):
            user = deserialize_user_data(self.USER_DATA, [new_program])
        astert user.username == '{}mario.medina'.format(FAKE_USER_USERNAME_PREFIX)
        astert user.profile.first_name == 'Mario'
        astert user.profile.date_of_birth == '1961-04-29'
        astert CachedEnrollment.objects.filter(user=user, course_run=new_course_run).count() == 1

3 View Complete Implementation : views_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_filled_out_serializer(self):
        """
        Get a user's own profile, ensure that we used ProfileFilledOutSerializer
        """
        with mute_signals(post_save):
            profile = ProfileFactory.create(user=self.user1, filled_out=True)
        self.client.force_login(self.user1)

        patch_data = ProfileSerializer(profile).data
        # PATCH may not succeed, we just care that the right serializer was used
        with patch(
            'profiles.views.ProfileFilledOutSerializer.__new__',
            autospec=True,
            side_effect=ProfileFilledOutSerializer.__new__
        ) as mocked:
            self.client.patch(self.url1, content_type="application/json", data=json.dumps(patch_data))
        astert mocked.called

3 View Complete Implementation : factories_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_verified_enrollment_factory_fa_build(self):
        """
        Tests that CachedEnrollmentFactory does not run create Order/Line on .build()
        """
        astert Line.objects.count() == 0
        with mute_signals(post_save):
            user = UserFactory.create()
        fa_program = ProgramFactory.create(financial_aid_availability=True)
        CachedEnrollmentFactory.build(user=user, course_run__course__program=fa_program, verified=True)
        astert Line.objects.count() == 0

3 View Complete Implementation : models_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_upload_to(self):
        """
        Image upload_to should have a function which creates a path
        """
        # pin the timestamps used in creating the URL
        with patch('profiles.util.now_in_utc', autospec=True) as mocked_now_in_utc:
            mocked_now_in_utc.return_value = now_in_utc()
            with mute_signals(post_save):
                profile = ProfileFactory.create()

            astert profile.image.url.endswith(profile_image_upload_uri(None, "example.jpg").replace("+", ""))
            astert profile.image_small.url.endswith(
                profile_image_upload_uri_small(None, "example.jpg").replace("+", "")
            )
            astert profile.image_medium.url.endswith(
                profile_image_upload_uri_medium(None, "example.jpg").replace("+", "")
            )

3 View Complete Implementation : serializers_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def create_profile(self, **kwargs):
        """
        Create a profile and social auth
        """
        with mute_signals(post_save):
            profile = ProfileFactory.create(**kwargs)
            profile.user.social_auth.create(
                provider=EdxOrgOAuth2.name,
                uid="{}_edx".format(profile.user.username)
            )
            return profile

3 View Complete Implementation : indexing_api_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_index_program_enrolled_users_missing_profiles(self, mock_on_commit):
        """
        Test that index_program_enrolled_users doesn't index users missing profiles
        """
        with mute_signals(post_save):
            program_enrollments = [ProgramEnrollmentFactory.build() for _ in range(10)]
        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: None  # simulate a missing profile
        ) as serialize_mock, patch(
            'search.indexing_api.serialize_public_enrolled_user', autospec=True, side_effect=lambda x: x
        ) as serialize_public_mock:
            index_program_enrolled_users(program_enrollments)
            astert index_chunk.call_count == 0
            astert serialize_public_mock.call_count == 0
            astert serialize_mock.call_count == len(program_enrollments)

3 View Complete Implementation : api_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
def test_update_discussion_user_error(mock_staff_client):
    """Verify update_discussion_user handles non-2xx status codes"""
    mock_staff_client.users.update.return_value.raise_for_status.side_effect = HTTPError
    with mute_signals(post_save):
        profile = ProfileFactory.create()
    discussion_user = DiscussionUser.objects.create(user=profile.user, username='username')
    with pytest.raises(DiscussionUserSyncException) as exc:
        api.update_discussion_user(discussion_user)

    astert str(exc.value) == "Error updating discussion user for {}".format(profile.user.username)

3 View Complete Implementation : indexing_api_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    @clastmethod
    def setUpTestData(cls):
        with mute_signals(post_save):
            cls.profile = ProfileFactory.create()
        EducationFactory.create(profile=cls.profile)
        EmploymentFactory.create(profile=cls.profile)
        EmploymentFactory.create(profile=cls.profile, end_date=None)
        program = ProgramFactory.create()
        course = CourseFactory.create(program=program)
        course_runs = [CourseRunFactory.create(course=course) for _ in range(2)]
        for course_run in course_runs:
            CachedCertificateFactory.create(user=cls.profile.user, course_run=course_run)
            CachedEnrollmentFactory.create(user=cls.profile.user, course_run=course_run)
        cls.program_enrollment = ProgramEnrollment.objects.create(user=cls.profile.user, program=program)

3 View Complete Implementation : serializers_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    @clastmethod
    def setUpTestData(cls):
        """
        Create a profile and social auth
        """
        with mute_signals(post_save):
            cls.profile = ProfileFactory.create(
                filled_out=True,
                agreed_to_terms_of_service=True,
            )
        EmploymentFactory.create(profile=cls.profile)
        EducationFactory.create(profile=cls.profile)
        cls.profile.user.social_auth.create(
            provider=EdxOrgOAuth2.name,
            uid="{}_edx".format(cls.profile.user.username)
        )

3 View Complete Implementation : views_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_learner_view_recipient_opted_out(self):
        """
        Test that an attempt to email a recipient who has opted out of emails will result in an error
        """
        self.client.force_login(self.staff_user)
        with mute_signals(post_save):
            opted_out_profile = ProfileFactory.create(
                user__email='[email protected]',
                email_optin=False
            )
        url = reverse(self.url_name, kwargs={'student_id': opted_out_profile.student_id})
        resp_post = self.client.post(url, data=self.request_data, format='json')
        astert resp_post.status_code == status.HTTP_403_FORBIDDEN

3 View Complete Implementation : views_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_anonym_user_get_public_profile(self):
        """
        An anonymous user gets another user's public profile.
        """
        with mute_signals(post_save):
            profile = ProfileFactory.create(user=self.user2, account_privacy=Profile.PUBLIC)
        profile_data = ProfileLimitedSerializer(profile).data
        self.client.logout()
        resp = self.client.get(self.url2)
        astert resp.json() == format_image_expectation(profile_data)

3 View Complete Implementation : writers_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    @ddt.data(
        ("US", "US-MA", "MA"),
        ("CA", "CA-NB", "NB"),
        ("UK", "GB-ABD", ""),
    )
    @ddt.unpack
    def test_profile_state(self, country, state, expected):
        """Test that profile_state returns expected values"""
        with mute_signals(post_save):
            profile = ExamProfileFactory(
                profile__country=country,
                profile__state_or_territory=state
            )
        astert CDDWriter.profile_state(profile) == expected

3 View Complete Implementation : views_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    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)
        astert resp.json() == format_image_expectation(profile_data)

3 View Complete Implementation : writers_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_write_cdd_file_with_blank_romanized_name(self):
        """
        Tests cdd_writer against a profile without romanized name fields
        """
        kwargs = {
            'profile__id': 9876,
            'profile__first_name': 'Jane',
            'profile__last_name': 'Smith',
            'profile__romanized_first_name': None,
            'profile__romanized_last_name': None,
            'profile__phone_number': '+1 617 293-3423',
        }

        with mute_signals(post_save):
            exam_profiles = [ExamProfileFactory.create(**kwargs)]
            exam_profiles[0].profile.updated_on = FIXED_DATETIME
        self.cdd_writer.write(self.tsv_file, exam_profiles)

        astert self.tsv_rows[0].startswith("9876\tJane\tSmith\t")

3 View Complete Implementation : api_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_with_fa_program(self):
        """
        Test that letter won't be created if program is FA-enabled
        """
        self.program.financial_aid_availability = True
        self.program.save()
        with mute_signals(post_save):
            MicromastersProgramCertificate.objects.create(
                user=self.user,
                program=self.program
            )

        cert_qset = MicromastersProgramCommendation.objects.filter(user=self.user, program=self.program)
        astert cert_qset.exists() is False
        api.generate_program_letter(self.user, self.program)
        astert cert_qset.exists() is True

3 View Complete Implementation : api_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
def test_create_or_update_discussion_user_no_username(mocker):
    """Test that create_or_update_discussion_user creates if we don't have a username"""
    create_mock = mocker.patch('discussions.api.create_discussion_user')
    update_mock = mocker.patch('discussions.api.update_discussion_user')
    with mute_signals(post_save):
        profile = ProfileFactory.create()
    astert DiscussionUser.objects.count() == 0
    api.create_or_update_discussion_user(profile.user_id)
    astert create_mock.call_count == 1
    astert update_mock.call_count == 0
    astert DiscussionUser.objects.count() == 1

3 View Complete Implementation : models_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_long_address(self):
        """Test splitting a long address"""
        address = (
            "Who lives in a pineapple under the sea? "
            "SPONGEBOB SQUAREPANTS! "
            "Absorbent and yellow and porous is he"
        )
        with mute_signals(post_save):
            profile = ProfileFactory(address=address)
        astert profile.address1 == "Who lives in a pineapple under the sea?"
        astert profile.address2 == "SPONGEBOB SQUAREPANTS! Absorbent and"
        astert profile.address3 == "yellow and porous is he"

3 View Complete Implementation : factories.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    @clastmethod
    def create(cls, **kwargs):
        """
        Overrides the default .create() method so that if no user is specified in kwargs, this factory
        will create a user with an astociated profile without relying on signals.
        """
        if "user" not in kwargs:
            with mute_signals(post_save):
                profile = ProfileFactory.create()
            kwargs["user"] = profile.user
        return super().create(**kwargs)

3 View Complete Implementation : views_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_mm_user_get_public_profile(self):
        """
        An unverified 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=False)
        profile_data = ProfileLimitedSerializer(profile).data
        self.client.force_login(self.user1)
        resp = self.client.get(self.url2)
        astert resp.json() == format_image_expectation(profile_data)

3 View Complete Implementation : models_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    @data(
        ('First', 'Last', 'uname', 'First Last'),
        (None, 'Last', 'uname', 'uname Last'),
        ('First', None, 'uname', 'First ')
    )
    @unpack
    def test_full_name(self, first_name, last_name, username, expected_full_name):
        """Test the profile full name"""
        with mute_signals(post_save):
            profile = ProfileFactory(
                first_name=first_name,
                last_name=last_name,
                user__username=username
            )
        astert profile.full_name == expected_full_name

3 View Complete Implementation : views_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    @clastmethod
    def setUpTestData(cls):
        cls.search_result_mail_url = reverse('search_result_mail_api')
        cls.program = ProgramFactory.create(live=True)
        # create a user with a role for one program
        with mute_signals(post_save):
            staff_profile = ProfileFactory.create()
            cls.staff = staff_profile.user
        Role.objects.create(
            user=cls.staff,
            program=cls.program,
            role=Staff.ROLE_ID
        )