def setUp(self): super(TestBlockListGetForm, self).setUp() self.student = UserFactory.create() self.student2 = UserFactory.create() self.staff = UserFactory.create(is_staff=True) CourseEnrollmentFactory.create(user=self.student, course_id=self.course.id) CourseEnrollmentFactory.create(user=self.student2, course_id=self.course.id) usage_key = self.course.location self.initial = {"requesting_user": self.student} self.form_data = QueryDict( urlencode({"username": self.student.username, "usage_key": unicode(usage_key)}), mutable=True ) self.cleaned_data = { "all_blocks": None, "block_counts": set(), "depth": 0, "nav_depth": None, "return_type": "dict", "requested_fields": {"display_name", "type"}, "student_view_data": set(), "usage_key": usage_key, "username": self.student.username, "user": self.student, }
def test_expiry_date_range(self): """ Test that the verifications are filtered on the given range. Email is not sent for any verification with expiry date out of range """ user = UserFactory.create() verification_in_range = self.create_and_submit(user) verification_in_range.status = 'approved' verification_in_range.expiry_date = now() - timedelta(days=1) verification_in_range.save() user = UserFactory.create() verification = self.create_and_submit(user) verification.status = 'approved' verification.expiry_date = now() - timedelta(days=5) verification.save() call_command('send_verification_expiry_email', '--days-range=2') # Check that only one email is sent self.assertEqual(len(mail.outbox), 1) # Verify that the email is not sent to the out of range verification expiry_email_date = SoftwareSecurePhotoVerification.objects.get(pk=verification.pk).expiry_email_date self.assertIsNone(expiry_email_date)
def test_enrolled_students_features_keys_cohorted(self): course = CourseFactory.create(org="test", course="course1", display_name="run1") course.cohort_config = {'cohorted': True, 'auto_cohort': True, 'auto_cohort_groups': ['cohort']} self.store.update_item(course, self.instructor.id) cohorted_students = [UserFactory.create() for _ in xrange(10)] cohort = CohortFactory.create(name='cohort', course_id=course.id, users=cohorted_students) cohorted_usernames = [student.username for student in cohorted_students] non_cohorted_student = UserFactory.create() for student in cohorted_students: cohort.users.add(student) CourseEnrollment.enroll(student, course.id) CourseEnrollment.enroll(non_cohorted_student, course.id) instructor = InstructorFactory(course_key=course.id) self.client.login(username=instructor.username, password='******') query_features = ('username', 'cohort') # There should be a constant of 2 SQL queries when calling # enrolled_students_features. The first query comes from the call to # User.objects.filter(...), and the second comes from # prefetch_related('course_groups'). with self.assertNumQueries(2): userreports = enrolled_students_features(course.id, query_features) self.assertEqual(len([r for r in userreports if r['username'] in cohorted_usernames]), len(cohorted_students)) self.assertEqual(len([r for r in userreports if r['username'] == non_cohorted_student.username]), 1) for report in userreports: self.assertEqual(set(report.keys()), set(query_features)) if report['username'] in cohorted_usernames: self.assertEqual(report['cohort'], cohort.name) else: self.assertEqual(report['cohort'], '[unassigned]')
def test_same_user_key_in_multiple_organizations(self): uox_program_enrollment = self._create_waiting_program_enrollment() second_organization = OrganizationFactory.create() SAMLProviderConfigFactory.create(organization=second_organization, slug='aiu') catalog_org = CatalogOrganizationFactory.create(key=second_organization.short_name) program_uuid = self._create_catalog_program(catalog_org)['uuid'] # aiu enrollment with the same student key as our uox user aiu_program_enrollment = ProgramEnrollmentFactory.create( user=None, external_user_key=self.external_id, program_uuid=program_uuid ) UserSocialAuth.objects.create( user=UserFactory.create(), uid='{0}:{1}'.format('not_used', self.external_id), ) UserSocialAuth.objects.create( user=self.user, uid='{0}:{1}'.format(self.provider_slug, self.external_id), ) self._assert_program_enrollment_user(uox_program_enrollment, self.user) aiu_user = UserFactory.create() UserSocialAuth.objects.create( user=aiu_user, uid='{0}:{1}'.format('aiu', self.external_id), ) self._assert_program_enrollment_user(aiu_program_enrollment, aiu_user)
def setUp(self): self.course = CourseFactory.create() seed_permissions_roles(self.course.id) self.student = UserFactory.create() self.enrollment = CourseEnrollmentFactory(user=self.student, course_id=self.course.id) self.other_user = UserFactory.create(username="******") CourseEnrollmentFactory(user=self.other_user, course_id=self.course.id)
def test_resolve_course_enrollments(self): """ Test that the CourseEnrollmentsScopeResolver actually returns all enrollments """ test_user_1 = UserFactory.create(password='******') CourseEnrollmentFactory(user=test_user_1, course_id=self.course.id) test_user_2 = UserFactory.create(password='******') CourseEnrollmentFactory(user=test_user_2, course_id=self.course.id) test_user_3 = UserFactory.create(password='******') enrollment = CourseEnrollmentFactory(user=test_user_3, course_id=self.course.id) # unenroll #3 enrollment.is_active = False enrollment.save() resolver = CourseEnrollmentsScopeResolver() user_ids = resolver.resolve('course_enrollments', {'course_id': self.course.id}, None) # should have first two, but the third should not be present self.assertTrue(test_user_1.id in user_ids) self.assertTrue(test_user_2.id in user_ids) self.assertFalse(test_user_3.id in user_ids)
def setUp(self): super(CohortedContentTestCase, self).setUp() self.course = CourseFactory.create( discussion_topics={ "cohorted topic": {"id": "cohorted_topic"}, "non-cohorted topic": {"id": "non_cohorted_topic"}, }, cohort_config={ "cohorted": True, "cohorted_discussions": ["cohorted_topic"] } ) self.student_cohort = CourseUserGroup.objects.create( name="student_cohort", course_id=self.course.id, group_type=CourseUserGroup.COHORT ) self.moderator_cohort = CourseUserGroup.objects.create( name="moderator_cohort", course_id=self.course.id, group_type=CourseUserGroup.COHORT ) seed_permissions_roles(self.course.id) self.student = UserFactory.create() self.moderator = UserFactory.create() CourseEnrollmentFactory(user=self.student, course_id=self.course.id) CourseEnrollmentFactory(user=self.moderator, course_id=self.course.id) self.moderator.roles.add(Role.objects.get(name="Moderator", course_id=self.course.id)) self.student_cohort.users.add(self.student) self.moderator_cohort.users.add(self.moderator)
def setup_students_and_grades(context): """ Create students and set their grades. :param context: class reference """ if context.course: context.student = student = UserFactory.create() CourseEnrollmentFactory.create(user=student, course_id=context.course.id) context.student2 = student2 = UserFactory.create() CourseEnrollmentFactory.create(user=student2, course_id=context.course.id) # create grades for self.student as if they'd submitted the ccx for chapter in context.course.get_children(): for i, section in enumerate(chapter.get_children()): for j, problem in enumerate(section.get_children()): # if not problem.visible_to_staff_only: StudentModuleFactory.create( grade=1 if i < j else 0, max_grade=1, student=context.student, course_id=context.course.id, module_state_key=problem.location ) StudentModuleFactory.create( grade=1 if i > j else 0, max_grade=1, student=context.student2, course_id=context.course.id, module_state_key=problem.location )
def setUp(self): """Create a user with a team to test signals.""" super(TeamSignalsTest, self).setUp("teams.utils.tracker") self.user = UserFactory.create(username="******") self.moderator = UserFactory.create(username="******") self.team = CourseTeamFactory(discussion_topic_id=self.DISCUSSION_TOPIC_ID) self.team_membership = CourseTeamMembershipFactory(user=self.user, team=self.team)
def setUp(self): """ Create a course and user, then log in. """ super(EnrollmentTest, self).setUp() self.course = CourseFactory.create() self.user = UserFactory.create(username=self.USERNAME, email=self.EMAIL, password=self.PASSWORD) self.other_user = UserFactory.create() self.client.login(username=self.USERNAME, password=self.PASSWORD)
def setUp(self): super(TestBlockListGetForm, self).setUp() self.student = UserFactory.create() self.student2 = UserFactory.create() self.staff = UserFactory.create(is_staff=True) CourseEnrollmentFactory.create(user=self.student, course_id=self.course.id) CourseEnrollmentFactory.create(user=self.student2, course_id=self.course.id) usage_key = self.course.location self.initial = {'requesting_user': self.student} self.form_data = QueryDict( urlencode({ 'username': self.student.username, 'usage_key': unicode(usage_key), }), mutable=True, ) self.cleaned_data = { 'all_blocks': None, 'block_counts': set(), 'depth': 0, 'nav_depth': None, 'return_type': 'dict', 'requested_fields': {'display_name', 'type'}, 'student_view_data': set(), 'usage_key': usage_key, 'username': self.student.username, 'user': self.student, }
def test_duplicate_email(self): """ Assert the expected error message from the email validation method for an email address that is already in use by another account. """ UserFactory.create(email=self.new_email) self.assertEqual(self.do_email_validation(self.new_email), 'An account with this e-mail already exists.')
def setUp(self): super(UserStandingTest, self).setUp() # create users self.bad_user = UserFactory.create(username="******") self.good_user = UserFactory.create(username="******") self.non_staff = UserFactory.create(username="******") self.admin = UserFactory.create(username="******", is_staff=True) # create clients self.bad_user_client = Client() self.good_user_client = Client() self.non_staff_client = Client() self.admin_client = Client() for user, client in [ (self.bad_user, self.bad_user_client), (self.good_user, self.good_user_client), (self.non_staff, self.non_staff_client), (self.admin, self.admin_client), ]: client.login(username=user.username, password="******") UserStandingFactory.create( user=self.bad_user, account_status=UserStanding.ACCOUNT_DISABLED, changed_by=self.admin ) # set stock url to test disabled accounts' access to site self.some_url = "/"
def setUp(self): super(RefundTests, self).setUp() self.course = CourseFactory.create( org='testorg', number='run1', display_name='refundable course' ) self.course_id = self.course.location.course_key self.client = Client() self.admin = UserFactory.create( username='******', email='*****@*****.**', password='******' ) SupportStaffRole().add_users(self.admin) self.client.login(username=self.admin.username, password='******') self.student = UserFactory.create( username='******', email='*****@*****.**' ) self.course_mode = CourseMode.objects.get_or_create( course_id=self.course_id, mode_slug='verified', min_price=1 )[0] self.order = None self.form_pars = {'course_id': str(self.course_id), 'user': self.student.email}
def test_enrollment_email_on(self): """ Do email on enroll test """ course = self.course #Create activated, but not enrolled, user UserFactory.create(username="******", email="*****@*****.**") url = reverse('instructor_dashboard', kwargs={'course_id': course.id}) response = self.client.post(url, {'action': 'Enroll multiple students', 'multiple_students': '[email protected], [email protected], [email protected]', 'auto_enroll': 'on', 'email_students': 'on'}) #Check the page output self.assertContains(response, '<td>[email protected]</td>') self.assertContains(response, '<td>[email protected]</td>') self.assertContains(response, '<td>[email protected]</td>') self.assertContains(response, '<td>added, email sent</td>') self.assertContains(response, '<td>user does not exist, enrollment allowed, pending with auto enrollment on, email sent</td>') #Check the outbox self.assertEqual(len(mail.outbox), 3) self.assertEqual(mail.outbox[0].subject, 'You have been enrolled in MITx/999/Robot_Super_Course') self.assertEqual(mail.outbox[1].subject, 'You have been invited to register for MITx/999/Robot_Super_Course') self.assertEqual(mail.outbox[1].body, "Dear student,\n\nYou have been invited to join MITx/999/Robot_Super_Course at edx.org by a member of the course staff.\n\n" + "To finish your registration, please visit https://edx.org/register and fill out the registration form.\n" + "Once you have registered and activated your account, you will see MITx/999/Robot_Super_Course listed on your dashboard.\n\n" + "----\nThis email was automatically sent from edx.org to [email protected]")
def test_site_config(self, this_org_list, other_org_list, expected_message_count, mock_ace): filtered_org = 'filtered_org' unfiltered_org = 'unfiltered_org' this_config = SiteConfigurationFactory.create(values={'course_org_filter': this_org_list}) other_config = SiteConfigurationFactory.create(values={'course_org_filter': other_org_list}) for config in (this_config, other_config): ScheduleConfigFactory.create(site=config.site) user1 = UserFactory.create(id=self.task.num_bins) user2 = UserFactory.create(id=self.task.num_bins * 2) current_day, offset, target_day, upgrade_deadline = self._get_dates() self._schedule_factory( enrollment__course__org=filtered_org, enrollment__user=user1, ) self._schedule_factory( enrollment__course__org=unfiltered_org, enrollment__user=user1, ) self._schedule_factory( enrollment__course__org=unfiltered_org, enrollment__user=user2, ) with patch.object(self.task, 'async_send_task') as mock_schedule_send: self.task().apply(kwargs=dict( site_id=this_config.site.id, target_day_str=serialize(target_day), day_offset=offset, bin_num=0 )) self.assertEqual(mock_schedule_send.apply_async.call_count, expected_message_count) self.assertFalse(mock_ace.send.called)
def setUp(self): super(ExternalAuthShibTest, self).setUp() self.course = CourseFactory.create( org='Stanford', number='456', display_name='NO SHIB', user_id=self.user.id, ) self.shib_course = CourseFactory.create( org='Stanford', number='123', display_name='Shib Only', enrollment_domain='shib:https://idp.stanford.edu/', user_id=self.user.id, ) self.user_w_map = UserFactory.create(email='*****@*****.**') self.extauth = ExternalAuthMap(external_id='*****@*****.**', external_email='*****@*****.**', external_domain='shib:https://idp.stanford.edu/', external_credentials="", user=self.user_w_map) self.user_w_map.save() self.extauth.save() self.user_wo_map = UserFactory.create(email='*****@*****.**') self.user_wo_map.save()
def setUp(self): super(DiscussionTabTestCase, self).setUp() self.course = CourseFactory.create() self.enrolled_user = UserFactory.create() self.staff_user = AdminFactory.create() CourseEnrollmentFactory.create(user=self.enrolled_user, course_id=self.course.id) self.unenrolled_user = UserFactory.create()
def setUp(self): """ Create users for use in the tests """ super(TpaAPITestCase, self).setUp() google = self.configure_google_provider(enabled=True) self.configure_facebook_provider(enabled=True) self.configure_linkedin_provider(enabled=False) self.enable_saml() testshib = self.configure_saml_provider(name='TestShib', enabled=True, idp_slug=IDP_SLUG_TESTSHIB) # Create several users and link each user to Google and TestShib for username in LINKED_USERS: make_superuser = (username == ADMIN_USERNAME) make_staff = (username == STAFF_USERNAME) or make_superuser user = UserFactory.create( username=username, password=PASSWORD, is_staff=make_staff, is_superuser=make_superuser ) UserSocialAuth.objects.create( user=user, provider=google.backend_name, uid='{}@gmail.com'.format(username), ) UserSocialAuth.objects.create( user=user, provider=testshib.backend_name, uid='{}:remote_{}'.format(testshib.idp_slug, username), ) # Create another user not linked to any providers: UserFactory.create(username=CARL_USERNAME, password=PASSWORD)
def setUp(self): """ Fixtures. """ super(TestDataDumps, self).setUp() due = datetime.datetime(2010, 5, 12, 2, 42, tzinfo=UTC) course = CourseFactory.create() week1 = ItemFactory.create(due=due, parent=course) week2 = ItemFactory.create(due=due, parent=course) homework = ItemFactory.create( parent=week1, due=due ) user1 = UserFactory.create() user2 = UserFactory.create() self.course = course self.week1 = week1 self.homework = homework self.week2 = week2 self.user1 = user1 self.user2 = user2 signals.extract_dates(None, course.id)
def setUp(self): super(TeamAPITestCase, self).setUp() self.topics_count = 4 self.users = { "student_unenrolled": UserFactory.create(password=self.test_password), "student_enrolled": UserFactory.create(password=self.test_password), "student_enrolled_not_on_team": UserFactory.create(password=self.test_password), # This student is enrolled in both test courses and is a member of a team in each course, but is not on the # same team as student_enrolled. "student_enrolled_both_courses_other_team": UserFactory.create(password=self.test_password), "staff": AdminFactory.create(password=self.test_password), "course_staff": StaffFactory.create(course_key=self.test_course_1.id, password=self.test_password), } # 'solar team' is intentionally lower case to test case insensitivity in name ordering self.test_team_1 = CourseTeamFactory.create( name=u"sólar team", course_id=self.test_course_1.id, topic_id="topic_0" ) self.test_team_2 = CourseTeamFactory.create(name="Wind Team", course_id=self.test_course_1.id) self.test_team_3 = CourseTeamFactory.create(name="Nuclear Team", course_id=self.test_course_1.id) self.test_team_4 = CourseTeamFactory.create(name="Coal Team", course_id=self.test_course_1.id, is_active=False) self.test_team_5 = CourseTeamFactory.create(name="Another Team", course_id=self.test_course_2.id) for user, course in [ ("student_enrolled", self.test_course_1), ("student_enrolled_not_on_team", self.test_course_1), ("student_enrolled_both_courses_other_team", self.test_course_1), ("student_enrolled_both_courses_other_team", self.test_course_2), ]: CourseEnrollment.enroll(self.users[user], course.id, check_access=True) self.test_team_1.add_user(self.users["student_enrolled"]) self.test_team_3.add_user(self.users["student_enrolled_both_courses_other_team"]) self.test_team_5.add_user(self.users["student_enrolled_both_courses_other_team"])
def setUp(self): # create users self.bad_user = UserFactory.create(username="******") self.good_user = UserFactory.create(username="******") self.non_staff = UserFactory.create(username="******") self.admin = UserFactory.create(username="******", is_staff=True) # create clients self.bad_user_client = Client() self.good_user_client = Client() self.non_staff_client = Client() self.admin_client = Client() for user, client in [ (self.bad_user, self.bad_user_client), (self.good_user, self.good_user_client), (self.non_staff, self.non_staff_client), (self.admin, self.admin_client), ]: client.login(username=user.username, password="******") UserStandingFactory.create( user=self.bad_user, account_status=UserStanding.ACCOUNT_DISABLED, changed_by=self.admin ) # set different stock urls for lms and cms # to test disabled accounts' access to site try: self.some_url = reverse("dashboard") except NoReverseMatch: self.some_url = "/course"
def setUp(self): super(CertificatesRestApiTest, self).setUp() self.student = UserFactory.create(password=USER_PASSWORD) self.student_no_cert = UserFactory.create(password=USER_PASSWORD) self.staff_user = UserFactory.create(password=USER_PASSWORD, is_staff=True) GeneratedCertificateFactory.create( user=self.student, course_id=self.course.id, status=CertificateStatuses.downloadable, mode='verified', download_url='www.google.com', grade="0.88" ) self.namespaced_url = 'certificates_api:v0:certificates:detail' # create a configuration for django-oauth-toolkit (DOT) dot_app_user = UserFactory.create(password=USER_PASSWORD) dot_app = dot_models.Application.objects.create( name='test app', user=dot_app_user, client_type='confidential', authorization_grant_type='authorization-code', redirect_uris='http://localhost:8079/complete/edxorg/' ) self.dot_access_token = dot_models.AccessToken.objects.create( user=self.student, application=dot_app, expires=datetime.utcnow() + timedelta(weeks=1), scope='read write', token='16MGyP3OaQYHmpT1lK7Q6MMNAZsjwF' )
def setUpTestData(cls): UserFactory.create( username='******', email='*****@*****.**', password='******', ) super(TestEnterpriseApi, cls).setUpTestData()
def test_course_bulk_notification_tests(self): # create new users and enroll them in the course. startup.startup_notification_subsystem() test_user_1 = UserFactory.create(password='******') CourseEnrollmentFactory(user=test_user_1, course_id=self.course.id) test_user_2 = UserFactory.create(password='******') CourseEnrollmentFactory(user=test_user_2, course_id=self.course.id) notification_type = get_notification_type(u'open-edx.studio.announcements.new-announcement') course = modulestore().get_course(self.course.id, depth=0) notification_msg = NotificationMessage( msg_type=notification_type, namespace=unicode(self.course.id), payload={ '_schema_version': '1', 'course_name': course.display_name, } ) # Send the notification_msg to the Celery task publish_course_notifications_task.delay(self.course.id, notification_msg) # now the enrolled users should get notification about the # course update where they are enrolled as student. self.assertTrue(get_notifications_count_for_user(test_user_1.id), 1) self.assertTrue(get_notifications_count_for_user(test_user_2.id), 1)
def test_user_details_force_sync_username_conflict(self): """ The user details were attempted to be synced but the incoming username already exists for another account. An email should still be sent in this case. """ # Create a user with an email that conflicts with the incoming value. UserFactory.create(username='******'.format(self.old_username)) # Begin the pipeline. pipeline.user_details_force_sync( auth_entry=pipeline.AUTH_ENTRY_LOGIN, strategy=self.strategy, details=self.details, user=self.user, ) # The username is not changed, but everything else is. user = User.objects.get(pk=self.user.pk) assert user.email == 'new+{}'.format(self.old_email) assert user.username == self.old_username assert user.profile.name == 'Grown Up {}'.format(self.old_fullname) assert user.profile.country == 'PK' # An email should still be sent because the email changed. assert len(mail.outbox) == 1
def setUp(self): """Set up data for the test case""" super(SubmitFeedbackTest, self).setUp() self._request_factory = RequestFactory() self._anon_user = AnonymousUser() self._auth_user = UserFactory.create( email="*****@*****.**", username="******", profile__name="Test User" ) self._anon_fields = { "email": "*****@*****.**", "name": "Test User", "subject": "a subject", "details": "some details", "issue_type": "test_issue" } # This does not contain issue_type nor course_id to ensure that they are optional self._auth_fields = {"subject": "a subject", "details": "some details"} # Create a service user, because the track selection page depends on it UserFactory.create( username='******', email="*****@*****.**", password="******", )
def setUp(self): super(BookmarksTestsBase, self).setUp() self.admin = AdminFactory() self.user = UserFactory.create(password=self.TEST_PASSWORD) self.other_user = UserFactory.create(password=self.TEST_PASSWORD) self.setup_data(self.STORE_TYPE)
def setUp(self): """ Fixtures. """ due = datetime.datetime(2010, 5, 12, 2, 42, tzinfo=utc) course = CourseFactory.create() week1 = ItemFactory.create(due=due, parent=course) week2 = ItemFactory.create(due=due, parent=course) week3 = ItemFactory.create(due=due, parent=course) homework = ItemFactory.create(parent=week1, due=due) user1 = UserFactory.create() StudentModule(state="{}", student_id=user1.id, course_id=course.id, module_state_key=week1.location).save() StudentModule(state="{}", student_id=user1.id, course_id=course.id, module_state_key=week2.location).save() StudentModule(state="{}", student_id=user1.id, course_id=course.id, module_state_key=week3.location).save() StudentModule(state="{}", student_id=user1.id, course_id=course.id, module_state_key=homework.location).save() user2 = UserFactory.create() StudentModule(state="{}", student_id=user2.id, course_id=course.id, module_state_key=week1.location).save() StudentModule(state="{}", student_id=user2.id, course_id=course.id, module_state_key=homework.location).save() user3 = UserFactory.create() StudentModule(state="{}", student_id=user3.id, course_id=course.id, module_state_key=week1.location).save() StudentModule(state="{}", student_id=user3.id, course_id=course.id, module_state_key=homework.location).save() self.course = course self.week1 = week1 self.homework = homework self.week2 = week2 self.user1 = user1 self.user2 = user2
def setUp(self): """ Create a course and user, then log in. """ super(EnrollmentTest, self).setUp() self.rate_limit_config = RateLimitConfiguration.current() self.rate_limit_config.enabled = False self.rate_limit_config.save() throttle = EnrollmentUserThrottle() self.rate_limit, __ = throttle.parse_rate(throttle.rate) # Pass emit_signals when creating the course so it would be cached # as a CourseOverview. self.course = CourseFactory.create(emit_signals=True) self.user = UserFactory.create( username=self.USERNAME, email=self.EMAIL, password=self.PASSWORD, ) self.other_user = UserFactory.create( username=self.OTHER_USERNAME, email=self.OTHER_EMAIL, password=self.PASSWORD, ) self.client.login(username=self.USERNAME, password=self.PASSWORD)
def setUp(self): self.request_factory = RequestFactory() self.user = UserFactory.create() self.request = self.request_factory.get("foo") update_commerce_config(enabled=True) super(EcommerceServiceTests, self).setUp()
def setUp(self): self.course = CourseFactory.create() seed_permissions_roles(self.course.id) self.student = UserFactory.create() CourseEnrollmentFactory(user=self.student, course_id=self.course.id)
def setUp(self): self.user = UserFactory.create(username='******') self.field_data_cache = FieldDataCache( [mock_descriptor([mock_field(Scope.user_state, 'a_field')])], course_id, self.user) self.kvs = DjangoKeyValueStore(self.field_data_cache)
def setUp(self): super(CertificateManagementTest, self).setUp() self.user = UserFactory.create() self.courses = [CourseFactory.create() for __ in range(3)] CourseCompleteImageConfigurationFactory.create()
def test_non_owner_or_staff_user(self): """ The endpoint should NOT be accessible if the request is not made by the submitter or staff user. """ user = UserFactory.create() self.client.login(username=user.username, password=self.PASSWORD) response = self.client.get(self.path) self.assertEqual(response.status_code, 403)
def test_no_verifications(self): """ The endpoint should return HTTP 404 if the user has no verifications. """ user = UserFactory.create() path = reverse('verification_status', kwargs={'username': user.username}) self.assert_path_not_found(path)
def test_get_course_func_with_access(self, course_access_func, num_mongo_calls): user = UserFactory.create() course = CourseFactory.create(emit_signals=True) with check_mongo_calls(num_mongo_calls): course_access_func(user, 'load', course.id)
def setUp(self): super(AdminCourseRolesPageTest, self).setUp() self.user = UserFactory.create(is_staff=True, is_superuser=True) self.user.save()
def setUp(self): super(TestSendBetaRoleEmail, self).setUp() self.user = UserFactory.create() self.email_params = {'course': 'Robot Super Course'}
def setUpClass(cls): """Setup class""" super(LoginFailuresAdminTest, cls).setUpClass() cls.user = UserFactory.create(is_staff=True, is_superuser=True) cls.user.save()
def setUpClass(cls): super(PythonAPITests, cls).setUpClass() cls.user1 = UserFactory.create(username='******') cls.user2 = UserFactory.create(username='******') cls.user3 = UserFactory.create(username='******') cls.user4 = UserFactory.create(username='******') topic_data = [(TOPIC1, TeamsetType.private_managed.value), (TOPIC2, TeamsetType.open.value), (TOPIC3, TeamsetType.public_managed.value)] topics = [{ 'id': topic_id, 'name': 'name-' + topic_id, 'description': 'desc-' + topic_id, 'type': teamset_type } for topic_id, teamset_type in topic_data] teams_config_1 = TeamsConfig({'topics': [topics[0]]}) teams_config_2 = TeamsConfig({'topics': [topics[1], topics[2]]}) cls.course1 = CourseFactory( org=COURSE_KEY1.org, course=COURSE_KEY1.course, run=COURSE_KEY1.run, teams_configuration=teams_config_1, ) cls.course2 = CourseFactory( org=COURSE_KEY2.org, course=COURSE_KEY2.course, run=COURSE_KEY2.run, teams_configuration=teams_config_2, ) for user in (cls.user1, cls.user2, cls.user3, cls.user4): CourseEnrollmentFactory.create(user=user, course_id=COURSE_KEY1) for user in (cls.user3, cls.user4): CourseEnrollmentFactory.create(user=user, course_id=COURSE_KEY2) cls.team1 = CourseTeamFactory( course_id=COURSE_KEY1, discussion_topic_id=DISCUSSION_TOPIC_ID, team_id='team1', topic_id=TOPIC1, ) cls.team1a = CourseTeamFactory( # Same topic / team set as team1 course_id=COURSE_KEY1, team_id='team1a', topic_id=TOPIC1, ) cls.team2 = CourseTeamFactory(course_id=COURSE_KEY2, team_id='team2', topic_id=TOPIC2) cls.team2a = CourseTeamFactory( # Same topic / team set as team2 course_id=COURSE_KEY2, team_id='team2a', topic_id=TOPIC2) cls.team3 = CourseTeamFactory(course_id=COURSE_KEY2, team_id='team3', topic_id=TOPIC3) cls.team1.add_user(cls.user1) cls.team1.add_user(cls.user2) cls.team2.add_user(cls.user3) cls.team1a.add_user(cls.user4) cls.team2a.add_user(cls.user4)
def setUp(self): """ Fixtures """ super(TestRequireStudentIdentifier, self).setUp() self.student = UserFactory.create()
def test_cohort_scheme_partition(self): """ Test that cohort-schemed user partitions are ignored in the grades export. """ # Set up a course with 'cohort' and 'random' user partitions. cohort_scheme_partition = UserPartition( 0, 'Cohort-schemed Group Configuration', 'Group Configuration based on Cohorts', [Group(0, 'Group A'), Group(1, 'Group B')], scheme_id='cohort') experiment_group_a = Group(2, u'Expériment Group A') experiment_group_b = Group(3, u'Expériment Group B') experiment_partition = UserPartition( 1, u'Content Expériment Configuration', u'Group Configuration for Content Expériments', [experiment_group_a, experiment_group_b], scheme_id='random') course = CourseFactory.create( cohort_config={'cohorted': True}, user_partitions=[cohort_scheme_partition, experiment_partition]) # Create user_a and user_b which are enrolled in the course # and assigned to experiment_group_a and experiment_group_b, # respectively. user_a = UserFactory.create(username='******') user_b = UserFactory.create(username='******') CourseEnrollment.enroll(user_a, course.id) CourseEnrollment.enroll(user_b, course.id) course_tag_api.set_course_tag( user_a, course.id, RandomUserPartitionScheme.key_for_partition(experiment_partition), experiment_group_a.id) course_tag_api.set_course_tag( user_b, course.id, RandomUserPartitionScheme.key_for_partition(experiment_partition), experiment_group_b.id) # Assign user_a to a group in the 'cohort'-schemed user # partition (by way of a cohort) to verify that the user # partition group does not show up in the "Experiment Group" # cell. cohort_a = CohortFactory.create(course_id=course.id, name=u'Cohørt A', users=[user_a]) CourseUserGroupPartitionGroup( course_user_group=cohort_a, partition_id=cohort_scheme_partition.id, group_id=cohort_scheme_partition.groups[0].id).save() # Verify that we see user_a and user_b in their respective # content experiment groups, and that we do not see any # content groups. experiment_group_message = u'Experiment Group ({content_experiment})' self._verify_cell_data_for_user( user_a.username, course.id, experiment_group_message.format( content_experiment=experiment_partition.name), experiment_group_a.name) self._verify_cell_data_for_user( user_b.username, course.id, experiment_group_message.format( content_experiment=experiment_partition.name), experiment_group_b.name) # Make sure cohort info is correct. cohort_name_header = 'Cohort Name' self._verify_cell_data_for_user(user_a.username, course.id, cohort_name_header, cohort_a.name) self._verify_cell_data_for_user(user_b.username, course.id, cohort_name_header, '')
def setUp(self): super(CookieTests, self).setUp() self.user = UserFactory.create() self.request = RequestFactory().get('/') self.request.user = self.user self.request.session = self._get_stub_session()
def setUp(self): super(ChangeEnrollmentViewTest, self).setUp() self.course = CourseFactory.create() self.user = UserFactory.create(password='******') self.client.login(username=self.user.username, password='******') self.url = reverse('change_enrollment')
def test_verification_for_datetime(self): user = UserFactory.create() now = datetime.now(pytz.UTC) # No attempts in the query set, so should return None query = SoftwareSecurePhotoVerification.objects.filter(user=user) result = SoftwareSecurePhotoVerification.verification_for_datetime( now, query) self.assertIs(result, None) # Should also return None if no deadline specified query = SoftwareSecurePhotoVerification.objects.filter(user=user) result = SoftwareSecurePhotoVerification.verification_for_datetime( None, query) self.assertIs(result, None) # Make an attempt attempt = SoftwareSecurePhotoVerification.objects.create(user=user) # Before the created date, should get no results before = attempt.created_at - timedelta(seconds=1) query = SoftwareSecurePhotoVerification.objects.filter(user=user) result = SoftwareSecurePhotoVerification.verification_for_datetime( before, query) self.assertIs(result, None) # Immediately after the created date, should get the attempt after_created = attempt.created_at + timedelta(seconds=1) query = SoftwareSecurePhotoVerification.objects.filter(user=user) result = SoftwareSecurePhotoVerification.verification_for_datetime( after_created, query) self.assertEqual(result, attempt) # If no deadline specified, should return first available query = SoftwareSecurePhotoVerification.objects.filter(user=user) result = SoftwareSecurePhotoVerification.verification_for_datetime( None, query) self.assertEqual(result, attempt) # Immediately before the expiration date, should get the attempt expiration = attempt.created_at + timedelta( days=settings.VERIFY_STUDENT["DAYS_GOOD_FOR"]) before_expiration = expiration - timedelta(seconds=1) query = SoftwareSecurePhotoVerification.objects.filter(user=user) result = SoftwareSecurePhotoVerification.verification_for_datetime( before_expiration, query) self.assertEqual(result, attempt) # Immediately after the expiration date, should not get the attempt after = expiration + timedelta(seconds=1) query = SoftwareSecurePhotoVerification.objects.filter(user=user) result = SoftwareSecurePhotoVerification.verification_for_datetime( after, query) self.assertIs(result, None) # Create a second attempt in the same window second_attempt = SoftwareSecurePhotoVerification.objects.create( user=user) # Now we should get the newer attempt deadline = second_attempt.created_at + timedelta(days=1) query = SoftwareSecurePhotoVerification.objects.filter(user=user) result = SoftwareSecurePhotoVerification.verification_for_datetime( deadline, query) self.assertEqual(result, second_attempt)
def setUp(self): self.student = UserFactory.create(password='******') self.client = Client()
def setUp(self): self.user = UserFactory.create() self.course = CourseFactory.create() CourseEnrollment.enroll(self.user, self.course.id) self.client.login(username=self.user.username, password='******')
def setUp(self): self.user = UserFactory.create(username=self.USER_USERNAME, first_name=self.USER_FIRST_NAME, last_name=self.USER_LAST_NAME) self.courses = [] self.enrollments = defaultdict(list)
def setUp(self): super(DashboardTest, self).setUp() self.course = CourseFactory.create() self.user = UserFactory.create(username="******", email="*****@*****.**", password='******') self.client = Client() cache.clear()
def setUp(self): self.user_1 = UserFactory.create() self.user_2 = UserFactory.create()
def test_user_status(self): # each part of the test is in it's own 'frozen time' block because the status is dependent on recency of # verifications and in order to control the recency, we just put everything inside of a frozen time # test for correct status when no error returned user = UserFactory.create() with freeze_time('2014-12-12'): status = IDVerificationService.user_status(user) expected_status = { 'status': 'none', 'error': '', 'should_display': True, 'verification_expiry': '', 'status_date': '' } self.assertDictEqual(status, expected_status) with freeze_time('2015-01-02'): # test for when photo verification has been created SoftwareSecurePhotoVerification.objects.create(user=user, status='approved') status = IDVerificationService.user_status(user) expected_status = { 'status': 'approved', 'error': '', 'should_display': True, 'verification_expiry': '', 'status_date': datetime.now(utc) } self.assertDictEqual(status, expected_status) with freeze_time('2015-02-02'): # create another photo verification for the same user, make sure the denial # is handled properly SoftwareSecurePhotoVerification.objects.create( user=user, status='denied', error_msg='[{"photoIdReasons": ["Not provided"]}]') status = IDVerificationService.user_status(user) expected_status = { 'status': 'must_reverify', 'error': ['id_image_missing'], 'should_display': True, 'verification_expiry': '', 'status_date': '', } self.assertDictEqual(status, expected_status) with freeze_time('2015-03-02'): # test for when sso verification has been created SSOVerification.objects.create(user=user, status='approved') status = IDVerificationService.user_status(user) expected_status = { 'status': 'approved', 'error': '', 'should_display': False, 'verification_expiry': '', 'status_date': datetime.now(utc) } self.assertDictEqual(status, expected_status) with freeze_time('2015-04-02'): # create another sso verification for the same user, make sure the denial # is handled properly SSOVerification.objects.create(user=user, status='denied') status = IDVerificationService.user_status(user) expected_status = { 'status': 'must_reverify', 'error': '', 'should_display': False, 'verification_expiry': '', 'status_date': '' } self.assertDictEqual(status, expected_status) with freeze_time('2015-05-02'): # test for when manual verification has been created ManualVerification.objects.create(user=user, status='approved') status = IDVerificationService.user_status(user) expected_status = { 'status': 'approved', 'error': '', 'should_display': False, 'verification_expiry': '', 'status_date': datetime.now(utc) } self.assertDictEqual(status, expected_status)
def test_enrollment_email_on(self, protocol): """ Do email on enroll test """ course = self.course # Create activated, but not enrolled, user UserFactory.create(username="******", email="*****@*****.**", first_name='Autoenrolled') url = reverse('instructor_dashboard_legacy', kwargs={'course_id': course.id.to_deprecated_string()}) params = { 'action': 'Enroll multiple students', 'multiple_students': '[email protected], [email protected], [email protected]', 'auto_enroll': 'on', 'email_students': 'on' } environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) # Check the page output self.assertContains(response, '<td>[email protected]</td>') self.assertContains(response, '<td>[email protected]</td>') self.assertContains(response, '<td>[email protected]</td>') self.assertContains(response, '<td>added, email sent</td>') self.assertContains( response, '<td>user does not exist, enrollment allowed, pending with auto enrollment on, email sent</td>' ) # Check the outbox self.assertEqual(len(mail.outbox), 3) self.assertEqual(mail.outbox[0].subject, 'You have been enrolled in Robot Super Course') self.assertEqual( mail.outbox[0].body, "Dear Autoenrolled Test\n\nYou have been enrolled in Robot Super Course " "at edx.org by a member of the course staff. " "The course should now appear on your edx.org dashboard.\n\n" "To start accessing course materials, please visit " "{}://edx.org/courses/MITx/999/Robot_Super_Course/\n\n" "----\nThis email was automatically sent from edx.org to Autoenrolled Test" .format(protocol)) self.assertEqual( mail.outbox[1].subject, 'You have been invited to register for Robot Super Course') self.assertEqual( mail.outbox[1].body, "Dear student,\n\nYou have been invited to join " "Robot Super Course at edx.org by a member of the " "course staff.\n\n" "To finish your registration, please visit " "{}://edx.org/register and fill out the registration form " "making sure to use [email protected] in the E-mail field.\n" "Once you have registered and activated your account, you will " "see Robot Super Course listed on your dashboard.\n\n" "----\nThis email was automatically sent from edx.org to " "*****@*****.**".format(protocol))
def setUp(self): super(InstructorTaskTestCase, self).setUp() self.student = UserFactory.create(username="******", email="*****@*****.**") self.instructor = UserFactory.create(username="******", email="*****@*****.**") self.problem_url = InstructorTaskTestCase.problem_location("test_urlname")
def setUp(self): super(TestSafeSessionMiddleware, self).setUp() self.user = UserFactory.create() self.request = create_mock_request() self.client.response = HttpResponse() self.client.response.cookies = SimpleCookie()
def test_satisfy_all_requirements(self): """ Test the credit requirements, eligibility notification, email content caching for a credit course. """ # Configure a course with two credit requirements self.add_credit_course() CourseFactory.create(org='edX', number='DemoX', display_name='Demo_Course') requirements = [{ "namespace": "grade", "name": "grade", "display_name": "Grade", "criteria": { "min_grade": 0.8 }, }, { "namespace": "reverification", "name": "i4x://edX/DemoX/edx-reverification-block/assessment_uuid", "display_name": "Assessment 1", "criteria": {}, }] api.set_credit_requirements(self.course_key, requirements) user = UserFactory.create(username=self.USER_INFO['username'], password=self.USER_INFO['password']) # Satisfy one of the requirements, but not the other with self.assertNumQueries(11): api.set_credit_requirement_status(user.username, self.course_key, requirements[0]["namespace"], requirements[0]["name"]) # The user should not be eligible (because only one requirement is satisfied) self.assertFalse( api.is_user_eligible_for_credit("bob", self.course_key)) # Satisfy the other requirement with self.assertNumQueries(15): api.set_credit_requirement_status("bob", self.course_key, requirements[1]["namespace"], requirements[1]["name"]) # Now the user should be eligible self.assertTrue(api.is_user_eligible_for_credit( "bob", self.course_key)) # Credit eligibility email should be sent self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Course Credit Eligibility') # Now verify them email content email_payload_first = mail.outbox[0].attachments[0]._payload # pylint: disable=protected-access # Test that email has two payloads [multipart (plain text and html # content), attached image] self.assertEqual(len(email_payload_first), 2) # pylint: disable=protected-access self.assertIn('text/plain', email_payload_first[0]._payload[0]['Content-Type']) # pylint: disable=protected-access self.assertIn('text/html', email_payload_first[0]._payload[1]['Content-Type']) self.assertIn('image/png', email_payload_first[1]['Content-Type']) # Now check that html email content has same logo image 'Content-ID' # as the attached logo image 'Content-ID' email_image = email_payload_first[1] html_content_first = email_payload_first[0]._payload[1]._payload # pylint: disable=protected-access # strip enclosing angle brackets from 'logo_image' cache 'Content-ID' image_id = email_image.get('Content-ID', '')[1:-1] self.assertIsNotNone(image_id) self.assertIn(image_id, html_content_first) # Delete the eligibility entries and satisfy the user's eligibility # requirement again to trigger eligibility notification CreditEligibility.objects.all().delete() with self.assertNumQueries(13): api.set_credit_requirement_status("bob", self.course_key, requirements[1]["namespace"], requirements[1]["name"]) # Credit eligibility email should be sent self.assertEqual(len(mail.outbox), 2) # Now check that on sending eligibility notification again cached # logo image is used email_payload_second = mail.outbox[1].attachments[0]._payload # pylint: disable=protected-access html_content_second = email_payload_second[0]._payload[1]._payload # pylint: disable=protected-access self.assertIn(image_id, html_content_second) # The user should remain eligible even if the requirement status is later changed api.set_credit_requirement_status("bob", self.course_key, requirements[0]["namespace"], requirements[0]["name"], status="failed") self.assertTrue(api.is_user_eligible_for_credit( "bob", self.course_key))
def setUp(self): super(ToyCourseCompletionTestCase, self).setUp() self.test_user = UserFactory.create() CourseEnrollment.enroll(self.test_user, self.course.id)
def setUp(self): super(TestSafeSessionProcessRequest, self).setUp() self.user = UserFactory.create() self.request = create_mock_request()
def setUp(self): super(UserProfilePropertiesTest, self).setUp() self.user = UserFactory.create(password=self.password) self.profile = self.user.profile
def setUp(self): super(CourseCompletionSerializerTestCase, self).setUp() self.test_user = UserFactory.create()