def setUp(self):
        enterprise_user = EnterpriseUserFactory(enterprise_user_id=1234)
        course_id = 'course-v1:edX+DemoX+DemoCourse'

        self.enrollment = EnterpriseEnrollmentFactory(
            enterprise_user=enterprise_user, course_id=course_id)
        super(TestEnterpriseEnrollment, self).setUp()
    def test_get_queryset_returns_learner_activity_filter_no_active_enrollments(
            self, activity_filter, has_passed, course_end_date):
        """
        Learner activity filter should not return enrollments if their course date is in past
        or learners have not passed the course yet.
        """
        enterprise_id = '413a0720-3efe-4cf5-98c8-3b4e42d3c509'
        url = u"{url}?learner_activity={activity_filter}".format(
            url=reverse('v0:enterprise-enrollments-list',
                        kwargs={'enterprise_id': enterprise_id}),
            activity_filter=activity_filter)

        enterprise_user = EnterpriseUserFactory(enterprise_user_id=1234)

        date_today = date.today()
        in_past_week_dates = [date_today, date_today - timedelta(days=2)]
        before_past_week_dates = [date_today - timedelta(weeks=2)]
        before_past_month_dates = [subtract_one_month(date.today())]
        activity_dates = in_past_week_dates + before_past_week_dates + before_past_month_dates
        for activity_date in activity_dates:
            EnterpriseEnrollmentFactory(
                enterprise_user=enterprise_user,
                enterprise_id=enterprise_id,
                last_activity_date=activity_date,
                course_end=course_end_date,
                has_passed=has_passed,
                consent_granted=True,
            )

        response = self.client.get(url)
        assert response.status_code == status.HTTP_404_NOT_FOUND
    def test_get_queryset_returns_learner_activity_filter_no_consent(
            self, activity_filter, expected_dates):
        """
        Learner activity filter should not return learner if their enrollments
        have no consent granted
        """
        enterprise_id = '413a0720-3efe-4cf5-98c8-3b4e42d3c509'
        url = u"{url}?learner_activity={activity_filter}".format(
            url=reverse('v0:enterprise-enrollments-list',
                        kwargs={'enterprise_id': enterprise_id}),
            activity_filter=activity_filter)

        enterprise_user = EnterpriseUserFactory(enterprise_user_id=1234)
        course_end_date = timezone.now() + timedelta(days=1)

        date_today = date.today()
        in_past_week_dates = [date_today, date_today - timedelta(days=2)]
        before_past_week_dates = [date_today - timedelta(weeks=2)]
        before_past_month_dates = [subtract_one_month(date.today())]
        activity_dates = in_past_week_dates + before_past_week_dates + before_past_month_dates
        for activity_date in activity_dates:
            EnterpriseEnrollmentFactory(
                enterprise_user=enterprise_user,
                enterprise_id=enterprise_id,
                last_activity_date=activity_date,
                course_end=course_end_date,
                has_passed=False,
                consent_granted=False,
            )

        response = self.client.get(url)
        assert response.status_code == status.HTTP_200_OK
        result = response.json()
        assert result['count'] == 0
    def test_get_queryset_returns_enrollments_with_learner_activity_filter(
            self, activity_filter, expected_dates):
        enterprise_id = '413a0720-3efe-4cf5-98c8-3b4e42d3c509'
        url = u"{url}?learner_activity={activity_filter}".format(
            url=reverse('v0:enterprise-enrollments-list',
                        kwargs={'enterprise_id': enterprise_id}),
            activity_filter=activity_filter)

        enterprise_user = EnterpriseUserFactory(enterprise_user_id=1234)

        date_today = date.today()
        in_past_week_dates = [date_today, date_today - timedelta(days=2)]
        before_past_week_dates = [date_today - timedelta(weeks=2)]
        before_past_month_dates = [subtract_one_month(date.today())]
        activity_dates = in_past_week_dates + before_past_week_dates + before_past_month_dates
        for activity_date in activity_dates:
            EnterpriseEnrollmentFactory(
                enterprise_user=enterprise_user,
                enterprise_id=enterprise_id,
                last_activity_date=activity_date,
                course_end=timezone.now() + timedelta(days=1),
                has_passed=False,
                consent_granted=True,
            )

        response = self.client.get(url)
        assert response.status_code == status.HTTP_200_OK
        result = response.json()
        assert result['count'] == len(expected_dates)
        for enrollment in result['results']:
            assert datetime.strptime(enrollment['last_activity_date'],
                                     "%Y-%m-%d").date() in expected_dates
    def test_get_queryset_returns_enrollments_with_audit_enrollment_filter(
            self, enable_audit_enrollment, total_enrollments,
            user_current_enrollment_mode, enrollments_count):
        enterprise_id = '413a0720-3efe-4cf5-98c8-3b4e42d3c501'
        url = reverse('v0:enterprise-enrollments-list',
                      kwargs={'enterprise_id': enterprise_id})

        dummy_enterprise_api_data = get_dummy_enterprise_api_data(
            enterprise_id=enterprise_id,
            enable_audit_enrollment=enable_audit_enrollment,
        )
        enterprise_api_client = mock.patch(
            'enterprise_data.permissions.EnterpriseApiClient',
            mock.Mock(return_value=mock.Mock(get_with_access_to=mock.Mock(
                return_value=dummy_enterprise_api_data))))
        self.enterprise_api_client = enterprise_api_client.start()
        enterprise_user = EnterpriseUserFactory(enterprise_user_id=1234)
        for index in range(total_enrollments):
            EnterpriseEnrollmentFactory(
                enterprise_user=enterprise_user,
                enterprise_id=enterprise_id,
                user_email='user{}@example.com'.format(index),
                user_current_enrollment_mode=user_current_enrollment_mode,
                course_title='course101',
                has_passed=True,
                consent_granted=True,
            )

        response = self.client.get(url)
        assert response.status_code == status.HTTP_200_OK
        result = response.json()
        assert result['count'] == enrollments_count
    def test_get_queryset_returns_enrollments_with_passed_date_filter(self):
        enterprise_id = '413a0720-3efe-4cf5-98c8-3b4e42d3c501'
        url = u"{url}?passed_date=last_week".format(
            url=reverse('v0:enterprise-enrollments-list',
                        kwargs={'enterprise_id': enterprise_id}))

        enterprise_user = EnterpriseUserFactory(enterprise_user_id=1234)

        date_today = date.today()
        in_past_week_passed_dates = [
            date_today, date_today - timedelta(days=2)
        ]
        before_past_week_passed_dates = [date_today - timedelta(weeks=2)]
        passed_dates = in_past_week_passed_dates + before_past_week_passed_dates
        for index, passed_date in enumerate(passed_dates):
            EnterpriseEnrollmentFactory(
                enterprise_user=enterprise_user,
                enterprise_id=enterprise_id,
                user_email='user{}@example.com'.format(index),
                passed_timestamp=passed_date,
                course_title='course101',
                has_passed=True,
                consent_granted=True,
            )

        response = self.client.get(url)
        assert response.status_code == status.HTTP_200_OK
        result = response.json()
        assert result['count'] == len(in_past_week_passed_dates)
        for enrollment, passed_date in zip(result['results'],
                                           in_past_week_passed_dates):
            assert enrollment['has_passed'] is True
            assert datetime.strptime(
                enrollment['passed_timestamp'],
                "%Y-%m-%dT%H:%M:%SZ").date() == passed_date
    def test_viewset_ordering(self, ordering, enrollments_data,
                              expected_results_count,
                              expected_completed_courses):
        """
        EnterpriseLearnerCompletedCoursesViewSet should order enrollments returned if the value
        for ordering query param is set.
        """
        # Add enrollments
        one_day = timedelta(days=1)
        date_in_past = timezone.now() - one_day
        ent_user = EnterpriseUserFactory(enterprise_user_id=1, )
        for enrollment in enrollments_data:
            for _idx in range(enrollment['user_enrollments']):
                EnterpriseEnrollmentFactory(
                    user_email=enrollment['user_email'],
                    enterprise_user=ent_user,
                    course_end=date_in_past,
                    has_passed=True,
                    consent_granted=True,
                )
        url = reverse('v0:enterprise-learner-completed-courses-list',
                      kwargs={'enterprise_id': self.enterprise_id})
        params = {'ordering': ordering}
        response = self.client.get(url, params)
        assert response.json()['count'] == expected_results_count

        for idx, expected_course_completed_count in enumerate(
                expected_completed_courses):
            assert response.json()['results'][idx][
                'completed_courses'] == expected_course_completed_count
    def setUp(self):
        super(TestEnterpriseUsersViewSet, self).setUp()
        self.user = UserFactory(is_staff=True)
        self.client.force_authenticate(user=self.user)
        enterprise_api_client = mock.patch(
            'enterprise_data.permissions.EnterpriseApiClient',
            mock.Mock(return_value=mock.Mock(get_with_access_to=mock.Mock(
                return_value=get_dummy_enterprise_api_data()))))
        self.enterprise_api_client = enterprise_api_client.start()
        self.addCleanup(enterprise_api_client.stop)

        one_day = timedelta(days=1)
        date_in_past = timezone.now() - one_day
        date_in_future = timezone.now() + one_day

        # Users without enrollments
        EnterpriseUserFactory(enterprise_user_id=1, )
        EnterpriseUserFactory(enterprise_user_id=2, )
        self.ent_user3 = EnterpriseUserFactory(enterprise_user_id=3, )
        # User with True & None for enrollment consent
        self.ent_user4 = EnterpriseUserFactory(enterprise_user_id=4, )
        EnterpriseEnrollmentFactory(
            enterprise_user=self.ent_user4,
            course_end=date_in_past,
            consent_granted=True,
            has_passed=True,
        )
        EnterpriseEnrollmentFactory(
            enterprise_user=self.ent_user4,
            course_end=date_in_future,
        )
        EnterpriseEnrollmentFactory(
            enterprise_user=self.ent_user4,
            course_end=date_in_future,
            consent_granted=True,
        )
        EnterpriseEnrollmentFactory(
            enterprise_user=self.ent_user4,
            course_end=date_in_past,
            consent_granted=True,
            has_passed=False,
        )
        # User with only True enrollment consent
        self.ent_user5 = EnterpriseUserFactory(enterprise_user_id=5, )
        EnterpriseEnrollmentFactory(
            enterprise_user=self.ent_user5,
            course_end=date_in_future,
            consent_granted=True,
        )
        # User with only False enrollment consent
        self.ent_user6 = EnterpriseUserFactory(enterprise_user_id=6, )
        EnterpriseEnrollmentFactory(
            enterprise_user=self.ent_user6,
            consent_granted=False,
            course_end=date_in_past,
        )
        # User with True and False enrollment consent
        self.ent_user7 = EnterpriseUserFactory(enterprise_user_id=7, )
        EnterpriseEnrollmentFactory(
            enterprise_user=self.ent_user7,
            consent_granted=True,
            has_passed=True,
        )
        EnterpriseEnrollmentFactory(
            enterprise_user=self.ent_user7,
            consent_granted=False,
            course_end=date_in_future,
            has_passed=False,
        )
        EnterpriseEnrollmentFactory(
            enterprise_user=self.ent_user7,
            consent_granted=False,
            course_end=date_in_past,
            has_passed=True,
        )

        # User with True & None for enrollment consent and course has ended
        self.ent_user8 = EnterpriseUserFactory(enterprise_user_id=8, )
        EnterpriseEnrollmentFactory(
            enterprise_user=self.ent_user8,
            course_end=date_in_past,
            has_passed=True,
        )
        EnterpriseEnrollmentFactory(
            enterprise_user=self.ent_user8,
            consent_granted=True,
            course_end=date_in_past,
            has_passed=True,
        )

        # User with a large number of enrollments of different kinds
        self.ent_user9 = EnterpriseUserFactory(enterprise_user_id=9, )
        EnterpriseEnrollmentFactory(
            enterprise_user=self.ent_user9,
            has_passed=True,
        )
        for i in range(2):
            EnterpriseEnrollmentFactory(
                enterprise_user=self.ent_user9,
                has_passed=False,
            )
        for i in range(3):
            EnterpriseEnrollmentFactory(
                enterprise_user=self.ent_user9,
                consent_granted=True,
                has_passed=True,
            )
        EnterpriseEnrollmentFactory(
            enterprise_user=self.ent_user9,
            consent_granted=False,
            has_passed=True,
        )
        EnterpriseEnrollmentFactory(
            enterprise_user=self.ent_user9,
            consent_granted=True,
            has_passed=False,
        )