Пример #1
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
Пример #2
0
def test_submission_conversion(capsys, submission_file, settings):
    # Override the celery settings
    settings.task_eager_propagates = (True,)
    settings.task_always_eager = (True,)

    challenge = ChallengeFactory()

    test_set = challenge.imageset_set.get(phase=ImageSet.TESTING)

    with mute_signals(post_save):
        submission = SubmissionFactory(
            file__from_path=submission_file, challenge=challenge
        )

    call_command("convertsubmissions", challenge.short_name)

    _, err = capsys.readouterr()

    assert err == ""

    annotation_set = AnnotationSet.objects.all()[0]

    assert annotation_set.submission == submission
    assert annotation_set.base == test_set

    images = annotation_set.images.all()

    assert len(images) == 1
    assert images[0].name == "image10x10x10.mhd"

    with mute_signals(post_save):
        submission = SubmissionFactory(
            file__from_path=Path(__file__).parent.parent
            / "evaluation_tests"
            / "resources"
            / "submission.csv",
            challenge=challenge,
        )

    call_command("convertsubmissions", challenge.short_name)

    _, err = capsys.readouterr()

    assert err == ""

    annotation_set = AnnotationSet.objects.all()[1]

    assert annotation_set.submission == submission
    assert annotation_set.base == test_set

    labels = annotation_set.labels

    assert len(labels) == 10
    assert labels[0]["class"] == 0
Пример #3
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)
Пример #4
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
Пример #5
0
 def setUpTestData(cls):
     """
     Create a profile
     """
     super().setUpTestData()
     with mute_signals(post_save):
         cls.profile = ProfileFactory.create()
Пример #6
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
        }
Пример #7
0
    def test_update_exam_authorization_final_grade(self):
        """
        Verify that update_exam_authorization_final_grade is called when a FinalGrade saves
        """
        create_order(self.profile.user, self.course_run)
        with mute_signals(post_save):
            # muted because enrollment also trigger signal for profile creation. right now we are just
            # looking final grades
            CachedEnrollmentFactory.create(user=self.profile.user, course_run=self.course_run)

        # There is no ExamProfile or ExamAuthorization before creating the FinalGrade.
        assert ExamProfile.objects.filter(profile=self.profile).exists() is False
        assert ExamAuthorization.objects.filter(
            user=self.profile.user,
            course=self.course_run.course
        ).exists() is False

        FinalGradeFactory.create(
            user=self.profile.user,
            course_run=self.course_run,
            passed=True,
        )

        # assert Exam Authorization and profile created.
        assert ExamProfile.objects.filter(profile=self.profile).exists() is True
        assert ExamAuthorization.objects.filter(
            user=self.profile.user,
            course=self.course_run.course
        ).exists() is True
Пример #8
0
    def test_update_exam_authorization_final_grade_when_user_not_paid(self):
        """
        Verify that update_exam_authorization_final_grade is called and log exception when
        FinalGrade saves user dont match exam authorization criteria
        """
        with mute_signals(post_save):
            # muting signal for CachedEnrollment. Because CachedEnrollment and FinalGrade both omits
            # signal, we want to see behaviour of FinalGrade here
            CachedEnrollmentFactory.create(user=self.profile.user, course_run=self.course_run)

        assert ExamProfile.objects.filter(profile=self.profile).exists() is False
        assert ExamAuthorization.objects.filter(
            user=self.profile.user,
            course=self.course_run.course
        ).exists() is False

        FinalGradeFactory.create(
            user=self.profile.user,
            course_run=self.course_run,
            passed=True,
            course_run_paid_on_edx=False,
        )

        # assert Exam Authorization and profile not created.
        assert ExamProfile.objects.filter(profile=self.profile).exists() is False
        assert ExamAuthorization.objects.filter(
            user=self.profile.user,
            course=self.course_run.course
        ).exists() is False
Пример #9
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
Пример #10
0
 def test_document_needs_update_missing(self):
     """
     If a document doesn't exist on Elasticsearch, document_needs_update should return true
     """
     with mute_signals(post_save):
         enrollment = ProgramEnrollmentFactory.create()
     assert document_needs_updating(enrollment) is True
Пример #11
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
Пример #12
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)
Пример #13
0
def test_null_results(settings):
    # Override the celery settings
    settings.task_eager_propagates = (True,)
    settings.task_always_eager = (True,)

    challenge = ChallengeFactory()

    with mute_signals(post_save):
        user1 = UserFactory()
        queryset = (
            ResultFactory(
                job__submission__challenge=challenge,
                metrics={"a": 0.6},
                job__submission__creator=user1,
            ),
            ResultFactory(
                job__submission__challenge=challenge,
                metrics={"a": None},
                job__submission__creator=user1,
            ),
        )

    challenge.evaluation_config.score_jsonpath = "a"
    challenge.evaluation_config.result_display_choice = Config.ALL
    challenge.evaluation_config.save()

    expected_ranks = [1, 0]
    assert_ranks(queryset, expected_ranks)
Пример #14
0
    def test_write_cdd_file(self):
        """
        Tests cdd_writer against a set of profiles
        """
        kwargs = {
            'profile__id': 14879,
            'profile__romanized_first_name': 'Jane',
            'profile__romanized_last_name': 'Smith',
            'profile__user__email': '*****@*****.**',
            'profile__address': '1 Main St, Room B345',
            'profile__city': 'Boston',
            'profile__state_or_territory': 'US-MA',
            'profile__country': 'US',
            'profile__postal_code': '02115',
            'profile__phone_number': '+1 617 293-3423',
        }

        with mute_signals(post_save):
            exam_profiles = [ExamProfileFactory.create(**kwargs)]
            exam_profiles[0].updated_on = FIXED_DATETIME

        self.cdd_writer.write(self.tsv_file, exam_profiles)

        assert self.tsv_rows[0] == (
            "14879\tJane\tSmith\[email protected]\t"
            "1 Main St, Room B345\t\t\t"  # triple tab is for blank address2 and address3
            "Boston\tMA\t02115\tUSA\t"
            "6172933423\t1\t2016/05/15 15:02:55"
        )
Пример #15
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
Пример #16
0
    def test_write_ead_file(self):
        """
        Tests that write_ead_file outputs correctly
        """
        kwargs = {
            'id': 143,
            'operation': 'add',
            'exam_run__exam_series_code': 'MM-DEDP',
            'exam_run__date_first_eligible': date(2016, 5, 15),
            'exam_run__date_last_eligible': date(2016, 10, 15),
        }

        with mute_signals(post_save):
            profile = ProfileFactory(id=14879)
            exam_auths = [ExamAuthorizationFactory.create(user=profile.user, **kwargs)]
            exam_auths[0].updated_on = FIXED_DATETIME

        self.ead_writer.write(self.tsv_file, exam_auths)

        assert self.tsv_rows[0] == (
            "add\t143\t"
            "14879\tMM-DEDP\t\t"
            "\t2016/05/15\t2016/10/15\t"  # accommodation blank intentionally
            "2016/05/15 15:02:55"
        )
Пример #17
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
Пример #18
0
def create_user_for_login(is_staff=True, username=None):
    """Create a test user that can log into the app"""
    later = now_in_utc() + timedelta(weeks=5000)
    with mute_signals(post_save):
        user = SocialProfileFactory.create(
            validated=True,
            user__is_staff=is_staff,
            image=None,  # make these None so the default image is used
            image_small=None,
            image_medium=None,
            **({'user__username': username} if username is not None else {}),
            user__social_auth__extra_data={
                'access_token': 'fake',
                'refresh_token': 'fake',
                'updated_at': later.timestamp(),
                'expires_in': 3600,
            }
        ).user

    UserCacheRefreshTime.objects.create(
        user=user,
        enrollment=later,
        certificate=later,
        current_grade=later,
    )
    user.set_password(DEFAULT_PASSWORD)
    user.save()
    return user
Пример #19
0
    def test_exam_authorization_when_not_paid(self):
        """
        test exam_authorization when user has passed course but not paid.
        """
        with mute_signals(post_save):
            self.final_grade.course_run_paid_on_edx = False
            self.final_grade.save()
        mmtrack = get_mmtrack(self.user, self.program)
        assert mmtrack.has_paid(self.course_run.edx_course_key) is False

        expected_errors_message = MESSAGE_NOT_ELIGIBLE_TEMPLATE.format(
            user=mmtrack.user.username,
            course_id=self.course_run.edx_course_key
        )

        # Neither user has exam profile nor authorization.
        assert ExamProfile.objects.filter(profile=mmtrack.user.profile).exists() is False
        assert ExamAuthorization.objects.filter(
            user=mmtrack.user,
            course=self.course_run.course
        ).exists() is False

        with self.assertRaises(ExamAuthorizationException) as eae:
            authorize_for_exam_run(mmtrack, self.course_run, self.exam_run)

        assert eae.exception.args[0] == expected_errors_message

        # Assert user has no exam profile and authorization after exception.
        assert ExamProfile.objects.filter(profile=mmtrack.user.profile).exists() is False
        assert ExamAuthorization.objects.filter(
            user=mmtrack.user,
            course=self.course_run.course
        ).exists() is False
Пример #20
0
 def setUpTestData(cls):
     with mute_signals(post_save):
         # valid profiles
         cls.expected_in_progress_profiles = ExamProfileFactory.create_batch(5, status=ExamProfile.PROFILE_PENDING)
         # invalid profiles
         cls.expected_invalid_profiles = ExamProfileFactory.create_batch(5, status=ExamProfile.PROFILE_PENDING)
         cls.all_profiles = cls.expected_in_progress_profiles + cls.expected_invalid_profiles
Пример #21
0
    def test_country_limit(self, browser, base_test_data):
        """
        There should be more than 20 countries in current country and birth country facets
        """
        with open("profiles/data/countries.csv") as f:
            reader = csv.DictReader(f)
            country_codes = [row['code'] for row in reader]
        create_enrolled_user_batch(len(country_codes), program=base_test_data.program, is_staff=False)

        # Don't update elasticsearch for each profile, do that in bulk after
        with mute_signals(post_save):
            for i, profile in enumerate(Profile.objects.all()):
                code = country_codes[i % len(country_codes)]
                profile.birth_country = code
                profile.country = code
                profile.save()

        recreate_index()

        browser.get("/learners")
        browser.wait_until_loaded(By.CLASS_NAME, 'menu-icon')

        current_selector = '.filter--country .sk-hierarchical-menu-list__item'

        country_count = browser.driver.execute_script(
            "return document.querySelectorAll('{}').length".format(current_selector)
        )
        assert country_count == len(country_codes)
Пример #22
0
    def test_view_delete_automated_poll(self):
        with mute_signals(post_save):
            poll_start = now() - timedelta(days=5)
            poll_user = UserFactory.create(groups=['Review'])
            poll_group = Group.objects.get(name='Review')
            bug = BugFactory.create()
            swag_poll = PollFactory.create(name='swag poll', start=poll_start,
                                           end=poll_start + timedelta(days=15),
                                           created_by=poll_user,
                                           valid_groups=poll_group,
                                           bug=bug,
                                           automated_poll=True,
                                           description='Swag poll description.',
                                           slug='swag-poll')

        with mock.patch('remo.voting.views.messages.success') as faked_message:
            with self.login(self.admin) as client:
                response = client.post(reverse('voting_delete_voting',
                                               kwargs={'slug': swag_poll.slug}),
                                       follow=True)
            self.assertJinja2TemplateUsed(response, 'list_votings.jinja')
            ok_(faked_message.called)
            eq_(faked_message.call_args_list[0][0][1], 'Voting successfully deleted.')
            ok_(not Poll.objects.filter(id=swag_poll.id).exists())
            ok_(not Bug.objects.filter(id=bug.id).exists())
Пример #23
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
Пример #24
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'
     }
Пример #25
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)]
Пример #26
0
 def setUpTestData(cls):
     cls.program, _ = create_program(past=True)
     cls.course_run = cls.program.course_set.first().courserun_set.first()
     cls.course = cls.course_run.course
     cls.program_enrollment = ProgramEnrollmentFactory.create(program=cls.program)
     cls.user = cls.program_enrollment.user
     with mute_signals(post_save):
         cls.final_grades = sorted([
             FinalGradeFactory.create(
                 user=cls.user,
                 course_run=cls.course_run,
                 passed=False,
                 status=FinalGradeStatus.PENDING
             ),
             FinalGradeFactory.create(
                 user=cls.user,
                 course_run__course=cls.course,
                 passed=True,
                 status=FinalGradeStatus.COMPLETE
             ),
             FinalGradeFactory.create(
                 user=cls.user,
                 course_run__course=cls.course,
                 passed=True,
                 status=FinalGradeStatus.COMPLETE
             ),
         ], key=lambda final_grade: final_grade.course_run.end_date, reverse=True)
Пример #27
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': ''})
Пример #28
0
    def test_extend_voting_period_majority(self):
        bug = BugFactory.create()
        start = now().replace(microsecond=0)
        end = datetime.combine(get_date(days=1), datetime.min.time())

        user = UserFactory.create(groups=['Admin'])
        group = Group.objects.get(name='Review')
        User.objects.filter(groups__name='Review').delete()
        UserFactory.create_batch(9, groups=['Review'])

        with mute_signals(post_save):
            automated_poll = PollFactory.create(name='poll',
                                                start=start, end=end,
                                                valid_groups=group,
                                                created_by=user,
                                                automated_poll=True,
                                                bug=bug)

        radio_poll = RadioPollFactory.create(poll=automated_poll,
                                             question='Budget Approval')
        RadioPollChoiceFactory.create(answer='Approved', votes=5,
                                      radio_poll=radio_poll)
        RadioPollChoiceFactory.create(answer='Denied', votes=3,
                                      radio_poll=radio_poll)

        extend_voting_period()

        poll = Poll.objects.get(pk=automated_poll.id)
        eq_(poll.end.year, end.year)
        eq_(poll.end.month, end.month)
        eq_(poll.end.day, end.day)
        eq_(poll.end.hour, 0)
        eq_(poll.end.minute, 0)
        eq_(poll.end.second, 0)
        ok_(not poll.is_extended)
Пример #29
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)
Пример #30
0
    def test_update_exam_authorization_order(self, order_status):
        """
        Verify that update_exam_authorization_final_grade is called when a fulfilled Order saves
        """
        with mute_signals(post_save):
            # muted because enrollment also trigger signal for profile creation. right now we are just
            # looking final grades
            CachedEnrollmentFactory.create(user=self.profile.user, course_run=self.course_run)

        FinalGradeFactory.create(
            user=self.profile.user,
            course_run=self.course_run,
            passed=True,
        )

        order = OrderFactory.create(user=self.profile.user, fulfilled=False)
        LineFactory.create(course_key=self.course_run.edx_course_key, order=order)

        # There is no ExamProfile or ExamAuthorization before creating the FinalGrade.
        assert ExamProfile.objects.filter(profile=self.profile).exists() is False
        assert ExamAuthorization.objects.filter(
            user=self.profile.user,
            course=self.course_run.course
        ).exists() is False

        order.status = order_status
        order.save()

        # assert Exam Authorization and profile created.
        assert ExamProfile.objects.filter(profile=self.profile).exists() is True
        assert ExamAuthorization.objects.filter(
            user=self.profile.user,
            course=self.course_run.course
        ).exists() is True
Пример #31
0
def test_calculate_ranks(mocker):
    challenge = ChallengeFactory()
    challenge.evaluation_config.score_jsonpath = "a"
    challenge.evaluation_config.save()
    with mute_signals(post_save):
        queryset = (
            ResultFactory(challenge=challenge, metrics={"a": 0.1}),
            ResultFactory(challenge=challenge, metrics={"a": 0.5}),
            ResultFactory(challenge=challenge, metrics={"a": 1.0}),
            ResultFactory(challenge=challenge, metrics={"a": 0.7}),
            ResultFactory(challenge=challenge, metrics={"a": 0.5}),
            ResultFactory(challenge=challenge, metrics={"a": 1.0}),
        )
    # An alternative implementation could be [4, 3, 1, 2, 3, 1] as there are
    # only 4 unique values, the current implementation is harsh on poor results
    expected_ranks = [6, 4, 1, 3, 4, 1]
    challenge = assert_ranks(challenge, expected_ranks, queryset)
    # now test reverse order
    challenge.evaluation_config.score_default_sort = (
        challenge.evaluation_config.ASCENDING)
    challenge.evaluation_config.save()
    expected_ranks = [1, 2, 5, 4, 2, 5]
    assert_ranks(challenge, expected_ranks, queryset)
Пример #32
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
Пример #33
0
def test_get_invoice(authenticated_api_client, settings, issued_invoice):
    invoice = issued_invoice
    customer = issued_invoice.customer

    issued_invoice.generate_pdf()

    with mute_signals(pre_save):
        [
            TransactionFactory.create(
                state=state,
                invoice=issued_invoice,
                payment_method=PaymentMethodFactory(customer=customer))
            for state in Transaction.States.as_list() if state not in [
                Transaction.States.Canceled, Transaction.States.Refunded,
                Transaction.States.Failed
            ]
        ]

    url = reverse('invoice-detail', kwargs={'pk': invoice.pk})

    response = authenticated_api_client.get(url, format='json')

    assert response.status_code == status.HTTP_200_OK, response.data
    invoice_definition.check_response(invoice, response_data=response.data)
Пример #34
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
Пример #35
0
    def test_update_exam_authorization_order(self, order_status):
        """
        Verify that update_exam_authorization_final_grade is called when a fulfilled Order saves
        """
        with mute_signals(post_save):
            # muted because enrollment also trigger signal for profile creation. right now we are just
            # looking final grades
            CachedEnrollmentFactory.create(user=self.profile.user,
                                           course_run=self.course_run)

        FinalGradeFactory.create(
            user=self.profile.user,
            course_run=self.course_run,
            passed=True,
        )

        order = OrderFactory.create(user=self.profile.user, fulfilled=False)
        LineFactory.create(course_key=self.course_run.edx_course_key,
                           order=order)

        # There is no ExamProfile or ExamAuthorization before creating the FinalGrade.
        assert ExamProfile.objects.filter(
            profile=self.profile).exists() is False
        assert ExamAuthorization.objects.filter(
            user=self.profile.user,
            course=self.course_run.course).exists() is False

        order.status = order_status
        order.save()

        # assert Exam Authorization and profile created.
        assert ExamProfile.objects.filter(
            profile=self.profile).exists() is True
        assert ExamAuthorization.objects.filter(
            user=self.profile.user,
            course=self.course_run.course).exists() is True
Пример #36
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)
        assert resp.json() == ProfileSerializer().to_representation(profile)
Пример #37
0
 def setUpTestData(cls):
     with mute_signals(post_save):
         cls.exam_auths = ExamAuthorizationFactory.create_batch(
             10, status=ExamAuthorization.STATUS_PENDING)
Пример #38
0
 def create(cls, *args, **kwargs):  # pylint: disable=arguments-differ
     """
     Overrides the default .create() method to turn off save signals
     """
     with mute_signals(post_save):
         return super().create(*args, **kwargs)
Пример #39
0
    def setUpTestData(cls):
        super().setUpTestData()

        with mute_signals(post_save):
            cls.user = ProfileFactory.create().user
Пример #40
0
 def setUpTestData(cls):
     with mute_signals(post_save):
         cls.profile = profile = ProfileFactory.create()
     cls.user = profile.user
     EducationFactory.create(profile=profile)
     EmploymentFactory.create(profile=profile)
     # create a normal program
     program = ProgramFactory.create()
     cls.enrollments = cls._generate_cached_enrollments(cls.user,
                                                        program,
                                                        num_course_runs=2)
     certificate_grades_vals = [0.7, 0.8]
     cls.current_grades_vals = [0.9, 1.0]
     cls.certificates = []
     cls.current_grades = []
     for i, enrollment in enumerate(cls.enrollments):
         cls.certificates.append(
             CachedCertificateFactory.create(
                 user=cls.user,
                 course_run=enrollment.course_run,
                 data={
                     "grade": certificate_grades_vals[i],
                     "certificate_type": "verified",
                     "course_id": enrollment.course_run.edx_course_key,
                     "status": "downloadable",
                 }))
         cls.current_grades.append(
             CachedCurrentGradeFactory.create(
                 user=cls.user,
                 course_run=enrollment.course_run,
                 data={
                     "passed": True,
                     "percent": cls.current_grades_vals[i],
                     "course_key": enrollment.course_run.edx_course_key,
                 }))
         FinalGradeFactory.create(
             user=cls.user,
             course_run=enrollment.course_run,
             grade=certificate_grades_vals[i],
             passed=True,
         )
     non_fa_cached_edx_data = CachedEdxUserData(cls.user, program=program)
     non_fa_mmtrack = MMTrack(cls.user, program, non_fa_cached_edx_data)
     cls.serialized_enrollments = UserProgramSearchSerializer.serialize_enrollments(
         non_fa_mmtrack)
     cls.serialized_course_enrollments = UserProgramSearchSerializer.serialize_course_enrollments(
         non_fa_mmtrack)
     cls.semester_enrollments = UserProgramSearchSerializer.serialize_course_runs_enrolled(
         non_fa_mmtrack)
     cls.program_enrollment = ProgramEnrollment.objects.create(
         user=cls.user, program=program)
     # create a financial aid program
     cls.fa_program, _ = create_program()
     cls.fa_program_enrollment = ProgramEnrollment.objects.create(
         user=cls.user, program=cls.fa_program)
     cls.fa_enrollments = cls._generate_cached_enrollments(
         cls.user, cls.fa_program, num_course_runs=2)
     cls.current_grades = []
     for i, enrollment in enumerate(cls.fa_enrollments):
         order = OrderFactory.create(user=cls.user, status='fulfilled')
         LineFactory.create(order=order,
                            course_key=enrollment.course_run.edx_course_key)
         cls.current_grades.append(
             CachedCurrentGradeFactory.create(
                 user=cls.user,
                 course_run=enrollment.course_run,
                 data={
                     "passed": True,
                     "percent": cls.current_grades_vals[i],
                     "course_key": enrollment.course_run.edx_course_key,
                 }))
         FinalGradeFactory.create(
             user=cls.user,
             course_run=enrollment.course_run,
             grade=cls.current_grades_vals[i],
             passed=True,
         )
     fa_cached_edx_data = CachedEdxUserData(cls.user,
                                            program=cls.fa_program)
     fa_mmtrack = MMTrack(cls.user, cls.fa_program, fa_cached_edx_data)
     cls.fa_serialized_course_enrollments = (
         UserProgramSearchSerializer.serialize_course_enrollments(
             fa_mmtrack))
     cls.fa_serialized_enrollments = (
         UserProgramSearchSerializer.serialize_enrollments(fa_mmtrack))
Пример #41
0
 def setUp(self):
     super(IsProfileFilledOutTests, self).setUp()
     with mute_signals(post_save):
         self.profile = ProfileFactory.create()
Пример #42
0
 def test_increments(self):
     """test that a student id increments correctly"""
     with mute_signals(post_save):
         profile_one = ProfileFactory()
         profile_two = ProfileFactory()
     assert profile_two.student_id > profile_one.student_id
Пример #43
0
    def test_get_invoice(self, mocked_settings):
        InvoiceFactory.reset_sequence(1)
        TransactionFactory.reset_sequence(1)

        customer = CustomerFactory.create()
        invoice = InvoiceFactory.create(customer=customer,
                                        state=Invoice.STATES.ISSUED)

        invoice.generate_pdf()

        with mute_signals(pre_save):
            transactions = [
                TransactionFactory.create(
                    state=state,
                    invoice=invoice,
                    payment_method=PaymentMethodFactory(customer=customer))
                for state in Transaction.States.as_list() if state not in [
                    Transaction.States.Canceled, Transaction.States.Refunded,
                    Transaction.States.Failed
                ]
            ]
        expected_transactions = [{
            "id":
            str(transaction.uuid),
            "url":
            build_absolute_test_url(
                reverse('transaction-detail',
                        [transaction.customer.pk, transaction.uuid])),
            "customer":
            build_absolute_test_url(
                reverse('customer-detail', [transaction.customer.id])),
            "provider":
            build_absolute_test_url(
                reverse('provider-detail', [transaction.provider.id])),
            "amount":
            "%.2f" % transaction.amount,
            "currency":
            "RON",
            "state":
            transaction.state,
            "proforma":
            build_absolute_test_url(
                reverse('proforma-detail', [transaction.proforma.id])),
            "invoice":
            build_absolute_test_url(
                reverse('invoice-detail', [transaction.invoice.id])),
            "can_be_consumed":
            transaction.can_be_consumed,
            "payment_processor":
            transaction.payment_processor,
            "payment_method":
            build_absolute_test_url(
                reverse(
                    'payment-method-detail',
                    [transaction.customer.pk, transaction.payment_method.pk])),
            "pay_url":
            (build_absolute_test_url(reverse('payment', ['token']))
             if transaction.state == Transaction.States.Initial else None),
        } for transaction in transactions]

        with patch('silver.utils.payments._get_jwt_token') as mocked_token:
            mocked_token.return_value = 'token'
            url = reverse('invoice-detail', kwargs={'pk': invoice.pk})

            for show_pdf_storage_url, pdf_url in [
                (True, build_absolute_test_url(invoice.pdf.url)),
                (False,
                 build_absolute_test_url(reverse('pdf',
                                                 args=[invoice.pdf.pk])))
            ]:
                mocked_settings.SILVER_SHOW_PDF_STORAGE_URL = show_pdf_storage_url

                response = self.client.get(url)

                self.assertEqual(response.status_code, status.HTTP_200_OK)
                expected_response = {
                    "id":
                    invoice.pk,
                    "series":
                    "InvoiceSeries",
                    "number":
                    1,
                    "provider":
                    build_absolute_test_url(
                        reverse('provider-detail', [invoice.provider.pk])),
                    "customer":
                    build_absolute_test_url(
                        reverse('customer-detail', [invoice.customer.pk])),
                    "archived_provider":
                    '{}',
                    "archived_customer":
                    '{}',
                    "due_date":
                    None,
                    "issue_date":
                    invoice.issue_date.strftime('%Y-%m-%d'),
                    "paid_date":
                    None,
                    "cancel_date":
                    None,
                    "sales_tax_name":
                    "VAT",
                    "sales_tax_percent":
                    '1.00',
                    "currency":
                    "RON",
                    "transaction_currency":
                    invoice.transaction_currency,
                    "transaction_xe_rate":
                    ("%.4f" % invoice.transaction_xe_rate
                     if invoice.transaction_xe_rate else None),
                    "transaction_xe_date":
                    invoice.transaction_xe_date,
                    "state":
                    "issued",
                    "proforma":
                    build_absolute_test_url(
                        reverse('proforma-detail',
                                [invoice.related_document.pk])),
                    "invoice_entries": [],
                    "pdf_url":
                    pdf_url,
                    "total":
                    0
                }
                for field in expected_response:
                    self.assertEqual(
                        expected_response[field],
                        response.data[field],
                        msg=("Expected %s, actual %s for field %s" %
                             (expected_response[field], response.data[field],
                              field)))

                self.assertEqual(len(response.data["transactions"]),
                                 len(expected_transactions))

                for actual_transaction in response.data["transactions"]:
                    expected_transaction = [
                        transaction for transaction in expected_transactions
                        if transaction["id"] == actual_transaction["id"]
                    ]
                    self.assertTrue(expected_transaction)
                    expected_transaction = expected_transaction[0]
                    for field in expected_transaction:
                        self.assertEqual(
                            expected_transaction[field],
                            actual_transaction[field],
                            msg=("Expected %s, actual %s for field %s" %
                                 (expected_transaction[field],
                                  actual_transaction[field], field)))
Пример #44
0
 def create(cls, *args, **kwargs):
     """
     Overrides the default .create() method to turn off save signals
     """
     with mute_signals(post_save):
         return super().create(*args, **kwargs)
Пример #45
0
 def create_batch(cls, *args, **kwargs):  # pylint: disable=arguments-differ
     """
     Ensure that signals are muted before running the base create_batch method
     """
     with mute_signals(post_save):
         return super().create_batch(*args, **kwargs)
Пример #46
0
    def test_get_invoice(self):
        InvoiceFactory.reset_sequence(1)
        TransactionFactory.reset_sequence(1)

        customer = CustomerFactory.create()
        invoice = InvoiceFactory.create(customer=customer,
                                        state=Invoice.STATES.ISSUED)
        with mute_signals(pre_save):
            transactions = [
                TransactionFactory.create(
                    state=state,
                    invoice=invoice,
                    payment_method=PaymentMethodFactory(customer=customer))
                for state in Transaction.States.as_list() if state not in [
                    Transaction.States.Canceled, Transaction.States.Refunded,
                    Transaction.States.Failed
                ]
            ]
        expected_transactions = [{
            "id":
            str(transaction.uuid),
            "url":
            "http://testserver/customers/%s/transactions/%s/" %
            (invoice.customer.pk, transaction.uuid),
            "customer":
            "http://testserver/customers/%s/" % invoice.customer.pk,
            "provider":
            "http://testserver/providers/%s/" % invoice.provider.pk,
            "amount":
            "%s.00" % str(transaction.amount),
            "currency":
            "USD",
            "state":
            transaction.state,
            "proforma":
            "http://testserver/proformas/%s/" % transaction.proforma.pk,
            "invoice":
            "http://testserver/invoices/%s/" % transaction.invoice.pk,
            "can_be_consumed":
            transaction.can_be_consumed,
            "payment_processor":
            transaction.payment_processor,
            "payment_method":
            "http://testserver/customers/%s/payment_methods/%s/" %
            (invoice.customer.pk, transaction.payment_method.pk),
            "pay_url":
            "http://testserver/pay/token/"
            if transaction.state == Transaction.States.Initial else None,
        } for transaction in transactions]

        with patch('silver.utils.payments._get_jwt_token') as mocked_token:
            mocked_token.return_value = 'token'

            url = reverse('invoice-detail', kwargs={'pk': invoice.pk})
            response = self.client.get(url)

            self.assertEqual(response.status_code, status.HTTP_200_OK)
            expected_response = {
                "id":
                invoice.pk,
                "series":
                "InvoiceSeries",
                "number":
                1,
                "provider":
                "http://testserver/providers/%s/" % invoice.provider.pk,
                "customer":
                "http://testserver/customers/%s/" % invoice.customer.pk,
                "archived_provider":
                '{}',
                "archived_customer":
                '{}',
                "due_date":
                None,
                "issue_date":
                str(invoice.issue_date),
                "paid_date":
                None,
                "cancel_date":
                None,
                "sales_tax_name":
                "VAT",
                "sales_tax_percent":
                '1.00',
                "currency":
                "RON",
                "transaction_currency":
                invoice.transaction_currency,
                "transaction_xe_rate": ("%.4f" % invoice.transaction_xe_rate if
                                        invoice.transaction_xe_rate else None),
                "transaction_xe_date":
                invoice.transaction_xe_date,
                "state":
                "issued",
                "proforma":
                "http://testserver/proformas/%s/" % invoice.proforma.pk,
                "invoice_entries": [],
                "pdf_url":
                invoice.pdf.url,
                "total":
                0
            }
            for field in expected_response:
                self.assertEqual(expected_response[field],
                                 response.data[field],
                                 msg=("Expected %s, actual %s for field %s" %
                                      (expected_response[field],
                                       response.data[field], field)))

            self.assertEqual(len(response.data["transactions"]),
                             len(expected_transactions))

            for actual_transaction in response.data["transactions"]:
                expected_transaction = [
                    transaction for transaction in expected_transactions
                    if transaction["id"] == actual_transaction["id"]
                ]
                self.assertTrue(expected_transaction)
                expected_transaction = expected_transaction[0]

                self.assertEqual(expected_transaction[field],
                                 actual_transaction[field],
                                 msg=("Expected %s, actual %s for field %s" %
                                      (expected_response[field],
                                       response.data[field], field)))
Пример #47
0
def test_calculate_ranks(settings):
    # Override the celery settings
    settings.task_eager_propagates = (True, )
    settings.task_always_eager = (True, )

    challenge = ChallengeFactory()

    with mute_signals(post_save):
        queryset = (
            # Warning: Do not change this values without updating the
            # expected_ranks below.
            ResultFactory(
                job__submission__challenge=challenge,
                metrics={
                    "a": 0.0,
                    "b": 0.0
                },
            ),
            ResultFactory(
                job__submission__challenge=challenge,
                metrics={
                    "a": 0.5,
                    "b": 0.2
                },
            ),
            ResultFactory(
                job__submission__challenge=challenge,
                metrics={
                    "a": 1.0,
                    "b": 0.3
                },
            ),
            ResultFactory(
                job__submission__challenge=challenge,
                metrics={
                    "a": 0.7,
                    "b": 0.4
                },
            ),
            ResultFactory(
                job__submission__challenge=challenge,
                metrics={
                    "a": 0.5,
                    "b": 0.5
                },
            ),
            # Following two are invalid if relative ranking is used
            ResultFactory(job__submission__challenge=challenge,
                          metrics={"a": 1.0}),
            ResultFactory(job__submission__challenge=challenge,
                          metrics={"b": 0.3}),
            # Add a valid, but unpublished result
            ResultFactory(
                job__submission__challenge=challenge,
                metrics={
                    "a": 0.1,
                    "b": 0.1
                },
            ),
        )

        # Unpublish the result
        queryset[-1].published = False
        queryset[-1].save()

    expected = {
        Config.DESCENDING: {
            Config.ABSOLUTE: {
                Config.DESCENDING: {
                    "ranks": [6, 4, 1, 3, 4, 1, 0, 0],
                    "rank_scores": [6, 4, 1, 3, 4, 1, 0, 0],
                },
                Config.ASCENDING: {
                    "ranks": [6, 4, 1, 3, 4, 1, 0, 0],
                    "rank_scores": [6, 4, 1, 3, 4, 1, 0, 0],
                },
            },
            Config.MEDIAN: {
                Config.DESCENDING: {
                    "ranks": [5, 4, 1, 1, 1, 0, 0, 0],
                    "rank_scores": [5, 3.5, 2, 2, 2, 0, 0, 0],
                },
                Config.ASCENDING: {
                    "ranks": [3, 2, 1, 3, 5, 0, 0, 0],
                    "rank_scores": [3, 2.5, 2, 3, 4, 0, 0, 0],
                },
            },
            Config.MEAN: {
                Config.DESCENDING: {
                    "ranks": [5, 4, 1, 1, 1, 0, 0, 0],
                    "rank_scores": [5, 3.5, 2, 2, 2, 0, 0, 0],
                },
                Config.ASCENDING: {
                    "ranks": [3, 2, 1, 3, 5, 0, 0, 0],
                    "rank_scores": [3, 2.5, 2, 3, 4, 0, 0, 0],
                },
            },
        },
        Config.ASCENDING: {
            Config.ABSOLUTE: {
                Config.DESCENDING: {
                    "ranks": [1, 2, 5, 4, 2, 5, 0, 0],
                    "rank_scores": [1, 2, 5, 4, 2, 5, 0, 0],
                },
                Config.ASCENDING: {
                    "ranks": [1, 2, 5, 4, 2, 5, 0, 0],
                    "rank_scores": [1, 2, 5, 4, 2, 5, 0, 0],
                },
            },
            Config.MEDIAN: {
                Config.DESCENDING: {
                    "ranks": [2, 2, 5, 2, 1, 0, 0, 0],
                    "rank_scores": [3, 3, 4, 3, 1.5, 0, 0, 0],
                },
                Config.ASCENDING: {
                    "ranks": [1, 2, 4, 4, 3, 0, 0, 0],
                    "rank_scores": [1, 2, 4, 4, 3.5, 0, 0, 0],
                },
            },
            Config.MEAN: {
                Config.DESCENDING: {
                    "ranks": [2, 2, 5, 2, 1, 0, 0, 0],
                    "rank_scores": [3, 3, 4, 3, 1.5, 0, 0, 0],
                },
                Config.ASCENDING: {
                    "ranks": [1, 2, 4, 4, 3, 0, 0, 0],
                    "rank_scores": [1, 2, 4, 4, 3.5, 0, 0, 0],
                },
            },
        },
    }

    for score_method in (Config.ABSOLUTE, Config.MEDIAN, Config.MEAN):
        for a_order in (Config.DESCENDING, Config.ASCENDING):
            for b_order in (Config.DESCENDING, Config.ASCENDING):
                challenge.evaluation_config.score_jsonpath = "a"
                challenge.evaluation_config.scoring_method_choice = (
                    score_method)
                challenge.evaluation_config.score_default_sort = a_order
                challenge.evaluation_config.extra_results_columns = [{
                    "path":
                    "b",
                    "title":
                    "b",
                    "order":
                    b_order
                }]
                challenge.evaluation_config.save()

                assert_ranks(
                    queryset,
                    expected[a_order][score_method][b_order]["ranks"],
                    expected[a_order][score_method][b_order]["rank_scores"],
                )
Пример #48
0
def test_results_display(settings):
    # Override the celery settings
    settings.task_eager_propagates = (True, )
    settings.task_always_eager = (True, )

    challenge = ChallengeFactory()

    with mute_signals(post_save):
        user1 = UserFactory()
        user2 = UserFactory()
        queryset = (
            ResultFactory(
                job__submission__challenge=challenge,
                metrics={"b": 0.3},  # Invalid result
                job__submission__creator=user1,
            ),
            ResultFactory(
                job__submission__challenge=challenge,
                metrics={"a": 0.6},
                job__submission__creator=user1,
            ),
            ResultFactory(
                job__submission__challenge=challenge,
                metrics={"a": 0.4},
                job__submission__creator=user1,
            ),
            ResultFactory(
                job__submission__challenge=challenge,
                metrics={"a": 0.2},
                job__submission__creator=user1,
            ),
            ResultFactory(
                job__submission__challenge=challenge,
                metrics={"a": 0.1},
                job__submission__creator=user2,
            ),
            ResultFactory(
                job__submission__challenge=challenge,
                metrics={"a": 0.5},
                job__submission__creator=user2,
            ),
            ResultFactory(
                job__submission__challenge=challenge,
                metrics={"a": 0.3},
                job__submission__creator=user2,
            ),
        )

    challenge.evaluation_config.score_jsonpath = "a"
    challenge.evaluation_config.result_display_choice = Config.ALL
    challenge.evaluation_config.save()

    expected_ranks = [0, 1, 3, 5, 6, 2, 4]
    assert_ranks(queryset, expected_ranks)

    challenge.evaluation_config.result_display_choice = Config.MOST_RECENT
    challenge.evaluation_config.save()

    expected_ranks = [0, 0, 0, 2, 0, 0, 1]
    assert_ranks(queryset, expected_ranks)

    challenge.evaluation_config.result_display_choice = Config.BEST
    challenge.evaluation_config.save()

    expected_ranks = [0, 1, 0, 0, 0, 2, 0]
    assert_ranks(queryset, expected_ranks)

    # now test reverse order
    challenge.evaluation_config.score_default_sort = (
        challenge.evaluation_config.ASCENDING)
    challenge.evaluation_config.save()

    expected_ranks = [0, 0, 0, 2, 1, 0, 0]
    assert_ranks(queryset, expected_ranks)

    challenge.evaluation_config.result_display_choice = Config.MOST_RECENT
    challenge.evaluation_config.save()

    expected_ranks = [0, 0, 0, 1, 0, 0, 2]
    assert_ranks(queryset, expected_ranks)
Пример #49
0
 def create_batch(cls, *args, **kwargs):
     """
     Ensure that signals are muted before running the base create_batch method
     """
     with mute_signals(post_save):
         return super().create_batch(*args, **kwargs)
Пример #50
0
    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)

        assert profile.country_subdivision == expected_result
Пример #51
0
 def test_should_pretty_print(self):
     """test pretty printing property method"""
     with mute_signals(post_save):
         profile = ProfileFactory()
     assert profile.pretty_printed_student_id == "MMM{0:06}".format(
         profile.student_id)
Пример #52
0
from django.core.exceptions import ValidationError
from django.db.models.signals import post_save
from django.test.testcases import TestCase
from factory.django import mute_signals

from tests.factories import SubmissionFactory

MutedFactory = mute_signals(post_save)(SubmissionFactory)


class SubmissionCreateTest(TestCase):
    def test_create_valid_submission(self):
        submission = MutedFactory(
            image='alpine:latest'
        )

    def test_create_invalid_image_submission(self):
        with self.assertRaises(ValidationError):
            submission = MutedFactory(
                image='blsfsdfd:3'
            )
Пример #53
0
 def setUpTestData(cls):
     with mute_signals(post_save):
         cls.user_profile = ProfileFactory.create()
     cls.user = cls.user_profile.user
Пример #54
0
    def test_serialize_pkcs12_cas_nopassphrase(self):
        root_key = Key().create_key("ed25519", None)
        subject = DistinguishedNameFactory(countryName="NL",
                                           stateOrProvinceName="Noord Holland",
                                           organizationName="Repleo")

        root_certificate = CertificateFactory(
            dn=subject,
            name="test_server_root_certificate",
            expires_at=arrow.get(timezone.now()).shift(days=+30).date())

        with mute_signals(signals.post_save):
            root_certificate.save()
        root_certhandler = Certificate()
        root_certhandler.create_certificate(root_certificate,
                                            root_key.serialize())
        keystore = KeyStore(certificate=root_certificate)
        keystore.crt = root_certhandler.serialize()
        keystore.key = root_key.serialize()
        keystore.save()

        int_key = Key().create_key("rsa", 2048)
        subject = DistinguishedNameFactory(
            countryName=root_certificate.dn.countryName,
            stateOrProvinceName=root_certificate.dn.stateOrProvinceName,
            organizationName=root_certificate.dn.organizationName,
        )
        int_certificate = CertificateFactory(
            expires_at=arrow.get(timezone.now()).shift(days=+5).date(),
            name="test_server_intermediate_certificate",
            type=CertificateTypes.INTERMEDIATE,
            parent=root_certificate,
            dn=subject,
            crl_distribution_url="https://example.com/crl/cert.crl.pem",
            ocsp_distribution_host="https://example.com/ocsp/",
        )

        with mute_signals(signals.post_save):
            int_certificate.save()

        int_certhandler = Certificate()
        int_certhandler.create_certificate(int_certificate,
                                           int_key.serialize())

        keystore = KeyStore(certificate=int_certificate)
        keystore.crt = int_certhandler.serialize()
        keystore.key = int_key.serialize()
        keystore.save()

        pkcs12 = int_key.serialize_pkcs12("test_pkcs12_cas",
                                          int_certhandler.certificate,
                                          cas=[root_certhandler.certificate])
        pkcs12_obj = load_pkcs12(pkcs12, None)

        self.assertEqual(pkcs12_obj.key.key_size, 2048)
        self.assertEqual(pkcs12_obj.cert.friendly_name.decode("utf-8"),
                         "test_pkcs12_cas")
        self.assertEqual(pkcs12_obj.cert.certificate.serial_number,
                         int_certhandler.certificate.serial_number)
        self.assertEqual(
            pkcs12_obj.additional_certs[0].certificate.serial_number,
            root_certhandler.certificate.serial_number)
    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])
Пример #56
0
 def setUp(self):
     super().setUp()
     with mute_signals(post_save):
         self.profile = ProfileFactory.create()
Пример #57
0
 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)
     assert CDDWriter.profile_state(profile) == expected
Пример #58
0
 def test_on_save(self):
     """test that a student id is set on save"""
     with mute_signals(post_save):
         profile = ProfileFactory()
     assert profile.student_id is not None
     assert profile.student_id == profile.id
Пример #59
0
 def setUpTestData(cls):
     super().setUpTestData()
     with mute_signals(post_save):
         cls.profile2 = ProfileFactory.create()
     cls.url = reverse("financialaid_api")