test_views.py 54.2 KB
Newer Older
1 2 3
"""
test views
"""
4 5 6
import datetime
import json
import re
7
import urlparse
8 9 10 11

import ddt
import pytz
from ccx_keys.locator import CCXLocator
12
from dateutil.tz import tzutc
13 14 15 16 17 18 19
from django.conf import settings
from django.core.urlresolvers import resolve, reverse
from django.test import RequestFactory
from django.test.utils import override_settings
from django.utils.timezone import UTC
from django.utils.translation import ugettext as _
from mock import MagicMock, patch
20
from nose.plugins.attrib import attr
21
from opaque_keys.edx.keys import CourseKey
22

23
from capa.tests.response_xml_factory import StringResponseXMLFactory
24
from courseware.courses import get_course_by_id
25
from courseware.tabs import get_course_tab_list
26 27
from courseware.tests.factories import StudentModuleFactory
from courseware.tests.helpers import LoginEnrollmentTestCase
28
from courseware.testutils import FieldOverrideTestMixin
29 30 31
from django_comment_client.utils import has_forum_access
from django_comment_common.models import FORUM_ROLE_ADMINISTRATOR
from django_comment_common.utils import are_permissions_roles_seeded
32
from edxmako.shortcuts import render_to_response
33 34 35
from lms.djangoapps.ccx.models import CustomCourseForEdX
from lms.djangoapps.ccx.overrides import get_override_for_ccx, override_field_for_ccx
from lms.djangoapps.ccx.tests.factories import CcxFactory
36 37
from lms.djangoapps.ccx.tests.utils import CcxTestCase, flatten
from lms.djangoapps.ccx.utils import ccx_course, is_email
38
from lms.djangoapps.ccx.views import get_date
39 40 41 42 43 44
from lms.djangoapps.instructor.access import allow_access, list_with_level
from request_cache.middleware import RequestCache
from student.models import CourseEnrollment, CourseEnrollmentAllowed
from student.roles import CourseCcxCoachRole, CourseInstructorRole, CourseStaffRole
from student.tests.factories import AdminFactory, CourseEnrollmentFactory, UserFactory
from xmodule.modulestore import ModuleStoreEnum
45
from xmodule.modulestore.django import modulestore
46 47 48 49 50 51 52
from xmodule.modulestore.tests.django_utils import (
    TEST_DATA_SPLIT_MODULESTORE,
    ModuleStoreTestCase,
    SharedModuleStoreTestCase
)
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory, SampleCourseFactory
from xmodule.x_module import XModuleMixin
53

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68

def intercept_renderer(path, context):
    """
    Intercept calls to `render_to_response` and attach the context dict to the
    response for examination in unit tests.
    """
    # I think Django already does this for you in their TestClient, except
    # we're bypassing that by using edxmako.  Probably edxmako should be
    # integrated better with Django's rendering and event system.
    response = render_to_response(path, context)
    response.mako_context = context
    response.mako_template = path
    return response


69 70 71 72 73 74 75 76 77 78 79
def ccx_dummy_request():
    """
    Returns dummy request object for CCX coach tab test
    """
    factory = RequestFactory()
    request = factory.get('ccx_coach_dashboard')
    request.user = MagicMock()

    return request


80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
def setup_students_and_grades(context):
    """
    Create students and set their grades.
    :param context:  class reference
    """
    if context.course:
        context.student = student = UserFactory.create()
        CourseEnrollmentFactory.create(user=student, course_id=context.course.id)

        context.student2 = student2 = UserFactory.create()
        CourseEnrollmentFactory.create(user=student2, course_id=context.course.id)

        # create grades for self.student as if they'd submitted the ccx
        for chapter in context.course.get_children():
            for i, section in enumerate(chapter.get_children()):
                for j, problem in enumerate(section.get_children()):
                    # if not problem.visible_to_staff_only:
                    StudentModuleFactory.create(
                        grade=1 if i < j else 0,
                        max_grade=1,
                        student=context.student,
                        course_id=context.course.id,
                        module_state_key=problem.location
                    )

                    StudentModuleFactory.create(
                        grade=1 if i > j else 0,
                        max_grade=1,
                        student=context.student2,
                        course_id=context.course.id,
                        module_state_key=problem.location
                    )


114 115 116 117 118 119 120 121 122 123
def unhide(unit):
    """
    Recursively unhide a unit and all of its children in the CCX
    schedule.
    """
    unit['hidden'] = False
    for child in unit.get('children', ()):
        unhide(child)


124 125 126 127 128 129
class TestAdminAccessCoachDashboard(CcxTestCase, LoginEnrollmentTestCase):
    """
    Tests for Custom Courses views.
    """
    MODULESTORE = TEST_DATA_SPLIT_MODULESTORE

130 131 132 133 134 135 136
    def setUp(self):
        super(TestAdminAccessCoachDashboard, self).setUp()
        self.make_coach()
        ccx = self.make_ccx()
        ccx_key = CCXLocator.from_course_locator(self.course.id, ccx.id)
        self.url = reverse('ccx_coach_dashboard', kwargs={'course_id': ccx_key})

137 138 139 140 141 142
    def test_staff_access_coach_dashboard(self):
        """
        User is staff, should access coach dashboard.
        """
        staff = self.make_staff()
        self.client.login(username=staff.username, password="test")
143 144

        response = self.client.get(self.url)
145 146 147 148 149 150 151 152
        self.assertEqual(response.status_code, 200)

    def test_instructor_access_coach_dashboard(self):
        """
        User is instructor, should access coach dashboard.
        """
        instructor = self.make_instructor()
        self.client.login(username=instructor.username, password="test")
153 154 155

        # Now access URL
        response = self.client.get(self.url)
156 157 158 159 160 161 162 163
        self.assertEqual(response.status_code, 200)

    def test_forbidden_user_access_coach_dashboard(self):
        """
        Assert user with no access must not see dashboard.
        """
        user = UserFactory.create(password="test")
        self.client.login(username=user.username, password="test")
164
        response = self.client.get(self.url)
165 166 167
        self.assertEqual(response.status_code, 403)


168
@attr(shard=1)
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
@override_settings(
    XBLOCK_FIELD_DATA_WRAPPERS=['lms.djangoapps.courseware.field_overrides:OverrideModulestoreFieldData.wrap'],
    MODULESTORE_FIELD_OVERRIDE_PROVIDERS=['ccx.overrides.CustomCoursesForEdxOverrideProvider'],
)
class TestCCXProgressChanges(CcxTestCase, LoginEnrollmentTestCase):
    """
    Tests ccx schedule changes in progress page
    """
    @classmethod
    def setUpClass(cls):
        """
        Set up tests
        """
        super(TestCCXProgressChanges, cls).setUpClass()
        start = datetime.datetime(2016, 7, 1, 0, 0, tzinfo=tzutc())
        due = datetime.datetime(2016, 7, 8, 0, 0, tzinfo=tzutc())

        cls.course = course = CourseFactory.create(enable_ccx=True, start=start)
        chapter = ItemFactory.create(start=start, parent=course, category=u'chapter')
        sequential = ItemFactory.create(
            parent=chapter,
            start=start,
            due=due,
            category=u'sequential',
            metadata={'graded': True, 'format': 'Homework'}
        )
        vertical = ItemFactory.create(
            parent=sequential,
            start=start,
            due=due,
            category=u'vertical',
            metadata={'graded': True, 'format': 'Homework'}
        )

        # Trying to wrap the whole thing in a bulk operation fails because it
        # doesn't find the parents. But we can at least wrap this part...
        with cls.store.bulk_operations(course.id, emit_signals=False):
            flatten([ItemFactory.create(
                parent=vertical,
                start=start,
                due=due,
                category="problem",
                data=StringResponseXMLFactory().build_xml(answer='foo'),
                metadata={'rerandomize': 'always'}
            )] for _ in xrange(2))

    def assert_progress_summary(self, ccx_course_key, due):
        """
        assert signal and schedule update.
        """
        student = UserFactory.create(is_staff=False, password="test")
        CourseEnrollment.enroll(student, ccx_course_key)
        self.assertTrue(
            CourseEnrollment.objects.filter(course_id=ccx_course_key, user=student).exists()
        )

        # login as student
        self.client.login(username=student.username, password="test")
        progress_page_response = self.client.get(
            reverse('progress', kwargs={'course_id': ccx_course_key})
        )
        grade_summary = progress_page_response.mako_context['courseware_summary']  # pylint: disable=no-member
        chapter = grade_summary[0]
        section = chapter['sections'][0]
233
        progress_page_due_date = section.due.strftime("%Y-%m-%d %H:%M")
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
        self.assertEqual(progress_page_due_date, due)

    @patch('ccx.views.render_to_response', intercept_renderer)
    @patch('courseware.views.views.render_to_response', intercept_renderer)
    @patch.dict('django.conf.settings.FEATURES', {'CUSTOM_COURSES_EDX': True})
    def test_edit_schedule(self):
        """
        Get CCX schedule, modify it, save it.
        """
        self.make_coach()
        ccx = self.make_ccx()
        ccx_course_key = CCXLocator.from_course_locator(self.course.id, unicode(ccx.id))
        self.client.login(username=self.coach.username, password="test")

        url = reverse('ccx_coach_dashboard', kwargs={'course_id': ccx_course_key})
        response = self.client.get(url)

        schedule = json.loads(response.mako_context['schedule'])  # pylint: disable=no-member
        self.assertEqual(len(schedule), 1)

        unhide(schedule[0])

        # edit schedule
        date = datetime.datetime.now() - datetime.timedelta(days=5)
        start = date.strftime("%Y-%m-%d %H:%M")
        due = (date + datetime.timedelta(days=3)).strftime("%Y-%m-%d %H:%M")

        schedule[0]['start'] = start
        schedule[0]['children'][0]['start'] = start
        schedule[0]['children'][0]['due'] = due
        schedule[0]['children'][0]['children'][0]['start'] = start
        schedule[0]['children'][0]['children'][0]['due'] = due

        url = reverse('save_ccx', kwargs={'course_id': ccx_course_key})
        response = self.client.post(url, json.dumps(schedule), content_type='application/json')

        self.assertEqual(response.status_code, 200)

        schedule = json.loads(response.content)['schedule']
        self.assertEqual(schedule[0]['hidden'], False)
        self.assertEqual(schedule[0]['start'], start)
        self.assertEqual(schedule[0]['children'][0]['start'], start)
        self.assertEqual(schedule[0]['children'][0]['due'], due)
        self.assertEqual(schedule[0]['children'][0]['children'][0]['due'], due)
        self.assertEqual(schedule[0]['children'][0]['children'][0]['start'], start)

        self.assert_progress_summary(ccx_course_key, due)


283
@attr(shard=1)
284
@ddt.ddt
285
class TestCoachDashboard(CcxTestCase, LoginEnrollmentTestCase):
286
    """
cewing committed
287
    Tests for Custom Courses views.
288
    """
289

290 291 292 293 294 295
    @classmethod
    def setUpClass(cls):
        super(TestCoachDashboard, cls).setUpClass()
        cls.course_disable_ccx = CourseFactory.create(enable_ccx=False)
        cls.course_with_ccx_connect_set = CourseFactory.create(enable_ccx=True, ccx_connector="http://ccx.com")

296 297 298 299 300
    def setUp(self):
        """
        Set up tests
        """
        super(TestCoachDashboard, self).setUp()
301 302
        # Login with the instructor account
        self.client.login(username=self.coach.username, password="test")
303

304 305 306 307 308 309 310 311 312 313
        # adding staff to master course.
        staff = UserFactory()
        allow_access(self.course, staff, 'staff')
        self.assertTrue(CourseStaffRole(self.course.id).has_user(staff))

        # adding instructor to master course.
        instructor = UserFactory()
        allow_access(self.course, instructor, 'instructor')
        self.assertTrue(CourseInstructorRole(self.course.id).has_user(instructor))

314 315 316 317
    def test_not_a_coach(self):
        """
        User is not a coach, should get Forbidden response.
        """
318
        self.make_coach()
cewing committed
319
        ccx = self.make_ccx()
320 321 322 323

        # create session of non-coach user
        user = UserFactory.create(password="test")
        self.client.login(username=user.username, password="test")
324
        url = reverse(
cewing committed
325
            'ccx_coach_dashboard',
cewing committed
326
            kwargs={'course_id': CCXLocator.from_course_locator(self.course.id, ccx.id)})
327 328 329
        response = self.client.get(url)
        self.assertEqual(response.status_code, 403)

cewing committed
330
    def test_no_ccx_created(self):
331
        """
cewing committed
332
        No CCX is created, coach should see form to add a CCX.
333 334 335
        """
        self.make_coach()
        url = reverse(
cewing committed
336
            'ccx_coach_dashboard',
337
            kwargs={'course_id': unicode(self.course.id)})
338 339 340
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(re.search(
cewing committed
341
            '<form action=".+create_ccx"',
342 343
            response.content))

344 345 346 347
    def test_create_ccx_with_ccx_connector_set(self):
        """
        Assert that coach cannot create ccx when ``ccx_connector`` url is set.
        """
348
        role = CourseCcxCoachRole(self.course_with_ccx_connect_set.id)
349 350 351 352
        role.add_users(self.coach)

        url = reverse(
            'create_ccx',
353
            kwargs={'course_id': unicode(self.course_with_ccx_connect_set.id)})
354 355 356 357 358 359 360 361 362

        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        error_message = _(
            "A CCX can only be created on this course through an external service."
            " Contact a course admin to give you access."
        )
        self.assertTrue(re.search(error_message, response.content))

363
    def test_create_ccx(self, ccx_name='New CCX'):
364
        """
cewing committed
365 366
        Create CCX. Follow redirect to coach dashboard, confirm we see
        the coach dashboard for the new CCX.
367
        """
368

369 370
        self.make_coach()
        url = reverse(
cewing committed
371
            'create_ccx',
372 373
            kwargs={'course_id': unicode(self.course.id)})

374
        response = self.client.post(url, {'name': ccx_name})
375
        self.assertEqual(response.status_code, 302)
376
        url = response.get('location')  # pylint: disable=no-member
377 378
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
379 380 381 382 383 384 385 386 387

        # Get the ccx_key
        path = urlparse.urlparse(url).path
        resolver = resolve(path)
        ccx_key = resolver.kwargs['course_id']

        course_key = CourseKey.from_string(ccx_key)

        self.assertTrue(CourseEnrollment.is_enrolled(self.coach, course_key))
cewing committed
388
        self.assertTrue(re.search('id="ccx-schedule"', response.content))
389

390 391 392 393 394
        # check if the max amount of student that can be enrolled has been overridden
        ccx = CustomCourseForEdX.objects.get()
        course_enrollments = get_override_for_ccx(ccx, self.course, 'max_student_enrollments_allowed')
        self.assertEqual(course_enrollments, settings.CCX_MAX_STUDENTS_ALLOWED)

395 396
        # assert ccx creator has role=staff
        role = CourseStaffRole(course_key)
397
        self.assertTrue(role.has_user(self.coach))
398

399 400 401 402
        # assert that staff and instructors of master course has staff and instructor roles on ccx
        list_staff_master_course = list_with_level(self.course, 'staff')
        list_instructor_master_course = list_with_level(self.course, 'instructor')

403 404 405 406
        # assert that forum roles are seeded
        self.assertTrue(are_permissions_roles_seeded(course_key))
        self.assertTrue(has_forum_access(self.coach.username, course_key, FORUM_ROLE_ADMINISTRATOR))

407 408
        with ccx_course(course_key) as course_ccx:
            list_staff_ccx_course = list_with_level(course_ccx, 'staff')
409 410 411 412 413 414
            # The "Coach" in the parent course becomes "Staff" on the CCX, so the CCX should have 1 "Staff"
            # user more than the parent course
            self.assertEqual(len(list_staff_master_course) + 1, len(list_staff_ccx_course))
            self.assertIn(list_staff_master_course[0].email, [ccx_staff.email for ccx_staff in list_staff_ccx_course])
            # Make sure the "Coach" on the parent course is "Staff" on the CCX
            self.assertIn(self.coach, list_staff_ccx_course)
415 416 417 418 419

            list_instructor_ccx_course = list_with_level(course_ccx, 'instructor')
            self.assertEqual(len(list_instructor_ccx_course), len(list_instructor_master_course))
            self.assertEqual(list_instructor_ccx_course[0].email, list_instructor_master_course[0].email)

420 421 422 423
    @ddt.data("CCX demo 1", "CCX demo 2", "CCX demo 3")
    def test_create_multiple_ccx(self, ccx_name):
        self.test_create_ccx(ccx_name)

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
    def test_dashboard_access_of_disabled_ccx(self):
        """
        User should not see coach dashboard if ccx is disbale in studio.
        """
        ccx = CcxFactory(course_id=self.course_disable_ccx.id, coach=self.coach)
        url = reverse(
            'ccx_coach_dashboard',
            kwargs={'course_id': CCXLocator.from_course_locator(self.course_disable_ccx.id, ccx.id)})
        response = self.client.get(url)
        self.assertEqual(response.status_code, 404)

    def test_dashboard_access_with_invalid_ccx_id(self):
        """
        User should not see coach dashboard if ccx id is invalid.
        """
        self.make_ccx()
        url = reverse(
            'ccx_coach_dashboard',
            kwargs={'course_id': CCXLocator.from_course_locator(self.course_disable_ccx.id, 700)})
        response = self.client.get(url)
        self.assertEqual(response.status_code, 404)

446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
    def test_get_date(self):
        """
        Assert that get_date returns valid date.
        """
        ccx = self.make_ccx()
        for section in self.course.get_children():
            self.assertEqual(get_date(ccx, section, 'start'), self.mooc_start)
            self.assertEqual(get_date(ccx, section, 'due'), None)
            for subsection in section.get_children():
                self.assertEqual(get_date(ccx, subsection, 'start'), self.mooc_start)
                self.assertEqual(get_date(ccx, subsection, 'due'), self.mooc_due)
                for unit in subsection.get_children():
                    self.assertEqual(get_date(ccx, unit, 'start', parent_node=subsection), self.mooc_start)
                    self.assertEqual(get_date(ccx, unit, 'due', parent_node=subsection), self.mooc_due)

cewing committed
461 462
    @patch('ccx.views.render_to_response', intercept_renderer)
    @patch('ccx.views.TODAY')
463 464
    def test_edit_schedule(self, today):
        """
cewing committed
465
        Get CCX schedule, modify it, save it.
466 467
        """
        today.return_value = datetime.datetime(2014, 11, 25, tzinfo=pytz.UTC)
cewing committed
468 469
        self.make_coach()
        ccx = self.make_ccx()
470
        url = reverse(
cewing committed
471
            'ccx_coach_dashboard',
cewing committed
472
            kwargs={'course_id': CCXLocator.from_course_locator(self.course.id, ccx.id)})
473
        response = self.client.get(url)
474
        schedule = json.loads(response.mako_context['schedule'])  # pylint: disable=no-member
475

476
        self.assertEqual(len(schedule), 2)
cewing committed
477
        self.assertEqual(schedule[0]['hidden'], False)
478 479 480 481 482
        # If a coach does not override dates, then dates will be imported from master course.
        self.assertEqual(
            schedule[0]['start'],
            self.chapters[0].start.strftime('%Y-%m-%d %H:%M')
        )
483
        self.assertEqual(
484 485
            schedule[0]['children'][0]['start'],
            self.sequentials[0].start.strftime('%Y-%m-%d %H:%M')
486 487
        )

488 489 490 491 492 493
        if self.sequentials[0].due:
            expected_due = self.sequentials[0].due.strftime('%Y-%m-%d %H:%M')
        else:
            expected_due = None
        self.assertEqual(schedule[0]['children'][0]['due'], expected_due)

494
        url = reverse(
cewing committed
495
            'save_ccx',
cewing committed
496
            kwargs={'course_id': CCXLocator.from_course_locator(self.course.id, ccx.id)})
497

498
        unhide(schedule[0])
499 500
        schedule[0]['start'] = u'2014-11-20 00:00'
        schedule[0]['children'][0]['due'] = u'2014-12-25 00:00'  # what a jerk!
501 502 503
        schedule[0]['children'][0]['children'][0]['start'] = u'2014-12-20 00:00'
        schedule[0]['children'][0]['children'][0]['due'] = u'2014-12-25 00:00'

504 505 506 507
        response = self.client.post(
            url, json.dumps(schedule), content_type='application/json'
        )

508
        schedule = json.loads(response.content)['schedule']
509 510 511 512 513 514
        self.assertEqual(schedule[0]['hidden'], False)
        self.assertEqual(schedule[0]['start'], u'2014-11-20 00:00')
        self.assertEqual(
            schedule[0]['children'][0]['due'], u'2014-12-25 00:00'
        )

515 516 517 518 519 520 521
        self.assertEqual(
            schedule[0]['children'][0]['children'][0]['due'], u'2014-12-25 00:00'
        )
        self.assertEqual(
            schedule[0]['children'][0]['children'][0]['start'], u'2014-12-20 00:00'
        )

522 523
        # Make sure start date set on course, follows start date of earliest
        # scheduled chapter
cewing committed
524 525
        ccx = CustomCourseForEdX.objects.get()
        course_start = get_override_for_ccx(ccx, self.course, 'start')
526
        self.assertEqual(str(course_start)[:-9], self.chapters[0].start.strftime('%Y-%m-%d %H:%M'))
527

528
        # Make sure grading policy adjusted
cewing committed
529
        policy = get_override_for_ccx(ccx, self.course, 'grading_policy',
530 531
                                      self.course.grading_policy)
        self.assertEqual(policy['GRADER'][0]['type'], 'Homework')
cewing committed
532
        self.assertEqual(policy['GRADER'][0]['min_count'], 8)
533 534 535 536 537 538 539
        self.assertEqual(policy['GRADER'][1]['type'], 'Lab')
        self.assertEqual(policy['GRADER'][1]['min_count'], 0)
        self.assertEqual(policy['GRADER'][2]['type'], 'Midterm Exam')
        self.assertEqual(policy['GRADER'][2]['min_count'], 0)
        self.assertEqual(policy['GRADER'][3]['type'], 'Final Exam')
        self.assertEqual(policy['GRADER'][3]['min_count'], 0)

540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
    @patch('ccx.views.render_to_response', intercept_renderer)
    def test_save_without_min_count(self):
        """
        POST grading policy without min_count field.
        """
        self.make_coach()
        ccx = self.make_ccx()

        course_id = CCXLocator.from_course_locator(self.course.id, ccx.id)
        save_policy_url = reverse(
            'ccx_set_grading_policy', kwargs={'course_id': course_id})

        # This policy doesn't include a min_count field
        policy = {
            "GRADE_CUTOFFS": {
                "Pass": 0.5
            },
            "GRADER": [
                {
                    "weight": 0.15,
                    "type": "Homework",
                    "drop_count": 2,
                    "short_label": "HW"
                }
            ]
        }

        response = self.client.post(
            save_policy_url, {"policy": json.dumps(policy)}
        )
        self.assertEqual(response.status_code, 302)

        ccx = CustomCourseForEdX.objects.get()

        # Make sure grading policy adjusted
        policy = get_override_for_ccx(
            ccx, self.course, 'grading_policy', self.course.grading_policy
        )
        self.assertEqual(len(policy['GRADER']), 1)
        self.assertEqual(policy['GRADER'][0]['type'], 'Homework')
        self.assertNotIn('min_count', policy['GRADER'][0])

        save_ccx_url = reverse('save_ccx', kwargs={'course_id': course_id})
        coach_dashboard_url = reverse(
            'ccx_coach_dashboard',
            kwargs={'course_id': course_id}
        )
        response = self.client.get(coach_dashboard_url)
        schedule = json.loads(response.mako_context['schedule'])  # pylint: disable=no-member
        response = self.client.post(
            save_ccx_url, json.dumps(schedule), content_type='application/json'
        )
        self.assertEqual(response.status_code, 200)

594 595 596 597 598 599 600 601 602 603 604 605 606 607
    @ddt.data(
        ('ccx_invite', True, 1, 'student-ids', ('enrollment-button', 'Enroll')),
        ('ccx_invite', False, 0, 'student-ids', ('enrollment-button', 'Enroll')),
        ('ccx_manage_student', True, 1, 'student-id', ('student-action', 'add')),
        ('ccx_manage_student', False, 0, 'student-id', ('student-action', 'add')),
    )
    @ddt.unpack
    def test_enroll_member_student(self, view_name, send_email, outbox_count, student_form_input_name, button_tuple):
        """
        Tests the enrollment of  a list of students who are members
        of the class.

        It tests 2 different views that use slightly different parameters,
        but that perform the same task.
608
        """
609
        self.make_coach()
cewing committed
610
        ccx = self.make_ccx()
611 612 613
        enrollment = CourseEnrollmentFactory(course_id=self.course.id)
        student = enrollment.user
        outbox = self.get_outbox()
614
        self.assertEqual(outbox, [])
615 616

        url = reverse(
617
            view_name,
cewing committed
618
            kwargs={'course_id': CCXLocator.from_course_locator(self.course.id, ccx.id)}
619 620
        )
        data = {
621 622
            button_tuple[0]: button_tuple[1],
            student_form_input_name: u','.join([student.email, ]),  # pylint: disable=no-member
623
        }
624 625
        if send_email:
            data['email-students'] = 'Notify-students-by-email'
626 627 628 629
        response = self.client.post(url, data=data, follow=True)
        self.assertEqual(response.status_code, 200)
        # we were redirected to our current location
        self.assertEqual(len(response.redirect_chain), 1)
630
        self.assertIn(302, response.redirect_chain[0])
631 632 633
        self.assertEqual(len(outbox), outbox_count)
        if send_email:
            self.assertIn(student.email, outbox[0].recipients())  # pylint: disable=no-member
cewing committed
634
        # a CcxMembership exists for this student
635
        self.assertTrue(
636
            CourseEnrollment.objects.filter(course_id=self.course.id, user=student).exists()
637 638
        )

639
    def test_ccx_invite_enroll_up_to_limit(self):
640
        """
641
        Enrolls a list of students up to the enrollment limit.
642

643 644 645 646 647 648 649
        This test is specific to one of the enrollment views: the reason is because
        the view used in this test can perform bulk enrollments.
        """
        self.make_coach()
        # create ccx and limit the maximum amount of students that can be enrolled to 2
        ccx = self.make_ccx(max_students_allowed=2)
        ccx_course_key = CCXLocator.from_course_locator(self.course.id, ccx.id)
650 651 652
        staff = self.make_staff()
        instructor = self.make_instructor()

653
        # create some users
654
        students = [instructor, staff, self.coach] + [
655 656
            UserFactory.create(is_staff=False) for _ in range(3)
        ]
657

658
        url = reverse(
cewing committed
659
            'ccx_invite',
660
            kwargs={'course_id': ccx_course_key}
661 662
        )
        data = {
663
            'enrollment-button': 'Enroll',
664
            'student-ids': u','.join([student.email for student in students]),
665 666 667
        }
        response = self.client.post(url, data=data, follow=True)
        self.assertEqual(response.status_code, 200)
668
        # even if course is coach can enroll staff and admins of master course into ccx
669
        self.assertTrue(
670
            CourseEnrollment.objects.filter(course_id=ccx_course_key, user=instructor).exists()
671 672
        )
        self.assertTrue(
673 674 675 676 677 678 679 680 681 682 683 684
            CourseEnrollment.objects.filter(course_id=ccx_course_key, user=staff).exists()
        )
        self.assertTrue(
            CourseEnrollment.objects.filter(course_id=ccx_course_key, user=self.coach).exists()
        )

        # a CcxMembership exists for the first five students but not the sixth
        self.assertTrue(
            CourseEnrollment.objects.filter(course_id=ccx_course_key, user=students[3]).exists()
        )
        self.assertTrue(
            CourseEnrollment.objects.filter(course_id=ccx_course_key, user=students[4]).exists()
685 686
        )
        self.assertFalse(
687
            CourseEnrollment.objects.filter(course_id=ccx_course_key, user=students[5]).exists()
688
        )
689

690
    def test_manage_student_enrollment_limit(self):
691
        """
692
        Enroll students up to the enrollment limit.
693

694 695 696 697 698
        This test is specific to one of the enrollment views: the reason is because
        the view used in this test cannot perform bulk enrollments.
        """
        students_limit = 1
        self.make_coach()
699
        staff = self.make_staff()
700 701 702 703 704
        ccx = self.make_ccx(max_students_allowed=students_limit)
        ccx_course_key = CCXLocator.from_course_locator(self.course.id, ccx.id)
        students = [
            UserFactory.create(is_staff=False) for _ in range(2)
        ]
705

706
        url = reverse(
707 708
            'ccx_manage_student',
            kwargs={'course_id': CCXLocator.from_course_locator(self.course.id, ccx.id)}
709
        )
710
        # enroll the first student
711
        data = {
712
            'student-action': 'add',
713
            'student-id': students[0].email,
714 715 716
        }
        response = self.client.post(url, data=data, follow=True)
        self.assertEqual(response.status_code, 200)
717
        # a CcxMembership exists for this student
718
        self.assertTrue(
719
            CourseEnrollment.objects.filter(course_id=ccx_course_key, user=students[0]).exists()
720
        )
721

722 723 724 725
        # try to enroll the second student without success
        # enroll the first student
        data = {
            'student-action': 'add',
726
            'student-id': students[1].email,
727 728 729 730 731 732 733 734 735 736 737
        }
        response = self.client.post(url, data=data, follow=True)
        self.assertEqual(response.status_code, 200)
        # a CcxMembership does not exist for this student
        self.assertFalse(
            CourseEnrollment.objects.filter(course_id=ccx_course_key, user=students[1]).exists()
        )
        error_message = 'The course is full: the limit is {students_limit}'.format(
            students_limit=students_limit
        )
        self.assertContains(response, error_message, status_code=200)
738

739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
        # try to enroll the 3rd student which is staff
        data = {
            'student-action': 'add',
            'student-id': staff.email,
        }
        response = self.client.post(url, data=data, follow=True)
        self.assertEqual(response.status_code, 200)
        # staff gets enroll
        self.assertTrue(
            CourseEnrollment.objects.filter(course_id=ccx_course_key, user=staff).exists()
        )

        self.assertEqual(CourseEnrollment.objects.num_enrolled_in_exclude_admins(ccx_course_key), 1)

        # asert that number of enroll is still 0 because staff and instructor do not count.
        CourseEnrollment.enroll(staff, self.course.id)
        self.assertEqual(CourseEnrollment.objects.num_enrolled_in_exclude_admins(self.course.id), 0)
        # assert that handles  wrong ccx id code
        ccx_course_key_fake = CCXLocator.from_course_locator(self.course.id, 55)
        self.assertEqual(CourseEnrollment.objects.num_enrolled_in_exclude_admins(ccx_course_key_fake), 0)

760 761 762 763 764 765 766 767 768 769 770 771 772
    @ddt.data(
        ('ccx_invite', True, 1, 'student-ids', ('enrollment-button', 'Unenroll')),
        ('ccx_invite', False, 0, 'student-ids', ('enrollment-button', 'Unenroll')),
        ('ccx_manage_student', True, 1, 'student-id', ('student-action', 'revoke')),
        ('ccx_manage_student', False, 0, 'student-id', ('student-action', 'revoke')),
    )
    @ddt.unpack
    def test_unenroll_member_student(self, view_name, send_email, outbox_count, student_form_input_name, button_tuple):
        """
        Tests the unenrollment of a list of students who are members of the class.

        It tests 2 different views that use slightly different parameters,
        but that perform the same task.
773
        """
774
        self.make_coach()
cewing committed
775
        ccx = self.make_ccx()
776 777 778
        course_key = CCXLocator.from_course_locator(self.course.id, ccx.id)
        enrollment = CourseEnrollmentFactory(course_id=course_key)
        student = enrollment.user
779
        outbox = self.get_outbox()
780
        self.assertEqual(outbox, [])
781 782

        url = reverse(
783
            view_name,
784
            kwargs={'course_id': course_key}
785 786
        )
        data = {
787 788
            button_tuple[0]: button_tuple[1],
            student_form_input_name: u','.join([student.email, ]),  # pylint: disable=no-member
789
        }
790 791
        if send_email:
            data['email-students'] = 'Notify-students-by-email'
792 793 794 795
        response = self.client.post(url, data=data, follow=True)
        self.assertEqual(response.status_code, 200)
        # we were redirected to our current location
        self.assertEqual(len(response.redirect_chain), 1)
796
        self.assertIn(302, response.redirect_chain[0])
797 798 799 800
        self.assertEqual(len(outbox), outbox_count)
        if send_email:
            self.assertIn(student.email, outbox[0].recipients())  # pylint: disable=no-member
        # a CcxMembership does not exists for this student
801
        self.assertFalse(
802
            CourseEnrollment.objects.filter(course_id=self.course.id, user=student).exists()
803 804
        )

805 806 807 808 809 810 811 812 813 814 815 816 817
    @ddt.data(
        ('ccx_invite', True, 1, 'student-ids', ('enrollment-button', 'Enroll'), 'nobody@nowhere.com'),
        ('ccx_invite', False, 0, 'student-ids', ('enrollment-button', 'Enroll'), 'nobody@nowhere.com'),
        ('ccx_invite', True, 0, 'student-ids', ('enrollment-button', 'Enroll'), 'nobody'),
        ('ccx_invite', False, 0, 'student-ids', ('enrollment-button', 'Enroll'), 'nobody'),
        ('ccx_manage_student', True, 0, 'student-id', ('student-action', 'add'), 'dummy_student_id'),
        ('ccx_manage_student', False, 0, 'student-id', ('student-action', 'add'), 'dummy_student_id'),
        ('ccx_manage_student', True, 1, 'student-id', ('student-action', 'add'), 'xyz@gmail.com'),
        ('ccx_manage_student', False, 0, 'student-id', ('student-action', 'add'), 'xyz@gmail.com'),
    )
    @ddt.unpack
    def test_enroll_non_user_student(
            self, view_name, send_email, outbox_count, student_form_input_name, button_tuple, identifier):
818
        """
819
        Tests the enrollment of a list of students who are not users yet.
820

821 822
        It tests 2 different views that use slightly different parameters,
        but that perform the same task.
823 824
        """
        self.make_coach()
cewing committed
825
        ccx = self.make_ccx()
826
        course_key = CCXLocator.from_course_locator(self.course.id, ccx.id)
827
        outbox = self.get_outbox()
828
        self.assertEqual(outbox, [])
829 830

        url = reverse(
831
            view_name,
832
            kwargs={'course_id': course_key}
833 834
        )
        data = {
835 836
            button_tuple[0]: button_tuple[1],
            student_form_input_name: u','.join([identifier, ]),
837
        }
838 839
        if send_email:
            data['email-students'] = 'Notify-students-by-email'
840 841 842 843
        response = self.client.post(url, data=data, follow=True)
        self.assertEqual(response.status_code, 200)
        # we were redirected to our current location
        self.assertEqual(len(response.redirect_chain), 1)
844
        self.assertIn(302, response.redirect_chain[0])
845 846 847 848
        self.assertEqual(len(outbox), outbox_count)

        # some error messages are returned for one of the views only
        if view_name == 'ccx_manage_student' and not is_email(identifier):
849
            self.assertContains(response, 'Could not find a user with name or email ', status_code=200)
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872

        if is_email(identifier):
            if send_email:
                self.assertIn(identifier, outbox[0].recipients())
            self.assertTrue(
                CourseEnrollmentAllowed.objects.filter(course_id=course_key, email=identifier).exists()
            )
        else:
            self.assertFalse(
                CourseEnrollmentAllowed.objects.filter(course_id=course_key, email=identifier).exists()
            )

    @ddt.data(
        ('ccx_invite', True, 0, 'student-ids', ('enrollment-button', 'Unenroll'), 'nobody@nowhere.com'),
        ('ccx_invite', False, 0, 'student-ids', ('enrollment-button', 'Unenroll'), 'nobody@nowhere.com'),
        ('ccx_invite', True, 0, 'student-ids', ('enrollment-button', 'Unenroll'), 'nobody'),
        ('ccx_invite', False, 0, 'student-ids', ('enrollment-button', 'Unenroll'), 'nobody'),
    )
    @ddt.unpack
    def test_unenroll_non_user_student(
            self, view_name, send_email, outbox_count, student_form_input_name, button_tuple, identifier):
        """
        Unenroll a list of students who are not users yet
873 874
        """
        self.make_coach()
875
        course = CourseFactory.create()
cewing committed
876
        ccx = self.make_ccx()
877
        course_key = CCXLocator.from_course_locator(course.id, ccx.id)
878
        outbox = self.get_outbox()
879
        CourseEnrollmentAllowed(course_id=course_key, email=identifier)
880
        self.assertEqual(outbox, [])
881 882

        url = reverse(
883 884
            view_name,
            kwargs={'course_id': course_key}
885 886
        )
        data = {
887 888
            button_tuple[0]: button_tuple[1],
            student_form_input_name: u','.join([identifier, ]),
889
        }
890 891
        if send_email:
            data['email-students'] = 'Notify-students-by-email'
892 893 894 895
        response = self.client.post(url, data=data, follow=True)
        self.assertEqual(response.status_code, 200)
        # we were redirected to our current location
        self.assertEqual(len(response.redirect_chain), 1)
896
        self.assertIn(302, response.redirect_chain[0])
897 898 899 900 901 902
        self.assertEqual(len(outbox), outbox_count)
        self.assertFalse(
            CourseEnrollmentAllowed.objects.filter(
                course_id=course_key, email=identifier
            ).exists()
        )
903 904


905
@attr(shard=1)
906 907 908 909 910 911 912 913 914
class TestCoachDashboardSchedule(CcxTestCase, LoginEnrollmentTestCase, ModuleStoreTestCase):
    """
    Tests of the CCX Coach Dashboard which need to modify the course content.
    """

    ENABLED_CACHES = ['default', 'mongo_inheritance_cache', 'loc_cache']

    def setUp(self):
        super(TestCoachDashboardSchedule, self).setUp()
915
        self.course = course = CourseFactory.create(enable_ccx=True)
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032

        # Create a course outline
        self.mooc_start = start = datetime.datetime(
            2010, 5, 12, 2, 42, tzinfo=pytz.UTC
        )
        self.mooc_due = due = datetime.datetime(
            2010, 7, 7, 0, 0, tzinfo=pytz.UTC
        )

        self.chapters = [
            ItemFactory.create(start=start, parent=course) for _ in xrange(2)
        ]
        self.sequentials = flatten([
            [
                ItemFactory.create(parent=chapter) for _ in xrange(2)
            ] for chapter in self.chapters
        ])
        self.verticals = flatten([
            [
                ItemFactory.create(
                    start=start, due=due, parent=sequential, graded=True, format='Homework', category=u'vertical'
                ) for _ in xrange(2)
            ] for sequential in self.sequentials
        ])

        # Trying to wrap the whole thing in a bulk operation fails because it
        # doesn't find the parents. But we can at least wrap this part...
        with self.store.bulk_operations(course.id, emit_signals=False):
            blocks = flatten([  # pylint: disable=unused-variable
                [
                    ItemFactory.create(parent=vertical) for _ in xrange(2)
                ] for vertical in self.verticals
            ])

        # Create instructor account
        self.coach = UserFactory.create()
        # create an instance of modulestore
        self.mstore = modulestore()

        # Login with the instructor account
        self.client.login(username=self.coach.username, password="test")

        # adding staff to master course.
        staff = UserFactory()
        allow_access(self.course, staff, 'staff')
        self.assertTrue(CourseStaffRole(self.course.id).has_user(staff))

        # adding instructor to master course.
        instructor = UserFactory()
        allow_access(self.course, instructor, 'instructor')
        self.assertTrue(CourseInstructorRole(self.course.id).has_user(instructor))

        self.assertTrue(modulestore().has_course(self.course.id))

    def assert_elements_in_schedule(self, url, n_chapters=2, n_sequentials=4, n_verticals=8):
        """
        Helper function to count visible elements in the schedule
        """
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        # the schedule contains chapters
        chapters = json.loads(response.mako_context['schedule'])  # pylint: disable=no-member
        sequentials = flatten([chapter.get('children', []) for chapter in chapters])
        verticals = flatten([sequential.get('children', []) for sequential in sequentials])
        # check that the numbers of nodes at different level are the expected ones
        self.assertEqual(n_chapters, len(chapters))
        self.assertEqual(n_sequentials, len(sequentials))
        self.assertEqual(n_verticals, len(verticals))
        # extract the locations of all the nodes
        all_elements = chapters + sequentials + verticals
        return [elem['location'] for elem in all_elements if 'location' in elem]

    def hide_node(self, node):
        """
        Helper function to set the node `visible_to_staff_only` property
        to True and save the change
        """
        node.visible_to_staff_only = True
        self.mstore.update_item(node, self.coach.id)

    @patch('ccx.views.render_to_response', intercept_renderer)
    @patch('ccx.views.TODAY')
    def test_get_ccx_schedule(self, today):
        """
        Gets CCX schedule and checks number of blocks in it.
        Hides nodes at a different depth and checks that these nodes
        are not in the schedule.
        """
        today.return_value = datetime.datetime(2014, 11, 25, tzinfo=pytz.UTC)
        self.make_coach()
        ccx = self.make_ccx()
        url = reverse(
            'ccx_coach_dashboard',
            kwargs={
                'course_id': CCXLocator.from_course_locator(
                    self.course.id, ccx.id)
            }
        )
        # all the elements are visible
        self.assert_elements_in_schedule(url)
        # hide a vertical
        vertical = self.verticals[0]
        self.hide_node(vertical)
        locations = self.assert_elements_in_schedule(url, n_verticals=7)
        self.assertNotIn(unicode(vertical.location), locations)
        # hide a sequential
        sequential = self.sequentials[0]
        self.hide_node(sequential)
        locations = self.assert_elements_in_schedule(url, n_sequentials=3, n_verticals=6)
        self.assertNotIn(unicode(sequential.location), locations)
        # hide a chapter
        chapter = self.chapters[0]
        self.hide_node(chapter)
        locations = self.assert_elements_in_schedule(url, n_chapters=1, n_sequentials=2, n_verticals=4)
        self.assertNotIn(unicode(chapter.location), locations)


1033 1034 1035
GET_CHILDREN = XModuleMixin.get_children


cewing committed
1036 1037 1038 1039
def patched_get_children(self, usage_key_filter=None):
    """Emulate system tools that mask courseware not visible to students"""
    def iter_children():
        """skip children not visible to students"""
1040
        for child in GET_CHILDREN(self, usage_key_filter=usage_key_filter):
1041 1042 1043 1044 1045 1046
            child._field_data_cache = {}  # pylint: disable=protected-access
            if not child.visible_to_staff_only:
                yield child
    return list(iter_children())


1047
@attr(shard=1)
1048 1049 1050 1051
@override_settings(
    XBLOCK_FIELD_DATA_WRAPPERS=['lms.djangoapps.courseware.field_overrides:OverrideModulestoreFieldData.wrap'],
    MODULESTORE_FIELD_OVERRIDE_PROVIDERS=['ccx.overrides.CustomCoursesForEdxOverrideProvider'],
)
1052
@patch('xmodule.x_module.XModuleMixin.get_children', patched_get_children, spec=True)
1053
class TestCCXGrades(FieldOverrideTestMixin, SharedModuleStoreTestCase, LoginEnrollmentTestCase):
1054
    """
cewing committed
1055
    Tests for Custom Courses views.
1056
    """
cewing committed
1057 1058
    MODULESTORE = TEST_DATA_SPLIT_MODULESTORE

1059 1060 1061 1062
    @classmethod
    def setUpClass(cls):
        super(TestCCXGrades, cls).setUpClass()
        cls._course = course = CourseFactory.create(enable_ccx=True)
1063 1064

        # Create a course outline
1065
        cls.mooc_start = start = datetime.datetime(
1066 1067
            2010, 5, 12, 2, 42, tzinfo=pytz.UTC
        )
1068
        chapter = ItemFactory.create(
1069
            start=start, parent=course, category='sequential'
1070
        )
1071
        cls.sections = sections = [
1072 1073 1074 1075
            ItemFactory.create(
                parent=chapter,
                category="sequential",
                metadata={'graded': True, 'format': 'Homework'})
1076 1077
            for _ in xrange(4)
        ]
1078
        # making problems available at class level for possible future use in tests
1079
        cls.problems = [
cewing committed
1080 1081
            [
                ItemFactory.create(
1082 1083 1084 1085
                    parent=section,
                    category="problem",
                    data=StringResponseXMLFactory().build_xml(answer='foo'),
                    metadata={'rerandomize': 'always'}
cewing committed
1086
                ) for _ in xrange(4)
1087
            ] for section in sections
cewing committed
1088 1089
        ]

1090 1091 1092 1093 1094 1095
    def setUp(self):
        """
        Set up tests
        """
        super(TestCCXGrades, self).setUp()

1096 1097 1098 1099
        # Create instructor account
        self.coach = coach = AdminFactory.create()
        self.client.login(username=coach.username, password="test")

cewing committed
1100
        # Create CCX
1101
        role = CourseCcxCoachRole(self._course.id)
cewing committed
1102
        role.add_users(coach)
1103
        ccx = CcxFactory(course_id=self._course.id, coach=self.coach)
1104

cewing committed
1105
        # override course grading policy and make last section invisible to students
1106
        override_field_for_ccx(ccx, self._course, 'grading_policy', {
1107 1108 1109 1110 1111 1112 1113 1114 1115
            'GRADER': [
                {'drop_count': 0,
                 'min_count': 2,
                 'short_label': 'HW',
                 'type': 'Homework',
                 'weight': 1}
            ],
            'GRADE_CUTOFFS': {'Pass': 0.75},
        })
cewing committed
1116
        override_field_for_ccx(
1117 1118
            ccx, self.sections[-1], 'visible_to_staff_only', True
        )
1119

cewing committed
1120 1121
        # create a ccx locator and retrieve the course structure using that key
        # which emulates how a student would get access.
1122
        self.ccx_key = CCXLocator.from_course_locator(self._course.id, unicode(ccx.id))
1123
        self.course = get_course_by_id(self.ccx_key, depth=None)
1124
        setup_students_and_grades(self)
cewing committed
1125
        self.client.login(username=coach.username, password="test")
1126
        self.addCleanup(RequestCache.clear_request_cache)
1127 1128 1129 1130 1131 1132 1133
        from xmodule.modulestore.django import SignalHandler

        # using CCX object as sender here.
        SignalHandler.course_published.send(
            sender=ccx,
            course_key=self.ccx_key
        )
1134

cewing committed
1135
    @patch('ccx.views.render_to_response', intercept_renderer)
1136
    @patch('lms.djangoapps.instructor.views.gradebook_api.MAX_STUDENTS_PER_PAGE_GRADE_BOOK', 1)
1137
    def test_gradebook(self):
1138
        self.course.enable_ccx = True
1139 1140
        RequestCache.clear_request_cache()

1141
        url = reverse(
cewing committed
1142
            'ccx_gradebook',
cewing committed
1143
            kwargs={'course_id': self.ccx_key}
1144 1145 1146
        )
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
1147 1148
        # Max number of student per page is one.  Patched setting MAX_STUDENTS_PER_PAGE_GRADE_BOOK = 1
        self.assertEqual(len(response.mako_context['students']), 1)  # pylint: disable=no-member
1149
        student_info = response.mako_context['students'][0]  # pylint: disable=no-member
1150
        self.assertEqual(student_info['grade_summary']['percent'], 0.5)
1151 1152
        self.assertEqual(student_info['grade_summary']['grade_breakdown'].values()[0]['percent'], 0.5)
        self.assertEqual(len(student_info['grade_summary']['section_breakdown']), 4)
1153 1154

    def test_grades_csv(self):
1155
        self.course.enable_ccx = True
1156 1157
        RequestCache.clear_request_cache()

1158
        url = reverse(
cewing committed
1159
            'ccx_grades_csv',
cewing committed
1160
            kwargs={'course_id': self.ccx_key}
1161 1162 1163
        )
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
1164 1165 1166 1167 1168
        # Are the grades downloaded as an attachment?
        self.assertEqual(
            response['content-disposition'],
            'attachment'
        )
1169 1170
        rows = response.content.strip().split('\r')
        headers = rows[0]
1171

1172 1173 1174 1175 1176 1177 1178
        # picking first student records
        data = dict(zip(headers.strip().split(','), rows[1].strip().split(',')))
        self.assertNotIn('HW 04', data)
        self.assertEqual(data['HW 01'], '0.75')
        self.assertEqual(data['HW 02'], '0.5')
        self.assertEqual(data['HW 03'], '0.25')
        self.assertEqual(data['HW Avg'], '0.5')
1179

1180
    @patch('courseware.views.views.render_to_response', intercept_renderer)
1181
    def test_student_progress(self):
1182
        self.course.enable_ccx = True
1183
        patch_context = patch('courseware.views.views.get_course_with_access')
1184 1185 1186 1187 1188 1189 1190
        get_course = patch_context.start()
        get_course.return_value = self.course
        self.addCleanup(patch_context.stop)

        self.client.login(username=self.student.username, password="test")
        url = reverse(
            'progress',
cewing committed
1191
            kwargs={'course_id': self.ccx_key}
1192
        )
1193 1194
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
1195
        grades = response.mako_context['grade_summary']  # pylint: disable=no-member
1196
        self.assertEqual(grades['percent'], 0.5)
1197
        self.assertEqual(grades['grade_breakdown'].values()[0]['percent'], 0.5)
1198
        self.assertEqual(len(grades['section_breakdown']), 4)
1199

1200

1201
@ddt.ddt
1202
class CCXCoachTabTestCase(CcxTestCase):
1203 1204 1205
    """
    Test case for CCX coach tab.
    """
1206 1207 1208 1209 1210 1211
    @classmethod
    def setUpClass(cls):
        super(CCXCoachTabTestCase, cls).setUpClass()
        cls.ccx_enabled_course = CourseFactory.create(enable_ccx=True)
        cls.ccx_disabled_course = CourseFactory.create(enable_ccx=False)

1212 1213
    def setUp(self):
        super(CCXCoachTabTestCase, self).setUp()
1214
        self.user = UserFactory.create()
1215 1216 1217 1218
        for course in [self.ccx_enabled_course, self.ccx_disabled_course]:
            CourseEnrollmentFactory.create(user=self.user, course_id=course.id)
            role = CourseCcxCoachRole(course.id)
            role.add_users(self.user)
1219

1220
    def check_ccx_tab(self, course, user):
1221
        """Helper function for verifying the ccx tab."""
1222
        request = RequestFactory().request()
1223
        request.user = user
1224
        all_tabs = get_course_tab_list(request, course)
1225
        return any(tab.type == 'ccx_coach' for tab in all_tabs)
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238

    @ddt.data(
        (True, True, True),
        (True, False, False),
        (False, True, False),
        (False, False, False),
        (True, None, False)
    )
    @ddt.unpack
    def test_coach_tab_for_ccx_advance_settings(self, ccx_feature_flag, enable_ccx, expected_result):
        """
        Test ccx coach tab state (visible or hidden) depending on the value of enable_ccx flag, ccx feature flag.
        """
1239
        with self.settings(FEATURES={'CUSTOM_COURSES_EDX': ccx_feature_flag}):
1240
            course = self.ccx_enabled_course if enable_ccx else self.ccx_disabled_course
1241 1242
            self.assertEquals(
                expected_result,
1243
                self.check_ccx_tab(course, self.user)
1244 1245
            )

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
    def test_ccx_tab_visibility_for_staff_when_not_coach_master_course(self):
        """
        Staff cannot view ccx coach dashboard on master course by default.
        """
        staff = self.make_staff()
        self.assertFalse(self.check_ccx_tab(self.course, staff))

    def test_ccx_tab_visibility_for_staff_when_coach_master_course(self):
        """
        Staff can view ccx coach dashboard only if he is coach on master course.
        """
        staff = self.make_staff()
        role = CourseCcxCoachRole(self.course.id)
        role.add_users(staff)
        self.assertTrue(self.check_ccx_tab(self.course, staff))

    def test_ccx_tab_visibility_for_staff_ccx_course(self):
        """
        Staff can access coach dashboard on ccx course.
        """
        self.make_coach()
        ccx = self.make_ccx()
        ccx_key = CCXLocator.from_course_locator(self.course.id, unicode(ccx.id))
1269
        staff = self.make_staff()
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297

        with ccx_course(ccx_key) as course_ccx:
            allow_access(course_ccx, staff, 'staff')
            self.assertTrue(self.check_ccx_tab(course_ccx, staff))

    def test_ccx_tab_visibility_for_instructor_when_not_coach_master_course(self):
        """
        Instructor cannot view ccx coach dashboard on master course by default.
        """
        instructor = self.make_instructor()
        self.assertFalse(self.check_ccx_tab(self.course, instructor))

    def test_ccx_tab_visibility_for_instructor_when_coach_master_course(self):
        """
        Instructor can view ccx coach dashboard only if he is coach on master course.
        """
        instructor = self.make_instructor()
        role = CourseCcxCoachRole(self.course.id)
        role.add_users(instructor)
        self.assertTrue(self.check_ccx_tab(self.course, instructor))

    def test_ccx_tab_visibility_for_instructor_ccx_course(self):
        """
        Instructor can access coach dashboard on ccx course.
        """
        self.make_coach()
        ccx = self.make_ccx()
        ccx_key = CCXLocator.from_course_locator(self.course.id, unicode(ccx.id))
1298
        instructor = self.make_instructor()
1299 1300 1301 1302 1303

        with ccx_course(ccx_key) as course_ccx:
            allow_access(course_ccx, instructor, 'instructor')
            self.assertTrue(self.check_ccx_tab(course_ccx, instructor))

1304

1305
class TestStudentViewsWithCCX(ModuleStoreTestCase):
1306
    """
1307
    Test to ensure that the student dashboard and courseware works for users enrolled in CCX
1308 1309 1310 1311 1312 1313 1314
    courses.
    """

    def setUp(self):
        """
        Set up courses and enrollments.
        """
1315
        super(TestStudentViewsWithCCX, self).setUp()
1316 1317 1318 1319

        # Create a Draft Mongo and a Split Mongo course and enroll a student user in them.
        self.student_password = "foobar"
        self.student = UserFactory.create(username="test", password=self.student_password, is_staff=False)
1320 1321
        self.draft_course = SampleCourseFactory.create(default_store=ModuleStoreEnum.Type.mongo)
        self.split_course = SampleCourseFactory.create(default_store=ModuleStoreEnum.Type.split)
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
        CourseEnrollment.enroll(self.student, self.draft_course.id)
        CourseEnrollment.enroll(self.student, self.split_course.id)

        # Create a CCX coach.
        self.coach = AdminFactory.create()
        role = CourseCcxCoachRole(self.split_course.id)
        role.add_users(self.coach)

        # Create a CCX course and enroll the user in it.
        self.ccx = CcxFactory(course_id=self.split_course.id, coach=self.coach)
        last_week = datetime.datetime.now(UTC()) - datetime.timedelta(days=7)
        override_field_for_ccx(self.ccx, self.split_course, 'start', last_week)  # Required by self.ccx.has_started().
1334 1335
        self.ccx_course_key = CCXLocator.from_course_locator(self.split_course.id, self.ccx.id)
        CourseEnrollment.enroll(self.student, self.ccx_course_key)
1336 1337 1338 1339 1340

    def test_load_student_dashboard(self):
        self.client.login(username=self.student.username, password=self.student_password)
        response = self.client.get(reverse('dashboard'))
        self.assertEqual(response.status_code, 200)
1341
        self.assertTrue(re.search('Test CCX', response.content))
1342 1343 1344 1345 1346

    def test_load_courseware(self):
        self.client.login(username=self.student.username, password=self.student_password)
        response = self.client.get(reverse('courseware', kwargs={'course_id': unicode(self.ccx_course_key)}))
        self.assertEqual(response.status_code, 200)