def test_add_employment(self): """ Test that we handle adding an employment correctly """ employment_object = { "city": "NY", "state_or_territory": "NY", "country": "USA", "company_name": "XYZ-ABC", "position": "SSE", "industry": "IT", "end_date": "2016-05-17", "start_date": "2016-05-28" } user1 = UserFactory.create() user2 = UserFactory.create() serializer = ProfileSerializer(instance=user1.profile, data={ 'work_history': [employment_object], 'education': [] }) serializer.is_valid(raise_exception=True) serializer.save() assert user1.profile.work_history.count() == 1 employment = user1.profile.work_history.first() employment_object['id'] = employment.id assert EmploymentSerializer(employment).data == employment_object # Other profile did not get the employment assigned to it assert user2.profile.work_history.count() == 0
def test_add_education(self): """ Test that we handle adding an Education correctly """ education_object = { 'degree_name': DOCTORATE, 'graduation_date': '9876-04-23', 'field_of_study': 'subject', 'online_degree': True, 'school_name': 'school_name', 'school_city': 'school_city', 'school_state_or_territory': 'school_state_or_territory', 'school_country': 'school_country,' } user1 = UserFactory.create() user2 = UserFactory.create() serializer = ProfileSerializer(instance=user1.profile, data={ 'education': [education_object], 'work_history': [] }) serializer.is_valid(raise_exception=True) serializer.save() assert user1.profile.education.count() == 1 education = user1.profile.education.first() education_object['id'] = education.id education_data = EducationSerializer(education).data assert education_data == education_object # Other profile did not get the education assigned to it assert user2.profile.education.count() == 0
def test_add_employment(self): """ Test that we handle adding an employment correctly """ employment_object = { "city": "NY", "state_or_territory": "NY", "country": "USA", "company_name": "XYZ-ABC", "position": "SSE", "industry": "IT", "end_date": "2016-05-17", "start_date": "2016-05-28" } user1 = UserFactory.create() user2 = UserFactory.create() serializer = ProfileSerializer(instance=user1.profile, data={ 'work_history': [employment_object], 'education': [] }) serializer.is_valid(raise_exception=True) serializer.save() assert user1.profile.work_history.count() == 1 employment = user1.profile.work_history.first() employment_object['id'] = employment.id assert EmploymentSerializer(employment).data == employment_object # Other profile did not get the employment assigned to it assert user2.profile.work_history.count() == 0
def test_add_education(self): """ Test that we handle adding an Education correctly """ education_object = { 'degree_name': DOCTORATE, 'graduation_date': '9876-04-23', 'field_of_study': 'subject', 'online_degree': True, 'school_name': 'school_name', 'school_city': 'school_city', 'school_state_or_territory': 'school_state_or_territory', 'school_country': 'school_country,' } user1 = UserFactory.create() user2 = UserFactory.create() serializer = ProfileSerializer(instance=user1.profile, data={ 'education': [education_object], 'work_history': [] }) serializer.is_valid(raise_exception=True) serializer.save() assert user1.profile.education.count() == 1 education = user1.profile.education.first() education_object['id'] = education.id education_data = EducationSerializer(education).data assert education_data == education_object # Other profile did not get the education assigned to it assert user2.profile.education.count() == 0
def setUpTestData(cls): super().setUpTestData() cls.user1 = UserFactory.create() cls.user2 = UserFactory.create() cls.course_run = CourseRunFactory.create() cls.grade1 = FinalGrade.objects.create( user=cls.user1, course_run=cls.course_run, grade=0.65, )
def setUpTestData(cls): super(ProgramEnrollmentTests, cls).setUpTestData() cls.user1 = UserFactory.create() cls.user2 = UserFactory.create() cls.program1 = ProgramFactory.create(live=True) cls.program2 = ProgramFactory.create(live=True) cls.program3 = ProgramFactory.create(live=True) cls.url = reverse('user_program_enrollments')
def test_autogenerated_uuid(self): """Test that MicromastersProgramCommendation auto-generates a unique uuid.""" user = UserFactory.create() user_1 = UserFactory.create() program = ProgramFactory.create() letter = MicromastersProgramCommendation.objects.create( user=user, program=program) letter_1 = MicromastersProgramCommendation.objects.create( user=user_1, program=program) assert letter.uuid != letter_1.uuid
def test_unseed_db(self): """Test that unseed_db deletes seed data""" for i in range(2): ProgramFactory.create(description='{} test program {}'.format(FAKE_PROGRAM_DESC_PREFIX, i)) UserFactory.create(username='******'.format(FAKE_USER_USERNAME_PREFIX, i)) fake_program_qset = Program.objects.filter(description__startswith=FAKE_PROGRAM_DESC_PREFIX) fake_user_qset = User.objects.filter(username__startswith=FAKE_USER_USERNAME_PREFIX) assert fake_program_qset.count() == 2 assert fake_user_qset.count() == 2 unseed_db() assert fake_program_qset.count() == 0 assert fake_user_qset.count() == 0
def test_get_users_without_frozen_final_grade(self): """ tests for get_users_without_frozen_final_grade function """ assert [user.pk for user in api.get_users_without_frozen_final_grade(self.run_fa)] == [self.user.pk] # create another user and enrollment other_user = UserFactory.create() CachedEnrollmentFactory.create(user=other_user, course_run=self.run_fa) assert sorted( [user.pk for user in api.get_users_without_frozen_final_grade(self.run_fa)] ) == sorted([self.user.pk]) CachedCurrentGradeFactory.create(user=other_user, course_run=self.run_fa) assert sorted( [user.pk for user in api.get_users_without_frozen_final_grade(self.run_fa)] ) == sorted([self.user.pk, other_user.pk]) # add the user to the FinalGrade model as in progress fg_status = FinalGrade.objects.create( user=other_user, course_run=self.run_fa, status=FinalGradeStatus.PENDING, grade=0.0) assert sorted( [user.pk for user in api.get_users_without_frozen_final_grade(self.run_fa)] ) == sorted([self.user.pk, other_user.pk]) # change the final grade status to complete fg_status.status = FinalGradeStatus.COMPLETE fg_status.save() assert [user.pk for user in api.get_users_without_frozen_final_grade(self.run_fa)] == [self.user.pk]
def setUpTestData(cls): super(APITests, cls).setUpTestData() # create an user cls.user = UserFactory.create() # create the programs cls.program1 = ProgramFactory.create(live=True) cls.program2 = ProgramFactory.create(live=True)
def test_multiple_success(self): """test retire_users command success with more than one user""" user_names = ["foo", "bar", "baz"] for user_name in user_names: user = UserFactory.create(username=user_name, is_active=True) user.profile.email_optin = True user.profile.save() UserSocialAuthFactory.create(user=user, provider='not_edx') for _ in range(TOTAL_PROGRAMS): ProgramEnrollmentFactory.create(user=user) assert user.is_active is True assert user.profile.email_optin is True assert UserSocialAuth.objects.filter(user=user).count() == 1 assert ProgramEnrollment.objects.filter(user=user).count() == TOTAL_PROGRAMS self.command.handle("retire_users", users=user_names) for user_name in user_names: user = User.objects.get(username=user_name) assert user.is_active is False assert user.profile.email_optin is False assert UserSocialAuth.objects.filter(user=user).count() == 0 assert ProgramEnrollment.objects.filter(user=user).count() == 0
def create_learner_with_image(privacy): """Helper function to create a user with account_privacy and image_small set""" user = UserFactory.create() user.profile.account_privacy = privacy user.profile.image_small = 'some_url' user.profile.save() return user
def setUpTestData(cls): super().setUpTestData() cls.program_enrollment_unsent = ProgramEnrollmentFactory.create() cls.program_enrollment_sent = ProgramEnrollmentFactory.create() cls.automatic_email = AutomaticEmailFactory.create(enabled=True) cls.percolate_query = cls.automatic_email.query cls.other_query = PercolateQueryFactory.create( source_type=PercolateQuery.DISCUSSION_CHANNEL_TYPE) cls.percolate_queries = [cls.percolate_query, cls.other_query] cls.automatic_email_disabled = AutomaticEmailFactory.create( enabled=False) cls.percolate_query_disabled = cls.automatic_email_disabled.query SentAutomaticEmail.objects.create( automatic_email=cls.automatic_email, user=cls.program_enrollment_sent.user, status=SentAutomaticEmail.SENT, ) # User was sent email connected to a different AutomaticEmail SentAutomaticEmail.objects.create( user=cls.program_enrollment_unsent.user, automatic_email=AutomaticEmailFactory.create(enabled=True), status=SentAutomaticEmail.SENT, ) with mute_signals(post_save): cls.staff_user = UserFactory.create()
def setUpTestData(cls): cls.user = UserFactory.create() # Create Programs, Courses, CourseRuns... cls.p1_course_run_keys = ['p1_course_run'] cls.p2_course_run_keys = ['p2_course_run_1', 'p2_course_run_2'] cls.p1_course_run = CourseRunFactory.create( edx_course_key=cls.p1_course_run_keys[0]) p2 = FullProgramFactory.create() first_course = p2.course_set.first() extra_course = CourseFactory.create(program=p2) cls.p2_course_run_1 = CourseRunFactory.create( course=first_course, edx_course_key=cls.p2_course_run_keys[0]) cls.p2_course_run_2 = CourseRunFactory.create( course=extra_course, edx_course_key=cls.p2_course_run_keys[1]) all_course_runs = [ cls.p1_course_run, cls.p2_course_run_1, cls.p2_course_run_2 ] # Create cached edX data cls.enrollments = [ CachedEnrollmentFactory.create(user=cls.user, course_run=course_run) for course_run in all_course_runs ] cls.certificates = [ CachedCertificateFactory.create(user=cls.user, course_run=course_run) for course_run in all_course_runs ] cls.current_grades = [ CachedCurrentGradeFactory.create(user=cls.user, course_run=course_run) for course_run in all_course_runs ]
def test_get_users_without_frozen_final_grade(self): """ tests for get_users_without_frozen_final_grade function """ assert [user.pk for user in api.get_users_without_frozen_final_grade(self.run_fa)] == [self.user.pk] # create another user and enrollment other_user = UserFactory.create() CachedEnrollmentFactory.create(user=other_user, course_run=self.run_fa) assert sorted( [user.pk for user in api.get_users_without_frozen_final_grade(self.run_fa)] ) == sorted([self.user.pk]) CachedCurrentGradeFactory.create(user=other_user, course_run=self.run_fa) assert sorted( [user.pk for user in api.get_users_without_frozen_final_grade(self.run_fa)] ) == sorted([self.user.pk, other_user.pk]) # add the user to the FinalGrade model as in progress fg_status = FinalGrade.objects.create( user=other_user, course_run=self.run_fa, status=FinalGradeStatus.PENDING, grade=0.0) assert sorted( [user.pk for user in api.get_users_without_frozen_final_grade(self.run_fa)] ) == sorted([self.user.pk, other_user.pk]) # change the final grade status to complete fg_status.status = FinalGradeStatus.COMPLETE fg_status.save() assert [user.pk for user in api.get_users_without_frozen_final_grade(self.run_fa)] == [self.user.pk]
def test_multiple_success(self): """test retire_users command success with more than one user""" user_names = ["foo", "bar", "baz"] for user_name in user_names: user = UserFactory.create(username=user_name, is_active=True) user.profile.email_optin = True user.profile.save() UserSocialAuthFactory.create(user=user, provider='not_edx') for _ in range(TOTAL_PROGRAMS): ProgramEnrollmentFactory.create(user=user) assert user.is_active is True assert user.profile.email_optin is True assert UserSocialAuth.objects.filter(user=user).count() == 1 assert ProgramEnrollment.objects.filter( user=user).count() == TOTAL_PROGRAMS self.command.handle("retire_users", users=user_names) for user_name in user_names: user = User.objects.get(username=user_name) assert user.is_active is False assert user.profile.email_optin is False assert UserSocialAuth.objects.filter(user=user).count() == 0 assert ProgramEnrollment.objects.filter(user=user).count() == 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': ''})
def test_get_token_for_user_force_discussion_user(settings, mocker): """ Assert that get_token_for_user returns a token for a valid DiscussionUser """ with mute_signals(post_save): user = UserFactory.create() settings.OPEN_DISCUSSIONS_JWT_SECRET = 'secret' settings.OPEN_DISCUSSIONS_JWT_EXPIRES_DELTA = 3600 mock_get_token = mocker.patch('open_discussions_api.utils.get_token') mock_create_user = mocker.patch('discussions.api.create_or_update_discussion_user') mock_create_user.return_value = DiscussionUser(user=user, username='******') assert get_token_for_user(user, force_create=True) is not None mock_get_token.assert_called_once_with( 'secret', user.username, [], expires_delta=3600, extra_payload={ 'site_key': 'mm_test', 'provider': 'micromasters', } ) assert mock_create_user.called_once_with(user.id)
def setUpTestData(cls): super(APITests, cls).setUpTestData() # create an user cls.user = UserFactory.create() # create the programs cls.program1 = ProgramFactory.create(live=True) cls.program2 = ProgramFactory.create(live=True)
def test_unseed_db(self): """Test that unseed_db deletes seed data""" for i in range(2): ProgramFactory.create(description='{} test program {}'.format( FAKE_PROGRAM_DESC_PREFIX, i)) UserFactory.create(username='******'.format( FAKE_USER_USERNAME_PREFIX, i)) fake_program_qset = Program.objects.filter( description__startswith=FAKE_PROGRAM_DESC_PREFIX) fake_user_qset = User.objects.filter( username__startswith=FAKE_USER_USERNAME_PREFIX) assert fake_program_qset.count() == 2 assert fake_user_qset.count() == 2 unseed_db() assert fake_program_qset.count() == 0 assert fake_user_qset.count() == 0
def test_attached_to_other_user(self): """ Coupons only attached to another user should not be shown """ UserCoupon.objects.all().delete() UserCoupon.objects.create(user=UserFactory.create(), coupon=CouponFactory.create()) assert pick_coupons(self.user) == []
def test_attached_to_other_user(self): """ Coupons only attached to another user should not be shown """ UserCoupon.objects.all().delete() UserCoupon.objects.create(user=UserFactory.create(), coupon=CouponFactory.create()) assert pick_coupons(self.user) == []
def test_missing_course(self): """ A 404 should be returned if the course does not exist """ user = UserFactory.create() self.client.force_login(user) resp = self.client.post(reverse('checkout'), {'course_id': 'missing'}, format='json') assert resp.status_code == status.HTTP_404_NOT_FOUND
def test_program_record_with_random_user(client): """Test that a request for program record with random (non-owner) user results in 404""" user = UserFactory.create() client.force_login(user) enrollment = ProgramEnrollmentFactory.create() resp = client.get( reverse("grade_records", kwargs=dict(enrollment_id=enrollment.id))) assert resp.status_code == status.HTTP_404_NOT_FOUND
def setUpTestData(cls): """ Create a user """ with mute_signals(post_save): cls.user1 = UserFactory.create() username = "******".format(cls.user1.username) cls.user1.social_auth.create(provider=EdxOrgOAuth2.name, uid=username) cls.url1 = reverse('profile-detail', kwargs={'user': username}) with mute_signals(post_save): cls.user2 = UserFactory.create(username="******") username = "******".format(cls.user2.username) cls.user2.social_auth.create(provider=EdxOrgOAuth2.name, uid=username) cls.url2 = reverse('profile-detail', kwargs={'user': username})
def test_missing_course(self): """ A 404 should be returned if the course does not exist """ user = UserFactory.create() self.client.force_login(user) resp = self.client.post(reverse('checkout'), {'course_id': 'missing'}, format='json') assert resp.status_code == status.HTTP_404_NOT_FOUND
def test_valid_course_id(self): """ If course_id is not present in payload a ValidationError is raised """ user = UserFactory.create() self.client.force_login(user) resp = self.client.post(reverse('checkout'), {}, format='json') assert resp.status_code == status.HTTP_400_BAD_REQUEST assert resp.json() == ['Missing course_id']
def test_valid_course_id(self): """ If course_id is not present in payload a ValidationError is raised """ user = UserFactory.create() self.client.force_login(user) resp = self.client.post(reverse('checkout'), {}, format='json') assert resp.status_code == status.HTTP_400_BAD_REQUEST assert resp.json() == ['Missing course_id']
def test_get_token_for_user_no_discussion_user(): """ Assert that get_token_for_user returns None for a user with no DiscussionUser """ with mute_signals(post_save): user = UserFactory.create() assert DiscussionUser.objects.count() == 0 assert get_token_for_user(user) is None
def test_get_token_for_user_no_username(): """ Assert that get_token_for_user returns None for a user with no username """ with mute_signals(post_save): user = UserFactory.create() DiscussionUser.objects.create(user=user, username=None) assert get_token_for_user(user) is None
def test_autogenerated_hash(self): """Test that MicromastersCourseCertificate auto-generates a hash when none is provided""" user = UserFactory.create() course = CourseFactory.create() mm_certificate = MicromastersCourseCertificate.objects.create( user=user, course=course) assert len(mm_certificate.hash) == 32 assert mm_certificate.hash == generate_md5('{}|{}'.format( user.id, course.id).encode('utf-8'))
def setUpTestData(cls): """Set up some coupons""" super().setUpTestData() cls.user = UserFactory.create() # Program 1 (cls.coupon1_attached_p1, cls.coupon2_attached_p1, cls.coupon1_auto_p1, cls.coupon2_auto_p1) = cls._create_coupons(cls.user) # Program 2 (coupon1_attached_p2, coupon2_attached_p2, cls.coupon1_auto_p2, cls.coupon2_auto_p2) = cls._create_coupons(cls.user) # Delete these coupons so that program 2 has only auto coupons coupon1_attached_p2.delete() coupon2_attached_p2.delete() # Coupon to verify that we filter this one out cls.not_auto_or_attached_coupon = CouponFactory.create() UserCoupon.objects.create(user=UserFactory.create(), coupon=cls.not_auto_or_attached_coupon)
def test_staff_and_instructor_can_access(self, role): """A user with staff or instructor role can access""" user = UserFactory.create() Role.objects.create( user=user, program=self.program1, role=role, ) self.client.force_login(user) self.assert_status_code()
def test_create_channel_normal_user(mocker, patched_users_api): """If a user is not a superuser they should get a forbidden status""" client = APIClient() user = UserFactory.create() client.force_login(user) program = RoleFactory.create().program add_channel_mock = mocker.patch('discussions.serializers.add_channel', return_value={}, autospec=True) resp = client.post(reverse('channel-list'), data=_make_create_channel_input(program.id), format="json") assert add_channel_mock.called is False assert resp.status_code == 403
def setUpTestData(cls): """Set up some coupons""" super().setUpTestData() cls.user = UserFactory.create() # Program 1 ( cls.coupon1_attached_p1, cls.coupon2_attached_p1, cls.coupon1_auto_p1, cls.coupon2_auto_p1 ) = cls._create_coupons(cls.user) # Program 2 ( coupon1_attached_p2, coupon2_attached_p2, cls.coupon1_auto_p2, cls.coupon2_auto_p2 ) = cls._create_coupons(cls.user) # Delete these coupons so that program 2 has only auto coupons coupon1_attached_p2.delete() coupon2_attached_p2.delete() # Coupon to verify that we filter this one out cls.not_auto_or_attached_coupon = CouponFactory.create() UserCoupon.objects.create(user=UserFactory.create(), coupon=cls.not_auto_or_attached_coupon)
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) assert not perm.has_object_permission(request, None, profile)
def setUpTestData(cls): """ Create a user """ with mute_signals(post_save): cls.user1 = UserFactory.create() username = "******".format(cls.user1.username) cls.user1.social_auth.create( provider=EdxOrgOAuth2.name, uid=username ) cls.url1 = reverse('profile-detail', kwargs={'user': username}) with mute_signals(post_save): cls.user2 = UserFactory.create(username="******") username = "******".format(cls.user2.username) cls.user2.social_auth.create( provider=EdxOrgOAuth2.name, uid=username ) cls.url2 = reverse('profile-detail', kwargs={'user': username})
def setUpTestData(cls): super().setUpTestData() # create an user cls.user = UserFactory.create() cls.cached_edx_user_data = MagicMock( spec=CachedEdxUserData, enrollments=CachedEnrollment.deserialize_edx_data(cls.enrollments_json), certificates=CachedCertificate.deserialize_edx_data(cls.certificates_json), current_grades=CachedCurrentGrade.deserialize_edx_data(cls.current_grades_json), ) # create the programs cls.program = ProgramFactory.create(live=True, financial_aid_availability=False, price=1000) cls.program_financial_aid = ProgramFactory.create(live=True, financial_aid_availability=True, price=1000) # create course runs for the normal program cls.course = CourseFactory.create(program=cls.program) expected_course_keys = [ "course-v1:edX+DemoX+Demo_Course", "course-v1:MITx+8.MechCX+2014_T1", '', None, 'course-v1:odl+FOO102+CR-FALL16' ] cls.cruns = [] for course_key in expected_course_keys: course_run = CourseRunFactory.create( course=cls.course, edx_course_key=course_key ) if course_key: cls.cruns.append(course_run) # and the program with financial aid finaid_course = CourseFactory.create(program=cls.program_financial_aid) cls.now = now_in_utc() cls.end_date = cls.now - timedelta(weeks=45) cls.crun_fa = CourseRunFactory.create( course=finaid_course, start_date=cls.now-timedelta(weeks=52), end_date=cls.end_date, enrollment_start=cls.now-timedelta(weeks=62), enrollment_end=cls.now-timedelta(weeks=53), edx_course_key="course-v1:odl+FOO101+CR-FALL15" ) cls.crun_fa2 = CourseRunFactory.create( course=finaid_course ) CourseRunFactory.create( course=finaid_course, edx_course_key=None )
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) assert not perm.has_object_permission(request, None, profile)
def setUpTestData(cls): """Create a set of course runs for testing""" super().setUpTestData() cls.run1 = CourseRunFactory.create( course__program__live=True, course__program__financial_aid_availability=True, ) cls.program = cls.run1.course.program cls.run2 = CourseRunFactory.create(course=cls.run1.course) cls.runs = [cls.run1, cls.run2] cls.user = UserFactory.create() ProgramEnrollment.objects.create(user=cls.user, program=cls.run1.course.program)
def setUpTestData(cls): super().setUpTestData() # create an user cls.user = UserFactory.create() cls.cached_edx_user_data = MagicMock( spec=CachedEdxUserData, enrollments=CachedEnrollment.deserialize_edx_data(cls.enrollments_json), certificates=CachedCertificate.deserialize_edx_data(cls.certificates_json), current_grades=CachedCurrentGrade.deserialize_edx_data(cls.current_grades_json), ) # create the programs cls.program = ProgramFactory.create(live=True, financial_aid_availability=False, price=1000) cls.program_financial_aid = ProgramFactory.create(live=True, financial_aid_availability=True, price=1000) # create course runs for the normal program cls.course = CourseFactory.create(program=cls.program) expected_course_keys = [ "course-v1:edX+DemoX+Demo_Course", "course-v1:MITx+8.MechCX+2014_T1", '', None, 'course-v1:odl+FOO102+CR-FALL16' ] cls.cruns = [] for course_key in expected_course_keys: course_run = CourseRunFactory.create( course=cls.course, edx_course_key=course_key ) if course_key: cls.cruns.append(course_run) # and the program with financial aid finaid_course = CourseFactory.create(program=cls.program_financial_aid) cls.now = now_in_utc() cls.end_date = cls.now - timedelta(weeks=45) cls.crun_fa = CourseRunFactory.create( course=finaid_course, start_date=cls.now-timedelta(weeks=52), end_date=cls.end_date, enrollment_start=cls.now-timedelta(weeks=62), enrollment_end=cls.now-timedelta(weeks=53), edx_course_key="course-v1:odl+FOO101+CR-FALL15" ) cls.crun_fa2 = CourseRunFactory.create( course=finaid_course ) CourseRunFactory.create( course=finaid_course, edx_course_key=None )
def setUpTestData(cls): """Create a set of course runs for testing""" super().setUpTestData() cls.run1 = CourseRunFactory.create( course__program__live=True, course__program__financial_aid_availability=True, ) cls.program = cls.run1.course.program cls.run2 = CourseRunFactory.create(course=cls.run1.course) cls.runs = [cls.run1, cls.run2] cls.user = UserFactory.create() ProgramEnrollment.objects.create(user=cls.user, program=cls.run1.course.program)
def test_logged_in_user_redirect_no_discussion_user(client, patched_users_api): """ Tests that logged in user gets cookie and redirect """ user = UserFactory.create() user.discussion_user.delete() client.force_login(user) response = client.get(reverse('discussions'), follow=True) assert response.redirect_chain[0] == ('http://localhost/', 302) assert 'jwt_cookie' in response.client.cookies assert response.client.cookies['jwt_cookie'] is not None
def test_verified_enrollment_factory_fa_build(self): """ Tests that CachedEnrollmentFactory does not run create Order/Line on .build() """ assert 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) assert Line.objects.count() == 0
def setUpTestData(cls): with mute_signals(post_save): cls.learner1 = UserFactory.create() cls.learner1_username = '******' cls.learner1.social_auth.create( provider=EdxOrgOAuth2.name, uid=cls.learner1_username ) cls.learner2 = UserFactory.create() cls.learner2_username = '******' cls.learner2.social_auth.create( provider=EdxOrgOAuth2.name, uid=cls.learner2_username ) cls.program = ProgramFactory.create() cls.staff = UserFactory.create() cls.staff_username = '******' for learner in (cls.learner1, cls.learner2): ProgramEnrollment.objects.create( program=cls.program, user=learner, )
def create(cls, **kwargs): """ Overrides default ProgramEnrollment object creation for the factory. """ user = kwargs.get('user', UserFactory.create()) program = kwargs.get('program', ProgramFactory.create()) course = CourseFactory.create(program=program) course_run = CourseRunFactory.create(course=course) CachedEnrollmentFactory.create(user=user, course_run=course_run) CachedCertificateFactory.create(user=user, course_run=course_run) CachedCurrentGradeFactory.create(user=user, course_run=course_run) program_enrollment = ProgramEnrollment.objects.create(user=user, program=program) return program_enrollment
def test_financial_aid_factory_create_with_user(self): """ Tests that FinancialAidFactory.create() will still work normally if provided a User object """ with mute_signals(post_save): user = UserFactory.create() assert FinancialAid.objects.count() == 0 assert User.objects.count() == 1 assert Profile.objects.count() == 0 FinancialAidFactory.create(user=user) assert FinancialAid.objects.count() == 1 assert User.objects.count() == 1 assert Profile.objects.count() == 0
def test_zero_price_checkout_failed_enroll(self): """ If we do a $0 checkout but the enrollment fails, we should send an email but leave the order as fulfilled """ user = UserFactory.create() self.client.force_login(user) course_run = CourseRunFactory.create( course__program__live=True, course__program__financial_aid_availability=True, ) order = LineFactory.create( order__status=Order.CREATED, order__total_price_paid=0, price=0, ).order with patch( 'ecommerce.views.create_unfulfilled_order', autospec=True, return_value=order, ) as create_mock, patch( 'ecommerce.views.enroll_user_on_success', side_effect=KeyError, ) as enroll_user_mock, patch( 'ecommerce.views.MailgunClient.send_individual_email', ) as send_email: resp = self.client.post(reverse('checkout'), {'course_id': course_run.edx_course_key}, format='json') assert resp.status_code == status.HTTP_200_OK assert resp.json() == { 'payload': {}, 'url': 'http://testserver/dashboard/?status=receipt&course_key={}'.format( quote_plus(course_run.edx_course_key) ), 'method': 'GET', } assert create_mock.call_count == 1 assert create_mock.call_args[0] == (course_run.edx_course_key, user) assert enroll_user_mock.call_count == 1 assert enroll_user_mock.call_args[0] == (order,) assert send_email.call_count == 1 assert send_email.call_args[0][0] == 'Error occurred when enrolling user during $0 checkout' assert send_email.call_args[0][1].startswith( 'Error occurred when enrolling user during $0 checkout for {order}. ' 'Exception: '.format( order=order, ) ) assert send_email.call_args[0][2] == '*****@*****.**'
def setUpTestData(cls): super().setUpTestData() cls.user = UserFactory.create() cls.program = ProgramFactory.create(live=True, financial_aid_availability=True, price=1000) cls.min_tier_program = TierProgramFactory.create( program=cls.program, discount_amount=750, current=True ) cls.max_tier_program = TierProgramFactory.create( program=cls.program, discount_amount=0, current=True )
def test_edx_is_not_refreshed_if_not_own_dashboard(self, role, update_mock): """ If the dashboard being queried is not the user's own dashboard the cached edx data should not be refreshed """ staff = UserFactory.create() self.client.force_login(staff) Role.objects.create( user=staff, program=self.program_1, role=role.ROLE_ID, ) self.client.get(self.url) assert update_mock.call_count == 0
def test_not_live_program(self): """ An order is created using create_unfulfilled_order and a payload is generated using generate_cybersource_sa_payload """ user = UserFactory.create() self.client.force_login(user) course_run = CourseRunFactory.create( course__program__live=False, course__program__financial_aid_availability=True, ) resp = self.client.post(reverse('checkout'), {'course_id': course_run.edx_course_key}, format='json') assert resp.status_code == status.HTTP_404_NOT_FOUND
def test_logged_in_user_through_maybe_wrapper(self): """ Test serialize_maybe_user """ with mute_signals(post_save): user = UserFactory.create(email="*****@*****.**") data = serialize_maybe_user(user) assert data == { "username": None, "email": "*****@*****.**", "first_name": None, "last_name": None, "preferred_name": None, }
def test_basic_user(self): """ Test serializing a basic user, no profile """ with mute_signals(post_save): user = UserFactory.create(email="*****@*****.**") data = UserSerializer(user).data assert data == { "username": None, "email": "*****@*****.**", "first_name": None, "last_name": None, "preferred_name": None, }
def setUpTestData(cls): cls.users = [UserFactory.create() for _ in range(35)] freeze_date = now_in_utc()-timedelta(days=1) future_freeze_date = now_in_utc()+timedelta(days=1) cls.course_run1 = CourseRunFactory.create(freeze_grade_date=freeze_date) cls.course_run2 = CourseRunFactory.create(freeze_grade_date=freeze_date) cls.all_freezable_runs = [cls.course_run1, cls.course_run2] cls.course_run_future = CourseRunFactory.create(freeze_grade_date=future_freeze_date) cls.course_run_frozen = CourseRunFactory.create(freeze_grade_date=freeze_date) CourseRunGradingStatus.objects.create(course_run=cls.course_run_frozen, status=FinalGradeStatus.COMPLETE) for user in cls.users: CachedEnrollmentFactory.create(user=user, course_run=cls.course_run1) CachedCurrentGradeFactory.create(user=user, course_run=cls.course_run1)
def test_populate_query_inactive_memberships(self, is_active, has_profile, mock_on_commit): """ Tests that memberships are handled correctly for users who are inactive or have no profiles """ with mute_signals(post_save): query = PercolateQueryFactory.create(source_type=PercolateQuery.DISCUSSION_CHANNEL_TYPE) user = UserFactory.create(is_active=is_active) if has_profile: ProfileFactory.create(user=user, filled_out=True) ProgramEnrollmentFactory.create(user=user) with patch('search.api.get_conn') as es_mock: populate_query_memberships(query.id) assert es_mock.return_value.percolate.call_count == (1 if has_profile and is_active else 0) assert PercolateQueryMembership.objects.filter(user=user, query=query).count() == ( 1 if is_active else 0 )
def test_staff_and_instructor_in_other_program_no_results(self, role, is_enrolled): """A user with staff or instructor role in another program gets no results""" user = UserFactory.create() Role.objects.create( user=user, program=self.program2, role=role, ) if is_enrolled: ProgramEnrollmentFactory.create(user=user, program=self.program1) params = { "post_filter": { "term": {"program.id": self.program1.id} } } self.client.force_login(user) resp = self.assert_status_code(json=params) assert len(resp.data['hits']['hits']) == 0
def test_financial_aid_for_user(self): """ Purchasable course runs must have a financial aid attached for the given user """ course_run, user = create_purchasable_course_run() program = course_run.course.program tier_program = program.tier_programs.first() financial_aid = tier_program.financialaid_set.first() financial_aid.user = UserFactory.create() financial_aid.save() with self.assertRaises(ValidationError) as ex: get_purchasable_course_run(course_run.edx_course_key, user) assert ex.exception.args[0] == ( "Course run {} does not have a current attached financial aid application".format( course_run.edx_course_key ) )
def test_provides_edx_link(self): """If the program doesn't have financial aid, the checkout API should provide a link to go to edX""" user = UserFactory.create() self.client.force_login(user) course_run = CourseRunFactory.create( course__program__live=True, course__program__financial_aid_availability=False, ) resp = self.client.post(reverse('checkout'), {'course_id': course_run.edx_course_key}, format='json') assert resp.status_code == status.HTTP_200_OK assert resp.json() == { 'payload': {}, 'url': 'http://edx_base/course_modes/choose/{}/'.format(course_run.edx_course_key), 'method': 'GET', } # We should only create Order objects for a Cybersource checkout assert Order.objects.count() == 0