test_api.py 33.8 KB
Newer Older
1
"""
2
Unit tests for instructor.api methods.
3
"""
David Baumgold committed
4
# pylint: disable=E1111
5
import unittest
6
import json
7
import requests
8
from urllib import quote
9
from django.conf import settings
10
from django.test import TestCase
11
from nose.tools import raises
Miles Steele committed
12
from mock import Mock, patch
13 14
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
15
from django.http import HttpRequest, HttpResponse
16

17
from django.contrib.auth.models import User
18
from courseware.tests.modulestore_config import TEST_DATA_MIXED_MODULESTORE
19 20 21 22 23 24
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from courseware.tests.helpers import LoginEnrollmentTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from student.tests.factories import UserFactory, AdminFactory

from student.models import CourseEnrollment
25
from courseware.models import StudentModule
26

Miles Steele committed
27 28 29
# modules which are mocked in test cases.
import instructor_task.api

30
from instructor.access import allow_access
31
import instructor.views.api
32 33 34 35 36 37
from instructor.views.api import (
    _split_input_list, _msk_from_problem_urlname, common_exceptions_400)
from instructor_task.api_helper import AlreadyRunningError


@common_exceptions_400
David Baumgold committed
38
def view_success(request):  # pylint: disable=W0613
39 40 41 42 43
    "A dummy view for testing that returns a simple HTTP response"
    return HttpResponse('success')


@common_exceptions_400
David Baumgold committed
44
def view_user_doesnotexist(request):  # pylint: disable=W0613
45 46 47 48 49
    "A dummy view that raises a User.DoesNotExist exception"
    raise User.DoesNotExist()


@common_exceptions_400
David Baumgold committed
50
def view_alreadyrunningerror(request):  # pylint: disable=W0613
51 52 53 54 55
    "A dummy view that raises an AlreadyRunningError exception"
    raise AlreadyRunningError()


class TestCommonExceptions400(unittest.TestCase):
David Baumgold committed
56 57 58
    """
    Testing the common_exceptions_400 decorator.
    """
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    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"])
92 93


94
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
95 96 97 98 99 100 101
class TestInstructorAPIDenyLevels(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
    Ensure that users cannot access endpoints they shouldn't be able to.
    """
    def setUp(self):
        self.user = UserFactory.create()
        self.course = CourseFactory.create()
102
        CourseEnrollment.enroll(self.user, self.course.id)
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
        self.client.login(username=self.user.username, password='test')

    def test_deny_students_update_enrollment(self):
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {})
        self.assertEqual(response.status_code, 403)

    def test_staff_level(self):
        """
        Ensure that an enrolled student can't access staff or instructor endpoints.
        """
        staff_level_endpoints = [
            'students_update_enrollment',
            'modify_access',
            'list_course_role_members',
            'get_grading_config',
            'get_students_features',
            'get_distribution',
            'get_student_progress_url',
            'reset_student_attempts',
            'rescore_problem',
            'list_instructor_tasks',
            'list_forum_members',
            'update_forum_role_membership',
127
            'proxy_legacy_analytics',
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
        ]
        for endpoint in staff_level_endpoints:
            url = reverse(endpoint, kwargs={'course_id': self.course.id})
            response = self.client.get(url, {})
            self.assertEqual(response.status_code, 403)

    def test_instructor_level(self):
        """
        Ensure that a staff member can't access instructor endpoints.
        """
        instructor_level_endpoints = [
            'modify_access',
            'list_course_role_members',
            'reset_student_attempts',
            'list_instructor_tasks',
            'update_forum_role_membership',
        ]
        for endpoint in instructor_level_endpoints:
            url = reverse(endpoint, kwargs={'course_id': self.course.id})
            response = self.client.get(url, {})
            self.assertEqual(response.status_code, 403)


151
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
152 153 154 155 156 157 158 159 160 161 162 163 164
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):
        self.instructor = AdminFactory.create()
        self.course = CourseFactory.create()
        self.client.login(username=self.instructor.username, password='test')

        self.enrolled_student = UserFactory()
165 166 167
        CourseEnrollment.enroll(
            self.enrolled_student,
            self.course.id
168 169 170 171 172 173
        )
        self.notenrolled_student = UserFactory()

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

Miles Steele committed
174
        # uncomment to enable enable printing of large diffs
175
        # from failed assertions in the event of a test failure.
Miles Steele committed
176 177
        # (comment because pylint C0103)
        # self.maxDiff = None
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240

    def test_missing_params(self):
        """ Test missing all query parameters. """
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id})
        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'
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {'emails': self.enrolled_student.email, 'action': action})
        self.assertEqual(response.status_code, 400)

    def test_enroll(self):
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {'emails': self.notenrolled_student.email, 'action': 'enroll'})
        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

        self.assertEqual(
            self.notenrolled_student.courseenrollment_set.filter(
                course_id=self.course.id
            ).count(),
            1
        )

        # test the response data
        expected = {
            "action": "enroll",
            "auto_enroll": False,
            "results": [
                {
                    "email": self.notenrolled_student.email,
                    "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)

    def test_unenroll(self):
        url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {'emails': self.enrolled_student.email, 'action': 'unenroll'})
        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

        self.assertEqual(
            self.enrolled_student.courseenrollment_set.filter(
241 242
                course_id=self.course.id,
                is_active=1,
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
            ).count(),
            0
        )

        # test the response data
        expected = {
            "action": "unenroll",
            "auto_enroll": False,
            "results": [
                {
                    "email": self.enrolled_student.email,
                    "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)


274
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
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.
    Actually, modify_access does not having a very meaningful
        response yet, so only the status code is tested.
    """
    def setUp(self):
        self.instructor = AdminFactory.create()
        self.course = CourseFactory.create()
        self.client.login(username=self.instructor.username, password='test')

        self.other_instructor = UserFactory()
        allow_access(self.course, self.other_instructor, 'instructor')
        self.other_staff = UserFactory()
        allow_access(self.course, self.other_staff, 'staff')
        self.other_user = UserFactory()

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

    def test_modify_access_bad_action(self):
        """ Test with an invalid action parameter. """
        url = reverse('modify_access', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'email': self.other_staff.email,
            'rolename': 'staff',
            'action': 'robot-not-an-action',
        })
        self.assertEqual(response.status_code, 400)

313 314 315 316 317 318 319 320 321 322
    def test_modify_access_bad_role(self):
        """ Test with an invalid action parameter. """
        url = reverse('modify_access', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'email': self.other_staff.email,
            'rolename': 'robot-not-a-roll',
            'action': 'revoke',
        })
        self.assertEqual(response.status_code, 400)

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
    def test_modify_access_allow(self):
        url = reverse('modify_access', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'email': self.other_instructor.email,
            'rolename': 'staff',
            'action': 'allow',
        })
        self.assertEqual(response.status_code, 200)

    def test_modify_access_revoke(self):
        url = reverse('modify_access', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'email': self.other_staff.email,
            'rolename': 'staff',
            'action': 'revoke',
        })
        self.assertEqual(response.status_code, 200)

    def test_modify_access_revoke_not_allowed(self):
        """ Test revoking access that a user does not have. """
        url = reverse('modify_access', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'email': self.other_staff.email,
            '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.
        """
        url = reverse('modify_access', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'email': self.instructor.email,
            'rolename': 'instructor',
            'action': 'revoke',
        })
        self.assertEqual(response.status_code, 400)

    def test_list_course_role_members_noparams(self):
        """ Test missing all query parameters. """
        url = reverse('list_course_role_members', kwargs={'course_id': self.course.id})
        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. """
        url = reverse('list_course_role_members', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'rolename': 'robot-not-a-rolename',
        })
        print response
        self.assertEqual(response.status_code, 400)

    def test_list_course_role_members_staff(self):
        url = reverse('list_course_role_members', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'rolename': 'staff',
        })
        print response
        self.assertEqual(response.status_code, 200)

        # check response content
        expected = {
            'course_id': self.course.id,
            '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):
        url = reverse('list_course_role_members', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'rolename': 'beta',
        })
        print response
        self.assertEqual(response.status_code, 200)

        # check response content
        expected = {
            'course_id': self.course.id,
            'beta': []
        }
        res_json = json.loads(response.content)
        self.assertEqual(res_json, expected)
416 417


418
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
419 420 421 422 423 424 425 426 427 428 429
class TestInstructorAPILevelsDataDump(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
    Test endpoints that show data without side effects.
    """
    def setUp(self):
        self.instructor = AdminFactory.create()
        self.course = CourseFactory.create()
        self.client.login(username=self.instructor.username, password='test')

        self.students = [UserFactory() for _ in xrange(6)]
        for student in self.students:
430
            CourseEnrollment.enroll(student, self.course.id)
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448

    def test_get_students_features(self):
        """
        Test that some minimum of information is formatted
        correctly in the response to get_students_features.
        """
        url = reverse('get_students_features', kwargs={'course_id': self.course.id})
        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)

449 450 451 452 453 454 455 456 457
    def test_get_students_features_csv(self):
        """
        Test that some minimum of information is formatted
        correctly in the response to get_students_features.
        """
        url = reverse('get_students_features', kwargs={'course_id': self.course.id})
        response = self.client.get(url + '/csv', {})
        self.assertEqual(response['Content-Type'], 'text/csv')

458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
    def test_get_distribution_no_feature(self):
        """
        Test that get_distribution lists available features
        when supplied no feature quparameter.
        """
        url = reverse('get_distribution', kwargs={'course_id': self.course.id})
        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)

        url = reverse('get_distribution', kwargs={'course_id': self.course.id})
        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.
        """
        url = reverse('get_distribution', kwargs={'course_id': self.course.id})
        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.
        """
        url = reverse('get_distribution', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {'feature': 'gender'})
        self.assertEqual(response.status_code, 200)
        res_json = json.loads(response.content)
        print res_json
        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. """
        url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id})
        url += "?student_email={}".format(
            quote(self.students[0].email.encode("utf-8"))
        )
        print url
        response = self.client.get(url)
        print response
        self.assertEqual(response.status_code, 200)
        res_json = json.loads(response.content)
        self.assertIn('progress_url', res_json)

    def test_get_student_progress_url_noparams(self):
        """ Test that the endpoint 404's without the required query params. """
        url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id})
        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. """
        url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id})
        response = self.client.get(url)
        self.assertEqual(response.status_code, 400)


525
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
526 527 528 529 530 531 532 533 534 535 536 537 538 539
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.instructor = AdminFactory.create()
        self.course = CourseFactory.create()
        self.client.login(username=self.instructor.username, password='test')

        self.student = UserFactory()
540
        CourseEnrollment.enroll(self.student, self.course.id)
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579

        self.problem_urlname = 'robot-some-problem-urlname'
        self.module_to_reset = StudentModule.objects.create(
            student=self.student,
            course_id=self.course.id,
            module_state_key=_msk_from_problem_urlname(
                self.course.id,
                self.problem_urlname
            ),
            state=json.dumps({'attempts': 10}),
        )

    def test_reset_student_attempts_deletall(self):
        """ Make sure no one can delete all students state on a problem. """
        url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'problem_to_reset': self.problem_urlname,
            'all_students': True,
            'delete_module': True,
        })
        print response.content
        self.assertEqual(response.status_code, 400)

    def test_reset_student_attempts_single(self):
        """ Test reset single student attempts. """
        url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'problem_to_reset': self.problem_urlname,
            'student_email': self.student.email,
        })
        print response.content
        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
580 581 582
    # 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):
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
        """ Test reset all student attempts. """
        url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'problem_to_reset': self.problem_urlname,
            'all_students': True,
        })
        print response.content
        self.assertEqual(response.status_code, 200)
        self.assertTrue(act.called)

    def test_reset_student_attempts_missingmodule(self):
        """ Test reset for non-existant problem. """
        url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'problem_to_reset': 'robot-not-a-real-module',
            'student_email': self.student.email,
        })
        print response.content
        self.assertEqual(response.status_code, 400)

    def test_reset_student_attempts_delete(self):
        """ Test delete single student state. """
        url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'problem_to_reset': self.problem_urlname,
            'student_email': self.student.email,
            'delete_module': True,
        })
        print response.content
        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,
                # module_state_key=self.module_to_reset.module_state_key,
            ).count(),
            0
        )

    def test_reset_student_attempts_nonsense(self):
        """ Test failure with both student_email and all_students. """
        url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'problem_to_reset': self.problem_urlname,
            'student_email': self.student.email,
            'all_students': True,
        })
        print response.content
        self.assertEqual(response.status_code, 400)

Miles Steele committed
634 635
    @patch.object(instructor_task.api, 'submit_rescore_problem_for_student')
    def test_rescore_problem_single(self, act):
636 637 638 639 640 641 642 643 644 645
        """ Test rescoring of a single student. """
        url = reverse('rescore_problem', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'problem_to_reset': self.problem_urlname,
            'student_email': self.student.email,
        })
        print response.content
        self.assertEqual(response.status_code, 200)
        self.assertTrue(act.called)

Miles Steele committed
646 647
    @patch.object(instructor_task.api, 'submit_rescore_problem_for_all_students')
    def test_rescore_problem_all(self, act):
648 649 650 651 652 653 654 655 656 657 658
        """ Test rescoring for all students. """
        url = reverse('rescore_problem', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'problem_to_reset': self.problem_urlname,
            'all_students': True,
        })
        print response.content
        self.assertEqual(response.status_code, 200)
        self.assertTrue(act.called)


659
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
660 661 662 663 664 665 666 667 668
class TestInstructorAPITaskLists(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
    Test instructor task list endpoint.
    """

    class FakeTask(object):
        """ Fake task object """
        FEATURES = ['task_type', 'task_input', 'task_id', 'requester', 'created', 'task_state']

Miles Steele committed
669
        def __init__(self):
670 671 672 673
            for feature in self.FEATURES:
                setattr(self, feature, 'expected')

        def to_dict(self):
Miles Steele committed
674
            """ Convert fake task to dictionary representation. """
675 676 677 678 679 680 681 682
            return {key: 'expected' for key in self.FEATURES}

    def setUp(self):
        self.instructor = AdminFactory.create()
        self.course = CourseFactory.create()
        self.client.login(username=self.instructor.username, password='test')

        self.student = UserFactory()
683
        CourseEnrollment.enroll(self.student, self.course.id)
684 685 686 687 688 689 690 691 692 693 694 695

        self.problem_urlname = 'robot-some-problem-urlname'
        self.module = StudentModule.objects.create(
            student=self.student,
            course_id=self.course.id,
            module_state_key=_msk_from_problem_urlname(
                self.course.id,
                self.problem_urlname
            ),
            state=json.dumps({'attempts': 10}),
        )

Miles Steele committed
696
        self.tasks = [self.FakeTask() for _ in xrange(6)]
697

Miles Steele committed
698 699
    @patch.object(instructor_task.api, 'get_running_instructor_tasks')
    def test_list_instructor_tasks_running(self, act):
700
        """ Test list of all running tasks. """
Miles Steele committed
701
        act.return_value = self.tasks
702 703 704 705 706 707 708 709 710 711 712
        url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {})
        print response.content
        self.assertEqual(response.status_code, 200)

        # check response
        self.assertTrue(act.called)
        expected_tasks = [ftask.to_dict() for ftask in self.tasks]
        expected_res = {'tasks': expected_tasks}
        self.assertEqual(json.loads(response.content), expected_res)

Miles Steele committed
713 714
    @patch.object(instructor_task.api, 'get_instructor_task_history')
    def test_list_instructor_tasks_problem(self, act):
715
        """ Test list task history for problem. """
Miles Steele committed
716
        act.return_value = self.tasks
717 718 719 720 721 722 723 724 725 726 727 728 729
        url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'problem_urlname': self.problem_urlname,
        })
        print response.content
        self.assertEqual(response.status_code, 200)

        # check response
        self.assertTrue(act.called)
        expected_tasks = [ftask.to_dict() for ftask in self.tasks]
        expected_res = {'tasks': expected_tasks}
        self.assertEqual(json.loads(response.content), expected_res)

Miles Steele committed
730 731
    @patch.object(instructor_task.api, 'get_instructor_task_history')
    def test_list_instructor_tasks_problem_student(self, act):
732
        """ Test list task history for problem AND student. """
Miles Steele committed
733
        act.return_value = self.tasks
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
        url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'problem_urlname': self.problem_urlname,
            'student_email': self.student.email,
        })
        print response.content
        self.assertEqual(response.status_code, 200)

        # check response
        self.assertTrue(act.called)
        expected_tasks = [ftask.to_dict() for ftask in self.tasks]
        expected_res = {'tasks': expected_tasks}
        self.assertEqual(json.loads(response.content), expected_res)


749
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
750 751 752 753 754 755 756 757 758 759
@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):
760
            self.status_code = requests.status_codes.codes.OK
761 762 763 764 765 766 767 768 769 770 771 772 773
            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.instructor = AdminFactory.create()
        self.course = CourseFactory.create()
        self.client.login(username=self.instructor.username, password='test')

Miles Steele committed
774 775
    @patch.object(instructor.views.api.requests, 'get')
    def test_analytics_proxy_url(self, act):
776
        """ Test legacy analytics proxy url generation. """
Miles Steele committed
777
        act.return_value = self.FakeProxyResponse()
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794

        url = reverse('proxy_legacy_analytics', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'aname': 'ProblemGradeDistribution'
        })
        print response.content
        self.assertEqual(response.status_code, 200)

        # check request url
        expected_url = "{url}get?aname={aname}&course_id={course_id}&apikey={api_key}".format(
            url="http://robotanalyticsserver.netbot:900/",
            aname="ProblemGradeDistribution",
            course_id=self.course.id,
            api_key="robot_api_key",
        )
        act.assert_called_once_with(expected_url)

Miles Steele committed
795 796
    @patch.object(instructor.views.api.requests, 'get')
    def test_analytics_proxy(self, act):
797
        """
Miles Steele committed
798
        Test legacy analytics content proxyin, actg.
799
        """
Miles Steele committed
800
        act.return_value = self.FakeProxyResponse()
801 802 803 804 805 806 807 808 809 810 811 812 813

        url = reverse('proxy_legacy_analytics', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'aname': 'ProblemGradeDistribution'
        })
        print response.content
        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
814 815
    @patch.object(instructor.views.api.requests, 'get')
    def test_analytics_proxy_reqfailed(self, act):
816
        """ Test proxy when server reponds with failure. """
Miles Steele committed
817
        act.return_value = self.FakeBadProxyResponse()
818 819 820 821 822 823 824 825

        url = reverse('proxy_legacy_analytics', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {
            'aname': 'ProblemGradeDistribution'
        })
        print response.content
        self.assertEqual(response.status_code, 500)

Miles Steele committed
826 827
    @patch.object(instructor.views.api.requests, 'get')
    def test_analytics_proxy_missing_param(self, act):
828
        """ Test proxy when missing the aname query parameter. """
Miles Steele committed
829
        act.return_value = self.FakeProxyResponse()
830 831 832 833 834 835 836 837

        url = reverse('proxy_legacy_analytics', kwargs={'course_id': self.course.id})
        response = self.client.get(url, {})
        print response.content
        self.assertEqual(response.status_code, 400)
        self.assertFalse(act.called)


838 839 840 841 842 843 844 845 846 847
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)
848 849 850 851 852 853 854

    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])
855 856 857 858 859 860 861 862 863 864

    def test_msk_from_problem_urlname(self):
        args = ('MITx/6.002x/2013_Spring', 'L2Node1')
        output = 'i4x://MITx/6.002x/problem/L2Node1'
        self.assertEqual(_msk_from_problem_urlname(*args), output)

    @raises(ValueError)
    def test_msk_from_problem_urlname_error(self):
        args = ('notagoodcourse', 'L2Node1')
        _msk_from_problem_urlname(*args)