示例#1
0
 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()
示例#2
0
 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.'
示例#3
0
 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_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)
示例#5
0
 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 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()
示例#7
0
def standard_test_users():
    """
    Fixture of four test users to test the combination of permissions.

        * regular_user (is_staff=False, is_superuser=False)
        * staff_user (is_staf=True, is_superuser=False)
        * super_user (is_staff=False, is_superuser=True)
        * superstaff_user (is_staff=True, is_superuser=True)
    """
    return [
        UserFactory.create(username='******'),
        UserFactory.create(username='******', is_staff=True),
        UserFactory.create(username='******', is_superuser=True),
        UserFactory.create(username='******',
                           is_staff=True,
                           is_superuser=True)
    ]
示例#8
0
 def users_setup(self):
     omar = UserFactory.create(email=self.non_member_email)
     user1 = MembershipFactory.create(user__email=self.member_email).user
     user2 = MembershipFactory.create().user
     UserOrganizationMappingFactory.create_for(
         self.my_org,
         users=[omar, user1, user2],
     )
示例#9
0
 def setUp(self):
     self.user_1 = UserFactory.create(is_active=True)
     self.enterprise_customer_1 = EnterpriseCustomerFactory(
         name='Test EnterpriseCustomer 1',
         enable_data_sharing_consent=True,
         enforce_data_sharing_consent='at_enrollment',
     )
     self.enterprise_customer_user_1 = EnterpriseCustomerUserFactory(
         user_id=self.user_1.id,
         enterprise_customer=self.enterprise_customer_1)
     self.user_2 = UserFactory.create(is_active=True)
     self.enterprise_customer_2 = EnterpriseCustomerFactory(
         name='Test EnterpriseCustomer 2',
         enable_data_sharing_consent=True,
         enforce_data_sharing_consent='at_enrollment',
     )
     self.enterprise_customer_user_2 = EnterpriseCustomerUserFactory(
         user_id=self.user_2.id,
         enterprise_customer=self.enterprise_customer_2)
     super(SaveEnterpriseCustomerUsersCommandTests, self).setUp()
示例#10
0
 def setUp(self):
     self.course_run_id = 'course-v1:edX+DemoX+Demo_Course'
     self.user = UserFactory.create(is_staff=True, is_active=True)
     self.enterprise_customer = EnterpriseCustomerFactory(
         name='Starfleet Academy',
         enable_data_sharing_consent=True,
         enforce_data_sharing_consent='at_enrollment',
     )
     self.enterprise_customer_user = EnterpriseCustomerUserFactory(
         user_id=self.user.id, enterprise_customer=self.enterprise_customer)
     super(CreateEnterpriseCourseEnrollmentCommandTests, self).setUp()
示例#11
0
    def test_on_customer_site(self):
        """
        Customer sites can use CAG APIs.
        """
        site = SiteFactory.create(domain='my_site.org')
        expected_org = OrganizationFactory.create(sites=[site])
        non_superuser = UserFactory.create()
        request = Mock(site=site, user=non_superuser, GET={})

        requested_org = get_requested_organization(request)
        assert requested_org == expected_org, 'Should return the site organization'
示例#12
0
    def test_org_admins_have_access(self, default_has_access):
        """
        Organization-wide admins have access to all org courses.
        """
        user = UserFactory.create()
        organization = OrganizationFactory.create()
        OrganizationCourse.objects.create(course_id=str(self.course.id),
                                          organization=organization)
        UserOrganizationMapping.objects.create(
            user=user,
            organization=organization,
            is_amc_admin=True,
        )
        assert user_has_access(user, self.course, default_has_access,
                               {}) == default_has_access

        # Basic test for `is_organization_staff` to ensure `user.is_active` is respected.
        inactive = UserFactory.create(is_active=False)
        assert not user_has_access(inactive, self.course, default_has_access,
                                   {})
    def setUp(self):
        super().setUp()

        self.course_ids = [
            'course-v1:edX+DemoX+Demo_Course',
            'course-v1:edX+Python+1T2019',
            'course-v1:edX+React+2T2019',
        ]
        self.enterprise_customer = EnterpriseCustomerFactory(
            name='Starfleet Academy',
            enable_data_sharing_consent=True,
            enforce_data_sharing_consent='at_enrollment',
        )

        learners = []
        for __ in range(5):
            user = UserFactory.create(is_staff=False, is_active=True)
            learners.append(user)

        self.learners_data = []
        for learner in learners:
            course_id = random.choice(self.course_ids)
            self.learners_data.append({
                'ENTERPRISE_UUID':
                self.enterprise_customer.uuid,
                'EMAIL':
                learner.email,
                'USERNAME':
                learner.username,
                'USER_ID':
                learner.id,
                'COURSE_ID':
                course_id
            })

            enterprise_customer_user = EnterpriseCustomerUserFactory(
                user_id=learner.id,
                enterprise_customer=self.enterprise_customer)

            EnterpriseCourseEnrollmentFactory(
                enterprise_customer_user=enterprise_customer_user,
                course_id=course_id,
            )

        self.existing_dsc_record_count = 2
        # create consent records for some learners with `granted` set to `False`
        # this is needed to verify that command is working for existing DSC records
        for learner in self.learners_data[:self.existing_dsc_record_count]:
            DataSharingConsentFactory(
                username=learner['USERNAME'],
                course_id=learner['COURSE_ID'],
                enterprise_customer=self.enterprise_customer,
                granted=False)
示例#14
0
 def setup(self, db, monkeypatch, standard_test_users):
     self.site = SiteFactory.create()
     self.organization = OrganizationFactory(sites=[self.site])
     self.callers = [
         UserFactory.create(username='******'),
         UserFactory.create(username='******'),
         UserFactory.create(username='******'),
     ]
     self.user_organization_mappings = [
         UserOrganizationMapping.objects.create(
             user=self.callers[0], organization=self.organization),
         UserOrganizationMapping.objects.create(
             user=self.callers[1],
             organization=self.organization,
             is_amc_admin=True)
     ]
     self.callers += standard_test_users
     self.request = APIRequestFactory().get('/')
     self.request.site = self.site
     monkeypatch.setattr(sites_shortcuts, 'get_current_site',
                         self.get_test_site)
示例#15
0
 def setup(self, client):
     client.defaults['SERVER_NAME'] = self.domain
     self.user = UserFactory.create(username='******')
     self.site = SiteFactory.create(domain=self.domain)
     self.my_org = OrganizationFactory.create(name='my_org', sites=[self.site])
     self.other_org = OrganizationFactory.create(name='other_org')
     self.staff = UserOrganizationMapping.objects.create(
         user=self.user,
         organization=self.my_org,
         is_amc_admin=True,
     )
     client.force_login(self.user)
示例#16
0
 def setUp(self) -> None:
     self.name = "My Class"
     self.uuid = uuid4()
     self.user = UserFactory.create()
     self.classroom_instance = ClassroomFactory.create(
         name=self.name,
         school=self.uuid,
     )
     self.classroom_enrollment = ClassroomEnrollmentFactory.create(
         classroom_instance=self.classroom_instance, user_id=self.user.id
     )
     return super().setUp()
示例#17
0
 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.views.CourseCatalogApiServiceClient')
     self.course_catalog_api_client = course_catalog_api_client.start()
     self.addCleanup(course_catalog_api_client.stop)
     super(TestProgramDataSharingPermissions, self).setUp()
示例#18
0
def test_failed_membership_rule_signals(monkeypatch, caplog, receiver_function, signal_name):
    """
    Ensure  errors in USER_ACCOUNT_ACTIVATED and REGISTER_USER are logged.
    """
    monkeypatch.delattr(Membership, 'create_from_rules')  # Act as if create_from_rules() don't work!

    user = UserFactory.create(email='*****@*****.**')
    MembershipRuleFactory(domain='example.com')

    with pytest.raises(AttributeError):
        receiver_function(object(), user)
    assert 'Error receiving {signal_name} signal for user'.format(signal_name=signal_name) in caplog.text
    assert '*****@*****.**' in caplog.text
    assert 'AttributeError' in caplog.text
示例#19
0
    def test_on_main_site_without_uuid_parameter(self, settings):
        """
        Non superusers shouldn't use the CAG on main site ( e.g. tahoe.appsembler.com/admin ).
        """
        main_site = SiteFactory.create(domain='main_site')
        settings.SITE_ID = main_site.id

        customer_site = SiteFactory.create(domain='customer_site')
        OrganizationFactory.create(sites=[customer_site
                                          ])  # Creates customer_org
        superuser = UserFactory.create(is_superuser=True)
        request = Mock(site=main_site, user=superuser, GET={})

        with pytest.raises(Organization.DoesNotExist,
                           match=r'Tahoe.*Should not find.*SITE_ID'):
            get_requested_organization(request)
 def setUp(self):
     """
     Set up reusable fake data.
     """
     self.user = UserFactory.create(is_staff=True, is_active=True)
     self.user.set_password("QWERTY")
     self.user.save()
     self.client = Client()
     self.demo_course_1 = FAKE_PROGRAM_RESPONSE3['courses'][0]
     self.demo_course_2 = FAKE_PROGRAM_RESPONSE3['courses'][1]
     self.demo_course_id1 = FAKE_PROGRAM_RESPONSE3['courses'][0]['key']
     self.demo_course_id2 = FAKE_PROGRAM_RESPONSE3['courses'][1]['key']
     self.demo_course_ids = [self.demo_course_id1, self.demo_course_id2]
     self.dummy_program_uuid = FAKE_PROGRAM_RESPONSE3['uuid']
     self.dummy_program = FAKE_PROGRAM_RESPONSE3
     super(TestProgramEnrollmentView, self).setUp()
示例#21
0
 def test_one_user_no_membership(self, client, org_name, status_code, skip_response_check):
     """
     Test JSON format for users without memberships.
     """
     org = Organization.objects.get(name=org_name)
     user = UserFactory.create()
     UserOrganizationMappingFactory.create(user=user, organization=org)
     response = client.get('{}{}/'.format(self.url, user.id))
     assert response.status_code == status_code, response.content
     result = response.json()
     assert skip_response_check or (result == {
         'id': user.id,
         'email': user.email,
         'name': user.profile.name,
         'username': user.username,
         'membership': None,
     }), 'Verify the serializer results.'
示例#22
0
    def test_on_main_site_with_uuid_parameter(self, settings):
        """
        Superusers can use the `get_requested_organization` helper with `organization_uuid`.
        """
        main_site = SiteFactory.create(domain='main_site')
        settings.SITE_ID = main_site.id

        customer_site = SiteFactory.create(domain='customer_site')
        customer_org = OrganizationFactory.create(sites=[customer_site])
        superuser = UserFactory.create(is_superuser=True)
        request = Mock(site=main_site,
                       user=superuser,
                       GET={
                           'organization_uuid': customer_org.edx_uuid,
                       })

        requested_org = get_requested_organization(request)
        assert requested_org == customer_org, 'Should return the site organization'
示例#23
0
    def setUp(self):
        self.user = UserFactory.create(is_active=True)
        self.user.set_password("QWERTY")
        self.user.save()
        self.client = Client()
        super(TestEnterpriseSelectionView, self).setUp()

        self.success_url = '/enterprise/grant_data_sharing_permissions'
        enterprises = ['Gryffindor', 'Hufflepuff', 'Ravenclaw', 'Slytherin']
        for enterprise in enterprises:
            enterprise_customer = EnterpriseCustomerFactory(name=enterprise)
            EnterpriseCustomerUserFactory(
                user_id=self.user.id, enterprise_customer=enterprise_customer)

        enterprises = EnterpriseCustomerUser.objects.filter(
            user_id=self.user.id).values_list('enterprise_customer__uuid',
                                              'enterprise_customer__name')
        self.enterprise_choices = [(str(uuid), name)
                                   for uuid, name in enterprises]
    def test_simple_match(self, email, should_enroll):
        """
        Basic test for membership rules.
        """
        assert not Membership.objects.count()
        user = UserFactory.create(is_active=True, email=email)
        group = CourseAccessGroupFactory.create()
        UserOrganizationMapping.objects.create(id=500,
                                               user=user,
                                               organization=group.organization)
        MembershipRule.objects.create(name='Something',
                                      domain='known_site.com',
                                      group=group)

        on_learner_account_activated(self.__class__, user)
        membership = Membership.objects.filter(user=user).first()

        assert bool(membership) == should_enroll
        assert not membership or (membership.group == group)
示例#25
0
 def test_add_membership(self, client, group_org, user_org, status_code,
                         expected_count, check_new_membership):
     assert not Membership.objects.count()
     group = CourseAccessGroupFactory.create(
         organization=Organization.objects.get(name=group_org), )
     user = UserFactory.create()
     UserOrganizationMapping.objects.create(
         organization=Organization.objects.get(name=user_org),
         user=user,
     )
     response = client.post(self.url, {
         'group': group.id,
         'user': user.id,
     })
     assert response.status_code == status_code, response.content
     assert Membership.objects.count() == expected_count
     if check_new_membership:
         new_membership = Membership.objects.get()
         assert new_membership.group.id == group.id
         assert new_membership.user.id == user.id
 def setUp(self):
     self.user = UserFactory.create(is_staff=True, is_active=True)
     self.user.set_password("QWERTY")
     self.user.save()
     self.client = Client()
     self.demo_course_id = 'course-v1:edX+DemoX+Demo_Course'
     self.dummy_demo_course_modes = [
         {
             "slug": "professional",
             "name": "Professional Track",
             "min_price": 100,
             "sku": "sku-audit",
         },
         {
             "slug": "audit",
             "name": "Audit Track",
             "min_price": 0,
             "sku": "sku-audit",
         },
     ]
     super(TestHandleConsentEnrollmentView, self).setUp()
    def setUp(self):
        """
        Setup middleware, request, session, user and enterprise customer for tests. Also mock imports from edx-platform.
        """
        self.mock_imports()

        super().setUp()
        self.middleware = EnterpriseLanguagePreferenceMiddleware()
        self.session_middleware = SessionMiddleware()
        self.user = UserFactory.create()
        self.anonymous_user = AnonymousUserFactory()
        self.request = RequestFactory().get('/somewhere')
        self.request.user = self.user
        self.request.META['HTTP_ACCEPT_LANGUAGE'] = 'ar;q=1.0'
        self.session_middleware.process_request(self.request)
        self.client = Client()
        self.enterprise_customer = EnterpriseCustomerFactory()
        self.enterprise_customer_user = EnterpriseCustomerUserFactory(
            enterprise_customer=self.enterprise_customer,
            user_id=self.user.id,
        )
示例#28
0
    def test_on_main_site_with_uuid_parameter_non_staff(self, settings):
        """
        Non superusers shouldn't be able to use the `organization_uuid` parameters.
        """
        main_site = SiteFactory.create(domain='main_site')
        settings.SITE_ID = main_site.id

        customer_site = SiteFactory.create(domain='customer_site')
        customer_org = OrganizationFactory.create(sites=[customer_site])
        non_superuser = UserFactory.create()
        request = Mock(site=main_site,
                       user=non_superuser,
                       GET={
                           'organization_uuid': customer_org.edx_uuid,
                       })

        with pytest.raises(
                PermissionDenied,
                match=r'Not permitted to use the `organization_uuid` parameter.'
        ):
            get_requested_organization(request)
示例#29
0
    def setUp(self):
        self.user = UserFactory.create(is_active=True)
        self.user.set_password("QWERTY")
        self.user.save()
        self.client = Client()
        super(TestEnterpriseSelectionView, self).setUp()

        self.success_url = '/enterprise/grant_data_sharing_permissions'
        enterprises = ['Gryffindor', 'Hufflepuff', 'Ravenclaw', 'Slytherin']
        for enterprise in enterprises:
            enterprise_customer = EnterpriseCustomerFactory(name=enterprise)
            EnterpriseCustomerUserFactory(
                user_id=self.user.id,
                enterprise_customer=enterprise_customer
            )

        enterprises = EnterpriseCustomerUser.objects.filter(
            user_id=self.user.id
        ).values_list(
            'enterprise_customer__uuid', 'enterprise_customer__name'
        )
        self.enterprise_choices = [(str(uuid), name) for uuid, name in enterprises]

        # create a temporary template file
        # rendering `enterprise/enterprise_customer_select_form.html` fails becuase of dependency on edx-platform
        tpl = tempfile.NamedTemporaryFile(
            prefix='test_template.',
            suffix=".html",
            dir=settings.REPO_ROOT + '/templates/enterprise/',
            delete=False,
        )
        tpl.close()
        self.addCleanup(os.remove, tpl.name)

        patcher = mock.patch(
            'enterprise.views.EnterpriseSelectionView.template_name',
            mock.PropertyMock(return_value=tpl.name)
        )
        patcher.start()
        self.addCleanup(patcher.stop)
    def setUp(self):
        self.user = UserFactory.create(is_staff=True, is_active=True)
        self.user.set_password("QWERTY")
        self.user.save()
        self.client = Client()
        self.url = reverse('grant_data_sharing_permissions')
        self.platform_name = 'Test platform'
        self.course_id = 'course-v1:edX+DemoX+Demo_Course'
        self.program_uuid = '25c10a26-0b00-0000-bd06-7813546c29eb'
        self.course_details = {
            'name': 'edX Demo Course',
        }
        self.course_run_details = {
            'start': '2013-02-05T05:00:00Z',
            'title': 'Demo Course'
        }
        self.next_url = 'https://google.com'
        self.failure_url = 'https://facebook.com'
        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.left_sidebar_text = """
        <p class="partnered-text">Welcome to {platform_name}</p>
        <p class="partnered-text"><b>{enterprise_customer_name}</b> has partnered with {platform_name}
        to offer you high-quality learning opportunities from the world\'s best universities.</p>
        """
        self.top_paragraph = """
        <h2 class="consent-title">Consent to share your data</h2>
        <p>To access this {item}, you must first consent to share your learning achievements with
        <b>{enterprise_customer_name}</b></p>
        <p>{enterprise_customer_name} would like to know about:</p>
        <p><ul><li>your enrollment in this course</li><li>your learning progress</li>
        <li>course completion</li></ul></p>
        """
        self.agreement_text = """
        I agree to allow {platform_name} to share data about my enrollment, completion and performance
        in all {platform_name} courses and programs where my enrollment is sponsored by {enterprise_customer_name}.
        """
        self.confirmation_modal_text = """
        In order to start this {item} and use your discount, you must consent
        to share your {item} data with {enterprise_customer_name}.
        """

        self.dsc_page = DataSharingConsentTextOverridesFactory(
            enterprise_customer=self.enterprise_customer,
            left_sidebar_text=self.left_sidebar_text,
            top_paragraph=self.top_paragraph,
            agreement_text=self.agreement_text,
            continue_text='Yes, continue',
            abort_text='No, take me back.',
            policy_dropdown_header='Data Sharing Policy',
            policy_paragraph='Policy paragraph',
            confirmation_modal_header='Are you aware...',
            confirmation_modal_text=self.confirmation_modal_text,
            modal_affirm_decline_text='I decline',
            modal_abort_decline_text='View the data sharing policy',
        )
        super(TestGrantDataSharingPermissionsWithDB, self).setUp()