def test_get_enterprise_customer_for_user(self): """ Test `get_enterprise_customer_for_user` helper method. """ faker = FakerFactory.create() provider_id = faker.slug() user = UserFactory() ecu = EnterpriseCustomerUserFactory(user_id=user.id, ) EnterpriseCustomerIdentityProviderFactory( enterprise_customer=ecu.enterprise_customer, provider_id=provider_id, ) # Assert that correct enterprise customer is returned self.assertEqual( utils.get_enterprise_customer_for_user(auth_user=user), ecu.enterprise_customer, ) # Assert that None is returned if user is not associated with any enterprise customer self.assertEqual( utils.get_enterprise_customer_for_user(auth_user=UserFactory()), None, )
def setUp(self) -> None: super().setUp() self.teacher_1 = UserFactory() self.teacher_2 = UserFactory() self.classroom_1 = ClassroomFactory.create(school=FAKE_UUIDS[0]) self.classroom_2 = ClassroomFactory.create(school=FAKE_UUIDS[0]) self.classroom_3 = ClassroomFactory.create(school=FAKE_UUIDS[0]) self.classroom_4 = ClassroomFactory.create(school=FAKE_UUIDS[1]) self.enrollment_1 = ClassroomEnrollmentFactory.create( classroom_instance=self.classroom_1, user_id=self.teacher_1.email) self.enrollment_2 = ClassroomEnrollmentFactory.create( classroom_instance=self.classroom_2, user_id=self.teacher_1.email) self.enrollment_3 = ClassroomEnrollmentFactory.create( classroom_instance=self.classroom_3, user_id=self.teacher_2.email) self.client.login(username=self.teacher_1, password=USER_PASSWORD) # Classroom URLs self.classroom_list_url = reverse("api:v1:classrooms-list") self.classroom_detail_url = reverse( "api:v1:classrooms-detail", kwargs={"classroom_uuid": self.classroom_1.uuid}, ) self.classroom_enroll_url = reverse( "api:v1:classrooms-enroll", kwargs={"classroom_uuid": str(self.classroom_1.uuid)}, ) self.courses_list_url = reverse( "api:v1:classrooms-courses", kwargs={"classroom_uuid": str(self.classroom_1.uuid)}, )
def test_inactive_email(self): backend = EmailBackend() credentials = {'email': '*****@*****.**', 'password': '******'} user = UserFactory(**credentials) user.is_active = False user.save() self.assertIsNone(backend.authenticate(**credentials))
def test_unlink_user_existing_user(self, email): other_email = "*****@*****.**" user1, user2 = UserFactory(email=email), UserFactory(email=other_email) enterprise_customer1, enterprise_customer2 = EnterpriseCustomerFactory( ), EnterpriseCustomerFactory() EnterpriseCustomerUserFactory(enterprise_customer=enterprise_customer1, user_id=user1.id) EnterpriseCustomerUserFactory(enterprise_customer=enterprise_customer1, user_id=user2.id) EnterpriseCustomerUserFactory(enterprise_customer=enterprise_customer2, user_id=user1.id) assert len(EnterpriseCustomerUser.objects.all()) == 3 query_method = EnterpriseCustomerUser.objects.filter EnterpriseCustomerUser.objects.unlink_user(enterprise_customer1, email) # removes what was asked assert len( query_method(enterprise_customer=enterprise_customer1, user_id=user1.id)) == 0 # keeps records of the same user with different EC (though it shouldn't be the case) assert len( query_method(enterprise_customer=enterprise_customer2, user_id=user1.id)) == 1 # keeps records of other users assert len(query_method(user_id=user2.id)) == 1
def setUp(self): self.api_user = UserFactory(username='******') self.user = UserFactory() self.course_id = COURSE_ID self.enterprise_customer = EnterpriseCustomerFactory() self.identity_provider = FakerFactory.create().slug() EnterpriseCustomerIdentityProviderFactory( provider_id=self.identity_provider, enterprise_customer=self.enterprise_customer) self.enterprise_customer_user = EnterpriseCustomerUserFactory( user_id=self.user.id, enterprise_customer=self.enterprise_customer, ) self.enrollment = EnterpriseCourseEnrollmentFactory( enterprise_customer_user=self.enterprise_customer_user, course_id=self.course_id, consent_granted=True, ) self.integrated_channel = SAPSuccessFactorsEnterpriseCustomerConfiguration( enterprise_customer=self.enterprise_customer, sapsf_base_url='enterprise.successfactors.com', key='key', secret='secret', ) super(TestTransmitLearnerData, self).setUp()
def test_clean_existing_username(self, username, expected_email): UserFactory(username="******", email="*****@*****.**", id=1) UserFactory(username="******", email="*****@*****.**", id=2) form = self._make_bound_form(username) assert form.is_valid() cleaned_data = form.clean() assert cleaned_data[ManageLearnersForm.Fields.EMAIL_OR_USERNAME] == expected_email
def test_clean_existing_username(self, username, expected_email): UserFactory(username="******", email="*****@*****.**") UserFactory(username="******", email="*****@*****.**") form = self._make_bound_form(username) assert form.is_valid() cleaned_data = form.clean() assert cleaned_data["email"] == expected_email
def setUp(self): """ Setup for `TestCourseEnrollmentSignals` test. """ self.user = UserFactory(id=2, email='*****@*****.**') self.enterprise_customer = EnterpriseCustomerFactory( name='Team Titans', ) self.enterprise_customer_user = EnterpriseCustomerUserFactory( user_id=self.user.id, enterprise_customer=self.enterprise_customer, ) self.non_enterprise_user = UserFactory(id=999, email='*****@*****.**') super(TestCourseEnrollmentSignals, self).setUp()
def test_post_patch_real_social_auth_enabled( self, mock_get_ec, mock_get_rsa, mock_get_ec2, mock_url, mock_render, mock_config, mock_lift, mock_quarantine, ): # pylint: disable=unused-argument """ Test an enforced request with consent and rendering patched in. """ customer = EnterpriseCustomerFactory() mock_get_ec.return_value = customer mock_get_ec2.return_value = customer mock_get_rsa.return_value = mock.MagicMock(user=UserFactory()) mock_url.return_value = '/' client = Client() session = client.session session['partial_pipeline'] = {'backend': 'fake_backend'} session.save() response = client.post(self.url, {'data_sharing_consent': True}) assert UserDataSharingConsentAudit.objects.all().count() == 1 assert EnterpriseCustomerUser.objects.all().count() == 1 assert UserDataSharingConsentAudit.objects.all()[0].enabled assert response.status_code == 302
def test_post_patch_real_social_auth_enforced( self, mock_get_ec, mock_get_rsa, mock_get_ec2, mock_url, mock_render, mock_config, mock_lift, mock_quarantine, ): # pylint: disable=unused-argument """ Test an enforecd request without consent. """ customer = EnterpriseCustomerFactory() mock_get_ec.return_value = customer mock_get_ec2.return_value = customer mock_get_rsa.return_value = mock.MagicMock(user=UserFactory()) with raises(NoReverseMatch) as excinfo: client = Client() session = client.session session['partial_pipeline'] = True session.save() client.post(self.url) expected = ( 'Reverse for \'dashboard\' with arguments \'()\' and keyword ' 'arguments \'{}\' not found. 0 pattern(s) tried: []' ) assert str(excinfo.value) == expected # Ensure that when consent hasn't been provided, we don't link the user to the Enterprise Customer. assert UserDataSharingConsentAudit.objects.all().count() == 0 assert EnterpriseCustomerUser.objects.all().count() == 0
def test_handle_user_post_save_modified_user_already_linked(self): email = "*****@*****.**" user = UserFactory(id=1, email=email) enterprise_customer1, enterprise_customer2 = EnterpriseCustomerFactory( ), EnterpriseCustomerFactory() existing_link = EnterpriseCustomerUserFactory( enterprise_customer=enterprise_customer1, user_id=user.id) PendingEnterpriseCustomerUserFactory( enterprise_customer=enterprise_customer2, user_email=email) assert len(EnterpriseCustomerUser.objects.filter( user_id=user.id)) == 1, "Precondition check: links exists" assert len(PendingEnterpriseCustomerUser.objects.filter(user_email=email)) == 1, \ "Precondition check: pending link exists" parameters = {"instance": user, "created": False} handle_user_post_save(mock.Mock(), **parameters) link = EnterpriseCustomerUser.objects.get(user_id=user.id) # TODO: remove suppression when https://github.com/landscapeio/pylint-django/issues/78 is fixed assert link.id == existing_link.id, "Should keep existing link intact" # pylint: disable=no-member assert link.enterprise_customer == enterprise_customer1, "Should keep existing link intact" assert len(PendingEnterpriseCustomerUser.objects.all() ) == 0, "Should delete pending link"
def test_handle_user_post_save_with_pending_course_enrollment( self, mock_course_enrollment, mock_course_key): mock_course_key.from_string.return_value = None mock_course_enrollment.enroll.return_value = None email = "*****@*****.**" user = UserFactory(id=1, email=email) pending_link = PendingEnterpriseCustomerUserFactory(user_email=email) pending_enrollment = PendingEnrollmentFactory(user=pending_link) assert len(EnterpriseCustomerUser.objects.filter( user_id=user.id)) == 0, "Precondition check: no links exists" assert len(PendingEnterpriseCustomerUser.objects.filter(user_email=email)) == 1, \ "Precondition check: pending link exists" assert len(PendingEnrollment.objects.filter( user=pending_link)) == 1, 'Check that only one enrollment exists.' parameters = {'instance': user, "created": False} handle_user_post_save(mock.Mock(), **parameters) assert len(PendingEnterpriseCustomerUser.objects.all()) == 0 assert len( EnterpriseCustomerUser.objects.filter( enterprise_customer=pending_link.enterprise_customer, user_id=user.id)) == 1 assert len(PendingEnrollment.objects.all()) == 0 assert len(EnterpriseCourseEnrollment.objects.all()) == 1 mock_course_enrollment.enroll.assert_called_once_with( user, None, mode='audit', check_access=True) mock_course_key.from_string.assert_called_once_with( pending_enrollment.course_id)
def test_one_user_with_membership(self, client): """ Test JSON format for a user with membership. """ user = UserFactory.create() UserOrganizationMappingFactory.create(user=user, organization=self.my_org) membership = MembershipFactory.create(group__organization=self.my_org, user=user) response = client.get('{}{}/'.format(self.url, user.id)) assert response.status_code == HTTP_200_OK, response.content result = response.json() assert result == { 'id': user.id, 'email': user.email, 'name': user.profile.name, 'username': user.username, 'membership': { 'id': membership.id, 'group': { 'id': membership.group.id, 'name': membership.group.name, } }, }, 'Verify the serializer results.'
def test_force_fresh_session_param_not_received( self, mock_get_identity_provider): """ Test that the force_fresh_session decorator redirects authenticated users with the appropriate provider config depending on the IdPs configuration. """ mock_get_identity_provider.return_value.configure_mock( provider_id=self.provider_id, ) view_function = mock_view_function() course_id = 'course-v1:edX+DemoX+Demo_Course' url_path = reverse( 'enterprise_course_run_enrollment_page', args=[self.customer.uuid, course_id], ) query = 'foo=bar' # Adding query parameter here to verify # the redirect URL is getting escaped properly. url = '{path}?{query}'.format(path=url_path, query=query) request = self._prepare_request(url, UserFactory(is_active=True)) response = force_fresh_session(view_function)( request, enterprise_uuid=self.customer.uuid, course_id=course_id) # Assert that redirect status code 302 is returned assert response.status_code == 302 # Assert the redirect URL query string is intact. redirect_url_query = parse_qs(urlparse(response.url).query) assert urlparse(unquote( redirect_url_query['redirect_url'][0])).query == query
def test_ready_disconnects_user_post_save_handler_for_migration(self): self.app_config.ready() pre_migrate.send(mock.Mock()) UserFactory() assert not self.post_save_mock.called
def setUp(self): self.user = UserFactory.create(username='******', is_staff=True, is_active=True) self.user.set_password("QWERTY") self.user.save() self.client = Client() get_dsc = mock.patch('enterprise.views.get_data_sharing_consent') self.get_data_sharing_consent = get_dsc.start() self.addCleanup(get_dsc.stop) course_catalog_api_client = mock.patch( 'enterprise.api_client.discovery.CourseCatalogApiServiceClient') self.course_catalog_api_client = course_catalog_api_client.start() self.addCleanup(course_catalog_api_client.stop) self.enterprise_customer = EnterpriseCustomerFactory( name='Starfleet Academy', enable_data_sharing_consent=True, enforce_data_sharing_consent='at_enrollment', ) self.ecu = EnterpriseCustomerUserFactory( user_id=self.user.id, enterprise_customer=self.enterprise_customer) self.valid_get_params = { 'enterprise_customer_uuid': self.enterprise_customer.uuid, 'next': 'https://google.com/', 'failure_url': 'https://facebook.com/', 'program_uuid': 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', } self.valid_post_params = { 'enterprise_customer_uuid': self.enterprise_customer.uuid, 'redirect_url': 'https://google.com/', 'failure_url': 'https://facebook.com/', 'program_uuid': 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'data_sharing_consent': 'true', } super(TestProgramDataSharingPermissions, self).setUp()
def test_site_staff_have_access(self, default_has_access): """ Site-wide staff access is controlled by the platform `default_has_access`. """ staff = UserFactory.create(is_staff=True) assert user_has_access(staff, self.course, default_has_access, {}) == default_has_access
def test_consent_necessary_for_course(self, consent_provided_state, ec_consent_enabled, ec_consent_enforcement, expected_result): user = UserFactory() enterprise_customer = EnterpriseCustomerFactory( enable_data_sharing_consent=ec_consent_enabled, enforce_data_sharing_consent=ec_consent_enforcement, ) enterprise_user = EnterpriseCustomerUserFactory( user_id=user.id, enterprise_customer=enterprise_customer) course_id = 'course-v1:edX+DemoX+Demo_Course' enrollment = EnterpriseCourseEnrollment.objects.create( enterprise_customer_user=enterprise_user, consent_granted=consent_provided_state, course_id=course_id) assert consent_necessary_for_course(user, course_id) is expected_result account_consent = UserDataSharingConsentAuditFactory( user=enterprise_user, state=UserDataSharingConsentAudit.ENABLED, ) assert consent_necessary_for_course(user, course_id) is False account_consent.delete() # pylint: disable=no-member enrollment.delete() assert consent_necessary_for_course(user, course_id) is False
def test_handle_user_post_save_modified_user_already_linked(self): email = "*****@*****.**" user = UserFactory(id=1, email=email) enterprise_customer1, enterprise_customer2 = EnterpriseCustomerFactory(), EnterpriseCustomerFactory() EnterpriseCustomerUserFactory(enterprise_customer=enterprise_customer1, user_id=user.id) PendingEnterpriseCustomerUserFactory(enterprise_customer=enterprise_customer2, user_email=email) assert EnterpriseCustomerUser.objects.filter(user_id=user.id).count() == 1, "Precondition check: links exists" assert PendingEnterpriseCustomerUser.objects.filter(user_email=email).count() == 1, \ "Precondition check: pending link exists" parameters = {"instance": user, "created": False} handle_user_post_save(mock.Mock(), **parameters) assert EnterpriseCustomerUser.objects.filter(user_id=user.id).count() == 2, "Should return 2 existing links" link_1 = EnterpriseCustomerUser.objects.get( user_id=user.id, enterprise_customer=enterprise_customer1, ) link_2 = EnterpriseCustomerUser.objects.get( user_id=user.id, enterprise_customer=enterprise_customer2, ) assert link_1.enterprise_customer == enterprise_customer1 assert link_2.enterprise_customer == enterprise_customer2 assert PendingEnterpriseCustomerUser.objects.count() == 0, "Should delete pending link"
def test_transmit_courseware_task_no_catalog(fake_catalog_client, caplog): """ Test the data transmission task. """ fake_catalog_client.return_value = mock.MagicMock( get_course_details=get_course_details, get_catalog_courses=get_catalog_courses, ) caplog.set_level(logging.INFO) UserFactory(username='******') enterprise_customer = EnterpriseCustomerFactory( catalog=None, name='Veridian Dynamics', ) SAPSuccessFactorsEnterpriseCustomerConfiguration.objects.create( enterprise_customer=enterprise_customer, sapsf_base_url='http://enterprise.successfactors.com/', key='key', secret='secret', active=True, ) call_command('transmit_courseware_data', '--catalog_user', 'C-3PO') # Because there are no EnterpriseCustomers with a catalog, the process will end early. assert len(caplog.records) == 0
def test_inactive_user(self): """ Ensure inactive user don't get a rule by mistake. """ user = UserFactory.create(is_active=False) with pytest.raises(ValueError): on_learner_account_activated(self.__class__, user)
def setUp(self): self.user = UserFactory.create(is_staff=True, is_active=True) self.enterprise_customer = EnterpriseCustomerFactory( name='Starfleet Academy', ) self.enterprise_catalog = EnterpriseCustomerCatalogFactory( enterprise_customer=self.enterprise_customer) super().setUp()
def test_handle_user_post_save_with_pending_enterprise_admin(self, mock_create_tableau_user): email = "*****@*****.**" user = UserFactory(id=1, email=email) enterprise_customer = EnterpriseCustomerFactory() PendingEnterpriseCustomerAdminUserFactory(enterprise_customer=enterprise_customer, user_email=email) assert PendingEnterpriseCustomerAdminUser.objects.filter(user_email=email).count() == 1, \ "Precondition check: pending admin user exists" parameters = {"instance": user, "created": False} handle_user_post_save(mock.Mock(), **parameters) assert EnterpriseCustomerUser.objects.filter(user_id=user.id).count() == 1, \ "Precondition check: enterprise customer user exists" enterprise_customer_user = EnterpriseCustomerUser.objects.get(user_id=user.id) enterprise_admin_role, __ = SystemWideEnterpriseRole.objects.get_or_create(name=ENTERPRISE_ADMIN_ROLE) admin_role_assignment = SystemWideEnterpriseUserRoleAssignment.objects.filter( user=user, role=enterprise_admin_role, ) assert admin_role_assignment.exists() mock_create_tableau_user.assert_called_once_with( str(enterprise_customer.uuid).replace('-', ''), enterprise_customer_user, ) assert PendingEnterpriseCustomerAdminUser.objects.filter(user_email=email).count() == 0, \ "Final check: pending admin user no longer exists"
def setUp(self): """ Setup the test cases. """ super(TestIsInEnterpriseGroupPermissions, self).setUp() self.user = UserFactory(email='*****@*****.**', password='******', is_staff=True) self.permissions_class_map['enterprise_data_api_access'].ALLOWED_API_GROUPS = ['enterprise_data_api_access']
def setUp(self): """ Setup for `TestEnterpriseAnalyticsUserSignals` test. """ self.admin_user = UserFactory(id=2, email='*****@*****.**') self.enterprise_customer = EnterpriseCustomerFactory() super(TestEnterpriseAnalyticsUserSignals, self).setUp()
def test_superuser_have_access(self, default_has_access): """ Superusers access is controlled by the platform `default_has_access`. """ superuser = UserFactory.create(is_superuser=True) assert user_has_access(superuser, self.course, default_has_access, {}) == default_has_access
def test_social_auth_user_login_associated_with_one_enterprise(self, new_association, backend_name, multiple_enterprises_feature): """ Test that if socialAuth user has edx attached account and is part of one enterprises then redirection url is not changed """ kwargs = {'new_association': new_association} backend = self.get_mocked_sso_backend() backend.name = backend_name backend.strategy.session_get.return_value = 'not-an-enrollment-url' self.user = UserFactory(is_active=True) multiple_enterprises_feature.return_value = True enterprise_customer = EnterpriseCustomerFactory( enable_data_sharing_consent=False ) EnterpriseCustomerUser.objects.create( enterprise_customer=enterprise_customer, user_id=self.user.id, active=False ) with mock.patch('enterprise.tpa_pipeline.get_enterprise_customer_for_running_pipeline') as fake_get_ec: with mock.patch('enterprise.tpa_pipeline.select_enterprise_page_as_redirect_url') as ent_page_redirect: # pylint: disable=invalid-name fake_get_ec.return_value = None handle_enterprise_logistration(backend, self.user, **kwargs) ent_page_redirect.assert_not_called()
def test_enterprise_login_required(self): """ Test that the enterprise login decorator calls the view function. Test that the decorator `enterprise_login_required` calls the view function when: 1. `enterprise_uuid` is provided and corresponding enterprise customer exists in database. 2. User making the request is authenticated. """ view_function = mock_view_function() course_id = 'course-v1:edX+DemoX+Demo_Course' enterprise_launch_url = reverse( 'enterprise_course_run_enrollment_page', args=[self.customer.uuid, course_id], ) request = self._prepare_request(enterprise_launch_url, UserFactory(is_active=True)) enterprise_login_required(view_function)( request, enterprise_uuid=self.customer.uuid, course_id=course_id) # Assert that view function was called. assert view_function.called
def test_handle_enterprise_logistration_user_multiple_enterprises_linking(self): """ Test that if user has multiple enterprise_customers then active status of latest enterprise_customer with which user is logged in will be marked as True and active status of other enterprise_customers will be marked as False. """ backend = self.get_mocked_sso_backend() self.user = UserFactory(is_active=True) with mock.patch('enterprise.tpa_pipeline.get_enterprise_customer_for_running_pipeline') as fake_get_ec: enterprise_customer = EnterpriseCustomerFactory( enable_data_sharing_consent=False ) enterprise_customer_old = EnterpriseCustomerFactory( enable_data_sharing_consent=False ) EnterpriseCustomerUser.objects.create( enterprise_customer=enterprise_customer_old, user_id=self.user.id, active=True ) fake_get_ec.return_value = enterprise_customer assert handle_enterprise_logistration(backend, self.user) is None assert EnterpriseCustomerUser.objects.filter( enterprise_customer=enterprise_customer, user_id=self.user.id, active=True ).count() == 1 assert EnterpriseCustomerUser.objects.filter( enterprise_customer=enterprise_customer_old, user_id=self.user.id, active=False ).count() == 1
def test_not_staff_but_in_group_permissions(self): user = UserFactory(email='*****@*****.**', password='******', is_staff=False) for group_name in self.permissions_class_map: group = GroupFactory(name=group_name) group.user_set.add(user) request = self.get_request(user=user) self.assertTrue(self.permissions_class_map[group_name].has_permission(request, None))
def setUp(self): email = '*****@*****.**' course_id = 'course-v1:edX+DemoX+DemoCourse' pending_link = PendingEnterpriseCustomerUserFactory(user_email=email) self.enrollment = PendingEnrollmentFactory(user=pending_link, course_id=course_id) self.user = UserFactory(email=email) super(TestPendingEnrollment, self).setUp()