test_api.py 90.5 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
"""
3
Unit tests for instructor.api methods.
4
"""
David Baumgold committed
5
# pylint: disable=E1111
6
import unittest
7
import json
8
import requests
9
import datetime
10
import ddt
11
from urllib import quote
12
from django.test import TestCase
13
from nose.tools import raises
Miles Steele committed
14
from mock import Mock, patch
15
from django.conf import settings
16 17
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
18
from django.http import HttpRequest, HttpResponse
19 20
from django_comment_common.models import FORUM_ROLE_COMMUNITY_TA, Role
from django_comment_common.utils import seed_permissions_roles
21
from django.core import mail
22
from django.utils.timezone import utc
23
from django.test import RequestFactory
24

25
from django.contrib.auth.models import User
26
from courseware.tests.modulestore_config import TEST_DATA_MIXED_MODULESTORE
27 28
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from courseware.tests.helpers import LoginEnrollmentTestCase
29
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
30
from student.tests.factories import UserFactory
31 32
from courseware.tests.factories import StaffFactory, InstructorFactory, BetaTesterFactory
from student.roles import CourseBetaTesterRole
33
from microsite_configuration import microsite
34

35
from student.models import CourseEnrollment, CourseEnrollmentAllowed
36
from courseware.models import StudentModule
37

Miles Steele committed
38 39
# modules which are mocked in test cases.
import instructor_task.api
40
from instructor.access import allow_access
41
import instructor.views.api
42
from instructor.views.api import _split_input_list, common_exceptions_400
43
from instructor_task.api_helper import AlreadyRunningError
44
from opaque_keys.edx.locations import SlashSeparatedCourseKey
45

46
from .test_tools import msk_from_problem_urlname, get_extended_due
47

48 49

@common_exceptions_400
David Baumgold committed
50
def view_success(request):  # pylint: disable=W0613
51 52 53 54 55
    "A dummy view for testing that returns a simple HTTP response"
    return HttpResponse('success')


@common_exceptions_400
David Baumgold committed
56
def view_user_doesnotexist(request):  # pylint: disable=W0613
57 58 59 60 61
    "A dummy view that raises a User.DoesNotExist exception"
    raise User.DoesNotExist()


@common_exceptions_400
David Baumgold committed
62
def view_alreadyrunningerror(request):  # pylint: disable=W0613
63 64 65 66 67
    "A dummy view that raises an AlreadyRunningError exception"
    raise AlreadyRunningError()


class TestCommonExceptions400(unittest.TestCase):
David Baumgold committed
68 69 70
    """
    Testing the common_exceptions_400 decorator.
    """
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
    def setUp(self):
        self.request = Mock(spec=HttpRequest)
        self.request.META = {}

    def test_happy_path(self):
        resp = view_success(self.request)
        self.assertEqual(resp.status_code, 200)

    def test_user_doesnotexist(self):
        self.request.is_ajax.return_value = False
        resp = view_user_doesnotexist(self.request)
        self.assertEqual(resp.status_code, 400)
        self.assertIn("User does not exist", resp.content)

    def test_user_doesnotexist_ajax(self):
        self.request.is_ajax.return_value = True
        resp = view_user_doesnotexist(self.request)
        self.assertEqual(resp.status_code, 400)
        result = json.loads(resp.content)
        self.assertIn("User does not exist", result["error"])

    def test_alreadyrunningerror(self):
        self.request.is_ajax.return_value = False
        resp = view_alreadyrunningerror(self.request)
        self.assertEqual(resp.status_code, 400)
        self.assertIn("Task is already running", resp.content)

    def test_alreadyrunningerror_ajax(self):
        self.request.is_ajax.return_value = True
        resp = view_alreadyrunningerror(self.request)
        self.assertEqual(resp.status_code, 400)
        result = json.loads(resp.content)
        self.assertIn("Task is already running", result["error"])
104 105


106
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
107
@patch.dict(settings.FEATURES, {'ENABLE_INSTRUCTOR_EMAIL': True, 'REQUIRE_COURSE_EMAIL_AUTH': False})
108 109 110 111 112 113
class TestInstructorAPIDenyLevels(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
    Ensure that users cannot access endpoints they shouldn't be able to.
    """
    def setUp(self):
        self.course = CourseFactory.create()
114
        self.user = UserFactory.create()
115
        CourseEnrollment.enroll(self.user, self.course.id)
116

117 118 119 120
        self.problem_location = msk_from_problem_urlname(
            self.course.id,
            'robot-some-problem-urlname'
        )
121
        self.problem_urlname = self.problem_location.to_deprecated_string()
122 123 124
        _module = StudentModule.objects.create(
            student=self.user,
            course_id=self.course.id,
125
            module_state_key=self.problem_location,
126 127 128 129 130
            state=json.dumps({'attempts': 10}),
        )

        # Endpoints that only Staff or Instructors can access
        self.staff_level_endpoints = [
131
            ('students_update_enrollment', {'identifiers': 'foo@example.org', 'action': 'enroll'}),
132 133 134 135 136
            ('get_grading_config', {}),
            ('get_students_features', {}),
            ('get_distribution', {}),
            ('get_student_progress_url', {'unique_student_identifier': self.user.username}),
            ('reset_student_attempts', {'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.user.email}),
137
            ('update_forum_role_membership', {'unique_student_identifier': self.user.email, 'rolename': 'Moderator', 'action': 'allow'}),
138 139 140 141 142
            ('list_forum_members', {'rolename': FORUM_ROLE_COMMUNITY_TA}),
            ('proxy_legacy_analytics', {'aname': 'ProblemGradeDistribution'}),
            ('send_email', {'send_to': 'staff', 'subject': 'test', 'message': 'asdf'}),
            ('list_instructor_tasks', {}),
            ('list_background_email_tasks', {}),
143
            ('list_report_downloads', {}),
144
            ('calculate_grades_csv', {}),
145 146 147
        ]
        # Endpoints that only Instructors can access
        self.instructor_level_endpoints = [
148
            ('bulk_beta_modify_access', {'identifiers': 'foo@example.org', 'action': 'add'}),
149
            ('modify_access', {'unique_student_identifier': self.user.email, 'rolename': 'beta', 'action': 'allow'}),
150 151 152 153 154 155 156 157 158 159 160 161 162
            ('list_course_role_members', {'rolename': 'beta'}),
            ('rescore_problem', {'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.user.email}),
        ]

    def _access_endpoint(self, endpoint, args, status_code, msg):
        """
        Asserts that accessing the given `endpoint` gets a response of `status_code`.

        endpoint: string, endpoint for instructor dash API
        args: dict, kwargs for `reverse` call
        status_code: expected HTTP status code response
        msg: message to display if assertion fails.
        """
163 164
        url = reverse(endpoint, kwargs={'course_id': self.course.id.to_deprecated_string()})
        if endpoint in ['send_email']:
165 166 167 168 169 170 171 172 173 174
            response = self.client.post(url, args)
        else:
            response = self.client.get(url, args)
        self.assertEqual(
            response.status_code,
            status_code,
            msg=msg
        )

    def test_student_level(self):
175 176 177
        """
        Ensure that an enrolled student can't access staff or instructor endpoints.
        """
178 179 180 181 182 183
        self.client.login(username=self.user.username, password='test')

        for endpoint, args in self.staff_level_endpoints:
            self._access_endpoint(
                endpoint,
                args,
184
                403,
185
                "Student should not be allowed to access endpoint " + endpoint
186
            )
187

188 189 190 191 192 193 194 195 196
        for endpoint, args in self.instructor_level_endpoints:
            self._access_endpoint(
                endpoint,
                args,
                403,
                "Student should not be allowed to access endpoint " + endpoint
            )

    def test_staff_level(self):
197 198 199
        """
        Ensure that a staff member can't access instructor endpoints.
        """
200
        staff_member = StaffFactory(course_key=self.course.id)
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
        CourseEnrollment.enroll(staff_member, self.course.id)
        self.client.login(username=staff_member.username, password='test')
        # Try to promote to forums admin - not working
        # update_forum_role(self.course.id, staff_member, FORUM_ROLE_ADMINISTRATOR, 'allow')

        for endpoint, args in self.staff_level_endpoints:
            # TODO: make these work
            if endpoint in ['update_forum_role_membership', 'proxy_legacy_analytics', 'list_forum_members']:
                continue
            self._access_endpoint(
                endpoint,
                args,
                200,
                "Staff member should be allowed to access endpoint " + endpoint
            )

        for endpoint, args in self.instructor_level_endpoints:
            self._access_endpoint(
                endpoint,
                args,
221
                403,
222 223 224 225 226 227 228
                "Staff member should not be allowed to access endpoint " + endpoint
            )

    def test_instructor_level(self):
        """
        Ensure that an instructor member can access all endpoints.
        """
229
        inst = InstructorFactory(course_key=self.course.id)
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
        CourseEnrollment.enroll(inst, self.course.id)
        self.client.login(username=inst.username, password='test')

        for endpoint, args in self.staff_level_endpoints:
            # TODO: make these work
            if endpoint in ['update_forum_role_membership', 'proxy_legacy_analytics']:
                continue
            self._access_endpoint(
                endpoint,
                args,
                200,
                "Instructor should be allowed to access endpoint " + endpoint
            )

        for endpoint, args in self.instructor_level_endpoints:
            # TODO: make this work
            if endpoint in ['rescore_problem']:
                continue
            self._access_endpoint(
                endpoint,
                args,
                200,
                "Instructor should be allowed to access endpoint " + endpoint
253
            )
254 255


256
@ddt.ddt
257
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
258 259 260 261 262 263 264 265
class TestInstructorAPIEnrollment(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
    Test enrollment modification endpoint.

    This test does NOT exhaustively test state changes, that is the
    job of test_enrollment. This tests the response and action switch.
    """
    def setUp(self):
266
        self.request = RequestFactory().request()
267
        self.course = CourseFactory.create()
268
        self.instructor = InstructorFactory(course_key=self.course.id)
269 270
        self.client.login(username=self.instructor.username, password='test')

271
        self.enrolled_student = UserFactory(username='EnrolledStudent', first_name='Enrolled', last_name='Student')
272 273 274
        CourseEnrollment.enroll(
            self.enrolled_student,
            self.course.id
275
        )
276 277 278 279 280 281
        self.notenrolled_student = UserFactory(username='NotEnrolledStudent', first_name='NotEnrolled', last_name='Student')

        # Create invited, but not registered, user
        cea = CourseEnrollmentAllowed(email='robot-allowed@robot.org', course_id=self.course.id)
        cea.save()
        self.allowed_email = 'robot-allowed@robot.org'
282 283 284 285

        self.notregistered_email = 'robot-not-an-email-yet@robot.org'
        self.assertEqual(User.objects.filter(email=self.notregistered_email).count(), 0)

286 287 288 289 290
        # Email URL values
        self.site_name = microsite.get_value(
            'SITE_NAME',
            settings.SITE_NAME
        )
291 292
        self.about_path = '/courses/MITx/999/Robot_Super_Course/about'
        self.course_path = '/courses/MITx/999/Robot_Super_Course/'
293

Miles Steele committed
294
        # uncomment to enable enable printing of large diffs
295
        # from failed assertions in the event of a test failure.
Miles Steele committed
296 297
        # (comment because pylint C0103)
        # self.maxDiff = None
298

299 300 301 302 303 304
    def tearDown(self):
        """
        Undo all patches.
        """
        patch.stopall()

305 306
    def test_missing_params(self):
        """ Test missing all query parameters. """
307
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
308 309 310 311 312 313
        response = self.client.get(url)
        self.assertEqual(response.status_code, 400)

    def test_bad_action(self):
        """ Test with an invalid action. """
        action = 'robot-not-an-action'
314
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
315
        response = self.client.get(url, {'identifiers': self.enrolled_student.email, 'action': action})
316 317
        self.assertEqual(response.status_code, 400)

318
    def test_invalid_email(self):
319
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
        response = self.client.get(url, {'identifiers': 'percivaloctavius@', 'action': 'enroll', 'email_students': False})
        self.assertEqual(response.status_code, 200)

        # test the response data
        expected = {
            "action": "enroll",
            'auto_enroll': False,
            "results": [
                {
                    "identifier": 'percivaloctavius@',
                    "invalidIdentifier": True,
                }
            ]
        }

        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)

    def test_invalid_username(self):
339
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
        response = self.client.get(url, {'identifiers': 'percivaloctavius', 'action': 'enroll', 'email_students': False})
        self.assertEqual(response.status_code, 200)

        # test the response data
        expected = {
            "action": "enroll",
            'auto_enroll': False,
            "results": [
                {
                    "identifier": 'percivaloctavius',
                    "invalidIdentifier": True,
                }
            ]
        }

        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)

358
    def test_enroll_with_username(self):
359
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
360
        response = self.client.get(url, {'identifiers': self.notenrolled_student.username, 'action': 'enroll', 'email_students': False})
361 362 363 364 365 366 367 368
        self.assertEqual(response.status_code, 200)

        # test the response data
        expected = {
            "action": "enroll",
            'auto_enroll': False,
            "results": [
                {
369 370 371 372 373 374 375 376 377 378 379 380 381
                    "identifier": self.notenrolled_student.username,
                    "before": {
                        "enrollment": False,
                        "auto_enroll": False,
                        "user": True,
                        "allowed": False,
                    },
                    "after": {
                        "enrollment": True,
                        "auto_enroll": False,
                        "user": True,
                        "allowed": False,
                    }
382 383 384 385 386 387 388
                }
            ]
        }

        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)

389
    def test_enroll_without_email(self):
390
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
391
        response = self.client.get(url, {'identifiers': self.notenrolled_student.email, 'action': 'enroll', 'email_students': False})
392 393
        print "type(self.notenrolled_student.email): {}".format(type(self.notenrolled_student.email))
        self.assertEqual(response.status_code, 200)
394

395
        # test that the user is now enrolled
396 397
        user = User.objects.get(email=self.notenrolled_student.email)
        self.assertTrue(CourseEnrollment.is_enrolled(user, self.course.id))
398

399 400 401 402 403 404
        # test the response data
        expected = {
            "action": "enroll",
            "auto_enroll": False,
            "results": [
                {
405
                    "identifier": self.notenrolled_student.email,
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
                    "before": {
                        "enrollment": False,
                        "auto_enroll": False,
                        "user": True,
                        "allowed": False,
                    },
                    "after": {
                        "enrollment": True,
                        "auto_enroll": False,
                        "user": True,
                        "allowed": False,
                    }
                }
            ]
        }

        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)

        # Check the outbox
        self.assertEqual(len(mail.outbox), 0)

428 429
    @ddt.data('http', 'https')
    def test_enroll_with_email(self, protocol):
430
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
431 432 433 434
        params = {'identifiers': self.notenrolled_student.email, 'action': 'enroll', 'email_students': True}
        environ = {'wsgi.url_scheme': protocol}
        response = self.client.get(url, params, **environ)

435 436 437 438 439 440
        print "type(self.notenrolled_student.email): {}".format(type(self.notenrolled_student.email))
        self.assertEqual(response.status_code, 200)

        # test that the user is now enrolled
        user = User.objects.get(email=self.notenrolled_student.email)
        self.assertTrue(CourseEnrollment.is_enrolled(user, self.course.id))
441 442 443 444 445 446 447

        # test the response data
        expected = {
            "action": "enroll",
            "auto_enroll": False,
            "results": [
                {
448
                    "identifier": self.notenrolled_student.email,
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
                    "before": {
                        "enrollment": False,
                        "auto_enroll": False,
                        "user": True,
                        "allowed": False,
                    },
                    "after": {
                        "enrollment": True,
                        "auto_enroll": False,
                        "user": True,
                        "allowed": False,
                    }
                }
            ]
        }

        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)

468 469 470 471 472 473 474 475 476 477 478 479
        # Check the outbox
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(
            mail.outbox[0].subject,
            'You have been enrolled in Robot Super Course'
        )
        self.assertEqual(
            mail.outbox[0].body,
            "Dear NotEnrolled Student\n\nYou have been enrolled in Robot Super Course "
            "at edx.org by a member of the course staff. "
            "The course should now appear on your edx.org dashboard.\n\n"
            "To start accessing course materials, please visit "
480
            "{proto}://{site}{course_path}\n\n----\n"
481
            "This email was automatically sent from edx.org to NotEnrolled Student".format(
482
                proto=protocol, site=self.site_name, course_path=self.course_path
483
            )
484 485
        )

486 487
    @ddt.data('http', 'https')
    def test_enroll_with_email_not_registered(self, protocol):
488
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
489 490 491
        params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True}
        environ = {'wsgi.url_scheme': protocol}
        response = self.client.get(url, params, **environ)
492 493
        self.assertEqual(response.status_code, 200)

494 495 496 497 498 499
        # Check the outbox
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(
            mail.outbox[0].subject,
            'You have been invited to register for Robot Super Course'
        )
500
        self.assertEqual(
501 502
            mail.outbox[0].body,
            "Dear student,\n\nYou have been invited to join Robot Super Course at edx.org by a member of the course staff.\n\n"
503 504
            "To finish your registration, please visit {proto}://{site}/register and fill out the "
            "registration form making sure to use robot-not-an-email-yet@robot.org in the E-mail field.\n"
505
            "Once you have registered and activated your account, "
506
            "visit {proto}://{site}{about_path} to join the course.\n\n----\n"
507
            "This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org".format(
508
                proto=protocol, site=self.site_name, about_path=self.about_path
509
            )
510 511
        )

512
    @ddt.data('http', 'https')
513
    @patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True})
514
    def test_enroll_email_not_registered_mktgsite(self, protocol):
515
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
516 517 518
        params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True}
        environ = {'wsgi.url_scheme': protocol}
        response = self.client.get(url, params, **environ)
519 520 521 522 523

        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            mail.outbox[0].body,
            "Dear student,\n\nYou have been invited to join Robot Super Course at edx.org by a member of the course staff.\n\n"
524
            "To finish your registration, please visit {proto}://{site}/register and fill out the registration form "
525 526
            "making sure to use robot-not-an-email-yet@robot.org in the E-mail field.\n"
            "You can then enroll in Robot Super Course.\n\n----\n"
527 528 529
            "This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org".format(
                proto=protocol, site=self.site_name
            )
530 531
        )

532 533
    @ddt.data('http', 'https')
    def test_enroll_with_email_not_registered_autoenroll(self, protocol):
534
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
535 536 537
        params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True, 'auto_enroll': True}
        environ = {'wsgi.url_scheme': protocol}
        response = self.client.get(url, params, **environ)
538 539 540 541 542 543 544 545 546 547 548 549
        print "type(self.notregistered_email): {}".format(type(self.notregistered_email))
        self.assertEqual(response.status_code, 200)

        # Check the outbox
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(
            mail.outbox[0].subject,
            'You have been invited to register for Robot Super Course'
        )
        self.assertEqual(
            mail.outbox[0].body,
            "Dear student,\n\nYou have been invited to join Robot Super Course at edx.org by a member of the course staff.\n\n"
550
            "To finish your registration, please visit {proto}://{site}/register and fill out the registration form "
551 552
            "making sure to use robot-not-an-email-yet@robot.org in the E-mail field.\n"
            "Once you have registered and activated your account, you will see Robot Super Course listed on your dashboard.\n\n----\n"
553
            "This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org".format(
554
                proto=protocol, site=self.site_name
555
            )
556 557 558
        )

    def test_unenroll_without_email(self):
559
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
560
        response = self.client.get(url, {'identifiers': self.enrolled_student.email, 'action': 'unenroll', 'email_students': False})
561 562 563 564 565 566 567
        print "type(self.enrolled_student.email): {}".format(type(self.enrolled_student.email))
        self.assertEqual(response.status_code, 200)

        # test that the user is now unenrolled
        user = User.objects.get(email=self.enrolled_student.email)
        self.assertFalse(CourseEnrollment.is_enrolled(user, self.course.id))

568 569 570 571 572 573
        # test the response data
        expected = {
            "action": "unenroll",
            "auto_enroll": False,
            "results": [
                {
574
                    "identifier": self.enrolled_student.email,
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
                    "before": {
                        "enrollment": True,
                        "auto_enroll": False,
                        "user": True,
                        "allowed": False,
                    },
                    "after": {
                        "enrollment": False,
                        "auto_enroll": False,
                        "user": True,
                        "allowed": False,
                    }
                }
            ]
        }

        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)

594 595 596 597
        # Check the outbox
        self.assertEqual(len(mail.outbox), 0)

    def test_unenroll_with_email(self):
598
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
599
        response = self.client.get(url, {'identifiers': self.enrolled_student.email, 'action': 'unenroll', 'email_students': True})
600 601 602 603 604 605 606 607 608 609 610 611 612
        print "type(self.enrolled_student.email): {}".format(type(self.enrolled_student.email))
        self.assertEqual(response.status_code, 200)

        # test that the user is now unenrolled
        user = User.objects.get(email=self.enrolled_student.email)
        self.assertFalse(CourseEnrollment.is_enrolled(user, self.course.id))

        # test the response data
        expected = {
            "action": "unenroll",
            "auto_enroll": False,
            "results": [
                {
613
                    "identifier": self.enrolled_student.email,
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
                    "before": {
                        "enrollment": True,
                        "auto_enroll": False,
                        "user": True,
                        "allowed": False,
                    },
                    "after": {
                        "enrollment": False,
                        "auto_enroll": False,
                        "user": True,
                        "allowed": False,
                    }
                }
            ]
        }

        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)

        # Check the outbox
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(
            mail.outbox[0].subject,
            'You have been un-enrolled from Robot Super Course'
        )
        self.assertEqual(
            mail.outbox[0].body,
            "Dear Enrolled Student\n\nYou have been un-enrolled in Robot Super Course "
            "at edx.org by a member of the course staff. "
            "The course will no longer appear on your edx.org dashboard.\n\n"
            "Your other courses have not been affected.\n\n----\n"
            "This email was automatically sent from edx.org to Enrolled Student"
        )

    def test_unenroll_with_email_allowed_student(self):
649
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
650
        response = self.client.get(url, {'identifiers': self.allowed_email, 'action': 'unenroll', 'email_students': True})
651 652 653 654 655 656 657 658 659
        print "type(self.allowed_email): {}".format(type(self.allowed_email))
        self.assertEqual(response.status_code, 200)

        # test the response data
        expected = {
            "action": "unenroll",
            "auto_enroll": False,
            "results": [
                {
660
                    "identifier": self.allowed_email,
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
                    "before": {
                        "enrollment": False,
                        "auto_enroll": False,
                        "user": False,
                        "allowed": True,
                    },
                    "after": {
                        "enrollment": False,
                        "auto_enroll": False,
                        "user": False,
                        "allowed": False,
                    }
                }
            ]
        }

        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)

        # Check the outbox
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(
            mail.outbox[0].subject,
            'You have been un-enrolled from Robot Super Course'
        )
        self.assertEqual(
            mail.outbox[0].body,
            "Dear Student,\n\nYou have been un-enrolled from course Robot Super Course by a member of the course staff. "
            "Please disregard the invitation previously sent.\n\n----\n"
            "This email was automatically sent from edx.org to robot-allowed@robot.org"
        )

693
    @ddt.data('http', 'https')
694
    @patch('instructor.enrollment.uses_shib')
695
    def test_enroll_with_email_not_registered_with_shib(self, protocol, mock_uses_shib):
696 697
        mock_uses_shib.return_value = True

698
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
699 700 701
        params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True}
        environ = {'wsgi.url_scheme': protocol}
        response = self.client.get(url, params, **environ)
702 703 704 705 706 707 708 709
        self.assertEqual(response.status_code, 200)

        # Check the outbox
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(
            mail.outbox[0].subject,
            'You have been invited to register for Robot Super Course'
        )
710

711 712 713
        self.assertEqual(
            mail.outbox[0].body,
            "Dear student,\n\nYou have been invited to join Robot Super Course at edx.org by a member of the course staff.\n\n"
714
            "To access the course visit {proto}://{site}{about_path} and register for the course.\n\n----\n"
715
            "This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org".format(
716
                proto=protocol, site=self.site_name, about_path=self.about_path
717
            )
718 719 720
        )

    @patch('instructor.enrollment.uses_shib')
721
    @patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True})
722
    def test_enroll_email_not_registered_shib_mktgsite(self, mock_uses_shib):
723
        # Try with marketing site enabled and shib on
724 725
        mock_uses_shib.return_value = True

726
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
727 728
        # Try with marketing site enabled
        with patch.dict('django.conf.settings.FEATURES', {'ENABLE_MKTG_SITE': True}):
729
            response = self.client.get(url, {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True})
730 731 732 733 734 735 736 737

        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            mail.outbox[0].body,
            "Dear student,\n\nYou have been invited to join Robot Super Course at edx.org by a member of the course staff.\n\n----\n"
            "This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org"
        )

738
    @ddt.data('http', 'https')
739
    @patch('instructor.enrollment.uses_shib')
740
    def test_enroll_with_email_not_registered_with_shib_autoenroll(self, protocol, mock_uses_shib):
741 742
        mock_uses_shib.return_value = True

743
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
744 745 746
        params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True, 'auto_enroll': True}
        environ = {'wsgi.url_scheme': protocol}
        response = self.client.get(url, params, **environ)
747 748 749 750 751 752 753 754 755
        print "type(self.notregistered_email): {}".format(type(self.notregistered_email))
        self.assertEqual(response.status_code, 200)

        # Check the outbox
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(
            mail.outbox[0].subject,
            'You have been invited to register for Robot Super Course'
        )
756

757 758 759
        self.assertEqual(
            mail.outbox[0].body,
            "Dear student,\n\nYou have been invited to join Robot Super Course at edx.org by a member of the course staff.\n\n"
760
            "To access the course visit {proto}://{site}{course_path} and login.\n\n----\n"
761
            "This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org".format(
762
                proto=protocol, site=self.site_name, course_path=self.course_path
763
            )
764 765
        )

766

767
@ddt.ddt
768
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
769 770 771 772 773 774
class TestInstructorAPIBulkBetaEnrollment(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
    Test bulk beta modify access endpoint.
    """
    def setUp(self):
        self.course = CourseFactory.create()
775
        self.instructor = InstructorFactory(course_key=self.course.id)
776 777
        self.client.login(username=self.instructor.username, password='test')

778
        self.beta_tester = BetaTesterFactory(course_key=self.course.id)
779 780 781 782
        CourseEnrollment.enroll(
            self.beta_tester,
            self.course.id
        )
783
        self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(self.beta_tester))
784 785 786 787 788 789

        self.notenrolled_student = UserFactory(username='NotEnrolledStudent')

        self.notregistered_email = 'robot-not-an-email-yet@robot.org'
        self.assertEqual(User.objects.filter(email=self.notregistered_email).count(), 0)

790 791 792 793 794 795 796
        self.request = RequestFactory().request()

        # Email URL values
        self.site_name = microsite.get_value(
            'SITE_NAME',
            settings.SITE_NAME
        )
797 798
        self.about_path = '/courses/MITx/999/Robot_Super_Course/about'
        self.course_path = '/courses/MITx/999/Robot_Super_Course/'
799

800 801 802 803 804 805 806
        # uncomment to enable enable printing of large diffs
        # from failed assertions in the event of a test failure.
        # (comment because pylint C0103)
        # self.maxDiff = None

    def test_missing_params(self):
        """ Test missing all query parameters. """
807
        url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
808 809 810 811 812 813
        response = self.client.get(url)
        self.assertEqual(response.status_code, 400)

    def test_bad_action(self):
        """ Test with an invalid action. """
        action = 'robot-not-an-action'
814
        url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
815
        response = self.client.get(url, {'identifiers': self.beta_tester.email, 'action': action})
816 817
        self.assertEqual(response.status_code, 400)

818 819
    def add_notenrolled(self, response, identifier):
        """
820 821
        Test Helper Method (not a test, called by other tests)

822
        Takes a client response from a call to bulk_beta_modify_access with 'email_students': False,
823
        and the student identifier (email or username) given as 'identifiers' in the request.
824

825 826 827 828 829
        Asserts the reponse returns cleanly, that the student was added as a beta tester, and the
        response properly contains their identifier, 'error': False, and 'userDoesNotExist': False.
        Additionally asserts no email was sent.
        """
        self.assertEqual(response.status_code, 200)
830
        self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(self.notenrolled_student))
831 832 833 834 835
        # test the response data
        expected = {
            "action": "add",
            "results": [
                {
836
                    "identifier": identifier,
837 838 839 840 841 842 843 844 845 846 847 848
                    "error": False,
                    "userDoesNotExist": False
                }
            ]
        }

        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)

        # Check the outbox
        self.assertEqual(len(mail.outbox), 0)

849
    def test_add_notenrolled_email(self):
850
        url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
851
        response = self.client.get(url, {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': False})
852 853 854 855
        self.add_notenrolled(response, self.notenrolled_student.email)
        self.assertFalse(CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id))

    def test_add_notenrolled_email_autoenroll(self):
856
        url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
857
        response = self.client.get(url, {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': False, 'auto_enroll': True})
858 859
        self.add_notenrolled(response, self.notenrolled_student.email)
        self.assertTrue(CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id))
860 861

    def test_add_notenrolled_username(self):
862
        url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
863
        response = self.client.get(url, {'identifiers': self.notenrolled_student.username, 'action': 'add', 'email_students': False})
864 865 866 867
        self.add_notenrolled(response, self.notenrolled_student.username)
        self.assertFalse(CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id))

    def test_add_notenrolled_username_autoenroll(self):
868
        url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
869
        response = self.client.get(url, {'identifiers': self.notenrolled_student.username, 'action': 'add', 'email_students': False, 'auto_enroll': True})
870 871
        self.add_notenrolled(response, self.notenrolled_student.username)
        self.assertTrue(CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id))
872

873 874
    @ddt.data('http', 'https')
    def test_add_notenrolled_with_email(self, protocol):
875
        url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
876 877 878
        params = {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': True}
        environ = {'wsgi.url_scheme': protocol}
        response = self.client.get(url, params, **environ)
879 880
        self.assertEqual(response.status_code, 200)

881
        self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(self.notenrolled_student))
882 883 884 885 886
        # test the response data
        expected = {
            "action": "add",
            "results": [
                {
887
                    "identifier": self.notenrolled_student.email,
888 889 890 891 892 893 894 895 896 897 898 899 900 901
                    "error": False,
                    "userDoesNotExist": False
                }
            ]
        }
        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)

        # Check the outbox
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(
            mail.outbox[0].subject,
            'You have been invited to a beta test for Robot Super Course'
        )
902

903 904
        self.assertEqual(
            mail.outbox[0].body,
905
            u"Dear {student_name}\n\nYou have been invited to be a beta tester "
906
            "for Robot Super Course at edx.org by a member of the course staff.\n\n"
907
            "Visit {proto}://{site}{about_path} to join "
908
            "the course and begin the beta test.\n\n----\n"
909 910 911 912 913 914
            "This email was automatically sent from edx.org to {student_email}".format(
                student_name=self.notenrolled_student.profile.name,
                student_email=self.notenrolled_student.email,
                proto=protocol,
                site=self.site_name,
                about_path=self.about_path
915 916 917
            )
        )

918 919
    @ddt.data('http', 'https')
    def test_add_notenrolled_with_email_autoenroll(self, protocol):
920
        url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
921 922 923
        params = {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': True, 'auto_enroll': True}
        environ = {'wsgi.url_scheme': protocol}
        response = self.client.get(url, params, **environ)
924 925
        self.assertEqual(response.status_code, 200)

926
        self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(self.notenrolled_student))
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
        # test the response data
        expected = {
            "action": "add",
            "results": [
                {
                    "identifier": self.notenrolled_student.email,
                    "error": False,
                    "userDoesNotExist": False
                }
            ]
        }
        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)

        # Check the outbox
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(
            mail.outbox[0].subject,
            'You have been invited to a beta test for Robot Super Course'
        )

        self.assertEqual(
            mail.outbox[0].body,
950
            u"Dear {student_name}\n\nYou have been invited to be a beta tester "
951 952
            "for Robot Super Course at edx.org by a member of the course staff.\n\n"
            "To start accessing course materials, please visit "
953 954 955 956 957 958 959
            "{proto}://{site}{course_path}\n\n----\n"
            "This email was automatically sent from edx.org to {student_email}".format(
                student_name=self.notenrolled_student.profile.name,
                student_email=self.notenrolled_student.email,
                proto=protocol,
                site=self.site_name,
                course_path=self.course_path
960 961 962
            )
        )

963
    @patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True})
964 965
    def test_add_notenrolled_email_mktgsite(self):
        # Try with marketing site enabled
966 967
        url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
        response = self.client.get(url, {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': True})
968 969 970 971 972 973 974 975

        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            mail.outbox[0].body,
            u"Dear {0}\n\nYou have been invited to be a beta tester "
            "for Robot Super Course at edx.org by a member of the course staff.\n\n"
            "Visit edx.org to enroll in the course and begin the beta test.\n\n----\n"
            "This email was automatically sent from edx.org to {1}".format(
976
                self.notenrolled_student.profile.name,
977
                self.notenrolled_student.email,
978 979 980 981 982
            )
        )

    def test_enroll_with_email_not_registered(self):
        # User doesn't exist
983
        url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
984
        response = self.client.get(url, {'identifiers': self.notregistered_email, 'action': 'add', 'email_students': True})
985 986 987 988 989 990
        self.assertEqual(response.status_code, 200)
        # test the response data
        expected = {
            "action": "add",
            "results": [
                {
991
                    "identifier": self.notregistered_email,
992 993 994 995 996 997 998 999 1000 1001 1002 1003
                    "error": True,
                    "userDoesNotExist": True
                }
            ]
        }
        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)

        # Check the outbox
        self.assertEqual(len(mail.outbox), 0)

    def test_remove_without_email(self):
1004
        url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
1005
        response = self.client.get(url, {'identifiers': self.beta_tester.email, 'action': 'remove', 'email_students': False})
1006 1007
        self.assertEqual(response.status_code, 200)

1008 1009 1010 1011 1012
        # Works around a caching bug which supposedly can't happen in prod. The instance here is not ==
        # the instance fetched from the email above which had its cache cleared
        if hasattr(self.beta_tester, '_roles'):
            del self.beta_tester._roles
        self.assertFalse(CourseBetaTesterRole(self.course.id).has_user(self.beta_tester))
1013 1014 1015 1016 1017 1018

        # test the response data
        expected = {
            "action": "remove",
            "results": [
                {
1019
                    "identifier": self.beta_tester.email,
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
                    "error": False,
                    "userDoesNotExist": False
                }
            ]
        }
        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)

        # Check the outbox
        self.assertEqual(len(mail.outbox), 0)

    def test_remove_with_email(self):
1032
        url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
1033
        response = self.client.get(url, {'identifiers': self.beta_tester.email, 'action': 'remove', 'email_students': True})
1034 1035
        self.assertEqual(response.status_code, 200)

1036 1037 1038 1039 1040
        # Works around a caching bug which supposedly can't happen in prod. The instance here is not ==
        # the instance fetched from the email above which had its cache cleared
        if hasattr(self.beta_tester, '_roles'):
            del self.beta_tester._roles
        self.assertFalse(CourseBetaTesterRole(self.course.id).has_user(self.beta_tester))
1041 1042 1043 1044 1045 1046

        # test the response data
        expected = {
            "action": "remove",
            "results": [
                {
1047
                    "identifier": self.beta_tester.email,
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
                    "error": False,
                    "userDoesNotExist": False
                }
            ]
        }
        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)
        # Check the outbox
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(
            mail.outbox[0].subject,
            'You have been removed from a beta test for Robot Super Course'
        )
        self.assertEqual(
            mail.outbox[0].body,
            "Dear {full_name}\n\nYou have been removed as a beta tester for "
            "Robot Super Course at edx.org by a member of the course staff. "
            "The course will remain on your dashboard, but you will no longer "
            "be part of the beta testing group.\n\n"
            "Your other courses have not been affected.\n\n----\n"
            "This email was automatically sent from edx.org to {email_address}".format(
                full_name=self.beta_tester.profile.name,
                email_address=self.beta_tester.email
            )
        )


@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
1076 1077 1078 1079 1080 1081 1082 1083
class TestInstructorAPILevelsAccess(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
    Test endpoints whereby instructors can change permissions
    of other users.

    This test does NOT test whether the actions had an effect on the
    database, that is the job of test_access.
    This tests the response and action switch.
1084 1085
    Actually, modify_access does not have a very meaningful
    response yet, so only the status code is tested.
1086 1087 1088
    """
    def setUp(self):
        self.course = CourseFactory.create()
1089
        self.instructor = InstructorFactory(course_key=self.course.id)
1090 1091
        self.client.login(username=self.instructor.username, password='test')

1092 1093
        self.other_instructor = InstructorFactory(course_key=self.course.id)
        self.other_staff = StaffFactory(course_key=self.course.id)
1094 1095 1096 1097
        self.other_user = UserFactory()

    def test_modify_access_noparams(self):
        """ Test missing all query parameters. """
1098
        url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
1099 1100 1101 1102 1103
        response = self.client.get(url)
        self.assertEqual(response.status_code, 400)

    def test_modify_access_bad_action(self):
        """ Test with an invalid action parameter. """
1104
        url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
1105
        response = self.client.get(url, {
1106
            'unique_student_identifier': self.other_staff.email,
1107 1108 1109 1110 1111
            'rolename': 'staff',
            'action': 'robot-not-an-action',
        })
        self.assertEqual(response.status_code, 400)

1112 1113
    def test_modify_access_bad_role(self):
        """ Test with an invalid action parameter. """
1114
        url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
1115
        response = self.client.get(url, {
1116
            'unique_student_identifier': self.other_staff.email,
1117 1118 1119 1120 1121
            'rolename': 'robot-not-a-roll',
            'action': 'revoke',
        })
        self.assertEqual(response.status_code, 400)

1122
    def test_modify_access_allow(self):
1123
        url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
1124
        response = self.client.get(url, {
1125
            'unique_student_identifier': self.other_user.email,
1126 1127 1128 1129 1130 1131
            'rolename': 'staff',
            'action': 'allow',
        })
        self.assertEqual(response.status_code, 200)

    def test_modify_access_allow_with_uname(self):
1132
        url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
1133 1134
        response = self.client.get(url, {
            'unique_student_identifier': self.other_instructor.username,
1135 1136 1137 1138 1139 1140
            'rolename': 'staff',
            'action': 'allow',
        })
        self.assertEqual(response.status_code, 200)

    def test_modify_access_revoke(self):
1141
        url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
1142
        response = self.client.get(url, {
1143 1144 1145 1146 1147 1148 1149
            'unique_student_identifier': self.other_staff.email,
            'rolename': 'staff',
            'action': 'revoke',
        })
        self.assertEqual(response.status_code, 200)

    def test_modify_access_revoke_with_username(self):
1150
        url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
1151 1152
        response = self.client.get(url, {
            'unique_student_identifier': self.other_staff.username,
1153 1154 1155 1156 1157
            'rolename': 'staff',
            'action': 'revoke',
        })
        self.assertEqual(response.status_code, 200)

1158
    def test_modify_access_with_fake_user(self):
1159
        url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
        response = self.client.get(url, {
            'unique_student_identifier': 'GandalfTheGrey',
            'rolename': 'staff',
            'action': 'revoke',
        })
        self.assertEqual(response.status_code, 200)
        expected = {
            'unique_student_identifier': 'GandalfTheGrey',
            'userDoesNotExist': True,
        }
        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)

    def test_modify_access_with_inactive_user(self):
        self.other_user.is_active = False
        self.other_user.save()  # pylint: disable=no-member
1176
        url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
        response = self.client.get(url, {
            'unique_student_identifier': self.other_user.username,
            'rolename': 'beta',
            'action': 'allow',
        })
        self.assertEqual(response.status_code, 200)
        expected = {
            'unique_student_identifier': self.other_user.username,
            'inactiveUser': True,
        }
        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)

1190 1191
    def test_modify_access_revoke_not_allowed(self):
        """ Test revoking access that a user does not have. """
1192
        url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
1193
        response = self.client.get(url, {
1194
            'unique_student_identifier': self.other_staff.email,
1195 1196 1197 1198 1199 1200 1201 1202 1203
            'rolename': 'instructor',
            'action': 'revoke',
        })
        self.assertEqual(response.status_code, 200)

    def test_modify_access_revoke_self(self):
        """
        Test that an instructor cannot remove instructor privelages from themself.
        """
1204
        url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
1205
        response = self.client.get(url, {
1206
            'unique_student_identifier': self.instructor.email,
1207 1208 1209
            'rolename': 'instructor',
            'action': 'revoke',
        })
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
        self.assertEqual(response.status_code, 200)
        # check response content
        expected = {
            'unique_student_identifier': self.instructor.username,
            'rolename': 'instructor',
            'action': 'revoke',
            'removingSelfAsInstructor': True,
        }
        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)
1220 1221 1222

    def test_list_course_role_members_noparams(self):
        """ Test missing all query parameters. """
1223
        url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()})
1224 1225 1226 1227 1228
        response = self.client.get(url)
        self.assertEqual(response.status_code, 400)

    def test_list_course_role_members_bad_rolename(self):
        """ Test with an invalid rolename parameter. """
1229
        url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()})
1230 1231 1232 1233 1234 1235
        response = self.client.get(url, {
            'rolename': 'robot-not-a-rolename',
        })
        self.assertEqual(response.status_code, 400)

    def test_list_course_role_members_staff(self):
1236
        url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()})
1237 1238 1239 1240 1241 1242 1243
        response = self.client.get(url, {
            'rolename': 'staff',
        })
        self.assertEqual(response.status_code, 200)

        # check response content
        expected = {
1244
            'course_id': self.course.id.to_deprecated_string(),
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
            'staff': [
                {
                    'username': self.other_staff.username,
                    'email': self.other_staff.email,
                    'first_name': self.other_staff.first_name,
                    'last_name': self.other_staff.last_name,
                }
            ]
        }
        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)

    def test_list_course_role_members_beta(self):
1258
        url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()})
1259 1260 1261 1262 1263 1264 1265
        response = self.client.get(url, {
            'rolename': 'beta',
        })
        self.assertEqual(response.status_code, 200)

        # check response content
        expected = {
1266
            'course_id': self.course.id.to_deprecated_string(),
1267 1268 1269 1270
            'beta': []
        }
        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)
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 1298 1299 1300 1301 1302 1303
    def test_update_forum_role_membership(self):
        """
        Test update forum role membership with user's email and username.
        """

        # Seed forum roles for course.
        seed_permissions_roles(self.course.id)

        # Test add discussion admin with email.
        self.assert_update_forum_role_membership(self.other_user.email, "Administrator", "allow")

        # Test revoke discussion admin with email.
        self.assert_update_forum_role_membership(self.other_user.email, "Administrator", "revoke")

        # Test add discussion moderator with username.
        self.assert_update_forum_role_membership(self.other_user.username, "Moderator", "allow")

        # Test revoke discussion moderator with username.
        self.assert_update_forum_role_membership(self.other_user.username, "Moderator", "revoke")

        # Test add discussion community TA with email.
        self.assert_update_forum_role_membership(self.other_user.email, "Community TA", "allow")

        # Test revoke discussion community TA with username.
        self.assert_update_forum_role_membership(self.other_user.username, "Community TA", "revoke")

    def assert_update_forum_role_membership(self, unique_student_identifier, rolename, action):
        """
        Test update forum role membership.
        Get unique_student_identifier, rolename and action and update forum role.
        """

1304
        url = reverse('update_forum_role_membership', kwargs={'course_id': self.course.id.to_deprecated_string()})
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
        response = self.client.get(
            url,
            {
                'unique_student_identifier': unique_student_identifier,
                'rolename': rolename,
                'action': action,
            }
        )

        # Status code should be 200.
        self.assertEqual(response.status_code, 200)

        user_roles = self.other_user.roles.filter(course_id=self.course.id).values_list("name", flat=True)
        if action == 'allow':
            self.assertIn(rolename, user_roles)
        elif action == 'revoke':
            self.assertNotIn(rolename, user_roles)


1324

1325
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
1326 1327 1328 1329 1330 1331
class TestInstructorAPILevelsDataDump(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
    Test endpoints that show data without side effects.
    """
    def setUp(self):
        self.course = CourseFactory.create()
1332
        self.instructor = InstructorFactory(course_key=self.course.id)
1333 1334 1335 1336
        self.client.login(username=self.instructor.username, password='test')

        self.students = [UserFactory() for _ in xrange(6)]
        for student in self.students:
1337
            CourseEnrollment.enroll(student, self.course.id)
1338 1339 1340 1341 1342 1343

    def test_get_students_features(self):
        """
        Test that some minimum of information is formatted
        correctly in the response to get_students_features.
        """
1344
        url = reverse('get_students_features', kwargs={'course_id': self.course.id.to_deprecated_string()})
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
        response = self.client.get(url, {})
        res_json = json.loads(response.content)
        self.assertIn('students', res_json)
        for student in self.students:
            student_json = [
                x for x in res_json['students']
                if x['username'] == student.username
            ][0]
            self.assertEqual(student_json['username'], student.username)
            self.assertEqual(student_json['email'], student.email)

1356 1357
    @patch.object(instructor.views.api, 'anonymous_id_for_user', Mock(return_value='42'))
    @patch.object(instructor.views.api, 'unique_id_for_user', Mock(return_value='41'))
1358 1359 1360 1361
    def test_get_anon_ids(self):
        """
        Test the CSV output for the anonymized user ids.
        """
1362
        url = reverse('get_anon_ids', kwargs={'course_id': self.course.id.to_deprecated_string()})
1363
        response = self.client.get(url, {})
1364 1365
        self.assertEqual(response['Content-Type'], 'text/csv')
        body = response.content.replace('\r', '')
1366
        self.assertTrue(body.startswith(
1367
            '"User ID","Anonymized User ID","Course Specific Anonymized User ID"'
1368 1369 1370
            '\n"2","41","42"\n'
        ))
        self.assertTrue(body.endswith('"7","41","42"\n'))
1371

1372
    def test_list_report_downloads(self):
1373
        url = reverse('list_report_downloads', kwargs={'course_id': self.course.id.to_deprecated_string()})
1374
        with patch('instructor_task.models.LocalFSReportStore.links_for') as mock_links_for:
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
            mock_links_for.return_value = [
                ('mock_file_name_1', 'https://1.mock.url'),
                ('mock_file_name_2', 'https://2.mock.url'),
            ]
            response = self.client.get(url, {})

        expected_response = {
            "downloads": [
                {
                    "url": "https://1.mock.url",
                    "link": "<a href=\"https://1.mock.url\">mock_file_name_1</a>",
                    "name": "mock_file_name_1"
                },
                {
                    "url": "https://2.mock.url",
                    "link": "<a href=\"https://2.mock.url\">mock_file_name_2</a>",
                    "name": "mock_file_name_2"
                }
            ]
        }
        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected_response)

    def test_calculate_grades_csv_success(self):
1399
        url = reverse('calculate_grades_csv', kwargs={'course_id': self.course.id.to_deprecated_string()})
1400 1401 1402 1403 1404 1405 1406 1407

        with patch('instructor_task.api.submit_calculate_grades_csv') as mock_cal_grades:
            mock_cal_grades.return_value = True
            response = self.client.get(url, {})
        success_status = "Your grade report is being generated! You can view the status of the generation task in the 'Pending Instructor Tasks' section."
        self.assertIn(success_status, response.content)

    def test_calculate_grades_csv_already_running(self):
1408
        url = reverse('calculate_grades_csv', kwargs={'course_id': self.course.id.to_deprecated_string()})
1409 1410 1411 1412 1413 1414 1415

        with patch('instructor_task.api.submit_calculate_grades_csv') as mock_cal_grades:
            mock_cal_grades.side_effect = AlreadyRunningError()
            response = self.client.get(url, {})
        already_running_status = "A grade report generation task is already in progress. Check the 'Pending Instructor Tasks' table for the status of the task. When completed, the report will be available for download in the table below."
        self.assertIn(already_running_status, response.content)

1416 1417 1418 1419 1420
    def test_get_students_features_csv(self):
        """
        Test that some minimum of information is formatted
        correctly in the response to get_students_features.
        """
1421
        url = reverse('get_students_features', kwargs={'course_id': self.course.id.to_deprecated_string()})
1422 1423 1424
        response = self.client.get(url + '/csv', {})
        self.assertEqual(response['Content-Type'], 'text/csv')

1425 1426 1427
    def test_get_distribution_no_feature(self):
        """
        Test that get_distribution lists available features
1428
        when supplied no feature parameter.
1429
        """
1430
        url = reverse('get_distribution', kwargs={'course_id': self.course.id.to_deprecated_string()})
1431 1432 1433 1434 1435
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        res_json = json.loads(response.content)
        self.assertEqual(type(res_json['available_features']), list)

1436
        url = reverse('get_distribution', kwargs={'course_id': self.course.id.to_deprecated_string()})
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
        response = self.client.get(url + u'?feature=')
        self.assertEqual(response.status_code, 200)
        res_json = json.loads(response.content)
        self.assertEqual(type(res_json['available_features']), list)

    def test_get_distribution_unavailable_feature(self):
        """
        Test that get_distribution fails gracefully with
            an unavailable feature.
        """
1447
        url = reverse('get_distribution', kwargs={'course_id': self.course.id.to_deprecated_string()})
1448 1449 1450 1451 1452 1453 1454 1455
        response = self.client.get(url, {'feature': 'robot-not-a-real-feature'})
        self.assertEqual(response.status_code, 400)

    def test_get_distribution_gender(self):
        """
        Test that get_distribution fails gracefully with
            an unavailable feature.
        """
1456
        url = reverse('get_distribution', kwargs={'course_id': self.course.id.to_deprecated_string()})
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
        response = self.client.get(url, {'feature': 'gender'})
        self.assertEqual(response.status_code, 200)
        res_json = json.loads(response.content)
        self.assertEqual(res_json['feature_results']['data']['m'], 6)
        self.assertEqual(res_json['feature_results']['choices_display_names']['m'], 'Male')
        self.assertEqual(res_json['feature_results']['data']['no_data'], 0)
        self.assertEqual(res_json['feature_results']['choices_display_names']['no_data'], 'No Data')

    def test_get_student_progress_url(self):
        """ Test that progress_url is in the successful response. """
1467
        url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()})
1468
        url += "?unique_student_identifier={}".format(
1469 1470 1471 1472 1473 1474 1475
            quote(self.students[0].email.encode("utf-8"))
        )
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        res_json = json.loads(response.content)
        self.assertIn('progress_url', res_json)

1476 1477
    def test_get_student_progress_url_from_uname(self):
        """ Test that progress_url is in the successful response. """
1478
        url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()})
1479 1480 1481 1482 1483 1484 1485 1486
        url += "?unique_student_identifier={}".format(
            quote(self.students[0].username.encode("utf-8"))
        )
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        res_json = json.loads(response.content)
        self.assertIn('progress_url', res_json)

1487 1488
    def test_get_student_progress_url_noparams(self):
        """ Test that the endpoint 404's without the required query params. """
1489
        url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()})
1490 1491 1492 1493 1494
        response = self.client.get(url)
        self.assertEqual(response.status_code, 400)

    def test_get_student_progress_url_nostudent(self):
        """ Test that the endpoint 400's when requesting an unknown email. """
1495
        url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()})
1496 1497 1498 1499
        response = self.client.get(url)
        self.assertEqual(response.status_code, 400)


1500
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
class TestInstructorAPIRegradeTask(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
    Test endpoints whereby instructors can change student grades.
    This includes resetting attempts and starting rescore tasks.

    This test does NOT test whether the actions had an effect on the
    database, that is the job of task tests and test_enrollment.
    """
    def setUp(self):
        self.course = CourseFactory.create()
1511
        self.instructor = InstructorFactory(course_key=self.course.id)
1512 1513 1514
        self.client.login(username=self.instructor.username, password='test')

        self.student = UserFactory()
1515
        CourseEnrollment.enroll(self.student, self.course.id)
1516

1517 1518 1519 1520
        self.problem_location = msk_from_problem_urlname(
            self.course.id,
            'robot-some-problem-urlname'
        )
1521
        self.problem_urlname = self.problem_location.to_deprecated_string()
1522

1523 1524 1525
        self.module_to_reset = StudentModule.objects.create(
            student=self.student,
            course_id=self.course.id,
1526
            module_state_key=self.problem_location,
1527 1528 1529 1530 1531
            state=json.dumps({'attempts': 10}),
        )

    def test_reset_student_attempts_deletall(self):
        """ Make sure no one can delete all students state on a problem. """
1532
        url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
1533 1534 1535 1536 1537 1538 1539 1540 1541
        response = self.client.get(url, {
            'problem_to_reset': self.problem_urlname,
            'all_students': True,
            'delete_module': True,
        })
        self.assertEqual(response.status_code, 400)

    def test_reset_student_attempts_single(self):
        """ Test reset single student attempts. """
1542
        url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
1543 1544
        response = self.client.get(url, {
            'problem_to_reset': self.problem_urlname,
1545
            'unique_student_identifier': self.student.email,
1546 1547 1548 1549 1550 1551 1552 1553 1554
        })
        self.assertEqual(response.status_code, 200)
        # make sure problem attempts have been reset.
        changed_module = StudentModule.objects.get(pk=self.module_to_reset.pk)
        self.assertEqual(
            json.loads(changed_module.state)['attempts'],
            0
        )

Miles Steele committed
1555 1556 1557
    # mock out the function which should be called to execute the action.
    @patch.object(instructor_task.api, 'submit_reset_problem_attempts_for_all_students')
    def test_reset_student_attempts_all(self, act):
1558
        """ Test reset all student attempts. """
1559
        url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
1560 1561 1562 1563 1564 1565 1566 1567 1568
        response = self.client.get(url, {
            'problem_to_reset': self.problem_urlname,
            'all_students': True,
        })
        self.assertEqual(response.status_code, 200)
        self.assertTrue(act.called)

    def test_reset_student_attempts_missingmodule(self):
        """ Test reset for non-existant problem. """
1569
        url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
1570 1571
        response = self.client.get(url, {
            'problem_to_reset': 'robot-not-a-real-module',
1572
            'unique_student_identifier': self.student.email,
1573 1574 1575 1576 1577
        })
        self.assertEqual(response.status_code, 400)

    def test_reset_student_attempts_delete(self):
        """ Test delete single student state. """
1578
        url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
1579 1580
        response = self.client.get(url, {
            'problem_to_reset': self.problem_urlname,
1581
            'unique_student_identifier': self.student.email,
1582 1583 1584 1585 1586 1587 1588 1589
            'delete_module': True,
        })
        self.assertEqual(response.status_code, 200)
        # make sure the module has been deleted
        self.assertEqual(
            StudentModule.objects.filter(
                student=self.module_to_reset.student,
                course_id=self.module_to_reset.course_id,
1590
                # module_id=self.module_to_reset.module_id,
1591 1592 1593 1594 1595
            ).count(),
            0
        )

    def test_reset_student_attempts_nonsense(self):
1596
        """ Test failure with both unique_student_identifier and all_students. """
1597
        url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
1598 1599
        response = self.client.get(url, {
            'problem_to_reset': self.problem_urlname,
1600
            'unique_student_identifier': self.student.email,
1601 1602 1603 1604
            'all_students': True,
        })
        self.assertEqual(response.status_code, 400)

Miles Steele committed
1605 1606
    @patch.object(instructor_task.api, 'submit_rescore_problem_for_student')
    def test_rescore_problem_single(self, act):
1607
        """ Test rescoring of a single student. """
1608
        url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})
1609 1610
        response = self.client.get(url, {
            'problem_to_reset': self.problem_urlname,
1611 1612 1613 1614 1615 1616 1617 1618
            'unique_student_identifier': self.student.email,
        })
        self.assertEqual(response.status_code, 200)
        self.assertTrue(act.called)

    @patch.object(instructor_task.api, 'submit_rescore_problem_for_student')
    def test_rescore_problem_single_from_uname(self, act):
        """ Test rescoring of a single student. """
1619
        url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})
1620 1621 1622
        response = self.client.get(url, {
            'problem_to_reset': self.problem_urlname,
            'unique_student_identifier': self.student.username,
1623 1624 1625 1626
        })
        self.assertEqual(response.status_code, 200)
        self.assertTrue(act.called)

Miles Steele committed
1627 1628
    @patch.object(instructor_task.api, 'submit_rescore_problem_for_all_students')
    def test_rescore_problem_all(self, act):
1629
        """ Test rescoring for all students. """
1630
        url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})
1631 1632 1633 1634 1635
        response = self.client.get(url, {
            'problem_to_reset': self.problem_urlname,
            'all_students': True,
        })
        self.assertEqual(response.status_code, 200)
1636
        self.assertTrue(act.called)
1637 1638 1639


@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
1640
@patch.dict(settings.FEATURES, {'ENABLE_INSTRUCTOR_EMAIL': True, 'REQUIRE_COURSE_EMAIL_AUTH': False})
1641 1642
class TestInstructorSendEmail(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
1643 1644 1645
    Checks that only instructors have access to email endpoints, and that
    these endpoints are only accessible with courses that actually exist,
    only with valid email messages.
1646 1647 1648
    """
    def setUp(self):
        self.course = CourseFactory.create()
1649
        self.instructor = InstructorFactory(course_key=self.course.id)
1650
        self.client.login(username=self.instructor.username, password='test')
1651 1652 1653 1654 1655 1656 1657 1658
        test_subject = u'\u1234 test subject'
        test_message = u'\u6824 test message'
        self.full_test_message = {
            'send_to': 'staff',
            'subject': test_subject,
            'message': test_message,
        }

1659
    def test_send_email_as_logged_in_instructor(self):
1660
        url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()})
1661
        response = self.client.post(url, self.full_test_message)
1662 1663 1664 1665
        self.assertEqual(response.status_code, 200)

    def test_send_email_but_not_logged_in(self):
        self.client.logout()
1666
        url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()})
1667
        response = self.client.post(url, self.full_test_message)
1668 1669 1670 1671
        self.assertEqual(response.status_code, 403)

    def test_send_email_but_not_staff(self):
        self.client.logout()
1672 1673
        student = UserFactory()
        self.client.login(username=student.username, password='test')
1674
        url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()})
1675
        response = self.client.post(url, self.full_test_message)
1676 1677 1678 1679
        self.assertEqual(response.status_code, 403)

    def test_send_email_but_course_not_exist(self):
        url = reverse('send_email', kwargs={'course_id': 'GarbageCourse/DNE/NoTerm'})
1680
        response = self.client.post(url, self.full_test_message)
1681 1682 1683
        self.assertNotEqual(response.status_code, 200)

    def test_send_email_no_sendto(self):
1684
        url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()})
1685 1686 1687
        response = self.client.post(url, {
            'subject': 'test subject',
            'message': 'test message',
1688
        })
1689 1690 1691
        self.assertEqual(response.status_code, 400)

    def test_send_email_no_subject(self):
1692
        url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()})
1693 1694 1695
        response = self.client.post(url, {
            'send_to': 'staff',
            'message': 'test message',
1696
        })
1697 1698 1699
        self.assertEqual(response.status_code, 400)

    def test_send_email_no_message(self):
1700
        url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()})
1701 1702 1703
        response = self.client.post(url, {
            'send_to': 'staff',
            'subject': 'test subject',
1704
        })
1705
        self.assertEqual(response.status_code, 400)
1706 1707


1708 1709 1710 1711 1712 1713 1714 1715
class MockCompletionInfo(object):
    """Mock for get_task_completion_info"""
    times_called = 0

    def mock_get_task_completion_info(self, *args):  # pylint: disable=unused-argument
        """Mock for get_task_completion_info"""
        self.times_called += 1
        if self.times_called % 2 == 0:
1716 1717
            return True, 'Task Completed'
        return False, 'Task Errored In Some Way'
1718 1719


1720
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
1721 1722 1723 1724 1725 1726 1727
class TestInstructorAPITaskLists(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
    Test instructor task list endpoint.
    """

    class FakeTask(object):
        """ Fake task object """
1728 1729 1730 1731 1732 1733 1734 1735 1736
        FEATURES = [
            'task_type',
            'task_input',
            'task_id',
            'requester',
            'task_state',
            'created',
            'status',
            'task_message',
1737
            'duration_sec'
1738
        ]
1739

1740
        def __init__(self, completion):
1741 1742
            for feature in self.FEATURES:
                setattr(self, feature, 'expected')
1743 1744
            # created needs to be a datetime
            self.created = datetime.datetime(2013, 10, 25, 11, 42, 35)
1745 1746 1747
            # set 'status' and 'task_message' attrs
            success, task_message = completion()
            if success:
1748
                self.status = "Complete"
1749
            else:
1750 1751
                self.status = "Incomplete"
            self.task_message = task_message
1752
            # Set 'task_output' attr, which will be parsed to the 'duration_sec' attr.
1753 1754
            self.task_output = '{"duration_ms": 1035000}'
            self.duration_sec = 1035000 / 1000.0
1755

1756 1757 1758 1759 1760 1761
        def make_invalid_output(self):
            """Munge task_output to be invalid json"""
            self.task_output = 'HI MY NAME IS INVALID JSON'
            # This should be given the value of 'unknown' if the task output
            # can't be properly parsed
            self.duration_sec = 'unknown'
1762 1763

        def to_dict(self):
Miles Steele committed
1764
            """ Convert fake task to dictionary representation. """
1765 1766 1767
            attr_dict = {key: getattr(self, key) for key in self.FEATURES}
            attr_dict['created'] = attr_dict['created'].isoformat()
            return attr_dict
1768 1769 1770

    def setUp(self):
        self.course = CourseFactory.create()
1771
        self.instructor = InstructorFactory(course_key=self.course.id)
1772 1773 1774
        self.client.login(username=self.instructor.username, password='test')

        self.student = UserFactory()
1775
        CourseEnrollment.enroll(self.student, self.course.id)
1776

1777 1778 1779 1780
        self.problem_location = msk_from_problem_urlname(
            self.course.id,
            'robot-some-problem-urlname'
        )
1781
        self.problem_urlname = self.problem_location.to_deprecated_string()
1782

1783 1784 1785
        self.module = StudentModule.objects.create(
            student=self.student,
            course_id=self.course.id,
1786
            module_state_key=self.problem_location,
1787 1788
            state=json.dumps({'attempts': 10}),
        )
1789
        mock_factory = MockCompletionInfo()
1790 1791
        self.tasks = [self.FakeTask(mock_factory.mock_get_task_completion_info) for _ in xrange(7)]
        self.tasks[-1].make_invalid_output()
1792

1793 1794 1795 1796 1797
    def tearDown(self):
        """
        Undo all patches.
        """
        patch.stopall()
1798

Miles Steele committed
1799 1800
    @patch.object(instructor_task.api, 'get_running_instructor_tasks')
    def test_list_instructor_tasks_running(self, act):
1801
        """ Test list of all running tasks. """
Miles Steele committed
1802
        act.return_value = self.tasks
1803
        url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})
1804 1805 1806 1807
        mock_factory = MockCompletionInfo()
        with patch('instructor.views.api.get_task_completion_info') as mock_completion_info:
            mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info
            response = self.client.get(url, {})
1808 1809 1810 1811 1812
        self.assertEqual(response.status_code, 200)

        # check response
        self.assertTrue(act.called)
        expected_tasks = [ftask.to_dict() for ftask in self.tasks]
1813 1814 1815 1816
        actual_tasks = json.loads(response.content)['tasks']
        for exp_task, act_task in zip(expected_tasks, actual_tasks):
            self.assertDictEqual(exp_task, act_task)
        self.assertEqual(actual_tasks, expected_tasks)
1817

Miles Steele committed
1818
    @patch.object(instructor_task.api, 'get_instructor_task_history')
1819 1820 1821
    def test_list_background_email_tasks(self, act):
        """Test list of background email tasks."""
        act.return_value = self.tasks
1822
        url = reverse('list_background_email_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
        mock_factory = MockCompletionInfo()
        with patch('instructor.views.api.get_task_completion_info') as mock_completion_info:
            mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info
            response = self.client.get(url, {})
        self.assertEqual(response.status_code, 200)

        # check response
        self.assertTrue(act.called)
        expected_tasks = [ftask.to_dict() for ftask in self.tasks]
        actual_tasks = json.loads(response.content)['tasks']
        for exp_task, act_task in zip(expected_tasks, actual_tasks):
            self.assertDictEqual(exp_task, act_task)
        self.assertEqual(actual_tasks, expected_tasks)

    @patch.object(instructor_task.api, 'get_instructor_task_history')
Miles Steele committed
1838
    def test_list_instructor_tasks_problem(self, act):
1839
        """ Test list task history for problem. """
Miles Steele committed
1840
        act.return_value = self.tasks
1841
        url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})
1842 1843 1844 1845
        mock_factory = MockCompletionInfo()
        with patch('instructor.views.api.get_task_completion_info') as mock_completion_info:
            mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info
            response = self.client.get(url, {
1846
                'problem_location_str': self.problem_urlname,
1847
            })
1848 1849 1850 1851 1852
        self.assertEqual(response.status_code, 200)

        # check response
        self.assertTrue(act.called)
        expected_tasks = [ftask.to_dict() for ftask in self.tasks]
1853 1854 1855 1856
        actual_tasks = json.loads(response.content)['tasks']
        for exp_task, act_task in zip(expected_tasks, actual_tasks):
            self.assertDictEqual(exp_task, act_task)
        self.assertEqual(actual_tasks, expected_tasks)
1857

Miles Steele committed
1858 1859
    @patch.object(instructor_task.api, 'get_instructor_task_history')
    def test_list_instructor_tasks_problem_student(self, act):
1860
        """ Test list task history for problem AND student. """
Miles Steele committed
1861
        act.return_value = self.tasks
1862
        url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})
1863 1864 1865 1866
        mock_factory = MockCompletionInfo()
        with patch('instructor.views.api.get_task_completion_info') as mock_completion_info:
            mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info
            response = self.client.get(url, {
1867
                'problem_location_str': self.problem_urlname,
1868 1869
                'unique_student_identifier': self.student.email,
            })
1870 1871 1872 1873 1874
        self.assertEqual(response.status_code, 200)

        # check response
        self.assertTrue(act.called)
        expected_tasks = [ftask.to_dict() for ftask in self.tasks]
1875 1876 1877 1878 1879
        actual_tasks = json.loads(response.content)['tasks']
        for exp_task, act_task in zip(expected_tasks, actual_tasks):
            self.assertDictEqual(exp_task, act_task)

        self.assertEqual(actual_tasks, expected_tasks)
1880 1881


1882
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
@override_settings(ANALYTICS_SERVER_URL="http://robotanalyticsserver.netbot:900/")
@override_settings(ANALYTICS_API_KEY="robot_api_key")
class TestInstructorAPIAnalyticsProxy(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
    Test instructor analytics proxy endpoint.
    """

    class FakeProxyResponse(object):
        """ Fake successful requests response object. """
        def __init__(self):
1893
            self.status_code = requests.status_codes.codes.OK
1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
            self.content = '{"test_content": "robot test content"}'

    class FakeBadProxyResponse(object):
        """ Fake strange-failed requests response object. """
        def __init__(self):
            self.status_code = 'notok.'
            self.content = '{"test_content": "robot test content"}'

    def setUp(self):
        self.course = CourseFactory.create()
1904
        self.instructor = InstructorFactory(course_key=self.course.id)
1905 1906
        self.client.login(username=self.instructor.username, password='test')

Miles Steele committed
1907 1908
    @patch.object(instructor.views.api.requests, 'get')
    def test_analytics_proxy_url(self, act):
1909
        """ Test legacy analytics proxy url generation. """
Miles Steele committed
1910
        act.return_value = self.FakeProxyResponse()
1911

1912
        url = reverse('proxy_legacy_analytics', kwargs={'course_id': self.course.id.to_deprecated_string()})
1913 1914 1915 1916 1917 1918
        response = self.client.get(url, {
            'aname': 'ProblemGradeDistribution'
        })
        self.assertEqual(response.status_code, 200)

        # check request url
1919
        expected_url = "{url}get?aname={aname}&course_id={course_id!s}&apikey={api_key}".format(
1920 1921
            url="http://robotanalyticsserver.netbot:900/",
            aname="ProblemGradeDistribution",
1922
            course_id=self.course.id.to_deprecated_string(),
1923 1924 1925 1926
            api_key="robot_api_key",
        )
        act.assert_called_once_with(expected_url)

Miles Steele committed
1927 1928
    @patch.object(instructor.views.api.requests, 'get')
    def test_analytics_proxy(self, act):
1929
        """
Miles Steele committed
1930
        Test legacy analytics content proxyin, actg.
1931
        """
Miles Steele committed
1932
        act.return_value = self.FakeProxyResponse()
1933

1934
        url = reverse('proxy_legacy_analytics', kwargs={'course_id': self.course.id.to_deprecated_string()})
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
        response = self.client.get(url, {
            'aname': 'ProblemGradeDistribution'
        })
        self.assertEqual(response.status_code, 200)

        # check response
        self.assertTrue(act.called)
        expected_res = {'test_content': "robot test content"}
        self.assertEqual(json.loads(response.content), expected_res)

Miles Steele committed
1945 1946
    @patch.object(instructor.views.api.requests, 'get')
    def test_analytics_proxy_reqfailed(self, act):
1947
        """ Test proxy when server reponds with failure. """
Miles Steele committed
1948
        act.return_value = self.FakeBadProxyResponse()
1949

1950
        url = reverse('proxy_legacy_analytics', kwargs={'course_id': self.course.id.to_deprecated_string()})
1951 1952 1953 1954 1955
        response = self.client.get(url, {
            'aname': 'ProblemGradeDistribution'
        })
        self.assertEqual(response.status_code, 500)

Miles Steele committed
1956 1957
    @patch.object(instructor.views.api.requests, 'get')
    def test_analytics_proxy_missing_param(self, act):
1958
        """ Test proxy when missing the aname query parameter. """
Miles Steele committed
1959
        act.return_value = self.FakeProxyResponse()
1960

1961
        url = reverse('proxy_legacy_analytics', kwargs={'course_id': self.course.id.to_deprecated_string()})
1962 1963 1964 1965 1966
        response = self.client.get(url, {})
        self.assertEqual(response.status_code, 400)
        self.assertFalse(act.called)


1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
class TestInstructorAPIHelpers(TestCase):
    """ Test helpers for instructor.api """
    def test_split_input_list(self):
        strings = []
        lists = []
        strings.append("Lorem@ipsum.dolor, sit@amet.consectetur\nadipiscing@elit.Aenean\r convallis@at.lacus\r, ut@lacinia.Sed")
        lists.append(['Lorem@ipsum.dolor', 'sit@amet.consectetur', 'adipiscing@elit.Aenean', 'convallis@at.lacus', 'ut@lacinia.Sed'])

        for (stng, lst) in zip(strings, lists):
            self.assertEqual(_split_input_list(stng), lst)
1977 1978 1979 1980 1981 1982 1983

    def test_split_input_list_unicode(self):
        self.assertEqual(_split_input_list('robot@robot.edu, robot2@robot.edu'), ['robot@robot.edu', 'robot2@robot.edu'])
        self.assertEqual(_split_input_list(u'robot@robot.edu, robot2@robot.edu'), ['robot@robot.edu', 'robot2@robot.edu'])
        self.assertEqual(_split_input_list(u'robot@robot.edu, robot2@robot.edu'), [u'robot@robot.edu', 'robot2@robot.edu'])
        scary_unistuff = unichr(40960) + u'abcd' + unichr(1972)
        self.assertEqual(_split_input_list(scary_unistuff), [scary_unistuff])
1984 1985

    def test_msk_from_problem_urlname(self):
1986 1987 1988 1989
        course_id = SlashSeparatedCourseKey('MITx', '6.002x', '2013_Spring')
        name = 'L2Node1'
        output = 'i4x://MITx/6.002x/problem/L2Node1'
        self.assertEqual(msk_from_problem_urlname(course_id, name).to_deprecated_string(), output)
1990

1991 1992 1993
    @raises(ValueError)
    def test_msk_from_problem_urlname_error(self):
        args = ('notagoodcourse', 'L2Node1')
1994
        msk_from_problem_urlname(*args)
1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011


@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
class TestDueDateExtensions(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
    Test data dumps for reporting.
    """

    def setUp(self):
        """
        Fixtures.
        """
        due = datetime.datetime(2010, 5, 12, 2, 42, tzinfo=utc)
        course = CourseFactory.create()
        week1 = ItemFactory.create(due=due)
        week2 = ItemFactory.create(due=due)
        week3 = ItemFactory.create(due=due)
2012 2013
        course.children = [week1.location.to_deprecated_string(), week2.location.to_deprecated_string(),
                           week3.location.to_deprecated_string()]
2014 2015 2016 2017 2018

        homework = ItemFactory.create(
            parent_location=week1.location,
            due=due
        )
2019
        week1.children = [homework.location.to_deprecated_string()]
2020 2021 2022 2023 2024 2025

        user1 = UserFactory.create()
        StudentModule(
            state='{}',
            student_id=user1.id,
            course_id=course.id,
2026
            module_state_key=week1.location).save()
2027 2028 2029 2030
        StudentModule(
            state='{}',
            student_id=user1.id,
            course_id=course.id,
2031
            module_state_key=week2.location).save()
2032 2033 2034 2035
        StudentModule(
            state='{}',
            student_id=user1.id,
            course_id=course.id,
2036
            module_state_key=week3.location).save()
2037 2038 2039 2040
        StudentModule(
            state='{}',
            student_id=user1.id,
            course_id=course.id,
2041
            module_state_key=homework.location).save()
2042 2043 2044 2045 2046 2047

        user2 = UserFactory.create()
        StudentModule(
            state='{}',
            student_id=user2.id,
            course_id=course.id,
2048
            module_state_key=week1.location).save()
2049 2050 2051 2052
        StudentModule(
            state='{}',
            student_id=user2.id,
            course_id=course.id,
2053
            module_state_key=homework.location).save()
2054 2055 2056 2057 2058 2059

        user3 = UserFactory.create()
        StudentModule(
            state='{}',
            student_id=user3.id,
            course_id=course.id,
2060
            module_state_key=week1.location).save()
2061 2062 2063 2064
        StudentModule(
            state='{}',
            student_id=user3.id,
            course_id=course.id,
2065
            module_state_key=homework.location).save()
2066 2067 2068 2069 2070 2071 2072 2073

        self.course = course
        self.week1 = week1
        self.homework = homework
        self.week2 = week2
        self.user1 = user1
        self.user2 = user2

2074
        self.instructor = InstructorFactory(course_key=course.id)
2075 2076 2077
        self.client.login(username=self.instructor.username, password='test')

    def test_change_due_date(self):
2078
        url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
2079 2080
        response = self.client.get(url, {
            'student': self.user1.username,
2081
            'url': self.week1.location.to_deprecated_string(),
2082 2083 2084 2085 2086 2087 2088 2089
            'due_datetime': '12/30/2013 00:00'
        })
        self.assertEqual(response.status_code, 200, response.content)
        self.assertEqual(datetime.datetime(2013, 12, 30, 0, 0, tzinfo=utc),
                         get_extended_due(self.course, self.week1, self.user1))

    def test_reset_date(self):
        self.test_change_due_date()
2090
        url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
2091 2092
        response = self.client.get(url, {
            'student': self.user1.username,
2093
            'url': self.week1.location.to_deprecated_string(),
2094 2095 2096 2097 2098 2099 2100 2101
        })
        self.assertEqual(response.status_code, 200, response.content)
        self.assertEqual(None,
                         get_extended_due(self.course, self.week1, self.user1))

    def test_show_unit_extensions(self):
        self.test_change_due_date()
        url = reverse('show_unit_extensions',
2102 2103
                      kwargs={'course_id': self.course.id.to_deprecated_string()})
        response = self.client.get(url, {'url': self.week1.location.to_deprecated_string()})
2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
        self.assertEqual(response.status_code, 200, response.content)
        self.assertEqual(json.loads(response.content), {
            u'data': [{u'Extended Due Date': u'2013-12-30 00:00',
                       u'Full Name': self.user1.profile.name,
                       u'Username': self.user1.username}],
            u'header': [u'Username', u'Full Name', u'Extended Due Date'],
            u'title': u'Users with due date extensions for %s' %
            self.week1.display_name})

    def test_show_student_extensions(self):
        self.test_change_due_date()
        url = reverse('show_student_extensions',
2116
                      kwargs={'course_id': self.course.id.to_deprecated_string()})
2117 2118 2119 2120 2121 2122 2123 2124
        response = self.client.get(url, {'student': self.user1.username})
        self.assertEqual(response.status_code, 200, response.content)
        self.assertEqual(json.loads(response.content), {
            u'data': [{u'Extended Due Date': u'2013-12-30 00:00',
                       u'Unit': self.week1.display_name}],
            u'header': [u'Unit', u'Extended Due Date'],
            u'title': u'Due date extensions for %s (%s)' % (
            self.user1.profile.name, self.user1.username)})