test_support_views.py 18.4 KB
Newer Older
1 2 3 4 5 6 7
"""
Tests for certificate app views used by the support team.
"""

import json

import ddt
8
from django.conf import settings
9
from django.core.urlresolvers import reverse
10
from django.test.utils import override_settings
11
from opaque_keys.edx.keys import CourseKey
12

13
from certificates.models import CertificateInvalidation, CertificateStatuses, GeneratedCertificate
14
from certificates.tests.factories import CertificateInvalidationFactory
15 16
from student.models import CourseEnrollment
from student.roles import GlobalStaff, SupportStaffRole
17
from student.tests.factories import UserFactory
18 19 20
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory

21 22 23
FEATURES_WITH_CERTS_ENABLED = settings.FEATURES.copy()
FEATURES_WITH_CERTS_ENABLED['CERTIFICATES_HTML_VIEW'] = True

24

asadiqbal committed
25
class CertificateSupportTestCase(ModuleStoreTestCase):
26 27 28 29 30 31 32 33 34 35 36 37 38
    """
    Base class for tests of the certificate support views.
    """

    SUPPORT_USERNAME = "support"
    SUPPORT_EMAIL = "support@example.com"
    SUPPORT_PASSWORD = "support"

    STUDENT_USERNAME = "student"
    STUDENT_EMAIL = "student@example.com"
    STUDENT_PASSWORD = "student"

    CERT_COURSE_KEY = CourseKey.from_string("edX/DemoX/Demo_Course")
asadiqbal committed
39 40 41
    COURSE_NOT_EXIST_KEY = CourseKey.from_string("test/TestX/Test_Course_Not_Exist")
    EXISTED_COURSE_KEY_1 = CourseKey.from_string("test1/Test1X/Test_Course_Exist_1")
    EXISTED_COURSE_KEY_2 = CourseKey.from_string("test2/Test2X/Test_Course_Exist_2")
42 43 44 45 46 47 48 49 50 51 52
    CERT_GRADE = 0.89
    CERT_STATUS = CertificateStatuses.downloadable
    CERT_MODE = "verified"
    CERT_DOWNLOAD_URL = "http://www.example.com/cert.pdf"

    def setUp(self):
        """
        Create a support team member and a student with a certificate.
        Log in as the support team member.
        """
        super(CertificateSupportTestCase, self).setUp()
asadiqbal committed
53 54 55 56 57
        CourseFactory(
            org=CertificateSupportTestCase.EXISTED_COURSE_KEY_1.org,
            course=CertificateSupportTestCase.EXISTED_COURSE_KEY_1.course,
            run=CertificateSupportTestCase.EXISTED_COURSE_KEY_1.run,
        )
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

        # Create the support staff user
        self.support = UserFactory(
            username=self.SUPPORT_USERNAME,
            email=self.SUPPORT_EMAIL,
            password=self.SUPPORT_PASSWORD,
        )
        SupportStaffRole().add_users(self.support)

        # Create a student
        self.student = UserFactory(
            username=self.STUDENT_USERNAME,
            email=self.STUDENT_EMAIL,
            password=self.STUDENT_PASSWORD,
        )

        # Create certificates for the student
75
        self.cert = GeneratedCertificate.eligible_certificates.create(
76 77 78 79 80 81 82 83 84 85 86 87 88 89
            user=self.student,
            course_id=self.CERT_COURSE_KEY,
            grade=self.CERT_GRADE,
            status=self.CERT_STATUS,
            mode=self.CERT_MODE,
            download_url=self.CERT_DOWNLOAD_URL,
        )

        # Login as support staff
        success = self.client.login(username=self.SUPPORT_USERNAME, password=self.SUPPORT_PASSWORD)
        self.assertTrue(success, msg="Couldn't log in as support staff")


@ddt.ddt
asadiqbal committed
90
class CertificateSearchTests(CertificateSupportTestCase):
91 92 93
    """
    Tests for the certificate search end-point used by the support team.
    """
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    def setUp(self):
        """
        Create a course
        """
        super(CertificateSearchTests, self).setUp()
        self.course = CourseFactory()
        self.course.cert_html_view_enabled = True

        #course certificate configurations
        certificates = [
            {
                'id': 1,
                'name': 'Name 1',
                'description': 'Description 1',
                'course_title': 'course_title_1',
                'signatories': [],
                'version': 1,
                'is_active': True
            }
        ]

        self.course.certificates = {'certificates': certificates}
        self.course.save()  # pylint: disable=no-member
        self.store.update_item(self.course, self.user.id)
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

    @ddt.data(
        (GlobalStaff, True),
        (SupportStaffRole, True),
        (None, False),
    )
    @ddt.unpack
    def test_access_control(self, role, has_access):
        # Create a user and log in
        user = UserFactory(username="foo", password="foo")
        success = self.client.login(username="foo", password="foo")
        self.assertTrue(success, msg="Could not log in")

        # Assign the user to the role
        if role is not None:
            role().add_users(user)

        # Retrieve the page
        response = self._search("foo")

        if has_access:
            self.assertContains(response, json.dumps([]))
        else:
            self.assertEqual(response.status_code, 403)

    @ddt.data(
        (CertificateSupportTestCase.STUDENT_USERNAME, True),
        (CertificateSupportTestCase.STUDENT_EMAIL, True),
        ("bar", False),
        ("bar@example.com", False),
asadiqbal committed
148 149 150 151
        ("", False),
        (CertificateSupportTestCase.STUDENT_USERNAME, False, 'invalid_key'),
        (CertificateSupportTestCase.STUDENT_USERNAME, False, unicode(CertificateSupportTestCase.COURSE_NOT_EXIST_KEY)),
        (CertificateSupportTestCase.STUDENT_USERNAME, True, unicode(CertificateSupportTestCase.EXISTED_COURSE_KEY_1)),
152 153
    )
    @ddt.unpack
asadiqbal committed
154 155 156 157 158 159 160 161
    def test_search(self, user_filter, expect_result, course_filter=None):
        response = self._search(user_filter, course_filter)
        if expect_result:
            self.assertEqual(response.status_code, 200)
            results = json.loads(response.content)
            self.assertEqual(len(results), 1)
        else:
            self.assertEqual(response.status_code, 400)
162

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
    def test_search_with_plus_sign(self):
        """
        Test that email address that contains '+' accepted by student support
        """
        self.student.email = "student+student@example.com"
        self.student.save()  # pylint: disable=no-member

        response = self._search(self.student.email)
        self.assertEqual(response.status_code, 200)
        results = json.loads(response.content)

        self.assertEqual(len(results), 1)
        retrieved_data = results[0]
        self.assertEqual(retrieved_data["username"], self.STUDENT_USERNAME)

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
    def test_results(self):
        response = self._search(self.STUDENT_USERNAME)
        self.assertEqual(response.status_code, 200)
        results = json.loads(response.content)

        self.assertEqual(len(results), 1)
        retrieved_cert = results[0]

        self.assertEqual(retrieved_cert["username"], self.STUDENT_USERNAME)
        self.assertEqual(retrieved_cert["course_key"], unicode(self.CERT_COURSE_KEY))
        self.assertEqual(retrieved_cert["created"], self.cert.created_date.isoformat())
        self.assertEqual(retrieved_cert["modified"], self.cert.modified_date.isoformat())
        self.assertEqual(retrieved_cert["grade"], unicode(self.CERT_GRADE))
        self.assertEqual(retrieved_cert["status"], self.CERT_STATUS)
        self.assertEqual(retrieved_cert["type"], self.CERT_MODE)
193 194 195 196
        self.assertEqual(retrieved_cert["download_url"], self.CERT_DOWNLOAD_URL)

    @override_settings(FEATURES=FEATURES_WITH_CERTS_ENABLED)
    def test_download_link(self):
197
        self.cert.course_id = self.course.id  # pylint: disable=no-member
198 199 200 201 202 203 204 205 206 207 208 209 210 211
        self.cert.download_url = ''
        self.cert.save()

        response = self._search(self.STUDENT_USERNAME)
        self.assertEqual(response.status_code, 200)
        results = json.loads(response.content)

        self.assertEqual(len(results), 1)
        retrieved_cert = results[0]

        self.assertEqual(
            retrieved_cert["download_url"],
            reverse(
                'certificates:html_view',
212
                kwargs={"user_id": self.student.id, "course_id": self.course.id}  # pylint: disable=no-member
213 214
            )
        )
215

asadiqbal committed
216
    def _search(self, user_filter, course_filter=None):
217
        """Execute a search and return the response. """
asadiqbal committed
218 219 220
        url = reverse("certificates:search") + "?user=" + user_filter
        if course_filter:
            url += '&course_id=' + course_filter
221 222 223 224
        return self.client.get(url)


@ddt.ddt
asadiqbal committed
225
class CertificateRegenerateTests(CertificateSupportTestCase):
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
    """
    Tests for the certificate regeneration end-point used by the support team.
    """

    def setUp(self):
        """
        Create a course and enroll the student in the course.
        """
        super(CertificateRegenerateTests, self).setUp()
        self.course = CourseFactory(
            org=self.CERT_COURSE_KEY.org,
            course=self.CERT_COURSE_KEY.course,
            run=self.CERT_COURSE_KEY.run,
        )
        CourseEnrollment.enroll(self.student, self.CERT_COURSE_KEY, self.CERT_MODE)

    @ddt.data(
        (GlobalStaff, True),
        (SupportStaffRole, True),
        (None, False),
    )
    @ddt.unpack
    def test_access_control(self, role, has_access):
        # Create a user and log in
        user = UserFactory(username="foo", password="foo")
        success = self.client.login(username="foo", password="foo")
        self.assertTrue(success, msg="Could not log in")

        # Assign the user to the role
        if role is not None:
            role().add_users(user)

        # Make a POST request
        # Since we're not passing valid parameters, we'll get an error response
        # but at least we'll know we have access
        response = self._regenerate()

        if has_access:
            self.assertEqual(response.status_code, 400)
        else:
            self.assertEqual(response.status_code, 403)

    def test_regenerate_certificate(self):
        response = self._regenerate(
            course_key=self.course.id,  # pylint: disable=no-member
            username=self.STUDENT_USERNAME,
        )
        self.assertEqual(response.status_code, 200)

        # Check that the user's certificate was updated
        # Since the student hasn't actually passed the course,
        # we'd expect that the certificate status will be "notpassing"
278
        cert = GeneratedCertificate.eligible_certificates.get(user=self.student)
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 313 314 315 316
        self.assertEqual(cert.status, CertificateStatuses.notpassing)

    def test_regenerate_certificate_missing_params(self):
        # Missing username
        response = self._regenerate(course_key=self.CERT_COURSE_KEY)
        self.assertEqual(response.status_code, 400)

        # Missing course key
        response = self._regenerate(username=self.STUDENT_USERNAME)
        self.assertEqual(response.status_code, 400)

    def test_regenerate_no_such_user(self):
        response = self._regenerate(
            course_key=unicode(self.CERT_COURSE_KEY),
            username="invalid_username",
        )
        self.assertEqual(response.status_code, 400)

    def test_regenerate_no_such_course(self):
        response = self._regenerate(
            course_key=CourseKey.from_string("edx/invalid/course"),
            username=self.STUDENT_USERNAME
        )
        self.assertEqual(response.status_code, 400)

    def test_regenerate_user_is_not_enrolled(self):
        # Unenroll the user
        CourseEnrollment.unenroll(self.student, self.CERT_COURSE_KEY)

        # Can no longer regenerate certificates for the user
        response = self._regenerate(
            course_key=self.CERT_COURSE_KEY,
            username=self.STUDENT_USERNAME
        )
        self.assertEqual(response.status_code, 400)

    def test_regenerate_user_has_no_certificate(self):
        # Delete the user's certificate
317
        GeneratedCertificate.eligible_certificates.all().delete()
318 319 320 321 322 323 324 325 326

        # Should be able to regenerate
        response = self._regenerate(
            course_key=self.CERT_COURSE_KEY,
            username=self.STUDENT_USERNAME
        )
        self.assertEqual(response.status_code, 200)

        # A new certificate is created
327
        num_certs = GeneratedCertificate.eligible_certificates.filter(user=self.student).count()
328 329
        self.assertEqual(num_certs, 1)

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
    def test_regenerate_cert_with_invalidated_record(self):
        """ If the certificate is marked as invalid, regenerate the certificate
        and verify the invalidate entry is deactivated. """

        # mark certificate as invalid
        self._invalidate_certificate(self.cert)
        self.assertInvalidatedCertExists()
        # after invalidation certificate status become un-available.
        self.assertGeneratedCertExists(
            user=self.student, status=CertificateStatuses.unavailable
        )

        # Should be able to regenerate
        response = self._regenerate(
            course_key=self.CERT_COURSE_KEY,
            username=self.STUDENT_USERNAME
        )
        self.assertEqual(response.status_code, 200)
        self.assertInvalidatedCertDoesNotExist()

        # Check that the user's certificate was updated
        # Since the student hasn't actually passed the course,
        # we'd expect that the certificate status will be "notpassing"
        self.assertGeneratedCertExists(
            user=self.student, status=CertificateStatuses.notpassing
        )

357 358 359 360 361 362 363 364 365 366 367 368
    def _regenerate(self, course_key=None, username=None):
        """Call the regeneration end-point and return the response. """
        url = reverse("certificates:regenerate_certificate_for_user")
        params = {}

        if course_key is not None:
            params["course_key"] = course_key

        if username is not None:
            params["username"] = username

        return self.client.post(url, params)
asadiqbal committed
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
    def _invalidate_certificate(self, certificate):
        """ Dry method to mark certificate as invalid. """
        CertificateInvalidationFactory.create(
            generated_certificate=certificate,
            invalidated_by=self.support,
            active=True
        )
        # Invalidate user certificate
        certificate.invalidate()
        self.assertFalse(certificate.is_valid())

    def assertInvalidatedCertExists(self):
        """ Dry method to check certificate invalidated entry exists. """
        self.assertTrue(
            CertificateInvalidation.objects.filter(
                generated_certificate__user=self.student, active=True
            ).exists()
        )

    def assertInvalidatedCertDoesNotExist(self):
        """ Dry method to check certificate invalidated entry does not exists. """
        self.assertFalse(
            CertificateInvalidation.objects.filter(
                generated_certificate__user=self.student, active=True
            ).exists()
        )

    def assertGeneratedCertExists(self, user, status):
        """ Dry method to check if certificate exists. """
        self.assertTrue(
            GeneratedCertificate.objects.filter(  # pylint: disable=no-member
                user=user, status=status
            ).exists()
        )

asadiqbal committed
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 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

@ddt.ddt
class CertificateGenerateTests(CertificateSupportTestCase):
    """
    Tests for the certificate generation end-point used by the support team.
    """

    def setUp(self):
        """
        Create a course and enroll the student in the course.
        """
        super(CertificateGenerateTests, self).setUp()
        self.course = CourseFactory(
            org=self.EXISTED_COURSE_KEY_2.org,
            course=self.EXISTED_COURSE_KEY_2.course,
            run=self.EXISTED_COURSE_KEY_2.run
        )
        CourseEnrollment.enroll(self.student, self.EXISTED_COURSE_KEY_2, self.CERT_MODE)

    @ddt.data(
        (GlobalStaff, True),
        (SupportStaffRole, True),
        (None, False),
    )
    @ddt.unpack
    def test_access_control(self, role, has_access):
        # Create a user and log in
        user = UserFactory(username="foo", password="foo")
        success = self.client.login(username="foo", password="foo")
        self.assertTrue(success, msg="Could not log in")

        # Assign the user to the role
        if role is not None:
            role().add_users(user)

        # Make a POST request
        # Since we're not passing valid parameters, we'll get an error response
        # but at least we'll know we have access
        response = self._generate()

        if has_access:
            self.assertEqual(response.status_code, 400)
        else:
            self.assertEqual(response.status_code, 403)

    def test_generate_certificate(self):
        response = self._generate(
            course_key=self.course.id,  # pylint: disable=no-member
            username=self.STUDENT_USERNAME,
        )
        self.assertEqual(response.status_code, 200)

    def test_generate_certificate_missing_params(self):
        # Missing username
        response = self._generate(course_key=self.EXISTED_COURSE_KEY_2)
        self.assertEqual(response.status_code, 400)

        # Missing course key
        response = self._generate(username=self.STUDENT_USERNAME)
        self.assertEqual(response.status_code, 400)

    def test_generate_no_such_user(self):
        response = self._generate(
            course_key=unicode(self.EXISTED_COURSE_KEY_2),
            username="invalid_username",
        )
        self.assertEqual(response.status_code, 400)

    def test_generate_no_such_course(self):
        response = self._generate(
            course_key=CourseKey.from_string("edx/invalid/course"),
            username=self.STUDENT_USERNAME
        )
        self.assertEqual(response.status_code, 400)

    def test_generate_user_is_not_enrolled(self):
        # Unenroll the user
        CourseEnrollment.unenroll(self.student, self.EXISTED_COURSE_KEY_2)

        # Can no longer regenerate certificates for the user
        response = self._generate(
            course_key=self.EXISTED_COURSE_KEY_2,
            username=self.STUDENT_USERNAME
        )
        self.assertEqual(response.status_code, 400)

    def test_generate_user_has_no_certificate(self):
        # Delete the user's certificate
493
        GeneratedCertificate.eligible_certificates.all().delete()
asadiqbal committed
494 495 496 497 498 499 500 501 502

        # Should be able to generate
        response = self._generate(
            course_key=self.EXISTED_COURSE_KEY_2,
            username=self.STUDENT_USERNAME
        )
        self.assertEqual(response.status_code, 200)

        # A new certificate is created
503
        num_certs = GeneratedCertificate.eligible_certificates.filter(user=self.student).count()
asadiqbal committed
504 505 506 507 508 509 510 511 512 513 514 515 516 517
        self.assertEqual(num_certs, 1)

    def _generate(self, course_key=None, username=None):
        """Call the generation end-point and return the response. """
        url = reverse("certificates:generate_certificate_for_user")
        params = {}

        if course_key is not None:
            params["course_key"] = course_key

        if username is not None:
            params["username"] = username

        return self.client.post(url, params)