def setUp(self): self.partition = UserPartition( 0, 'first_partition', 'First Partition', [ Group(0, 'alpha'), Group(1, 'beta') ] ) self.course = CourseFactory.create( number=self.COURSE_NUMBER, user_partitions=[self.partition] ) self.chapter = ItemFactory.create( parent_location=self.course.location, category="chapter", display_name="test chapter", ) self.sequential = ItemFactory.create( parent_location=self.chapter.location, category="sequential", display_name="Split Test Tests", ) self.student = UserFactory.create() CourseEnrollmentFactory.create(user=self.student, course_id=self.course.id) self.client.login(username=self.student.username, password='******')
def setup_course(self): self.course = CourseFactory.create(data=self.COURSE_DATA) # Turn off cache. modulestore().request_cache = None modulestore().metadata_inheritance_cache_subsystem = None chapter = ItemFactory.create( parent_location=self.course.location, category="sequential", ) self.section = ItemFactory.create( parent_location=chapter.location, category="sequential" ) # username = robot{0}, password = '******' self.users = [ UserFactory.create() for i in range(self.USER_COUNT) ] for user in self.users: CourseEnrollmentFactory.create(user=user, course_id=self.course.id) # login all users for acces to Xmodule self.clients = {user.username: Client() for user in self.users} self.login_statuses = [ self.clients[user.username].login( username=user.username, password='******') for user in self.users ] self.assertTrue(all(self.login_statuses))
def _create_user(self, username, email=None, is_staff=False, mode="honor"): """Creates a user and enrolls them in the test course.""" if email is None: email = InstructorTaskCourseTestCase.get_user_email(username) thisuser = UserFactory.create(username=username, email=email, is_staff=is_staff) CourseEnrollmentFactory.create(user=thisuser, course_id=self.course.id, mode=mode) return thisuser
def test_unicode_students_send_to_all(self): """ Make sure email (with Unicode characters) send to all goes there. """ # Create a student with Unicode in their first & last names unicode_user = UserFactory(first_name=u'Ⓡⓞⓑⓞⓣ', last_name=u'ՇﻉรՇ') CourseEnrollmentFactory.create(user=unicode_user, course_id=self.course.id) self.students.append(unicode_user) test_email = { 'action': 'Send email', 'send_to': '["myself", "staff", "learners"]', 'subject': 'test subject for all', 'message': 'test message for all' } response = self.client.post(self.send_mail_url, test_email) self.assertEquals(json.loads(response.content), self.success_content) self.assertEquals(len(mail.outbox), 1 + len(self.staff) + len(self.students)) self.assertItemsEqual( [e.to[0] for e in mail.outbox], [self.instructor.email] + [s.email for s in self.staff] + [s.email for s in self.students] )
def test_access_course_team_users(self, role_factory): """ Test that members of the course team do not lose access to graded content """ # There are two types of course team members: instructor and staff # they have different privileges, but for the purpose of this test the important thing is that they should both # have access to all graded content if role_factory == GlobalStaffFactory: user = role_factory.create() else: user = role_factory.create(course_key=self.course.id) CourseEnrollmentFactory.create( user=user, course_id=self.course.id, mode='audit', ) # assert that course team members have access to graded content _assert_block_is_gated( block=self.blocks_dict['problem'], user=user, course=self.course, is_gated=False, request_factory=self.factory, )
def setUp(self): super(TestGetProblemGradeDistribution, self).setUp() self.request_factory = RequestFactory() self.instructor = AdminFactory.create() self.client.login(username=self.instructor.username, password='******') self.attempts = 3 self.course = CourseFactory.create( display_name=u"test course omega \u03a9", ) section = ItemFactory.create( parent_location=self.course.location, category="chapter", display_name=u"test factory section omega \u03a9", ) self.sub_section = ItemFactory.create( parent_location=section.location, category="sequential", display_name=u"test subsection omega \u03a9", ) unit = ItemFactory.create( parent_location=self.sub_section.location, category="vertical", metadata={'graded': True, 'format': 'Homework'}, display_name=u"test unit omega \u03a9", ) self.users = [UserFactory.create(username="******" + str(__)) for __ in xrange(USER_COUNT)] for user in self.users: CourseEnrollmentFactory.create(user=user, course_id=self.course.id) for i in xrange(USER_COUNT - 1): category = "problem" self.item = ItemFactory.create( parent_location=unit.location, category=category, data=StringResponseXMLFactory().build_xml(answer='foo'), metadata={'rerandomize': 'always'}, display_name=u"test problem omega \u03a9 " + str(i) ) for j, user in enumerate(self.users): StudentModuleFactory.create( grade=1 if i < j else 0, max_grade=1 if i < j else 0.5, student=user, course_id=self.course.id, module_state_key=self.item.location, state=json.dumps({'attempts': self.attempts}), ) for j, user in enumerate(self.users): StudentModuleFactory.create( course_id=self.course.id, module_type='sequential', module_state_key=self.item.location, )
def test_unicode_students_send_to_all(self): """ Make sure email (with Unicode characters) send to all goes there. """ # Now we know we have pulled up the instructor dash's email view # (in the setUp method), we can test sending an email. # Create a student with Unicode in their first & last names unicode_user = UserFactory(first_name=u'Ⓡⓞⓑⓞⓣ', last_name=u'ՇﻉรՇ') CourseEnrollmentFactory.create(user=unicode_user, course_id=self.course.id) self.students.append(unicode_user) test_email = { 'action': 'Send email', 'send_to': 'all', 'subject': 'test subject for all', 'message': 'test message for all' } # Post the email to the instructor dashboard API response = self.client.post(self.send_mail_url, test_email) self.assertEquals(json.loads(response.content), self.success_content) self.assertEquals(len(mail.outbox), 1 + len(self.staff) + len(self.students)) self.assertItemsEqual( [e.to[0] for e in mail.outbox], [self.instructor.email] + [s.email for s in self.staff] + [s.email for s in self.students] )
def setUp(self): course_title = u"ẗëṡẗ title イ乇丂イ ᄊ乇丂丂ムg乇 キo尺 ムレレ тэѕт мэѕѕаБэ" self.course = CourseFactory.create(display_name=course_title) self.instructor = InstructorFactory(course=self.course.id) # Create staff self.staff = [StaffFactory(course=self.course.id) for _ in xrange(STAFF_COUNT)] # Create students self.students = [UserFactory() for _ in xrange(STUDENT_COUNT)] for student in self.students: CourseEnrollmentFactory.create(user=student, course_id=self.course.id) # load initial content (since we don't run migrations as part of tests): call_command("loaddata", "course_email_template.json") self.client.login(username=self.instructor.username, password="******") # Pull up email view on instructor dashboard self.url = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()}) # Response loads the whole instructor dashboard, so no need to explicitly # navigate to a particular email section response = self.client.get(self.url) email_section = '<div class="vert-left send-email" id="section-send-email">' # If this fails, it is likely because ENABLE_INSTRUCTOR_EMAIL is set to False self.assertTrue(email_section in response.content) self.send_mail_url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()}) self.success_content = { 'course_id': self.course.id.to_deprecated_string(), 'success': True, }
def test_masquerade_expired(self, mock_get_course_run_details): mock_get_course_run_details.return_value = {'weeks_to_complete': 1} audit_student = UserFactory(username='******') enrollment = CourseEnrollmentFactory.create( user=audit_student, course_id=self.course.id, mode='audit', ) enrollment.created = self.course.start enrollment.save() CourseDurationLimitConfig.objects.create( enabled=True, course=CourseOverview.get_from_id(self.course.id), enabled_as_of=self.course.start, ) instructor = UserFactory.create(username='******') CourseEnrollmentFactory.create( user=instructor, course_id=self.course.id, mode='audit' ) CourseInstructorRole(self.course.id).add_users(instructor) self.client.login(username=instructor.username, password='******') self.update_masquerade(username='******') course_home_url = reverse('openedx.course_experience.course_home', args=[six.text_type(self.course.id)]) response = self.client.get(course_home_url, follow=True) self.assertEqual(response.status_code, 200) self.assertItemsEqual(response.redirect_chain, []) banner_text = 'This learner does not have access to this course. Their access expired on' self.assertIn(banner_text, response.content)
def test_chunked_queries_send_numerous_emails(self, email_mock): """ Test sending a large number of emails, to test the chunked querying """ mock_factory = MockCourseEmailResult() email_mock.side_effect = mock_factory.get_mock_update_subtask_status() added_users = [] for _ in xrange(LARGE_NUM_EMAILS): user = UserFactory() added_users.append(user) CourseEnrollmentFactory.create(user=user, course_id=self.course.id) optouts = [] for i in [1, 3, 9, 10, 18]: # 5 random optouts user = added_users[i] optouts.append(user) optout = Optout(user=user, course_id=self.course.id) optout.save() test_email = { 'action': 'Send email', 'to_option': 'all', 'subject': 'test subject for all', 'message': 'test message for all' } response = self.client.post(self.url, test_email) self.assertContains(response, "Your email was successfully queued for sending.") self.assertEquals(mock_factory.emails_sent, 1 + len(self.staff) + len(self.students) + LARGE_NUM_EMAILS - len(optouts)) outbox_contents = [e.to[0] for e in mail.outbox] should_send_contents = ([self.instructor.email] + [s.email for s in self.staff] + [s.email for s in self.students] + [s.email for s in added_users if s not in optouts]) self.assertItemsEqual(outbox_contents, should_send_contents)
def setUp(self): course_title = u"ẗëṡẗ title イ乇丂イ ᄊ乇丂丂ムg乇 キo尺 ムレレ тэѕт мэѕѕаБэ" self.course = CourseFactory.create(display_name=course_title) self.instructor = InstructorFactory(course=self.course.location) # Create staff self.staff = [StaffFactory(course=self.course.location) for _ in xrange(STAFF_COUNT)] # Create students self.students = [UserFactory() for _ in xrange(STUDENT_COUNT)] for student in self.students: CourseEnrollmentFactory.create(user=student, course_id=self.course.id) # load initial content (since we don't run migrations as part of tests): call_command("loaddata", "course_email_template.json") self.client.login(username=self.instructor.username, password="******") # Pull up email view on instructor dashboard self.url = reverse('instructor_dashboard', kwargs={'course_id': self.course.id}) response = self.client.get(self.url) email_link = '<a href="#" onclick="goto(\'Email\')" class="None">Email</a>' # If this fails, it is likely because ENABLE_INSTRUCTOR_EMAIL is set to False self.assertTrue(email_link in response.content) # Select the Email view of the instructor dash session = self.client.session session['idash_mode'] = 'Email' session.save() response = self.client.get(self.url) selected_email_link = '<a href="#" onclick="goto(\'Email\')" class="selectedmode">Email</a>' self.assertTrue(selected_email_link in response.content)
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_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): 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 setUp(self): """ Create the test data. """ super(CompletionBatchTestCase, self).setUp() self.url = reverse('completion_api:v1:completion-batch') # Enable the waffle flag for all tests self.override_waffle_switch(True) # Create course self.course = CourseFactory.create(org='TestX', number='101', display_name='Test') self.problem = ItemFactory.create( parent=self.course, category="problem", display_name="Test Problem", ) # Create users self.staff_user = UserFactory(is_staff=True) self.enrolled_user = UserFactory(username=self.ENROLLED_USERNAME) self.unenrolled_user = UserFactory(username=self.UNENROLLED_USERNAME) # Enrol one user in the course CourseEnrollmentFactory.create(user=self.enrolled_user, course_id=self.course.id) # Login the enrolled user by for all tests self.client = APIClient() self.client.force_authenticate(user=self.enrolled_user)
def setUp(self): super(CCXCoachTabTestCase, self).setUp() self.course = CourseFactory.create() self.user = UserFactory.create() CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id) role = CourseCcxCoachRole(self.course.id) role.add_users(self.user)
def _create_cert(self, course_key, user, status): """Create a certificate entry. """ # Enroll the user in the course CourseEnrollmentFactory.create(user=user, course_id=course_key) # Create the certificate GeneratedCertificate.objects.create(user=user, course_id=course_key, status=status)
def setUp(self): super(CertificatesViewsTests, self).setUp() self.client = Client() self.course = CourseFactory.create( org='testorg', number='run1', display_name='refundable course' ) self.course_id = self.course.location.course_key self.user = UserFactory.create( email='*****@*****.**', username='******', password='******' ) self.user.profile.name = "Joe User" self.user.profile.save() self.client.login(username=self.user.username, password='******') self.request = RequestFactory().request() self.cert = GeneratedCertificateFactory.create( user=self.user, course_id=self.course_id, download_uuid=uuid4(), download_url="http://www.example.com/certificates/download", grade="0.95", key='the_key', distinction=True, status='downloadable', mode='honor', name=self.user.profile.name, ) CourseEnrollmentFactory.create( user=self.user, course_id=self.course_id ) CertificateHtmlViewConfigurationFactory.create() LinkedInAddToProfileConfigurationFactory.create()
def setUp(self): self.course_name = 'edX/toy/2012_Fall' # Create student account student = UserFactory.create() CourseEnrollmentFactory.create( user=student, course_id=SlashSeparatedCourseKey.from_deprecated_string(self.course_name) ) self.client.login(username=student.username, password="******") try: # URL for dashboard self.url = reverse('dashboard') except NoReverseMatch: raise SkipTest("Skip this test if url cannot be found (ie running from CMS tests)") # URL for email settings modal self.email_modal_link = ( ('<a href="#email-settings-modal" class="email-settings" rel="leanModal" ' 'data-course-id="{0}/{1}/{2}" data-course-number="{1}" ' 'data-optout="False">Email Settings</a>').format( 'edX', 'toy', '2012_Fall' ) )
def setUp(self): super(TestGradebook, self).setUp() instructor = AdminFactory.create() self.client.login(username=instructor.username, password='******') self.users = [UserFactory.create() for _ in xrange(USER_COUNT)] for user in self.users: CourseEnrollmentFactory.create(user=user, course_id=self.course.id) for i, item in enumerate(self.items): for j, user in enumerate(self.users): StudentModuleFactory.create( grade=1 if i < j else 0, max_grade=1, student=user, course_id=self.course.id, module_state_key=item.location ) self.response = self.client.get(reverse( 'spoc_gradebook', args=(self.course.id.to_deprecated_string(),) )) self.assertEquals(self.response.status_code, 200)
def setUp(self): super(TestGetProblemGradeDistribution, self).setUp() self.request_factory = RequestFactory() self.instructor = AdminFactory.create() self.client.login(username=self.instructor.username, password='******') self.attempts = 3 self.users = [ UserFactory.create(username="******" + str(__)) for __ in xrange(USER_COUNT) ] for user in self.users: CourseEnrollmentFactory.create(user=user, course_id=self.course.id) for i, item in enumerate(self.items): for j, user in enumerate(self.users): StudentModuleFactory.create( grade=1 if i < j else 0, max_grade=1 if i < j else 0.5, student=user, course_id=self.course.id, module_state_key=item.location, state=json.dumps({'attempts': self.attempts}), ) for j, user in enumerate(self.users): StudentModuleFactory.create( course_id=self.course.id, module_type='sequential', module_state_key=item.location, )
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_data_err_fail(self, retry, result, get_conn): """ Test that celery handles permanent SMTPDataErrors by failing and not retrying. """ # have every fourth email fail due to blacklisting: get_conn.return_value.send_messages.side_effect = cycle([SMTPDataError(554, "Email address is blacklisted"), None, None, None]) students = [UserFactory() for _ in xrange(settings.BULK_EMAIL_EMAILS_PER_TASK)] for student in students: CourseEnrollmentFactory.create(user=student, course_id=self.course.id) test_email = { 'action': 'Send email', 'send_to': 'all', 'subject': 'test subject for all', 'message': 'test message for all' } response = self.client.post(self.send_mail_url, test_email) self.assertEquals(json.loads(response.content), self.success_content) # We shouldn't retry when hitting a 5xx error self.assertFalse(retry.called) # Test that after the rejected email, the rest still successfully send ((_entry_id, _current_task_id, subtask_status), _kwargs) = result.call_args self.assertEquals(subtask_status.skipped, 0) expected_fails = int((settings.BULK_EMAIL_EMAILS_PER_TASK + 3) / 4.0) self.assertEquals(subtask_status.failed, expected_fails) self.assertEquals(subtask_status.succeeded, settings.BULK_EMAIL_EMAILS_PER_TASK - expected_fails)
def setUp(self): super(CCXCoachTabTestCase, self).setUp() self.user = UserFactory.create() for course in [self.ccx_enabled_course, self.ccx_disabled_course]: CourseEnrollmentFactory.create(user=self.user, course_id=course.id) role = CourseCcxCoachRole(course.id) role.add_users(self.user)
def test_access_masquerade_as_course_team_users(self, role_factory): """ Test that when masquerading as members of the course team you do not lose access to graded content """ # There are two types of course team members: instructor and staff # they have different privileges, but for the purpose of this test the important thing is that they should both # have access to all graded content staff_user = StaffFactory.create(password=TEST_PASSWORD, course_key=self.course.id) CourseEnrollmentFactory.create( user=staff_user, course_id=self.course.id, mode='audit' ) self.client.login(username=staff_user.username, password=TEST_PASSWORD) if role_factory == GlobalStaffFactory: user = role_factory.create() else: user = role_factory.create(course_key=self.course.id) self.update_masquerade(username=user.username) block = self.blocks_dict['problem'] block_view_url = reverse('render_xblock', kwargs={'usage_key_string': six.text_type(block.scope_ids.usage_id)}) response = self.client.get(block_view_url) self.assertEquals(response.status_code, 200)
def create_course(self, modules_count, module_store, topics): """ Create a course in a specified module store with discussion module and topics """ course = CourseFactory.create( org="a", course="b", run="c", start=datetime.now(UTC), default_store=module_store, discussion_topics=topics ) CourseEnrollmentFactory.create(user=self.user, course_id=course.id) course_url = reverse("course_topics", kwargs={"course_id": unicode(course.id)}) # add some discussion modules for i in range(modules_count): ItemFactory.create( parent_location=course.location, category='discussion', discussion_id='id_module_{}'.format(i), discussion_category='Category {}'.format(i), discussion_target='Discussion {}'.format(i), publish_item=False, ) return course_url
def setUp(self): """ Setup course structure and create user for split test transformer test. """ super(SplitTestTransformerTestCase, self).setUp() # Set up user partitions and groups. self.groups = [Group(1, 'Group 1'), Group(2, 'Group 2'), Group(3, 'Group 3')] self.split_test_user_partition_id = self.TEST_PARTITION_ID self.split_test_user_partition = UserPartition( id=self.split_test_user_partition_id, name='Split Partition', description='This is split partition', groups=self.groups, scheme=RandomUserPartitionScheme ) self.split_test_user_partition.scheme.name = "random" # Build course. self.course_hierarchy = self.get_course_hierarchy() self.blocks = self.build_course(self.course_hierarchy) self.course = self.blocks['course'] # Enroll user in course. CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id, is_active=True) self.transformer = UserPartitionTransformer()
def test_data_err_fail(self, retry, result): """ Test that celery handles permanent SMTPDataErrors by failing and not retrying. """ self.smtp_server_thread.server.set_errtype( "DATA", "554 Message rejected: Email address is not verified." ) students = [UserFactory() for _ in xrange(settings.EMAILS_PER_TASK)] for student in students: CourseEnrollmentFactory.create(user=student, course_id=self.course.id) test_email = { 'action': 'Send email', 'to_option': 'all', 'subject': 'test subject for all', 'message': 'test message for all' } self.client.post(self.url, test_email) # We shouldn't retry when hitting a 5xx error self.assertFalse(retry.called) # Test that after the rejected email, the rest still successfully send ((sent, fail, optouts), _) = result.call_args self.assertEquals(optouts, 0) self.assertEquals(fail, 1) self.assertEquals(sent, settings.EMAILS_PER_TASK - 1)
def test_double_denied(self): ''' First graded problem should show message, second shouldn't ''' course = self._create_course() blocks_dict = course['blocks'] blocks_dict['graded_1'] = ItemFactory.create( parent=blocks_dict['vertical'], category='problem', graded=True, metadata=METADATA, ) blocks_dict['graded_2'] = ItemFactory.create( parent=blocks_dict['vertical'], category='problem', graded=True, metadata=METADATA, ) CourseEnrollmentFactory.create( user=self.user, course_id=course['course'].id, mode='audit' ) _assert_block_is_gated( block=blocks_dict['graded_1'], user=self.user, course=course['course'], is_gated=True, request_factory=self.request_factory, ) _assert_block_is_empty( block=blocks_dict['graded_2'], user_id=self.user.id, course=course['course'], request_factory=self.request_factory, )
def test_access_masquerade_as_user_with_forum_role(self, role_name): """ Test that when masquerading as a user with a given forum role you do not lose access to graded content """ staff_user = StaffFactory.create(password=TEST_PASSWORD, course_key=self.course.id) CourseEnrollmentFactory.create( user=staff_user, course_id=self.course.id, mode='audit' ) self.client.login(username=staff_user.username, password=TEST_PASSWORD) user = UserFactory.create() role = RoleFactory(name=role_name, course_id=self.course.id) role.users.add(user) CourseEnrollmentFactory.create( user=user, course_id=self.course.id, mode='audit' ) self.update_masquerade(username=user.username) _assert_block_is_gated( block=self.blocks_dict['problem'], user=user, course=self.course, is_gated=False, request_factory=self.factory, )
def setUpClass(cls): super(CourseTeamTest, cls).setUpClass() cls.course_id = "edx/the-course/1" cls.course1 = create_course(CourseKey.from_string(cls.course_id), TEAMS_CONFIG_1) cls.audit_learner = UserFactory.create(username="******") CourseEnrollmentFactory.create(user=cls.audit_learner, course_id="edx/the-course/1", mode=CourseMode.AUDIT) cls.audit_team = CourseTeamFactory( course_id="edx/the-course/1", team_id="audit-team", topic_id=TEAMSET_1_ID, name="The Team" ) cls.masters_learner = UserFactory.create(username="******") CourseEnrollmentFactory.create(user=cls.masters_learner, course_id="edx/the-course/1", mode=CourseMode.MASTERS) cls.masters_team = CourseTeamFactory( course_id="edx/the-course/1", team_id="masters-team", topic_id=TEAMSET_1_ID, name="The Team", organization_protected=True )
def setUp(self): super(TestOptoutCourseEmails, self).setUp() course_title = u"ẗëṡẗ title イ乇丂イ ᄊ乇丂丂ムg乇 キo尺 ムレレ тэѕт мэѕѕаБэ" self.course = CourseFactory.create(run='testcourse1', display_name=course_title) self.instructor = AdminFactory.create() self.student = UserFactory.create() CourseEnrollmentFactory.create(user=self.student, course_id=self.course.id) # load initial content (since we don't run migrations as part of tests): call_command("loaddata", "course_email_template.json") self.client.login(username=self.student.username, password="******") self.send_mail_url = reverse( 'send_email', kwargs={'course_id': text_type(self.course.id)}) self.success_content = { 'course_id': text_type(self.course.id), 'success': True, } BulkEmailFlag.objects.create(enabled=True, require_course_email_auth=False)
def setUp(self): super(TestGradebook, self).setUp() instructor = AdminFactory.create() self.client.login(username=instructor.username, password='******') self.users = [UserFactory.create() for _ in xrange(USER_COUNT)] for user in self.users: CourseEnrollmentFactory.create(user=user, course_id=self.course.id) for i, item in enumerate(self.items): for j, user in enumerate(self.users): StudentModuleFactory.create(grade=1 if i < j else 0, max_grade=1, student=user, course_id=self.course.id, module_state_key=item.location) self.response = self.client.get( reverse('spoc_gradebook', args=(self.course.id.to_deprecated_string(), ))) self.assertEquals(self.response.status_code, 200)
def setUp(self): super(SupportViewEnrollmentsTests, self).setUp() SupportStaffRole().add_users(self.user) self.course = CourseFactory(display_name=u'teꜱᴛ') self.student = UserFactory.create(username='******', email='*****@*****.**', password='******') for mode in (CourseMode.AUDIT, CourseMode.VERIFIED): CourseModeFactory.create(mode_slug=mode, course_id=self.course.id) # pylint: disable=no-member self.verification_deadline = VerificationDeadline( course_key=self.course.id, # pylint: disable=no-member deadline=datetime.now(UTC) + timedelta(days=365)) self.verification_deadline.save() CourseEnrollmentFactory.create(mode=CourseMode.AUDIT, user=self.student, course_id=self.course.id) # pylint: disable=no-member self.url = reverse('support:enrollment_list', kwargs={'username_or_email': self.student.username})
def test_access_masquerade_as_user_with_forum_role(self, role_name): """ Test that when masquerading as a user with a given forum role you do not lose access to graded content """ staff_user = StaffFactory.create(password=TEST_PASSWORD, course_key=self.course.id) CourseEnrollmentFactory.create(user=staff_user, course_id=self.course.id, mode='audit') self.client.login(username=staff_user.username, password=TEST_PASSWORD) user = UserFactory.create() role = RoleFactory(name=role_name, course_id=self.course.id) role.users.add(user) self.update_masquerade(username=user.username) _assert_block_is_gated( block=self.blocks_dict['problem'], user_id=user.id, course=self.course, is_gated=False, request_factory=self.factory, )
def test_enroll_existing_course_enrollment(self, original_mode, result_mode): course_enrollment = CourseEnrollmentFactory.create( course_id=self.course_key, user=self.user, mode=original_mode) program_course_enrollment = self._create_waiting_program_course_enrollment( ) program_course_enrollment.enroll(self.user) course_enrollment = CourseEnrollment.objects.get( user=self.user, course_id=self.course_key) self.assertEqual(course_enrollment.user, self.user) self.assertEqual(course_enrollment.course.id, self.course_key) self.assertEqual(course_enrollment.mode, result_mode)
def setUp(self): self.course_name = 'edX/toy/2012_Fall' # Create student account student = UserFactory.create() CourseEnrollmentFactory.create(user=student, course_id=self.course_name) self.client.login(username=student.username, password="******") try: # URL for dashboard self.url = reverse('dashboard') except NoReverseMatch: raise SkipTest( "Skip this test if url cannot be found (ie running from CMS tests)" ) # URL for email settings modal self.email_modal_link = (( '<a href="#email-settings-modal" class="email-settings" rel="leanModal" ' 'data-course-id="{0}/{1}/{2}" data-course-number="{1}" ' 'data-optout="False">Email Settings</a>').format( 'edX', 'toy', '2012_Fall'))
def setUp(self): self.course_name = 'edX/toy/2012_Fall' # Create student account student = UserFactory.create() CourseEnrollmentFactory.create( user=student, course_id=SlashSeparatedCourseKey.from_deprecated_string( self.course_name)) self.client.login(username=student.username, password="******") self.url = reverse('dashboard') # URL for email settings modal self.email_modal_link = ( '<a href="#email-settings-modal" class="action action-email-settings" rel="leanModal" ' 'data-course-id="{org}/{num}/{name}" data-course-number="{num}" ' 'data-dashboard-index="0" data-optout="False">Email Settings</a>' ).format( org='edX', num='toy', name='2012_Fall', )
def setUp(self): self.partition = UserPartition( 0, 'first_partition', 'First Partition', [Group(0, 'alpha'), Group(1, 'beta')]) self.course = CourseFactory.create(number=self.COURSE_NUMBER, user_partitions=[self.partition]) self.chapter = ItemFactory.create( parent_location=self.course.location, category="chapter", display_name="test chapter", ) self.sequential = ItemFactory.create( parent_location=self.chapter.location, category="sequential", display_name="Split Test Tests", ) self.student = UserFactory.create() CourseEnrollmentFactory.create(user=self.student, course_id=self.course.id) self.client.login(username=self.student.username, password='******')
def test_with_another_users_username(self, is_staff): """ Test scenario when requested user and logged in user are not same. """ other_user = UserFactory() if is_staff: self.user.is_staff = True self.user.save() CourseEnrollmentFactory.create(user=other_user, course_id=self.course.id) self.login() response = self.api_response(expected_response_code=None, data={ 'course_id': str(self.course.id), 'username': other_user.username }) if is_staff: self.assertEqual(response.status_code, 200) else: self.assertEqual(response.status_code, 403)
def _create_completed_program_course_enrollment(self): """ helper function create program course enrollment """ course_enrollment = CourseEnrollmentFactory.create( course_id=self.course_key, user=self.user, mode=CourseMode.MASTERS ) program_course_enrollment = ProgramCourseEnrollment.objects.create( program_enrollment=self.program_enrollment, course_key=self.course_key, course_enrollment=course_enrollment, status="active" ) return program_course_enrollment
def test_data_err_fail(self, retry, result, get_conn): """ Test that celery handles permanent SMTPDataErrors by failing and not retrying. """ # have every fourth email fail due to blacklisting: get_conn.return_value.send_messages.side_effect = cycle([ SMTPDataError(554, "Email address is blacklisted"), None, None, None ]) # Don't forget to account for the "myself" instructor user students = [ UserFactory() for _ in xrange(settings.BULK_EMAIL_EMAILS_PER_TASK - 1) ] for student in students: CourseEnrollmentFactory.create(user=student, course_id=self.course.id) test_email = { 'action': 'Send email', 'send_to': '["myself", "staff", "learners"]', 'subject': 'test subject for all', 'message': 'test message for all' } response = self.client.post(self.send_mail_url, test_email) self.assertEquals(json.loads(response.content), self.success_content) # We shouldn't retry when hitting a 5xx error self.assertFalse(retry.called) # Test that after the rejected email, the rest still successfully send ((_entry_id, _current_task_id, subtask_status), _kwargs) = result.call_args self.assertEquals(subtask_status.skipped, 0) expected_fails = int((settings.BULK_EMAIL_EMAILS_PER_TASK + 3) / 4.0) self.assertEquals(subtask_status.failed, expected_fails) self.assertEquals(subtask_status.succeeded, settings.BULK_EMAIL_EMAILS_PER_TASK - expected_fails)
def test_grades_view_oauth2(self): """ Test the grades view using OAuth2 Authentication """ self.users_and_problem_setup() CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id) query_string = urlencode({ 'course_id': self.course.id, 'username': self.user.username }) url = '/api/server/mobile/v1/users/courses/grades/?{}'.format( query_string) self.request.user = self.user answer_problem(self.course, self.request, self.problem, score=1, max_value=1) # Try with no authentication: self.client.logout() response = self.client.get(url) self.assertEqual(response.status_code, 401) user_grade = 0.8 StudentGradebook.objects.update_or_create(user=self.user, course_id=self.course.id, defaults={ 'grade': user_grade, 'proforma_grade': 1, 'is_passed': True, }) # Now, try with a valid token header: token = self.create_oauth2_token(self.user) response = self.client.get( url, HTTP_AUTHORIZATION="Bearer {}".format(token)) self.assertEqual(response.status_code, 200) self.assertEqual(response.data['course_grade'], user_grade)
def setUp(self): self.course = CourseFactory.create() self.instructor = InstructorFactory(course=self.course.location) # Create staff self.staff = [ StaffFactory(course=self.course.location) for _ in xrange(STAFF_COUNT) ] # Create students self.students = [UserFactory() for _ in xrange(STUDENT_COUNT)] for student in self.students: CourseEnrollmentFactory.create(user=student, course_id=self.course.id) # load initial content (since we don't run migrations as part of tests): call_command("loaddata", "course_email_template.json") self.client.login(username=self.instructor.username, password="******") # Pull up email view on instructor dashboard self.url = reverse('instructor_dashboard', kwargs={'course_id': self.course.id}) response = self.client.get(self.url) email_link = '<a href="#" onclick="goto(\'Email\')" class="None">Email</a>' # If this fails, it is likely because ENABLE_INSTRUCTOR_EMAIL is set to False self.assertTrue(email_link in response.content) # Select the Email view of the instructor dash session = self.client.session session['idash_mode'] = 'Email' session.save() response = self.client.get(self.url) selected_email_link = '<a href="#" onclick="goto(\'Email\')" class="selectedmode">Email</a>' self.assertTrue(selected_email_link in response.content)
def test_chunked_queries_send_numerous_emails(self, email_mock): """ Test sending a large number of emails, to test the chunked querying """ mock_factory = MockCourseEmailResult() email_mock.side_effect = mock_factory.get_mock_update_subtask_status() added_users = [] for _ in xrange(LARGE_NUM_EMAILS): user = UserFactory() added_users.append(user) CourseEnrollmentFactory.create(user=user, course_id=self.course.id) optouts = [] for i in [1, 3, 9, 10, 18]: # 5 random optouts user = added_users[i] optouts.append(user) optout = Optout(user=user, course_id=self.course.id) optout.save() test_email = { 'action': 'Send email', 'to_option': 'all', 'subject': 'test subject for all', 'message': 'test message for all' } response = self.client.post(self.url, test_email) self.assertContains(response, "Your email was successfully queued for sending.") self.assertEquals( mock_factory.emails_sent, 1 + len(self.staff) + len(self.students) + LARGE_NUM_EMAILS - len(optouts)) outbox_contents = [e.to[0] for e in mail.outbox] should_send_contents = ( [self.instructor.email] + [s.email for s in self.staff] + [s.email for s in self.students] + [s.email for s in added_users if s not in optouts]) self.assertItemsEqual(outbox_contents, should_send_contents)
def test_content_type_gate_for_block(self): ''' Verify that the method returns a content type gate when appropriate ''' course = self._create_course() blocks_dict = course['blocks'] CourseEnrollmentFactory.create( user=self.user, course_id=course['course'].id, mode='audit' ) blocks_dict['graded_1'] = ItemFactory.create( parent=blocks_dict['vertical'], category='problem', graded=True, metadata=METADATA, ) blocks_dict['not_graded_1'] = ItemFactory.create( parent=blocks_dict['vertical'], category='problem', graded=False, metadata=METADATA, ) # The method returns a content type gate for blocks that should be gated self.assertIn( 'content-paywall', ContentTypeGatingService().content_type_gate_for_block( self.user, blocks_dict['graded_1'], course['course'].id ).content ) # The method returns None for blocks that should not be gated self.assertEquals( None, ContentTypeGatingService().content_type_gate_for_block( self.user, blocks_dict['not_graded_1'], course['course'].id ) )
def test_masquerade_in_holdback(self, mock_get_course_run_details): mock_get_course_run_details.return_value = {'weeks_to_complete': 12} audit_student = UserFactory(username='******') CourseEnrollmentFactory.create( user=audit_student, course_id=self.course.id, mode='audit' ) ExperimentData.objects.create( user=audit_student, experiment_id=EXPERIMENT_ID, key=EXPERIMENT_DATA_HOLDBACK_KEY, value='True' ) CourseDurationLimitConfig.objects.create( enabled=True, course=CourseOverview.get_from_id(self.course.id), enabled_as_of=self.course.start, ) instructor = UserFactory.create(username='******') CourseEnrollmentFactory.create( user=instructor, course_id=self.course.id, mode='audit' ) CourseInstructorRole(self.course.id).add_users(instructor) self.client.login(username=instructor.username, password='******') self.update_masquerade(username='******') course_home_url = reverse('openedx.course_experience.course_home', args=[six.text_type(self.course.id)]) response = self.client.get(course_home_url, follow=True) self.assertEqual(response.status_code, 200) self.assertItemsEqual(response.redirect_chain, []) banner_text = 'You lose all access to this course, including your progress,' self.assertNotIn(banner_text, response.content)
def test_enabled_for_enrollment( self, already_enrolled, pass_enrollment, enrolled_before_enabled, ): # Tweak the day to enable the config so that it is either before # or after today (which is when the enrollment will be created) if enrolled_before_enabled: enabled_as_of = date.today() + timedelta(days=1) else: enabled_as_of = date.today() - timedelta(days=1) config = ContentTypeGatingConfig.objects.create( enabled=True, course=self.course_overview, enabled_as_of=enabled_as_of, ) if already_enrolled: existing_enrollment = CourseEnrollmentFactory.create( user=self.user, course=self.course_overview, ) else: existing_enrollment = None if pass_enrollment: enrollment = existing_enrollment user = None course_key = None else: enrollment = None user = self.user course_key = self.course_overview.id if pass_enrollment: query_count = 4 else: query_count = 5 with self.assertNumQueries(query_count): enabled = ContentTypeGatingConfig.enabled_for_enrollment( enrollment=enrollment, user=user, course_key=course_key, ) self.assertEqual(not enrolled_before_enabled, enabled)
def test_send_to_track_other_enrollments(self): """ Failing test for EDUCATOR-217: verifies that emails are only sent to users in a specific track if they're in that track in the course the email is being sent from. """ # Create a mode and designate an enrolled user to be placed in that mode CourseMode.objects.create(mode_slug='test_mode', course_id=self.course.id) test_mode_student = self.students[0] update_enrollment(test_mode_student, six.text_type(self.course.id), 'test_mode') # Take another user already enrolled in the course, then enroll them in # another course but in that same test mode test_mode_student_other_course = self.students[1] other_course = CourseFactory.create() CourseMode.objects.create(mode_slug='test_mode', course_id=other_course.id) CourseEnrollmentFactory.create( user=test_mode_student_other_course, course_id=other_course.id ) update_enrollment(test_mode_student_other_course, six.text_type(other_course.id), 'test_mode') # Send the emails... test_email = { 'action': 'Send email', 'send_to': '["track:test_mode"]', 'subject': 'test subject for test_mode track', 'message': 'test message for test_mode track', } response = self.client.post(self.send_mail_url, test_email) self.assertEquals(json.loads(response.content.decode('utf-8')), self.success_content) # Only the the student in the test mode in the course the email was # sent from should receive an email self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to[0], test_mode_student.email)
def test_enroll_mb_create_external_id(self): course_run_key = self.program['courses'][0]['course_runs'][0]['key'] # Enroll user enrollment = CourseEnrollmentFactory.create( course_id=course_run_key, user=self.user, mode=CourseMode.VERIFIED, ) enrollment.save() external_id = ExternalId.objects.get( user=self.user ) assert external_id is not None assert external_id.external_id_type.name == ExternalIdType.MICROBACHELORS_COACHING
def setUp(self): super(TestGradebook, self).setUp() instructor = AdminFactory.create() self.client.login(username=instructor.username, password='******') self.users = [UserFactory.create() for _ in range(USER_COUNT)] for user in self.users: CourseEnrollmentFactory.create(user=user, course_id=self.course.id) for i, item in enumerate(self.items): for j, user in enumerate(self.users): StudentModuleFactory.create(grade=1 if i < j else 0, max_grade=1, student=user, course_id=self.course.id, module_state_key=item.location) task_compute_all_grades_for_course.apply_async( kwargs={'course_key': text_type(self.course.id)}) self.response = self.client.get( reverse('spoc_gradebook', args=(text_type(self.course.id), ))) self.assertEqual(self.response.status_code, 200)
def setup_partitions_and_course(self, active=True): """ Setup course structure and create user for user partition transformer test. Args: active: boolean representing if the user partitions are active or not """ # Set up user partitions and groups. self.setup_groups_partitions(active=active) self.user_partition = self.user_partitions[0] # Build course. self.course_hierarchy = self.get_course_hierarchy() self.blocks = self.build_course(self.course_hierarchy) self.course = self.blocks['course'] # Enroll user in course. CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id, is_active=True) # Set up cohorts. self.setup_cohorts(self.course)
def test_group_access(self, role_name, course_is_cohorted, thread_group_state): cohort_course = CourseFactory.create(cohort_config={"cohorted": course_is_cohorted}) CourseEnrollmentFactory.create(user=self.user, course_id=cohort_course.id) cohort = CohortFactory.create(course_id=cohort_course.id, users=[self.user]) role = Role.objects.create(name=role_name, course_id=cohort_course.id) role.users = [self.user] thread = self.make_minimal_cs_thread({ "course_id": unicode(cohort_course.id), "group_id": ( None if thread_group_state == "no_group" else cohort.id if thread_group_state == "match_group" else cohort.id + 1 ), }) expected_error = ( role_name == FORUM_ROLE_STUDENT and course_is_cohorted and thread_group_state == "different_group" ) try: self.get_comment_list(thread) self.assertFalse(expected_error) except Http404: self.assertTrue(expected_error)
def setUp(self): super(CertificatesViewsTests, self).setUp() self.client = Client() self.course = CourseFactory.create( org='testorg', number='run1', display_name='refundable course' ) self.course_id = self.course.location.course_key self.user = UserFactory.create( email='*****@*****.**', username='******', password='******' ) self.user.profile.name = "Joe User" self.user.profile.save() self.client.login(username=self.user.username, password='******') self.request = RequestFactory().request() self.cert = GeneratedCertificate.objects.create( user=self.user, course_id=self.course_id, verify_uuid=uuid4(), download_uuid=uuid4(), download_url="http://www.example.com/certificates/download", grade="0.95", key='the_key', distinction=True, status='generated', mode='honor', name=self.user.profile.name, ) CourseEnrollmentFactory.create( user=self.user, course_id=self.course_id ) CertificateHtmlViewConfigurationFactory.create() LinkedInAddToProfileConfigurationFactory.create()
def setUp(self): """ Create a course and user to test with. """ super(BadgeHandlerTestCase, self).setUp() # Need key to be deterministic to test slugs. self.course = CourseFactory.create(org='edX', course='course_test', run='test_run', display_name='Badged', start=datetime(year=2015, month=5, day=19), end=datetime(year=2015, month=5, day=20)) self.user = UserFactory.create(email='*****@*****.**') CourseEnrollmentFactory.create( user=self.user, course_id=self.course.location.course_key, mode='honor') # Need for force empty this dict on each run. BadgeHandler.badges = {} BadgeImageConfigurationFactory()
def create_course(self, modules_count, module_store, topics): """ Create a course in a specified module store with discussion module and topics """ course = CourseFactory.create(org="a", course="b", run="c", start=datetime.now(UTC), default_store=module_store, discussion_topics=topics) CourseEnrollmentFactory.create(user=self.user, course_id=course.id) course_url = reverse("course_topics", kwargs={"course_id": unicode(course.id)}) # add some discussion modules for i in range(modules_count): ItemFactory.create( parent_location=course.location, category='discussion', discussion_id='id_module_{}'.format(i), discussion_category='Category {}'.format(i), discussion_target='Discussion {}'.format(i), publish_item=False, ) return course_url
def setUp(self): """ Create the test data. """ super(CompletionBatchTestCase, self).setUp() self.url = reverse('completion_api:v1:completion-batch') # Enable the waffle flag for all tests _overrider = waffle.waffle().override( waffle.ENABLE_COMPLETION_TRACKING, True) _overrider.__enter__() self.addCleanup(_overrider.__exit__, None, None, None) # Create course self.course = CourseFactory.create(org='TestX', number='101', display_name='Test') self.problem = ItemFactory.create( parent=self.course, category="problem", display_name="Test Problem", ) update_course_structure(unicode(self.course.id)) # Create users self.staff_user = UserFactory(is_staff=True) self.enrolled_user = UserFactory(username=self.ENROLLED_USERNAME) self.unenrolled_user = UserFactory(username=self.UNENROLLED_USERNAME) # Enrol one user in the course CourseEnrollmentFactory.create(user=self.enrolled_user, course_id=self.course.id) # Login the enrolled user by for all tests self.client = APIClient() self.client.force_authenticate(user=self.enrolled_user)
def test_enabled_for_enrollment( self, already_enrolled, pass_enrollment, enrolled_before_enabled, ): # Tweak the datetime to enable the config so that it is either before # or after now (which is when the enrollment will be created) if enrolled_before_enabled: enabled_as_of = timezone.now() + timedelta(days=1) else: enabled_as_of = timezone.now() - timedelta(days=1) CourseDurationLimitConfig.objects.create( enabled=True, course=self.course_overview, enabled_as_of=enabled_as_of, ) if already_enrolled: existing_enrollment = CourseEnrollmentFactory.create( user=self.user, course=self.course_overview, ) else: existing_enrollment = None if pass_enrollment: enrollment = existing_enrollment user = None course_key = None else: enrollment = None user = self.user course_key = self.course_overview.id query_count = 7 if not pass_enrollment and already_enrolled: query_count = 8 with self.assertNumQueries(query_count): enabled = CourseDurationLimitConfig.enabled_for_enrollment( enrollment=enrollment, user=user, course_key=course_key, ) self.assertEqual(not enrolled_before_enabled, enabled)
def make_course_request(self, enable_university_id): """ Requests a course page with a logged and enrolled user. """ course = CourseFactory.create(enable_university_id=enable_university_id) password = '******' user = UserFactory.create(password=password) user.save() enrollment = CourseEnrollmentFactory.create(course_id=course.id, user=user) enrollment.save() self.quick_login(user.username, password) return self.client.get(reverse('progress', args=[unicode(course.id)]))
def create_enrollment(self, expired): """ Create an enrollment """ if expired: course = CourseFactory.create(start=self.THREE_YEARS_AGO, mobile_available=True) enrollment = CourseEnrollmentFactory.create(user=self.user, course_id=course.id) ScheduleFactory(start=self.THREE_YEARS_AGO, enrollment=enrollment) else: course = CourseFactory.create(start=self.LAST_WEEK, mobile_available=True) self.enroll(course.id) add_course_mode(course, upgrade_deadline_expired=False)