def setUp(self): """ Create a course and user, then log in. """ super(StudentDashboardTests, self).setUp() self.user = UserFactory() self.client.login(username=self.user.username, password=PASSWORD) self.path = reverse('dashboard')
def create_user(self): """ Creates a normal student user. """ return UserFactory()
def test_cohort_membership_changed(self, mock_tracker): cohort_list = [CohortFactory() for _ in range(2)] non_cohort = CourseUserGroup.objects.create(name="dummy", course_id=self.course_key, group_type="dummy") user_list = [UserFactory() for _ in range(2)] mock_tracker.reset_mock() def assert_events(event_name_suffix, user_list, cohort_list): """ Confirms the presence of the specifed event for each user in the specified list of cohorts """ expected_calls = [ call( "edx.cohort.user_" + event_name_suffix, { "user_id": user.id, "cohort_id": cohort.id, "cohort_name": cohort.name, }) for user in user_list for cohort in cohort_list ] mock_tracker.emit.assert_has_calls(expected_calls, any_order=True) # Add users to cohort cohort_list[0].users.add(*user_list) assert_events("added", user_list, cohort_list[:1]) mock_tracker.reset_mock() # Remove users from cohort cohort_list[0].users.remove(*user_list) assert_events("removed", user_list, cohort_list[:1]) mock_tracker.reset_mock() # Clear users from cohort cohort_list[0].users.add(*user_list) cohort_list[0].users.clear() assert_events("removed", user_list, cohort_list[:1]) mock_tracker.reset_mock() # Clear users from non-cohort group non_cohort.users.add(*user_list) non_cohort.users.clear() self.assertFalse(mock_tracker.emit.called) # Add cohorts to user user_list[0].course_groups.add(*cohort_list) assert_events("added", user_list[:1], cohort_list) mock_tracker.reset_mock() # Remove cohorts from user user_list[0].course_groups.remove(*cohort_list) assert_events("removed", user_list[:1], cohort_list) mock_tracker.reset_mock() # Clear cohorts from user user_list[0].course_groups.add(*cohort_list) user_list[0].course_groups.clear() assert_events("removed", user_list[:1], cohort_list) mock_tracker.reset_mock() # Clear non-cohort groups from user user_list[0].course_groups.add(non_cohort) user_list[0].course_groups.clear() self.assertFalse(mock_tracker.emit.called)
def setUp(self): super(TestCredentialsSignalsSendGrade, self).setUp() self.user = UserFactory() self.key = CourseKey.from_string(CourseRunFactory()['key'])
def setUp(self): super(CourseModuleCompletionTests, self).setUp() self.user = UserFactory() self._create_course() initialize_notifications()
def setUp(self): super(UserMixin, self).setUp() self.user = UserFactory()
def setUp(self): super(TestWeightedProblems, self).setUp() self.user = UserFactory() self.request = get_mock_request(self.user)
def test_bad_mode(self): user = UserFactory() with pytest.raises(ValueError): update_forum_role(self.course.id, user, FORUM_ROLE_MODERATOR, 'robot-not-a-mode')
def test_allow_twice(self): user = UserFactory() allow_access(self.course, user, 'staff') allow_access(self.course, user, 'staff') self.assertTrue(CourseStaffRole(self.course.id).has_user(user))
def test_revoke_badrolename(self): user = UserFactory() with pytest.raises(ValueError): revoke_access(self.course, user, 'robot-not-a-level')
def test_revoke_notallowed(self): user = UserFactory() update_forum_role(self.course.id, user, FORUM_ROLE_MODERATOR, 'revoke') self.assertNotIn(user, self.mod_role.users.all())
def setUp(self): super(TestCourseRunFullfillableForEntitlement, self).setUp() self.user = UserFactory(is_staff=True) self.client.login(username=self.user.username, password=TEST_PASSWORD)
def test_look_up_valid_registration_code(self): """ test lookup for the valid registration code and that registration code has been redeemed by user and then mark the registration code as in_valid when marking as invalidate, it also lookup for registration redemption entry and also delete that redemption entry and un_enroll the student who used that registration code for their enrollment. """ for i in range(2): CourseRegistrationCode.objects.create( code='reg_code{}'.format(i), course_id=six.text_type(self.course.id), created_by=self.instructor, invoice=self.sale_invoice, invoice_item=self.invoice_item, mode_slug=CourseMode.DEFAULT_MODE_SLUG ) reg_code = CourseRegistrationCode.objects.all()[0] student = UserFactory() enrollment = CourseEnrollment.enroll(student, self.course.id) RegistrationCodeRedemption.objects.create( registration_code=reg_code, redeemed_by=student, course_enrollment=enrollment ) data = { 'registration_code': reg_code.code } response = self.client.get(self.lookup_code_url, data) self.assertEqual(response.status_code, 200) json_dict = json.loads(response.content) self.assertTrue(json_dict['is_registration_code_valid']) self.assertTrue(json_dict['is_registration_code_redeemed']) # now mark that registration code as invalid data = { 'registration_code': reg_code.code, 'action_type': 'invalidate_registration_code' } response = self.client.post(self.registration_code_detail_url, data) self.assertEqual(response.status_code, 200) json_dict = json.loads(response.content) message = _('This enrollment code has been canceled. It can no longer be used.') self.assertEqual(message, json_dict['message']) # now check that the registration code should be marked as invalid in the db. reg_code = CourseRegistrationCode.objects.get(code=reg_code.code) self.assertEqual(reg_code.is_valid, False) redemption = RegistrationCodeRedemption.get_registration_code_redemption(reg_code.code, self.course.id) self.assertIsNone(redemption) # now the student course enrollment should be false. enrollment = CourseEnrollment.get_enrollment(student, self.course.id) self.assertEqual(enrollment.is_active, False)
def setUp(self): """ Create a library, staff user, and non-staff user """ super(TestLibraryAccess, self).setUp() self.non_staff_user_password = '******' self.non_staff_user = UserFactory( password=self.non_staff_user_password, is_staff=False)
def setUp(self): super(TestGetCourseRuns, self).setUp() self.catalog_integration = self.create_catalog_integration(cache_ttl=1) self.user = UserFactory(username=self.catalog_integration.service_username)
def test_allow_ccx_coach(self): user = UserFactory() allow_access(self.course, user, 'ccx_coach') self.assertTrue(CourseCcxCoachRole(self.course.id).has_user(user))
def setUp(self): super(TestEolProgressTabView, self).setUp() # create a course self.course = CourseFactory.create(org='mss', course='999', display_name='eol progress tab') # Patch the comment client user save method so it does not try # to create a new cc user when creating a django user with patch('student.models.cc.User.save'): # Create the student self.student = UserFactory(username='******', password='******', email='*****@*****.**') # Enroll the student in the course CourseEnrollmentFactory(user=self.student, course_id=self.course.id) # Create and Enroll staff user self.staff_user = UserFactory(username='******', password='******', email='*****@*****.**', is_staff=True) CourseEnrollmentFactory(user=self.staff_user, course_id=self.course.id) CourseStaffRole(self.course.id).add_users(self.staff_user) # Log the student in self.client = Client() self.assertTrue( self.client.login(username='******', password='******')) # Log the user staff in self.staff_client = Client() self.assertTrue( self.staff_client.login(username='******', password='******')) # Give course some content (1 chapter, 2 category grades, 3 sections) with self.store.bulk_operations(self.course.id, emit_signals=False): chapter = ItemFactory.create( parent_location=self.course.location, category="sequential", ) # Homework section = ItemFactory.create(parent_location=chapter.location, category="sequential", metadata={ 'graded': True, 'format': 'Homework' }) self.items = [ ItemFactory.create( parent_location=section.location, category="problem", data=StringResponseXMLFactory().build_xml(answer='foo'), metadata={'rerandomize': 'always'}) for __ in range(5) ] # Homework_2 section_2 = ItemFactory.create(parent_location=chapter.location, category="sequential", metadata={ 'graded': True, 'format': 'Homework_2' }) self.items_2 = [ ItemFactory.create( parent_location=section_2.location, category="problem", data=StringResponseXMLFactory().build_xml(answer='foo'), metadata={'rerandomize': 'always'}) for __ in range(5) ] # Homework_2 section_3 = ItemFactory.create(parent_location=chapter.location, category="sequential", metadata={ 'graded': True, 'format': 'Homework_2' }) self.items_2 = [ ItemFactory.create( parent_location=section_3.location, category="problem", data=StringResponseXMLFactory().build_xml(answer='foo'), metadata={'rerandomize': 'always'}) for __ in range(5) ]
def test_allow_beta(self): """ Test allow beta against list beta. """ user = UserFactory() allow_access(self.course, user, 'beta') self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(user))
def setUp(self): self.course_key = SlashSeparatedCourseKey('robot', 'course', 'id') self.users = tuple(UserFactory() for _ in xrange(30)) self.ces = tuple(CourseEnrollment.enroll(user, self.course_key) for user in self.users) self.instructor = InstructorFactory(course_key=self.course_key)
def test_allow_badlevel(self): user = UserFactory() with pytest.raises(ValueError): allow_access(self.course, user, 'robot-not-a-level')
def test_cert_changed(self, mock_send_grade_if_interesting): user = UserFactory() self.assertFalse(mock_send_grade_if_interesting.called) GeneratedCertificateFactory(user=user) self.assertTrue(mock_send_grade_if_interesting.called)
def setUpTestData(cls): """Set up and enroll our fake user in the course.""" cls.user = UserFactory(password=TEST_PASSWORD) CourseEnrollment.enroll(cls.user, cls.course.id)
def test_reindex_no_permissions(self): # register a non-staff member and try to delete the course branch user2 = UserFactory() with self.assertRaises(PermissionDenied): reindex_course_and_check_access(self.course.id, user2)
def setUp(self): super(TestJwtBuilder, self).setUp() self.user = UserFactory() self.profile = UserProfileFactory(user=self.user)
def test_custom_form(self): """ Use the Google provider to test the custom login/register form feature. """ # The pipeline starts by a user GETting /auth/login/google-oauth2/?auth_entry=custom1 # Synthesize that request and check that it redirects to the correct # provider page. auth_entry = 'custom1' # See definition in lms/envs/test.py login_url = pipeline.get_login_url(self.provider.provider_id, auth_entry) login_url += "&next=/misc/final-destination" self.assert_redirect_to_provider_looks_correct( self.client.get(login_url)) def fake_auth_complete(inst, *args, **kwargs): """ Mock the backend's auth_complete() method """ kwargs.update({ 'response': self.get_response_data(), 'backend': inst }) return inst.strategy.authenticate(*args, **kwargs) # Next, the provider makes a request against /auth/complete/<provider>. complete_url = pipeline.get_complete_url(self.provider.backend_name) with patch.object(self.provider.backend_class, 'auth_complete', fake_auth_complete): response = self.client.get(complete_url) # This should redirect to the custom login/register form: self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], '/auth/custom_auth_entry') response = self.client.get(response['Location']) self.assertEqual(response.status_code, 200) self.assertIn( 'action="/misc/my-custom-registration-form" method="post"', response.content.decode('utf-8')) data_decoded = base64.b64decode( response.context['data']).decode('utf-8') data_parsed = json.loads(data_decoded) # The user's details get passed to the custom page as a base64 encoded query parameter: self.assertEqual( data_parsed, { 'auth_entry': 'custom1', 'backend_name': 'google-oauth2', 'provider_id': 'oa2-google-oauth2', 'user_details': { 'username': '******', 'email': '*****@*****.**', 'fullname': 'name_value', 'first_name': 'given_name_value', 'last_name': 'family_name_value', }, }) # Check the hash that is used to confirm the user's data in the GET parameter is correct secret_key = settings.THIRD_PARTY_AUTH_CUSTOM_AUTH_FORMS['custom1'][ 'secret_key'] hmac_expected = hmac.new(secret_key.encode('utf-8'), msg=data_decoded.encode('utf-8'), digestmod=hashlib.sha256).digest() self.assertEqual(base64.b64decode(response.context['hmac']), hmac_expected) # Now our custom registration form creates or logs in the user: email, password = data_parsed['user_details'][ 'email'], 'random_password' created_user = UserFactory(email=email, password=password) login_response = self.client.post(reverse('login'), { 'email': email, 'password': password }) self.assertEqual(login_response.status_code, 200) # Now our custom login/registration page must resume the pipeline: response = self.client.get(complete_url) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], '/misc/final-destination') _, strategy = self.get_request_and_strategy() self.assert_social_auth_exists_for_user(created_user, strategy)
def setUp(self): super(UsernameReplacementViewTests, self).setUp() self.service_user = UserFactory(username=self.SERVICE_USERNAME) self.url = reverse("username_replacement")
def setUp(self): super(TestLoginWithAccessTokenView, self).setUp() self.user = UserFactory() self.oauth2_client = Client.objects.create(client_type=provider.constants.CONFIDENTIAL)
def setUp(self): """ Create a course and user, then log in. """ super(LogoutTests, self).setUp() self.user = UserFactory() self.client.login(username=self.user.username, password=PASSWORD)
def test_add_user_to_cohort(self, mock_signal, mock_tracker): """ Make sure cohorts.add_user_to_cohort() properly adds a user to a cohort and handles errors. """ course_user = UserFactory(username="******", email="*****@*****.**") UserFactory(username="******", email="*****@*****.**") course = modulestore().get_course(self.toy_course_key) CourseEnrollment.enroll(course_user, self.toy_course_key) first_cohort = CohortFactory(course_id=course.id, name="FirstCohort") second_cohort = CohortFactory(course_id=course.id, name="SecondCohort") def check_and_reset_signal(): mock_signal.send.assert_called_with(sender=None, user=course_user, course_key=self.toy_course_key) mock_signal.reset_mock() # Success cases # We shouldn't get back a previous cohort, since the user wasn't in one self.assertEqual(cohorts.add_user_to_cohort(first_cohort, "Username"), (course_user, None, False)) mock_tracker.emit.assert_any_call( "edx.cohort.user_add_requested", { "user_id": course_user.id, "cohort_id": first_cohort.id, "cohort_name": first_cohort.name, "previous_cohort_id": None, "previous_cohort_name": None, }) check_and_reset_signal() # Should get (user, previous_cohort_name) when moved from one cohort to # another self.assertEqual(cohorts.add_user_to_cohort(second_cohort, "Username"), (course_user, "FirstCohort", False)) mock_tracker.emit.assert_any_call( "edx.cohort.user_add_requested", { "user_id": course_user.id, "cohort_id": second_cohort.id, "cohort_name": second_cohort.name, "previous_cohort_id": first_cohort.id, "previous_cohort_name": first_cohort.name, }) check_and_reset_signal() # Should preregister email address for a cohort if an email address # not associated with a user is added (user, previous_cohort, prereg) = cohorts.add_user_to_cohort(first_cohort, "*****@*****.**") self.assertEqual((user, previous_cohort, prereg), (None, None, True)) mock_tracker.emit.assert_any_call( "edx.cohort.email_address_preassigned", { "user_email": "*****@*****.**", "cohort_id": first_cohort.id, "cohort_name": first_cohort.name, }) # Error cases # Should get ValueError if user already in cohort self.assertRaises( ValueError, lambda: cohorts.add_user_to_cohort(second_cohort, "Username")) # UserDoesNotExist if user truly does not exist self.assertRaises( User.DoesNotExist, lambda: cohorts.add_user_to_cohort( first_cohort, "non_existent_username"))
def setUp(self): """ Create a course and user, then log in. """ super(LogoutTests, self).setUp() self.user = UserFactory() self.client.login(username=self.user.username, password=PASSWORD) LogoutViewConfiguration.objects.create(enabled=True)