def course_test_data():
    """Temporary fixture. Will remove as we abstract testing
    """
    months_back = 6
    site = SiteFactory()
    course_overview = CourseOverviewFactory()
    if organizations_support_sites():
        org = OrganizationFactory(sites=[site])
    else:
        org = OrganizationFactory()

    OrganizationCourseFactory(organization=org,
                              course_id=str(course_overview.id))

    enrollments = [
        CourseEnrollmentFactory(course_id=course_overview.id) for i in range(3)
    ]

    users = [enrollment.user for enrollment in enrollments]
    student_modules = []
    dates = generate_date_series(months_back=months_back)
    assert dates
    data_spec = list(zip(dates, list(range(months_back))))

    return dict(
        site=site,
        org=org,
        users=users,
        course_overview=course_overview,
        enrollments=enrollments,
        student_modules=student_modules,
        months_back=months_back,
        dates=dates,
        data_spec=data_spec,
    )
    def test_registered_learners(self, monkeypatch, user_reg_test_data):
        """

        Example response data:
            {'registered_users': {'current_month': 20,
            'history': [
            {'period': '2019/08', 'value': 3},
            {'period': '2019/09', 'value': 4},
            {'period': '2019/10', 'value': 7},
            {'period': '2019/11', 'value': 11},
            {'period': '2019/12', 'value': 20},
            {'period': '2020/01', 'value': 20},
            {'period': '2020/02', 'value': 20}]}}
        """
        request_method = 'get'
        endpoint = 'registered_users'
        site = user_reg_test_data['site']
        users = user_reg_test_data['users']
        dates = user_reg_test_data['dates']
        months_back = user_reg_test_data['months_back']

        if organizations_support_sites():
            caller = UserFactory(is_staff=True)
            map_users_to_org_site(caller=caller, site=site, users=users)
        else:
            caller = UserFactory(is_staff=True)

        request = APIRequestFactory().get(self.request_path)
        request.META['HTTP_HOST'] = site.domain
        monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site',
                            lambda req: site)
        force_authenticate(request, user=caller)
        view = self.view_class.as_view({request_method: endpoint})
        response = view(request)
        assert self.check_response(response=response, endpoint=endpoint)
    def test_active_users(self, monkeypatch, user_reg_test_data):
        endpoint = 'active_users'
        request_method = 'get'
        site = user_reg_test_data['site']

        if organizations_support_sites():
            caller = UserFactory(is_staff=True)
            map_users_to_org_site(caller=caller, site=site, users=[])
        else:
            caller = UserFactory(is_staff=True)

        expected_response = 'active_users history metric data'
        monkeypatch.setattr(
            'figures.views.metrics.get_site_mau_history_metrics',
            lambda **_kwargs: expected_response)

        request = APIRequestFactory().get(self.request_path)
        request.META['HTTP_HOST'] = site.domain
        monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site',
                            lambda req: site)
        force_authenticate(request, user=caller)
        view = self.view_class.as_view({request_method: endpoint})
        response = view(request)

        assert response.data['active_users'] == expected_response
    def test_avg_progress(self, monkeypatch, sog_data):
        site = sog_data['site']
        course_overview = sog_data['course_overview']
        if organizations_support_sites():
            caller = UserFactory(is_staff=True)
            map_users_to_org_site(caller=caller, site=site, users=[])
        else:
            caller = UserFactory(is_staff=True)

        expected_response = 'avg_progress history metric data'

        def mock_get_course_history_metric(**kwargs):
            return expected_response

        monkeypatch.setattr('figures.views.get_course_history_metric',
                            mock_get_course_history_metric)

        request_path = self.base_request_path + str(
            course_overview.id) + '/avg_progress/'
        request = APIRequestFactory().get(request_path)

        request.META['HTTP_HOST'] = site.domain
        monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site',
                            lambda req: site)
        force_authenticate(request, user=caller)
        view = self.view_class.as_view({'get': 'avg_progress'})
        response = view(request, pk=str(course_overview.id))
        assert response.status_code == status.HTTP_200_OK
        assert response.data['avg_progress'] == expected_response
Beispiel #5
0
def sm_test_data(db):
    """
    WIP StudentModule test data to test MAU
    """
    year_for = 2019
    month_for = 10
    created_date = datetime(year_for, month_for, 1).replace(tzinfo=utc)
    modified_date = datetime(year_for, month_for, 10).replace(tzinfo=utc)
    course_overviews = [CourseOverviewFactory() for i in range(3)]
    site = SiteFactory()

    sm = []
    for co in course_overviews:
        sm += [StudentModuleFactory(course_id=co.id,
                                    created=created_date,
                                    modified=modified_date) for co in course_overviews]

    if organizations_support_sites():
        org = OrganizationFactory(sites=[site])
        for co in course_overviews:
            OrganizationCourseFactory(organization=org, course_id=str(co.id))
        for rec in sm:
            UserOrganizationMappingFactory(user=rec.student, organization=org)
    else:
        org = OrganizationFactory()

    return dict(site=site,
                organization=org,
                course_overviews=course_overviews,
                student_modules=sm,
                year_for=year_for,
                month_for=month_for)
    def setup(self, db):
        self.date_for = datetime.date(2018, 10, 1)
        self.site = Site.objects.first()
        self.users = [
            UserFactory(date_joined=as_datetime(self.date_for -
                                                datetime.timedelta(days=60)))
            for i in range(0, 3)
        ]
        self.course_overviews = [
            CourseOverviewFactory(
                created=as_datetime(self.date_for -
                                    datetime.timedelta(days=60)))
            for i in range(0, 3)
        ]
        self.cdm_recs = [
            CourseDailyMetricsFactory(site=self.site,
                                      date_for=self.date_for,
                                      **cdm) for cdm in CDM_INPUT_TEST_DATA
        ]
        self.prev_day_sdm = SiteDailyMetricsFactory(site=self.site,
                                                    date_for=prev_day(
                                                        self.date_for),
                                                    **SDM_DATA[1])

        if is_multisite():
            self.organization = OrganizationFactory(sites=[self.site])
            for co in self.course_overviews:
                OrganizationCourseFactory(organization=self.organization,
                                          course_id=str(co.id))
            if organizations_support_sites():
                for user in self.users:
                    UserOrganizationMappingFactory(
                        user=user, organization=self.organization)
Beispiel #7
0
    def test_no_update_has_lcgm_no_sm(self, monkeypatch):
        """We have an LCGM but not an SM record

        The function under test should return the existing LCGM
        """
        monkeypatch.setattr(
            'figures.pipeline.enrollment_metrics.get_site_for_course',
            lambda val: self.site)
        monkeypatch.setattr(
            'figures.pipeline.enrollment_metrics._collect_progress_data',
            lambda val: self.progress_data)
        # Create a course enrollment for which we won't have student module records
        ce = CourseEnrollmentFactory(
            course_id=self.course_enrollment.course_id)
        if organizations_support_sites():
            UserOrganizationMappingFactory(organization=self.org, user=ce.user)
        lcgm = LearnerCourseGradeMetricsFactory(course_id=ce.course_id,
                                                user=ce.user)

        ce_sm = StudentModule.objects.filter(course_id=ce.course_id,
                                             student_id=ce.user.id)
        assert not ce_sm
        metrics = collect_metrics_for_enrollment(site=self.site,
                                                 course_enrollment=ce,
                                                 date_for=self.today,
                                                 student_modules=ce_sm)
        assert not metrics
Beispiel #8
0
    def setup(self, db, settings):

        # Set up data that's the same for standalone or multisite
        self.date_for = utc_yesterday()
        self.site = Site.objects.first()
        self.courses = [CourseOverviewFactory(), CourseOverviewFactory()]

        # Two for "our" course, one for another course in the same site
        self.enrollments = [
            CourseEnrollmentFactory(course_id=self.courses[0].id),
            CourseEnrollmentFactory(course_id=self.courses[0].id),
            CourseEnrollmentFactory(course_id=self.courses[1].id),
        ]

        self.ce0_sm = StudentModuleFactory.from_course_enrollment(
            self.enrollments[0],
            created=as_datetime(self.date_for),
            modified=as_datetime(self.date_for))

        # Handle site mode specifices
        if organizations_support_sites():
            settings.FEATURES['FIGURES_IS_MULTISITE'] = True
            self.org = OrganizationFactory(sites=[self.site])
            for course in self.courses:
                OrganizationCourseFactory(organization=self.org,
                                          course_id=str(course.id))
            map_users_to_org(self.org, [ce.user for ce in self.enrollments])

            # For our tests, we focus on a single enrollment. We should not
            # need to stand up other site data, but if we find we do need to,
            # then here's the place to do it
        else:
            self.org = OrganizationFactory()
Beispiel #9
0
 def make_caller(self, site, users):
     """Convenience method to create the API caller user
     """
     if organizations_support_sites():
         # TODO: set is_staff to False after we have test coverage
         caller = UserFactory(is_staff=True)
         map_users_to_org_site(caller=caller, site=site, users=users)
     else:
         caller = UserFactory(is_staff=True)
     return caller
 def setup(self, db):
     super(TestUserIndexViewSet, self).setup(db)
     self.users = [make_user(**data) for data in USER_DATA]
     self.usernames = [data['username'] for data in USER_DATA]
     self.expected_result_keys = ['id', 'username', 'fullname']
     if organizations_support_sites():
         self.organization = OrganizationFactory(sites=[self.site])
         for user in self.users:
             UserOrganizationMappingFactory(user=user,
                                            organization=self.organization)
     assert len(self.users) == len(USER_DATA)
Beispiel #11
0
    def setup(self, db):
        self.today = date.today()
        self.site = SiteFactory()
        if organizations_support_sites():
            self.org = OrganizationFactory(sites=[self.site])
        else:
            self.org = OrganizationFactory()

        self.datetime_1 = datetime(2020, 2, 2, tzinfo=utc)
        self.datetime_2 = self.datetime_1 + relativedelta(
            months=1)  # future of date_1
        self.course_overview = CourseOverviewFactory()
        self.course_enrollment = CourseEnrollmentFactory(
            course_id=self.course_overview.id)
        self.course_enrollment_2 = CourseEnrollmentFactory(
            course_id=self.course_overview.id)
        if organizations_support_sites():
            OrganizationCourseFactory(organization=self.org,
                                      course_id=str(self.course_overview.id))
            UserOrganizationMappingFactory(organization=self.org,
                                           user=self.course_enrollment.user)
            UserOrganizationMappingFactory(organization=self.org,
                                           user=self.course_enrollment_2.user)
        self.student_modules = [
            StudentModuleFactory(student=self.course_enrollment.user,
                                 course_id=self.course_enrollment.course_id,
                                 modified=self.datetime_1),
            StudentModuleFactory(student=self.course_enrollment.user,
                                 course_id=self.course_enrollment.course_id,
                                 modified=self.datetime_2),
            # This student module does not belong to the user in course_enrollment
            StudentModuleFactory(course_id=self.course_enrollment.course_id,
                                 modified=self.datetime_2)
        ]
        self.learner_sm = StudentModule.objects.filter(
            course_id=self.course_enrollment.course_id,
            student=self.course_enrollment.user).order_by('-modified')
        self.progress_data = dict(points_possible=100,
                                  points_earned=25,
                                  sections_worked=4,
                                  count=5)
Beispiel #12
0
def make_caller(org):
    """Convenience method to create the API caller user
    """
    if organizations_support_sites():
        # TODO: set is_staff to False after we have test coverage
        caller = UserFactory(is_staff=True)
        UserOrganizationMappingFactory(user=caller,
                                       organization=org,
                                       is_amc_admin=True)
    else:
        caller = UserFactory(is_staff=True)
    return caller
Beispiel #13
0
def simple_mau_test_data(settings):
    """
    Pytest fixture to create the base test data we need for the MAU tests here

    We set up single site vs multisite mode in this fixture based on which
    edx-organizations package is declared in the pip requirements file used to
    run the tests:

    Community:
    edx-organizations==0.4.10

    Tahoe:
    git+https://github.com/appsembler/[email protected]
    """
    our_site = SiteFactory()
    our_org = OrganizationFactory()
    our_course = CourseOverviewFactory()
    our_other_course = CourseOverviewFactory()
    other_site = SiteFactory()
    other_site_course = CourseOverviewFactory()
    our_course_data = create_student_module_recs(our_course.id)
    our_other_course_sm = [
        StudentModuleFactory(course_id=our_other_course.id) for i in range(10)
    ]
    month_for = date(year=our_course_data['year_for'],
                     month=our_course_data['month_for'],
                     day=1)
    expected_mau_ids = set(
        [rec.student.id for rec in our_course_data['in_range']])

    test_data = dict(
        month_for=month_for,
        expected_mau_ids=expected_mau_ids,
        our_site=our_site,
        our_course=our_course,
        our_course_data=our_course_data,
        our_other_course=our_other_course,
        our_other_course_sm=our_other_course_sm,
        other_site=other_site,
        other_site_course=other_site_course,
    )

    if organizations_support_sites():
        settings.FEATURES['FIGURES_IS_MULTISITE'] = True
        our_org = OrganizationFactory(sites=[our_site])
        for user in set([obj.student for obj in our_course_data['in_range']]):
            UserOrganizationMappingFactory(user=user, organization=our_org)
        for course_id in set(
            [obj.course_id for obj in our_course_data['in_range']]):
            OrganizationCourseFactory(organization=our_org,
                                      course_id=str(course_id))
    return test_data
    def setup(self, db):
        self.course_enrollments = [CourseEnrollmentFactory() for i in range(1, 5)]

        if organizations_support_sites():
            self.my_site = SiteFactory(domain='my-site.test')
            self.my_site_org = OrganizationFactory(sites=[self.my_site])
            for ce in self.course_enrollments:
                OrganizationCourseFactory(organization=self.my_site_org,
                                          course_id=str(ce.course.id))
                UserOrganizationMappingFactory(user=ce.user,
                                               organization=self.my_site_org)

        self.student_module = StudentModuleFactory()
Beispiel #15
0
    def setup(self, db):
        self.today = datetime.date(2018, 6, 1)
        self.course_overview = CourseOverviewFactory()
        if OPENEDX_RELEASE == GINKGO:
            self.course_enrollments = [
                CourseEnrollmentFactory(course_id=self.course_overview.id)
                for i in range(4)
            ]
        else:
            self.course_enrollments = [
                CourseEnrollmentFactory(course=self.course_overview)
                for i in range(4)
            ]

        if organizations_support_sites():
            self.my_site = SiteFactory(domain='my-site.test')
            self.my_site_org = OrganizationFactory(sites=[self.my_site])
            OrganizationCourseFactory(organization=self.my_site_org,
                                      course_id=str(self.course_overview.id))
            for ce in self.course_enrollments:
                UserOrganizationMappingFactory(user=ce.user,
                                               organization=self.my_site_org)

        self.course_access_roles = [
            CourseAccessRoleFactory(
                user=self.course_enrollments[i].user,
                course_id=self.course_enrollments[i].course_id,
                role=role,
            ) for i, role in enumerate(self.COURSE_ROLES)
        ]

        # create student modules for yesterday and today
        for day in [prev_day(self.today), self.today]:
            self.student_modules = [
                StudentModuleFactory(course_id=ce.course_id,
                                     student=ce.user,
                                     created=ce.created,
                                     modified=as_datetime(day))
                for ce in self.course_enrollments
            ]

        self.cert_days_to_complete = [10, 20, 30]
        self.expected_avg_cert_days_to_complete = 20
        self.generated_certificates = [
            GeneratedCertificateFactory(
                user=self.course_enrollments[i].user,
                course_id=self.course_enrollments[i].course_id,
                created_date=(self.course_enrollments[i].created +
                              datetime.timedelta(days=days)),
            ) for i, days in enumerate(self.cert_days_to_complete)
        ]
def make_site_data(num_users=3, num_courses=2):
    """
    This is a copy-n-paste hack from figures/tests/conftest.py
    """
    site = SiteFactory()
    if organizations_support_sites():
        org = OrganizationFactory(sites=[site])
    else:
        org = OrganizationFactory()
    courses = [CourseOverviewFactory() for i in range(num_courses)]
    users = [UserFactory() for i in range(num_users)]
    enrollments = []

    users = [UserFactory() for i in range(num_users)]

    enrollments = []
    for i, user in enumerate(users):
        # Create increasing number of enrollments for each user, maximum to one less
        # than the number of courses
        for j in range(i):
            enrollments.append(
                CourseEnrollmentFactory(course=courses[j - 1], user=user))

    if organizations_support_sites():
        for course in courses:
            OrganizationCourseFactory(organization=org,
                                      course_id=str(course.id))

        # Set up user mappings
        map_users_to_org(org, users)

    return dict(
        site=site,
        org=org,
        courses=courses,
        users=users,
        enrollments=enrollments,
    )
Beispiel #17
0
def cdm_test_data(db, settings):
    """Build CourseDailyMetrics data to test certificate counts
    """
    our_site = SiteFactory()
    mock_today = date(year=2020, month=6, day=7)
    last_month = mock_today - relativedelta(months=1)
    courses = [CourseOverviewFactory() for i in range(2)]
    # Create data for previous month. Just need one record
    # purpose is to make sure it is not included in our production code request
    prev_month_cdm = [
        CourseDailyMetrics(site=our_site,
                           course_id=str(courses[0].id),
                           date_for=last_month)
    ]

    # Create data for our current month
    curr_month_cdm = []
    cdm_data = [
        dict(day=1, course_id=str(courses[0].id), num_learners_completed=1),
        dict(day=6, course_id=str(courses[0].id), num_learners_completed=10),
        dict(day=1, course_id=str(courses[1].id), num_learners_completed=2),
        dict(day=6, course_id=str(courses[1].id), num_learners_completed=20),
    ]

    expected_cert_count = 30
    for rec in cdm_data:
        date_for = date(year=mock_today.year,
                        month=mock_today.month,
                        day=rec['day'])
        cdm = CourseDailyMetricsFactory(
            site=our_site,
            course_id=rec['course_id'],
            date_for=date_for,
            num_learners_completed=rec['num_learners_completed'])
        curr_month_cdm.append(cdm)

    if organizations_support_sites():
        settings.FEATURES['FIGURES_IS_MULTISITE'] = True
        our_org = OrganizationFactory(sites=[our_site])
        for course in courses:
            OrganizationCourseFactory(organization=our_org,
                                      course_id=str(course.id))
    return dict(
        mock_today=mock_today,
        our_site=our_site,
        courses=courses,
        prev_month_cdm=prev_month_cdm,
        curr_month_cdm=curr_month_cdm,
        expected_cert_count=expected_cert_count,
    )
Beispiel #18
0
def lm_test_data(db, settings):
    """Learner Metrics Test Data

    user0 not enrolled in any courses
    user1 enrolled in 1 course
    user2 enrolled in 2 courses

    """
    if organizations_support_sites():
        settings.FEATURES['FIGURES_IS_MULTISITE'] = True

    our_site_data = make_site_data()
    other_site_data = make_site_data()
    return dict(us=our_site_data, them=other_site_data)
Beispiel #19
0
def test_site_course_ids(monkeypatch):
    site = SiteFactory()
    course_overviews = [CourseOverviewFactory() for i in range(2)]
    if organizations_support_sites():
        monkeypatch.setattr('figures.sites.is_multisite', lambda: True)
        our_org = OrganizationFactory(sites=[site])
        # associate the course overviews with our org
        for co in course_overviews:
            OrganizationCourseFactory(course_id=co.id, organization=our_org)
        other_org = OrganizationFactory(sites=[SiteFactory()])
        # create a course associated with another org
        co = CourseOverviewFactory()
        OrganizationCourseFactory(course_id=co.id, organization=other_org)

    course_ids = figures.sites.site_course_ids(site)
    assert set(course_ids) == set([str(co.id) for co in course_overviews])
def site_data(db, settings):
    """Simple fake site data
    """
    if organizations_support_sites():
        settings.FEATURES['FIGURES_IS_MULTISITE'] = True
    site_data = make_site_data()

    ce = site_data['enrollments'][0]

    lcgm = [
        LearnerCourseGradeMetricsFactory(site=site_data['site'],
                                         user=ce.user,
                                         course_id=str(ce.course_id),
                                         date_for='2020-10-01'),
    ]

    site_data['lcgm'] = lcgm
    return site_data
def sog_data():
    """Fixture to create site, organization, and course overview

    This fixture exists mostly to help abstract multisite handing from tests

    Returns a dict of 'site', 'organization', and 'course_overview' objects
    """
    site = SiteFactory()
    course_overview = CourseOverviewFactory()
    if organizations_support_sites():
        organization = OrganizationFactory(sites=[site])
    else:
        organization = OrganizationFactory()
    OrganizationCourseFactory(organization=organization,
                              course_id=str(course_overview.id))
    return dict(site=site,
                organization=organization,
                course_overview=course_overview)
Beispiel #22
0
def backfill_test_data(db):
    """
    TODO: make counts different for each course per month
    """
    months_back = 6
    sm_per_month = [10 + i for i in range(months_back + 1)]
    site = SiteFactory()
    now = datetime.utcnow().replace(tzinfo=utc)

    first_month = now - relativedelta(months=months_back)
    last_month = now - relativedelta(months=1)
    course_overviews = [CourseOverviewFactory() for i in range(1)]
    count_check = []
    sm = []
    for i, dt in enumerate(
            rrule(freq=MONTHLY, dtstart=first_month, until=last_month)):
        for co in course_overviews:
            sm_count = sm_per_month[i]
            month_sm = [
                StudentModuleFactory(course_id=co.id, created=dt, modified=dt)
                for i in range(sm_count)
            ]
            sm += month_sm
        count_check.append(dict(month=dt, month_sm=month_sm,
                                sm_count=sm_count))
    if organizations_support_sites():
        org = OrganizationFactory(sites=[site])
        for co in course_overviews:
            OrganizationCourseFactory(organization=org, course_id=str(co.id))
        for rec in sm:
            UserOrganizationMappingFactory(user=rec.student, organization=org)
    else:
        org = OrganizationFactory()

    return dict(site=site,
                organization=org,
                course_overview=course_overviews,
                student_modules=sm,
                first_month=first_month,
                now=now,
                months_back=months_back,
                sm_per_month=sm_per_month,
                count_check=count_check)
Beispiel #23
0
    def test_list(self, monkeypatch, sm_test_data):

        site = sm_test_data['site']
        org = sm_test_data['organization']
        if organizations_support_sites():
            caller = UserFactory()
            UserOrganizationMappingFactory(user=caller,
                                           organization=org,
                                           is_amc_admin=True)
        else:
            caller = UserFactory(is_staff=True)
        request = APIRequestFactory().get(self.request_path)
        request.META['HTTP_HOST'] = site.domain
        monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site',
                            lambda req: site)
        force_authenticate(request, user=caller)
        view = self.view_class.as_view({'get': 'list'})
        response = view(request)

        assert response.status_code == status.HTTP_200_OK
    def test_retrieve_method(self, monkeypatch, course_test_data):
        site = course_test_data['site']
        users = course_test_data['users']
        course_overview = course_test_data['course_overview']

        if organizations_support_sites():
            caller = UserFactory(is_staff=True)
            map_users_to_org_site(caller=caller, site=site, users=users)
        else:
            caller = UserFactory(is_staff=True)

        request_path = self.base_request_path
        request = APIRequestFactory().get(request_path)
        request.META['HTTP_HOST'] = site.domain
        monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site',
                            lambda req: site)
        force_authenticate(request, user=caller)
        view = self.view_class.as_view({'get': 'retrieve'})
        response = view(request, pk=str(course_overview.id))
        assert response.status_code == status.HTTP_200_OK
    def test_retrieve_invalid_course_id(self, monkeypatch, course_test_data,
                                        invalid_course_id):
        """Tests that invalid course ids return '404 NOT FOUND'
        """
        site = course_test_data['site']
        users = course_test_data['users']
        if organizations_support_sites():
            caller = UserFactory(is_staff=True)
            map_users_to_org_site(caller=caller, site=site, users=users)
        else:
            caller = UserFactory(is_staff=True)

        request_path = self.base_request_path
        request = APIRequestFactory().get(request_path)
        request.META['HTTP_HOST'] = site.domain
        monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site',
                            lambda req: site)
        force_authenticate(request, user=caller)
        view = self.view_class.as_view({'get': 'retrieve'})
        response = view(request, pk=invalid_course_id)
        assert response.status_code == status.HTTP_404_NOT_FOUND
    def test_site_courses(self, monkeypatch, user_reg_test_data):
        endpoint = 'site_courses'
        request_method = 'get'
        site = user_reg_test_data['site']
        users = user_reg_test_data['users']
        dates = user_reg_test_data['dates']
        months_back = user_reg_test_data['months_back']

        if organizations_support_sites():
            caller = UserFactory(is_staff=True)
            map_users_to_org_site(caller=caller, site=site, users=users)
        else:
            caller = UserFactory(is_staff=True)

        request = APIRequestFactory().get(self.request_path)
        request.META['HTTP_HOST'] = site.domain
        monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site',
                            lambda req: site)
        force_authenticate(request, user=caller)
        view = self.view_class.as_view({request_method: endpoint})
        response = view(request)
        assert self.check_response(response=response, endpoint=endpoint)
Beispiel #27
0
def test_student_modules_for_course_enrollment(monkeypatch):
    """Test we get the correct student modules for the given course enrollment
    """
    site = SiteFactory()
    ce = CourseEnrollmentFactory()
    ce_sm = [StudentModuleFactory(student=ce.user, course_id=ce.course_id)]
    # Create another student module record to make sure this is not in our
    # query results
    StudentModuleFactory()

    if organizations_support_sites():
        monkeypatch.setattr('figures.sites.is_multisite', lambda: True)
        our_org = OrganizationFactory(sites=[site])
        other_org = OrganizationFactory(sites=[SiteFactory()])
        other_org_ce = CourseEnrollmentFactory()
        other_sm = StudentModuleFactory(student=other_org_ce.user,
                                        course_id=other_org_ce.course_id)
        UserOrganizationMappingFactory(user=ce.user, organization=our_org)
        UserOrganizationMappingFactory(user=other_org_ce.user,
                                       organization=other_org)

    sm = figures.sites.student_modules_for_course_enrollment(site, ce)
    assert set(sm) == set(ce_sm)
Beispiel #28
0
def test_get_site_mau_current_month(db):

    mock_today = date(year=2020, month=3, day=1)
    freezer = freeze_time(mock_today)
    freezer.start()

    start_dt = datetime(mock_today.year,
                        mock_today.month,
                        1,
                        tzinfo=fuzzy.compat.UTC)
    end_dt = datetime(mock_today.year,
                      mock_today.month,
                      31,
                      tzinfo=fuzzy.compat.UTC)
    date_gen = fuzzy.FuzzyDateTime(start_dt=start_dt, end_dt=end_dt)
    site = SiteFactory()
    course_overviews = [CourseOverviewFactory() for i in range(2)]
    users = [UserFactory() for i in range(2)]
    sm = []
    for user in users:
        for co in course_overviews:
            sm.append(
                StudentModuleFactory(course_id=co.id,
                                     student=user,
                                     modified=date_gen.evaluate(
                                         2, None, False)))

    if organizations_support_sites():
        org = OrganizationFactory(sites=[site])
        for co in course_overviews:
            OrganizationCourseFactory(organization=org, course_id=str(co.id))
        for user in users:
            UserOrganizationMappingFactory(user=user, organization=org)

    active_user_count = get_site_mau_current_month(site)
    freezer.stop()
    assert active_user_count == len(users)
Beispiel #29
0
    save_course_mau,
    collect_course_mau,
)

from tests.factories import (
    SiteFactory,
    CourseOverviewFactory,
    OrganizationFactory,
    OrganizationCourseFactory,
    StudentModuleFactory,
)

from tests.helpers import organizations_support_sites
from six.moves import range

if organizations_support_sites():
    from tests.factories import UserOrganizationMappingFactory


def create_student_module_recs(course_id):
    """
    Create StudentModule records for our test data
    We create records within the test month and before and after our test month

    Improve this by passing the year and month for which we want to check
    record inclusion and deriving dates outside of our month range for the
    StudentModule records we want to exclude
    """
    # Create SM in our month
    year_for = 2020
    month_for = 1
Beispiel #30
0
import figures.helpers
import figures.sites

from tests.factories import (
    CourseEnrollmentFactory,
    CourseOverviewFactory,
    OrganizationFactory,
    OrganizationCourseFactory,
    SiteFactory,
    StudentModuleFactory,
    UserFactory,
)
from tests.helpers import organizations_support_sites

if organizations_support_sites():
    from tests.factories import UserOrganizationMappingFactory


@pytest.mark.django_db
class TestHandlersForStandaloneMode(object):
    """
    Tests figures.sites site handling functions in standalone site mode
    These tests should pass regardless of whether or not and if so how
    organizations supports organization-site mapping
    """
    @pytest.fixture(autouse=True)
    def setup(self, db, settings):
        settings.FEATURES['FIGURES_IS_MULTISITE'] = False
        is_multisite = figures.helpers.is_multisite()
        assert not is_multisite