test_module_render.py 85.5 KB
Newer Older
1
# -*- coding: utf-8 -*-
2 3 4
"""
Test for lms courseware app, module render unit
"""
5
from datetime import datetime
6 7
import ddt
import itertools
8
import json
9
from nose.plugins.attrib import attr
10
from functools import partial
11

12
from bson import ObjectId
13
from django.http import Http404, HttpResponse
Brian Wilson committed
14
from django.core.urlresolvers import reverse
15
from django.conf import settings
16
from django.test.client import RequestFactory
17
from django.test.utils import override_settings
18
from django.contrib.auth.models import AnonymousUser
19
from freezegun import freeze_time
20
from mock import MagicMock, patch, Mock
21
from opaque_keys.edx.keys import UsageKey, CourseKey
22
from opaque_keys.edx.locations import SlashSeparatedCourseKey
23
from pyquery import PyQuery
24
import pytz
25 26 27
from xblock.field_data import FieldData
from xblock.runtime import Runtime
from xblock.fields import ScopeIds
28
from xblock.core import XBlock, XBlockAside
29
from xblock.fragment import Fragment
30

31
from capa.tests.response_xml_factory import OptionResponseXMLFactory
32
from course_modes.models import CourseMode
33
from courseware import module_render as render
34
from courseware.courses import get_course_with_access, get_course_info_section
35
from courseware.field_overrides import OverrideFieldData
36
from courseware.model_data import FieldDataCache
37
from courseware.module_render import hash_resource, get_module_for_descriptor
38
from courseware.models import StudentModule
39
from courseware.tests.factories import StudentModuleFactory, UserFactory, GlobalStaffFactory
40
from courseware.tests.tests import LoginEnrollmentTestCase
41
from courseware.tests.test_submitting_problems import TestSubmittingProblems
42
from lms.djangoapps.lms_xblock.field_data import LmsFieldData
43
from openedx.core.lib.courses import course_image_url
44
from openedx.core.lib.gating import api as gating_api
45
from openedx.core.lib.url_utils import quote_slashes
46
from student.models import anonymous_id_for_user
47
from xmodule.modulestore.tests.django_utils import (
48 49 50
    ModuleStoreTestCase,
    SharedModuleStoreTestCase,
    TEST_DATA_MIXED_MODULESTORE
51
)
52
from xmodule.lti_module import LTIDescriptor
53
from xmodule.modulestore import ModuleStoreEnum
54
from xmodule.modulestore.django import modulestore
55
from xmodule.modulestore.tests.factories import ItemFactory, CourseFactory, ToyCourseFactory, check_mongo_calls
56
from xmodule.modulestore.tests.test_asides import AsideTestType
57
from xmodule.x_module import XModuleDescriptor, XModule, STUDENT_VIEW, CombinedSystem
58

59 60 61 62 63
from openedx.core.djangoapps.credit.models import CreditCourse
from openedx.core.djangoapps.credit.api import (
    set_credit_requirements,
    set_credit_requirement_status
)
64
from xblock_django.models import XBlockConfiguration
65 66 67 68 69 70 71 72

from edx_proctoring.api import (
    create_exam,
    create_exam_attempt,
    update_attempt_status
)
from edx_proctoring.runtime import set_runtime_service
from edx_proctoring.tests.test_services import MockCreditService
73
from verify_student.tests.factories import SoftwareSecurePhotoVerificationFactory
74

75 76
from milestones.tests.utils import MilestonesTestCaseMixin

77

78
TEST_DATA_DIR = settings.COMMON_TEST_DATA_ROOT
Jay Zoldak committed
79

Jay Zoldak committed
80

81 82 83 84
@XBlock.needs("field-data")
@XBlock.needs("i18n")
@XBlock.needs("fs")
@XBlock.needs("user")
85
@XBlock.needs("bookmarks")
86 87 88 89 90 91 92
class PureXBlock(XBlock):
    """
    Pure XBlock to use in tests.
    """
    pass


93 94 95 96
class EmptyXModule(XModule):  # pylint: disable=abstract-method
    """
    Empty XModule for testing with no dependencies.
    """
97 98 99
    pass


100 101 102 103
class EmptyXModuleDescriptor(XModuleDescriptor):  # pylint: disable=abstract-method
    """
    Empty XModule for testing with no dependencies.
    """
104 105 106
    module_class = EmptyXModule


107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
class GradedStatelessXBlock(XBlock):
    """
    This XBlock exists to test grade storage for blocks that don't store
    student state in a scoped field.
    """

    @XBlock.json_handler
    def set_score(self, json_data, suffix):  # pylint: disable=unused-argument
        """
        Set the score for this testing XBlock.
        """
        self.runtime.publish(
            self,
            'grade',
            {
                'value': json_data['grade'],
                'max_value': 1
            }
        )


128
@attr(shard=1)
129
@ddt.ddt
130
class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase):
131 132 133
    """
    Tests of courseware.module_render
    """
134 135 136 137 138 139 140

    @classmethod
    def setUpClass(cls):
        super(ModuleRenderTestCase, cls).setUpClass()
        cls.course_key = ToyCourseFactory.create().id
        cls.toy_course = modulestore().get_course(cls.course_key)

141 142
    # TODO: this test relies on the specific setup of the toy course.
    # It should be rewritten to build the course it needs and then test that.
143
    def setUp(self):
144 145 146 147 148
        """
        Set up the course and user context
        """
        super(ModuleRenderTestCase, self).setUp()

149 150 151 152 153 154 155 156 157 158
        self.mock_user = UserFactory()
        self.mock_user.id = 1
        self.request_factory = RequestFactory()

        # Construct a mock module for the modulestore to return
        self.mock_module = MagicMock()
        self.mock_module.id = 1
        self.dispatch = 'score_update'

        # Construct a 'standard' xqueue_callback url
159 160 161 162 163 164 165 166 167
        self.callback_url = reverse(
            'xqueue_callback',
            kwargs=dict(
                course_id=self.course_key.to_deprecated_string(),
                userid=str(self.mock_user.id),
                mod_id=self.mock_module.id,
                dispatch=self.dispatch
            )
        )
168 169

    def test_get_module(self):
170 171
        self.assertEqual(
            None,
172
            render.get_module('dummyuser', None, 'invalid location', None)
173
        )
174

175 176 177 178 179 180 181 182 183
    def test_module_render_with_jump_to_id(self):
        """
        This test validates that the /jump_to_id/<id> shorthand for intracourse linking works assertIn
        expected. Note there's a HTML element in the 'toy' course with the url_name 'toyjumpto' which
        defines this linkage
        """
        mock_request = MagicMock()
        mock_request.user = self.mock_user

184
        course = get_course_with_access(self.mock_user, 'load', self.course_key)
185

Calen Pennington committed
186
        field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
187
            self.course_key, self.mock_user, course, depth=2)
188

Chris Dodge committed
189 190 191
        module = render.get_module(
            self.mock_user,
            mock_request,
192
            self.course_key.make_usage_key('html', 'toyjumpto'),
Calen Pennington committed
193
            field_data_cache,
Chris Dodge committed
194
        )
195 196

        # get the rendered HTML output which should have the rewritten link
197
        html = module.render(STUDENT_VIEW).content
198 199 200

        # See if the url got rewritten to the target link
        # note if the URL mapping changes then this assertion will break
201
        self.assertIn('/courses/' + self.course_key.to_deprecated_string() + '/jump_to_id/vertical_test', html)
202

203 204 205 206 207 208 209 210 211 212 213 214
    def test_xqueue_callback_success(self):
        """
        Test for happy-path xqueue_callback
        """
        fake_key = 'fake key'
        xqueue_header = json.dumps({'lms_key': fake_key})
        data = {
            'xqueue_header': xqueue_header,
            'xqueue_body': 'hello world',
        }

        # Patch getmodule to return our mock module
215
        with patch('courseware.module_render.load_single_xblock', return_value=self.mock_module):
216 217
            # call xqueue_callback with our mocked information
            request = self.request_factory.post(self.callback_url, data)
218 219 220 221 222 223 224
            render.xqueue_callback(
                request,
                unicode(self.course_key),
                self.mock_user.id,
                self.mock_module.id,
                self.dispatch
            )
225 226 227 228 229 230 231 232 233 234 235

        # Verify that handle ajax is called with the correct data
        request.POST['queuekey'] = fake_key
        self.mock_module.handle_ajax.assert_called_once_with(self.dispatch, request.POST)

    def test_xqueue_callback_missing_header_info(self):
        data = {
            'xqueue_header': '{}',
            'xqueue_body': 'hello world',
        }

236
        with patch('courseware.module_render.load_single_xblock', return_value=self.mock_module):
237 238 239
            # Test with missing xqueue data
            with self.assertRaises(Http404):
                request = self.request_factory.post(self.callback_url, {})
240 241 242 243 244 245 246
                render.xqueue_callback(
                    request,
                    unicode(self.course_key),
                    self.mock_user.id,
                    self.mock_module.id,
                    self.dispatch
                )
247 248 249 250

            # Test with missing xqueue_header
            with self.assertRaises(Http404):
                request = self.request_factory.post(self.callback_url, data)
251 252 253 254 255 256 257
                render.xqueue_callback(
                    request,
                    unicode(self.course_key),
                    self.mock_user.id,
                    self.mock_module.id,
                    self.dispatch
                )
258

259
    def test_anonymous_handle_xblock_callback(self):
260
        dispatch_url = reverse(
261
            'xblock_handler',
262
            args=[
263 264
                self.course_key.to_deprecated_string(),
                quote_slashes(self.course_key.make_usage_key('videosequence', 'Toy_Videos').to_deprecated_string()),
265
                'xmodule_handler',
266 267 268 269
                'goto_position'
            ]
        )
        response = self.client.post(dispatch_url, {'position': 2})
polesye committed
270 271
        self.assertEquals(403, response.status_code)
        self.assertEquals('Unauthenticated', response.content)
272

273 274 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
    def test_missing_position_handler(self):
        """
        Test that sending POST request without or invalid position argument don't raise server error
        """
        self.client.login(username=self.mock_user.username, password="test")
        dispatch_url = reverse(
            'xblock_handler',
            args=[
                self.course_key.to_deprecated_string(),
                quote_slashes(self.course_key.make_usage_key('videosequence', 'Toy_Videos').to_deprecated_string()),
                'xmodule_handler',
                'goto_position'
            ]
        )
        response = self.client.post(dispatch_url)
        self.assertEqual(200, response.status_code)
        self.assertEqual(json.loads(response.content), {'success': True})

        response = self.client.post(dispatch_url, {'position': ''})
        self.assertEqual(200, response.status_code)
        self.assertEqual(json.loads(response.content), {'success': True})

        response = self.client.post(dispatch_url, {'position': '-1'})
        self.assertEqual(200, response.status_code)
        self.assertEqual(json.loads(response.content), {'success': True})

        response = self.client.post(dispatch_url, {'position': "string"})
        self.assertEqual(200, response.status_code)
        self.assertEqual(json.loads(response.content), {'success': True})

        response = self.client.post(dispatch_url, {'position': u"Φυσικά"})
        self.assertEqual(200, response.status_code)
        self.assertEqual(json.loads(response.content), {'success': True})

        response = self.client.post(dispatch_url, {'position': None})
        self.assertEqual(200, response.status_code)
        self.assertEqual(json.loads(response.content), {'success': True})

311 312 313 314 315 316 317 318
    @ddt.data('pure', 'vertical')
    @XBlock.register_temp_plugin(PureXBlock, identifier='pure')
    def test_rebinding_same_user(self, block_type):
        request = self.request_factory.get('')
        request.user = self.mock_user
        course = CourseFactory()
        descriptor = ItemFactory(category=block_type, parent=course)
        field_data_cache = FieldDataCache([self.toy_course, descriptor], self.toy_course.id, self.mock_user)
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
        # This is verifying that caching doesn't cause an error during get_module_for_descriptor, which
        # is why it calls the method twice identically.
        render.get_module_for_descriptor(
            self.mock_user,
            request,
            descriptor,
            field_data_cache,
            self.toy_course.id,
            course=self.toy_course
        )
        render.get_module_for_descriptor(
            self.mock_user,
            request,
            descriptor,
            field_data_cache,
            self.toy_course.id,
            course=self.toy_course
        )
337

338
    @override_settings(FIELD_OVERRIDE_PROVIDERS=(
339
        'courseware.student_field_overrides.IndividualStudentOverrideProvider',
340
    ))
341
    def test_rebind_different_users(self):
342 343
        """
        This tests the rebinding a descriptor to a student does not result
344
        in overly nested _field_data.
345 346 347
        """
        request = self.request_factory.get('')
        request.user = self.mock_user
348
        course = CourseFactory.create()
349 350 351

        descriptor = ItemFactory(category='html', parent=course)
        field_data_cache = FieldDataCache(
352
            [course, descriptor], course.id, self.mock_user
353 354 355 356 357 358
        )

        # grab what _field_data was originally set to
        original_field_data = descriptor._field_data  # pylint: disable=protected-access, no-member

        render.get_module_for_descriptor(
359
            self.mock_user, request, descriptor, field_data_cache, course.id, course=course
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
        )

        # check that _unwrapped_field_data is the same as the original
        # _field_data, but now _field_data as been reset.
        # pylint: disable=protected-access, no-member
        self.assertIs(descriptor._unwrapped_field_data, original_field_data)
        self.assertIsNot(descriptor._unwrapped_field_data, descriptor._field_data)

        # now bind this module to a few other students
        for user in [UserFactory(), UserFactory(), UserFactory()]:
            render.get_module_for_descriptor(
                user,
                request,
                descriptor,
                field_data_cache,
375 376
                course.id,
                course=course
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
            )

        # _field_data should now be wrapped by LmsFieldData
        # pylint: disable=protected-access, no-member
        self.assertIsInstance(descriptor._field_data, LmsFieldData)

        # the LmsFieldData should now wrap OverrideFieldData
        self.assertIsInstance(
            # pylint: disable=protected-access, no-member
            descriptor._field_data._authored_data._source,
            OverrideFieldData
        )

        # the OverrideFieldData should point to the original unwrapped field_data
        self.assertIs(
            # pylint: disable=protected-access, no-member
            descriptor._field_data._authored_data._source.fallback,
            descriptor._unwrapped_field_data
        )

397 398 399 400 401 402 403 404
    def test_hash_resource(self):
        """
        Ensure that the resource hasher works and does not fail on unicode,
        decoded or otherwise.
        """
        resources = ['ASCII text', u'❄ I am a special snowflake.', "❄ So am I, but I didn't tell you."]
        self.assertEqual(hash_resource(resources), 'a76e27c8e80ca3efd7ce743093aa59e0')

Jay Zoldak committed
405

406
@attr(shard=1)
407
class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCase):
408 409 410
    """
    Test the handle_xblock_callback function
    """
411 412 413 414 415
    @classmethod
    def setUpClass(cls):
        super(TestHandleXBlockCallback, cls).setUpClass()
        cls.course_key = ToyCourseFactory.create().id
        cls.toy_course = modulestore().get_course(cls.course_key)
416 417

    def setUp(self):
418 419
        super(TestHandleXBlockCallback, self).setUp()

420
        self.location = self.course_key.make_usage_key('chapter', 'Overview')
421
        self.mock_user = UserFactory.create()
422 423 424 425 426 427 428 429
        self.request_factory = RequestFactory()

        # Construct a mock module for the modulestore to return
        self.mock_module = MagicMock()
        self.mock_module.id = 1
        self.dispatch = 'score_update'

        # Construct a 'standard' xqueue_callback url
430 431 432 433 434 435 436 437
        self.callback_url = reverse(
            'xqueue_callback', kwargs={
                'course_id': self.course_key.to_deprecated_string(),
                'userid': str(self.mock_user.id),
                'mod_id': self.mock_module.id,
                'dispatch': self.dispatch
            }
        )
438 439 440 441 442 443 444 445 446 447 448 449 450

    def _mock_file(self, name='file', size=10):
        """Create a mock file object for testing uploads"""
        mock_file = MagicMock(
            size=size,
            read=lambda: 'x' * size
        )
        # We can't use `name` as a kwarg to Mock to set the name attribute
        # because mock uses `name` to name the mock itself
        mock_file.name = name
        return mock_file

    def test_invalid_location(self):
451 452
        request = self.request_factory.post('dummy_url', data={'position': 1})
        request.user = self.mock_user
453 454
        with self.assertRaises(Http404):
            render.handle_xblock_callback(
455
                request,
456
                self.course_key.to_deprecated_string(),
457 458 459 460 461 462 463 464 465 466 467 468 469 470
                'invalid Location',
                'dummy_handler'
                'dummy_dispatch'
            )

    def test_too_many_files(self):
        request = self.request_factory.post(
            'dummy_url',
            data={'file_id': (self._mock_file(), ) * (settings.MAX_FILEUPLOADS_PER_INPUT + 1)}
        )
        request.user = self.mock_user
        self.assertEquals(
            render.handle_xblock_callback(
                request,
471 472
                self.course_key.to_deprecated_string(),
                quote_slashes(self.location.to_deprecated_string()),
473 474 475 476 477
                'dummy_handler'
            ).content,
            json.dumps({
                'success': 'Submission aborted! Maximum %d files may be submitted at once' %
                           settings.MAX_FILEUPLOADS_PER_INPUT
478
            }, indent=2)
479 480 481 482 483 484 485 486 487 488 489 490
        )

    def test_too_large_file(self):
        inputfile = self._mock_file(size=1 + settings.STUDENT_FILEUPLOAD_MAX_SIZE)
        request = self.request_factory.post(
            'dummy_url',
            data={'file_id': inputfile}
        )
        request.user = self.mock_user
        self.assertEquals(
            render.handle_xblock_callback(
                request,
491 492
                self.course_key.to_deprecated_string(),
                quote_slashes(self.location.to_deprecated_string()),
493 494 495 496 497
                'dummy_handler'
            ).content,
            json.dumps({
                'success': 'Submission aborted! Your file "%s" is too large (max size: %d MB)' %
                           (inputfile.name, settings.STUDENT_FILEUPLOAD_MAX_SIZE / (1000 ** 2))
498
            }, indent=2)
499 500 501 502 503 504 505
        )

    def test_xmodule_dispatch(self):
        request = self.request_factory.post('dummy_url', data={'position': 1})
        request.user = self.mock_user
        response = render.handle_xblock_callback(
            request,
506 507
            self.course_key.to_deprecated_string(),
            quote_slashes(self.location.to_deprecated_string()),
508 509 510 511 512 513 514 515 516 517 518 519
            'xmodule_handler',
            'goto_position',
        )
        self.assertIsInstance(response, HttpResponse)

    def test_bad_course_id(self):
        request = self.request_factory.post('dummy_url')
        request.user = self.mock_user
        with self.assertRaises(Http404):
            render.handle_xblock_callback(
                request,
                'bad_course_id',
520
                quote_slashes(self.location.to_deprecated_string()),
521 522 523 524 525 526 527 528 529 530
                'xmodule_handler',
                'goto_position',
            )

    def test_bad_location(self):
        request = self.request_factory.post('dummy_url')
        request.user = self.mock_user
        with self.assertRaises(Http404):
            render.handle_xblock_callback(
                request,
531 532
                self.course_key.to_deprecated_string(),
                quote_slashes(self.course_key.make_usage_key('chapter', 'bad_location').to_deprecated_string()),
533 534 535 536 537 538 539 540 541 542
                'xmodule_handler',
                'goto_position',
            )

    def test_bad_xmodule_dispatch(self):
        request = self.request_factory.post('dummy_url')
        request.user = self.mock_user
        with self.assertRaises(Http404):
            render.handle_xblock_callback(
                request,
543 544
                self.course_key.to_deprecated_string(),
                quote_slashes(self.location.to_deprecated_string()),
545 546 547 548 549 550 551 552 553 554
                'xmodule_handler',
                'bad_dispatch',
            )

    def test_missing_handler(self):
        request = self.request_factory.post('dummy_url')
        request.user = self.mock_user
        with self.assertRaises(Http404):
            render.handle_xblock_callback(
                request,
555 556
                self.course_key.to_deprecated_string(),
                quote_slashes(self.location.to_deprecated_string()),
557 558 559 560
                'bad_handler',
                'bad_dispatch',
            )

561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
    @XBlock.register_temp_plugin(GradedStatelessXBlock, identifier='stateless_scorer')
    def test_score_without_student_state(self):
        course = CourseFactory.create()
        block = ItemFactory.create(category='stateless_scorer', parent=course)

        request = self.request_factory.post(
            'dummy_url',
            data=json.dumps({"grade": 0.75}),
            content_type='application/json'
        )
        request.user = self.mock_user

        response = render.handle_xblock_callback(
            request,
            unicode(course.id),
            quote_slashes(unicode(block.scope_ids.usage_id)),
            'set_score',
            '',
        )
        self.assertEquals(response.status_code, 200)
        student_module = StudentModule.objects.get(
            student=self.mock_user,
            module_state_key=block.scope_ids.usage_id,
        )
        self.assertEquals(student_module.grade, 0.75)
        self.assertEquals(student_module.max_grade, 1)

588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
    @patch.dict('django.conf.settings.FEATURES', {'ENABLE_XBLOCK_VIEW_ENDPOINT': True})
    def test_xblock_view_handler(self):
        args = [
            'edX/toy/2012_Fall',
            quote_slashes('i4x://edX/toy/videosequence/Toy_Videos'),
            'student_view'
        ]
        xblock_view_url = reverse(
            'xblock_view',
            args=args
        )

        request = self.request_factory.get(xblock_view_url)
        request.user = self.mock_user
        response = render.xblock_view(request, *args)
        self.assertEquals(200, response.status_code)

        expected = ['csrf_token', 'html', 'resources']
        content = json.loads(response.content)
        for section in expected:
            self.assertIn(section, content)
609
        doc = PyQuery(content['html'])
610
        self.assertEquals(len(doc('div.xblock-student_view-videosequence')), 1)
611

612

613
@attr(shard=1)
614
@ddt.ddt
615
class TestTOC(ModuleStoreTestCase):
Jay Zoldak committed
616
    """Check the Table of Contents for a course"""
617 618 619 620 621
    def setup_request_and_course(self, num_finds, num_sends):
        """
        Sets up the toy course in the modulestore and the request object.
        """
        self.course_key = ToyCourseFactory.create().id  # pylint: disable=attribute-defined-outside-init
622 623
        self.chapter = 'Overview'
        chapter_url = '%s/%s/%s' % ('/courses', self.course_key, self.chapter)
Jay Zoldak committed
624
        factory = RequestFactory()
625 626
        self.request = factory.get(chapter_url)
        self.request.user = UserFactory()
627
        self.modulestore = self.store._get_modulestore_for_courselike(self.course_key)  # pylint: disable=protected-access, attribute-defined-outside-init
628 629
        with self.modulestore.bulk_operations(self.course_key):
            with check_mongo_calls(num_finds, num_sends):
630
                self.toy_course = self.store.get_course(self.course_key, depth=2)  # pylint: disable=attribute-defined-outside-init
631
                self.field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
632
                    self.course_key, self.request.user, self.toy_course, depth=2
633
                )
634

635 636 637 638 639 640 641
    # Mongo makes 3 queries to load the course to depth 2:
    #     - 1 for the course
    #     - 1 for its children
    #     - 1 for its grandchildren
    # Split makes 6 queries to load the course to depth 2:
    #     - load the structure
    #     - load 5 definitions
642
    # Split makes 5 queries to render the toc:
643
    #     - it loads the active version at the start of the bulk operation
644
    #     - it loads 4 definitions, because it instantiates 4 VideoModules
645
    #       each of which access a Scope.content field in __init__
646
    @ddt.data((ModuleStoreEnum.Type.mongo, 3, 0, 0), (ModuleStoreEnum.Type.split, 6, 0, 5))
647
    @ddt.unpack
648
    def test_toc_toy_from_chapter(self, default_ms, setup_finds, setup_sends, toc_finds):
649
        with self.store.default_store(default_ms):
650
            self.setup_request_and_course(setup_finds, setup_sends)
651

652 653 654 655 656 657 658 659 660
            expected = ([{'active': True, 'sections':
                          [{'url_name': 'Toy_Videos', 'display_name': u'Toy Videos', 'graded': True,
                            'format': u'Lecture Sequence', 'due': None, 'active': False},
                           {'url_name': 'Welcome', 'display_name': u'Welcome', 'graded': True,
                            'format': '', 'due': None, 'active': False},
                           {'url_name': 'video_123456789012', 'display_name': 'Test Video', 'graded': True,
                            'format': '', 'due': None, 'active': False},
                           {'url_name': 'video_4f66f493ac8f', 'display_name': 'Video', 'graded': True,
                            'format': '', 'due': None, 'active': False}],
661
                          'url_name': 'Overview', 'display_name': u'Overview', 'display_id': u'overview'},
662 663 664
                         {'active': False, 'sections':
                          [{'url_name': 'toyvideo', 'display_name': 'toyvideo', 'graded': True,
                            'format': '', 'due': None, 'active': False}],
665
                          'url_name': 'secret:magic', 'display_name': 'secret:magic', 'display_id': 'secretmagic'}])
666

667
            course = self.store.get_course(self.toy_course.id, depth=2)
668
            with check_mongo_calls(toc_finds):
669
                actual = render.toc_for_course(
670
                    self.request.user, self.request, course, self.chapter, None, self.field_data_cache
671
                )
672
        for toc_section in expected:
673 674 675
            self.assertIn(toc_section, actual['chapters'])
        self.assertIsNone(actual['previous_of_active_section'])
        self.assertIsNone(actual['next_of_active_section'])
Jay Zoldak committed
676

677 678 679 680 681 682 683
    # Mongo makes 3 queries to load the course to depth 2:
    #     - 1 for the course
    #     - 1 for its children
    #     - 1 for its grandchildren
    # Split makes 6 queries to load the course to depth 2:
    #     - load the structure
    #     - load 5 definitions
684
    # Split makes 5 queries to render the toc:
685
    #     - it loads the active version at the start of the bulk operation
686
    #     - it loads 4 definitions, because it instantiates 4 VideoModules
687
    #       each of which access a Scope.content field in __init__
688
    @ddt.data((ModuleStoreEnum.Type.mongo, 3, 0, 0), (ModuleStoreEnum.Type.split, 6, 0, 5))
689
    @ddt.unpack
690
    def test_toc_toy_from_section(self, default_ms, setup_finds, setup_sends, toc_finds):
691
        with self.store.default_store(default_ms):
692
            self.setup_request_and_course(setup_finds, setup_sends)
693 694 695 696 697 698 699 700 701 702
            section = 'Welcome'
            expected = ([{'active': True, 'sections':
                          [{'url_name': 'Toy_Videos', 'display_name': u'Toy Videos', 'graded': True,
                            'format': u'Lecture Sequence', 'due': None, 'active': False},
                           {'url_name': 'Welcome', 'display_name': u'Welcome', 'graded': True,
                            'format': '', 'due': None, 'active': True},
                           {'url_name': 'video_123456789012', 'display_name': 'Test Video', 'graded': True,
                            'format': '', 'due': None, 'active': False},
                           {'url_name': 'video_4f66f493ac8f', 'display_name': 'Video', 'graded': True,
                            'format': '', 'due': None, 'active': False}],
703
                          'url_name': 'Overview', 'display_name': u'Overview', 'display_id': u'overview'},
704 705 706
                         {'active': False, 'sections':
                          [{'url_name': 'toyvideo', 'display_name': 'toyvideo', 'graded': True,
                            'format': '', 'due': None, 'active': False}],
707
                          'url_name': 'secret:magic', 'display_name': 'secret:magic', 'display_id': 'secretmagic'}])
708

709
            with check_mongo_calls(toc_finds):
710
                actual = render.toc_for_course(
711
                    self.request.user, self.request, self.toy_course, self.chapter, section, self.field_data_cache
712
                )
713
            for toc_section in expected:
714 715 716
                self.assertIn(toc_section, actual['chapters'])
            self.assertEquals(actual['previous_of_active_section']['url_name'], 'Toy_Videos')
            self.assertEquals(actual['next_of_active_section']['url_name'], 'video_123456789012')
717 718


719
@attr(shard=1)
720
@ddt.ddt
721
@patch.dict('django.conf.settings.FEATURES', {'ENABLE_SPECIAL_EXAMS': True})
722 723 724 725 726 727
class TestProctoringRendering(SharedModuleStoreTestCase):
    @classmethod
    def setUpClass(cls):
        super(TestProctoringRendering, cls).setUpClass()
        cls.course_key = ToyCourseFactory.create().id

728 729 730 731 732 733 734 735 736 737
    """Check the Table of Contents for a course"""
    def setUp(self):
        """
        Set up the initial mongo datastores
        """
        super(TestProctoringRendering, self).setUp()
        self.chapter = 'Overview'
        chapter_url = '%s/%s/%s' % ('/courses', self.course_key, self.chapter)
        factory = RequestFactory()
        self.request = factory.get(chapter_url)
738 739
        self.request.user = UserFactory.create()
        self.user = UserFactory.create()
740
        SoftwareSecurePhotoVerificationFactory.create(user=self.request.user)
741
        self.modulestore = self.store._get_modulestore_for_courselike(self.course_key)  # pylint: disable=protected-access
742
        with self.modulestore.bulk_operations(self.course_key):
743
            self.toy_course = self.store.get_course(self.course_key, depth=2)
744
            self.field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
745
                self.course_key, self.request.user, self.toy_course, depth=2
746 747 748
            )

    @ddt.data(
749
        (CourseMode.DEFAULT_MODE_SLUG, False, None, None),
750
        (
751
            CourseMode.DEFAULT_MODE_SLUG,
752 753 754 755 756
            True,
            'eligible',
            {
                'status': 'eligible',
                'short_description': 'Ungraded Practice Exam',
757
                'suggested_icon': '',
758 759 760 761
                'in_completed_state': False
            }
        ),
        (
762
            CourseMode.DEFAULT_MODE_SLUG,
763 764 765 766 767 768 769 770 771 772
            True,
            'submitted',
            {
                'status': 'submitted',
                'short_description': 'Practice Exam Completed',
                'suggested_icon': 'fa-check',
                'in_completed_state': True
            }
        ),
        (
773
            CourseMode.DEFAULT_MODE_SLUG,
774 775 776 777 778 779 780 781 782 783
            True,
            'error',
            {
                'status': 'error',
                'short_description': 'Practice Exam Failed',
                'suggested_icon': 'fa-exclamation-triangle',
                'in_completed_state': True
            }
        ),
        (
784
            CourseMode.VERIFIED,
785 786 787 788 789
            False,
            None,
            {
                'status': 'eligible',
                'short_description': 'Proctored Option Available',
790
                'suggested_icon': 'fa-pencil-square-o',
791 792 793 794
                'in_completed_state': False
            }
        ),
        (
795
            CourseMode.VERIFIED,
796 797 798 799 800
            False,
            'declined',
            {
                'status': 'declined',
                'short_description': 'Taking As Open Exam',
801
                'suggested_icon': 'fa-pencil-square-o',
802 803 804 805
                'in_completed_state': False
            }
        ),
        (
806
            CourseMode.VERIFIED,
807 808 809 810 811 812 813 814 815 816
            False,
            'submitted',
            {
                'status': 'submitted',
                'short_description': 'Pending Session Review',
                'suggested_icon': 'fa-spinner fa-spin',
                'in_completed_state': True
            }
        ),
        (
817
            CourseMode.VERIFIED,
818 819 820 821 822 823 824 825 826 827
            False,
            'verified',
            {
                'status': 'verified',
                'short_description': 'Passed Proctoring',
                'suggested_icon': 'fa-check',
                'in_completed_state': True
            }
        ),
        (
828
            CourseMode.VERIFIED,
829 830 831 832 833 834 835 836 837 838
            False,
            'rejected',
            {
                'status': 'rejected',
                'short_description': 'Failed Proctoring',
                'suggested_icon': 'fa-exclamation-triangle',
                'in_completed_state': True
            }
        ),
        (
839
            CourseMode.VERIFIED,
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
            False,
            'error',
            {
                'status': 'error',
                'short_description': 'Failed Proctoring',
                'suggested_icon': 'fa-exclamation-triangle',
                'in_completed_state': True
            }
        ),
    )
    @ddt.unpack
    def test_proctored_exam_toc(self, enrollment_mode, is_practice_exam,
                                attempt_status, expected):
        """
        Generate TOC for a course with a single chapter/sequence which contains proctored exam
        """
        self._setup_test_data(enrollment_mode, is_practice_exam, attempt_status)

858
        actual = render.toc_for_course(
859 860 861 862 863 864 865
            self.request.user,
            self.request,
            self.toy_course,
            self.chapter,
            'Toy_Videos',
            self.field_data_cache
        )
866
        section_actual = self._find_section(actual['chapters'], 'Overview', 'Toy_Videos')
867 868 869 870 871 872

        if expected:
            self.assertIn(expected, [section_actual['proctoring']])
        else:
            # we expect there not to be a 'proctoring' key in the dict
            self.assertNotIn('proctoring', section_actual)
873 874
        self.assertIsNone(actual['previous_of_active_section'])
        self.assertEquals(actual['next_of_active_section']['url_name'], u"Welcome")
875 876 877

    @ddt.data(
        (
878
            CourseMode.DEFAULT_MODE_SLUG,
879 880
            True,
            None,
881
            'Try a proctored exam',
882 883 884
            True
        ),
        (
885
            CourseMode.DEFAULT_MODE_SLUG,
886 887 888 889 890 891
            True,
            'submitted',
            'You have submitted this practice proctored exam',
            False
        ),
        (
892
            CourseMode.DEFAULT_MODE_SLUG,
893 894 895 896 897 898
            True,
            'error',
            'There was a problem with your practice proctoring session',
            True
        ),
        (
899
            CourseMode.VERIFIED,
900 901
            False,
            None,
902
            'This exam is proctored',
903 904 905
            False
        ),
        (
906
            CourseMode.VERIFIED,
907 908 909 910 911 912
            False,
            'submitted',
            'You have submitted this proctored exam for review',
            True
        ),
        (
913
            CourseMode.VERIFIED,
914 915 916 917 918 919
            False,
            'verified',
            'Your proctoring session was reviewed and passed all requirements',
            False
        ),
        (
920
            CourseMode.VERIFIED,
921 922 923 924 925 926
            False,
            'rejected',
            'Your proctoring session was reviewed and did not pass requirements',
            True
        ),
        (
927
            CourseMode.VERIFIED,
928 929
            False,
            'error',
930
            'A technical error has occurred with your proctored exam',
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
            False
        ),
    )
    @ddt.unpack
    def test_render_proctored_exam(self, enrollment_mode, is_practice_exam,
                                   attempt_status, expected, with_credit_context):
        """
        Verifies gated content from the student view rendering of a sequence
        this is labeled as a proctored exam
        """
        usage_key = self._setup_test_data(enrollment_mode, is_practice_exam, attempt_status)

        # initialize some credit requirements, if so then specify
        if with_credit_context:
            credit_course = CreditCourse(course_key=self.course_key, enabled=True)
            credit_course.save()
            set_credit_requirements(
                self.course_key,
                [
                    {
                        'namespace': 'reverification',
                        'name': 'reverification-1',
                        'display_name': 'ICRV1',
                        'criteria': {},
                    },
                    {
                        'namespace': 'proctored-exam',
                        'name': 'Exam1',
                        'display_name': 'A Proctored Exam',
                        'criteria': {}
                    }
                ]
            )

            set_credit_requirement_status(
966
                self.request.user,
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
                self.course_key,
                'reverification',
                'ICRV1'
            )

        module = render.get_module(
            self.request.user,
            self.request,
            usage_key,
            self.field_data_cache,
            wrap_xmodule_display=True,
        )
        content = module.render(STUDENT_VIEW).content

        self.assertIn(expected, content)

    def _setup_test_data(self, enrollment_mode, is_practice_exam, attempt_status):
        """
        Helper method to consolidate some courseware/proctoring/credit
        test harness data
        """
        usage_key = self.course_key.make_usage_key('videosequence', 'Toy_Videos')
        sequence = self.modulestore.get_item(usage_key)

        sequence.is_time_limited = True
992
        sequence.is_proctored_exam = True
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
        sequence.is_practice_exam = is_practice_exam

        self.modulestore.update_item(sequence, self.user.id)

        self.toy_course = self.modulestore.get_course(self.course_key)

        # refresh cache after update
        self.field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
            self.course_key, self.request.user, self.toy_course, depth=2
        )

        set_runtime_service(
            'credit',
            MockCreditService(enrollment_mode=enrollment_mode)
        )

        exam_id = create_exam(
            course_id=unicode(self.course_key),
            content_id=unicode(sequence.location),
            exam_name='foo',
            time_limit_mins=10,
            is_proctored=True,
            is_practice_exam=is_practice_exam
        )

        if attempt_status:
            create_exam_attempt(exam_id, self.request.user.id, taking_as_proctored=True)
            update_attempt_status(exam_id, self.request.user.id, attempt_status)
1021

1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
        return usage_key

    def _find_url_name(self, toc, url_name):
        """
        Helper to return the dict TOC section associated with a Chapter of url_name
        """

        for entry in toc:
            if entry['url_name'] == url_name:
                return entry

        return None

    def _find_section(self, toc, chapter_url_name, section_url_name):
        """
        Helper to return the dict TOC section associated with a section of url_name
        """

        chapter = self._find_url_name(toc, chapter_url_name)
        if chapter:
            return self._find_url_name(chapter['sections'], section_url_name)

        return None


1047
@attr(shard=1)
1048 1049 1050 1051 1052 1053 1054 1055 1056
class TestGatedSubsectionRendering(SharedModuleStoreTestCase, MilestonesTestCaseMixin):
    @classmethod
    def setUpClass(cls):
        super(TestGatedSubsectionRendering, cls).setUpClass()
        cls.course = CourseFactory.create()
        cls.course.enable_subsection_gating = True
        cls.course.save()
        cls.store.update_item(cls.course, 0)

1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
    """
    Test the toc for a course is rendered correctly when there is gated content
    """
    def setUp(self):
        """
        Set up the initial test data
        """
        super(TestGatedSubsectionRendering, self).setUp()

        self.chapter = ItemFactory.create(
            parent=self.course,
            category="chapter",
            display_name="Chapter"
        )
        self.open_seq = ItemFactory.create(
            parent=self.chapter,
            category='sequential',
            display_name="Open Sequential"
        )
        self.gated_seq = ItemFactory.create(
            parent=self.chapter,
            category='sequential',
            display_name="Gated Sequential"
        )
        self.request = RequestFactory().get('%s/%s/%s' % ('/courses', self.course.id, self.chapter.display_name))
        self.request.user = UserFactory()
        self.field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
            self.course.id, self.request.user, self.course, depth=2
        )
        gating_api.add_prerequisite(self.course.id, self.open_seq.location)
        gating_api.set_required_content(self.course.id, self.gated_seq.location, self.open_seq.location, 100)

    def _find_url_name(self, toc, url_name):
        """
        Helper to return the TOC section associated with url_name
        """

        for entry in toc:
            if entry['url_name'] == url_name:
                return entry

        return None

    def _find_sequential(self, toc, chapter_url_name, sequential_url_name):
        """
        Helper to return the sequential associated with sequential_url_name
        """

        chapter = self._find_url_name(toc, chapter_url_name)
        if chapter:
            return self._find_url_name(chapter['sections'], sequential_url_name)

        return None

    def test_toc_with_gated_sequential(self):
        """
        Test generation of TOC for a course with a gated subsection
        """
1115
        actual = render.toc_for_course(
1116 1117 1118 1119 1120 1121 1122
            self.request.user,
            self.request,
            self.course,
            self.chapter.display_name,
            self.open_seq.display_name,
            self.field_data_cache
        )
1123 1124 1125 1126 1127
        self.assertIsNotNone(self._find_sequential(actual['chapters'], 'Chapter', 'Open_Sequential'))
        self.assertIsNone(self._find_sequential(actual['chapters'], 'Chapter', 'Gated_Sequential'))
        self.assertIsNone(self._find_sequential(actual['chapters'], 'Non-existent_Chapter', 'Non-existent_Sequential'))
        self.assertIsNone(actual['previous_of_active_section'])
        self.assertIsNone(actual['next_of_active_section'])
1128 1129


1130
@attr(shard=1)
1131
@ddt.ddt
1132 1133 1134 1135 1136 1137
class TestHtmlModifiers(ModuleStoreTestCase):
    """
    Tests to verify that standard modifications to the output of XModule/XBlock
    student_view are taking place
    """
    def setUp(self):
1138
        super(TestHtmlModifiers, self).setUp()
1139
        self.course = CourseFactory.create()
1140 1141 1142 1143 1144
        self.request = RequestFactory().get('/')
        self.request.user = self.user
        self.request.session = {}
        self.content_string = '<p>This is the content<p>'
        self.rewrite_link = '<a href="/static/foo/content">Test rewrite</a>'
1145
        self.rewrite_bad_link = '<img src="/static//file.jpg" />'
1146 1147 1148
        self.course_link = '<a href="/course/bar/content">Test course rewrite</a>'
        self.descriptor = ItemFactory.create(
            category='html',
1149
            data=self.content_string + self.rewrite_link + self.rewrite_bad_link + self.course_link
1150 1151
        )
        self.location = self.descriptor.location
Calen Pennington committed
1152
        self.field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
            self.course.id,
            self.user,
            self.descriptor
        )

    def test_xmodule_display_wrapper_enabled(self):
        module = render.get_module(
            self.user,
            self.request,
            self.location,
Calen Pennington committed
1163
            self.field_data_cache,
1164 1165
            wrap_xmodule_display=True,
        )
1166
        result_fragment = module.render(STUDENT_VIEW)
1167

1168
        self.assertEquals(len(PyQuery(result_fragment.content)('div.xblock.xblock-student_view.xmodule_HtmlModule')), 1)
1169 1170 1171 1172 1173 1174

    def test_xmodule_display_wrapper_disabled(self):
        module = render.get_module(
            self.user,
            self.request,
            self.location,
Calen Pennington committed
1175
            self.field_data_cache,
1176 1177
            wrap_xmodule_display=False,
        )
1178
        result_fragment = module.render(STUDENT_VIEW)
1179

1180
        self.assertNotIn('div class="xblock xblock-student_view xmodule_display xmodule_HtmlModule"', result_fragment.content)
1181 1182 1183 1184 1185 1186

    def test_static_link_rewrite(self):
        module = render.get_module(
            self.user,
            self.request,
            self.location,
Calen Pennington committed
1187
            self.field_data_cache,
1188
        )
1189
        result_fragment = module.render(STUDENT_VIEW)
1190 1191 1192 1193 1194 1195 1196 1197 1198

        self.assertIn(
            '/c4x/{org}/{course}/asset/foo_content'.format(
                org=self.course.location.org,
                course=self.course.location.course,
            ),
            result_fragment.content
        )

1199 1200 1201 1202 1203
    def test_static_badlink_rewrite(self):
        module = render.get_module(
            self.user,
            self.request,
            self.location,
Calen Pennington committed
1204
            self.field_data_cache,
1205
        )
1206
        result_fragment = module.render(STUDENT_VIEW)
1207 1208

        self.assertIn(
1209
            '/c4x/{org}/{course}/asset/file.jpg'.format(
1210 1211
                org=self.course.location.org,
                course=self.course.location.course,
1212 1213 1214 1215
            ),
            result_fragment.content
        )

1216 1217
    def test_static_asset_path_use(self):
        '''
1218
        when a course is loaded with do_import_static=False (see xml_importer.py), then
1219 1220 1221 1222 1223 1224 1225
        static_asset_path is set as an lms kv in course.  That should make static paths
        not be mangled (ie not changed to c4x://).
        '''
        module = render.get_module(
            self.user,
            self.request,
            self.location,
Calen Pennington committed
1226
            self.field_data_cache,
1227 1228
            static_asset_path="toy_course_dir",
        )
1229
        result_fragment = module.render(STUDENT_VIEW)
1230 1231 1232 1233 1234 1235
        self.assertIn('href="/static/toy_course_dir', result_fragment.content)

    def test_course_image(self):
        url = course_image_url(self.course)
        self.assertTrue(url.startswith('/c4x/'))

Calen Pennington committed
1236
        self.course.static_asset_path = "toy_course_dir"
1237 1238
        url = course_image_url(self.course)
        self.assertTrue(url.startswith('/static/toy_course_dir/'))
Calen Pennington committed
1239
        self.course.static_asset_path = ""
1240

1241 1242
    @override_settings(DEFAULT_COURSE_ABOUT_IMAGE_URL='test.png')
    @override_settings(STATIC_URL='static/')
1243 1244 1245
    @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
    def test_course_image_for_split_course(self, store):
        """
1246 1247
        for split courses if course_image is empty then course_image_url will be
        the default image url defined in settings
1248 1249 1250 1251 1252
        """
        self.course = CourseFactory.create(default_store=store)
        self.course.course_image = ''

        url = course_image_url(self.course)
1253
        self.assertEqual('static/test.png', url)
1254

1255
    def test_get_course_info_section(self):
Calen Pennington committed
1256
        self.course.static_asset_path = "toy_course_dir"
1257
        get_course_info_section(self.request, self.request.user, self.course, "handouts")
Chris Dodge committed
1258
        # NOTE: check handouts output...right now test course seems to have no such content
1259 1260
        # at least this makes sure get_course_info_section returns without exception

1261 1262 1263 1264 1265
    def test_course_link_rewrite(self):
        module = render.get_module(
            self.user,
            self.request,
            self.location,
Calen Pennington committed
1266
            self.field_data_cache,
1267
        )
1268
        result_fragment = module.render(STUDENT_VIEW)
1269 1270 1271

        self.assertIn(
            '/courses/{course_id}/bar/content'.format(
1272
                course_id=self.course.id.to_deprecated_string()
1273 1274 1275 1276
            ),
            result_fragment.content
        )

1277

1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
class XBlockWithJsonInitData(XBlock):
    """
    Pure XBlock to use in tests, with JSON init data.
    """
    the_json_data = None

    def student_view(self, context=None):       # pylint: disable=unused-argument
        """
        A simple view that returns just enough to test.
        """
        frag = Fragment(u"Hello there!")
        frag.add_javascript(u'alert("Hi!");')
        frag.initialize_js('ThumbsBlock', self.the_json_data)
        return frag


1294
@attr(shard=1)
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
@ddt.ddt
class JsonInitDataTest(ModuleStoreTestCase):
    """Tests for JSON data injected into the JS init function."""

    @ddt.data(
        ({'a': 17}, '''{"a": 17}'''),
        ({'xss': '</script>alert("XSS")'}, r'''{"xss": "<\/script>alert(\"XSS\")"}'''),
    )
    @ddt.unpack
    @XBlock.register_temp_plugin(XBlockWithJsonInitData, identifier='withjson')
    def test_json_init_data(self, json_data, json_output):
        XBlockWithJsonInitData.the_json_data = json_data
        mock_user = UserFactory()
        mock_request = MagicMock()
        mock_request.user = mock_user
        course = CourseFactory()
        descriptor = ItemFactory(category='withjson', parent=course)
        field_data_cache = FieldDataCache([course, descriptor], course.id, mock_user)   # pylint: disable=no-member
        module = render.get_module_for_descriptor(
            mock_user,
            mock_request,
            descriptor,
            field_data_cache,
            course.id,                          # pylint: disable=no-member
1319
            course=course
1320 1321 1322 1323 1324 1325 1326
        )
        html = module.render(STUDENT_VIEW).content
        self.assertIn(json_output, html)
        # No matter what data goes in, there should only be one close-script tag.
        self.assertEqual(html.count("</script>"), 1)


1327 1328 1329 1330 1331
class ViewInStudioTest(ModuleStoreTestCase):
    """Tests for the 'View in Studio' link visiblity."""

    def setUp(self):
        """ Set up the user and request that will be used. """
1332
        super(ViewInStudioTest, self).setUp()
1333 1334 1335 1336 1337
        self.staff_user = GlobalStaffFactory.create()
        self.request = RequestFactory().get('/')
        self.request.user = self.staff_user
        self.request.session = {}
        self.module = None
1338
        self.default_context = {'bookmarked': False, 'username': self.user.username}
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349

    def _get_module(self, course_id, descriptor, location):
        """
        Get the module from the course from which to pattern match (or not) the 'View in Studio' buttons
        """
        field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
            course_id,
            self.staff_user,
            descriptor
        )

1350
        return render.get_module(
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
            self.staff_user,
            self.request,
            location,
            field_data_cache,
        )

    def setup_mongo_course(self, course_edit_method='Studio'):
        """ Create a mongo backed course. """
        course = CourseFactory.create(
            course_edit_method=course_edit_method
        )

        descriptor = ItemFactory.create(
            category='vertical',
Don Mitchell committed
1365
            parent_location=course.location,
1366 1367
        )

1368 1369
        child_descriptor = ItemFactory.create(
            category='vertical',
cahrens committed
1370
            parent_location=descriptor.location
1371 1372 1373 1374
        )

        self.module = self._get_module(course.id, descriptor, descriptor.location)

1375
        # pylint: disable=attribute-defined-outside-init
1376
        self.child_module = self._get_module(course.id, child_descriptor, child_descriptor.location)
1377 1378


1379
@attr(shard=1)
1380 1381 1382 1383 1384 1385
class MongoViewInStudioTest(ViewInStudioTest):
    """Test the 'View in Studio' link visibility in a mongo backed course."""

    def test_view_in_studio_link_studio_course(self):
        """Regular Studio courses should see 'View in Studio' links."""
        self.setup_mongo_course()
1386
        result_fragment = self.module.render(STUDENT_VIEW, context=self.default_context)
1387 1388
        self.assertIn('View Unit in Studio', result_fragment.content)

1389 1390 1391 1392
    def test_view_in_studio_link_only_in_top_level_vertical(self):
        """Regular Studio courses should not see 'View in Studio' for child verticals of verticals."""
        self.setup_mongo_course()
        # Render the parent vertical, then check that there is only a single "View Unit in Studio" link.
1393
        result_fragment = self.module.render(STUDENT_VIEW, context=self.default_context)
1394
        # The single "View Unit in Studio" link should appear before the first xmodule vertical definition.
1395 1396
        parts = result_fragment.content.split('data-block-type="vertical"')
        self.assertEqual(3, len(parts), "Did not find two vertical blocks")
1397 1398 1399 1400
        self.assertIn('View Unit in Studio', parts[0])
        self.assertNotIn('View Unit in Studio', parts[1])
        self.assertNotIn('View Unit in Studio', parts[2])

1401 1402 1403
    def test_view_in_studio_link_xml_authored(self):
        """Courses that change 'course_edit_method' setting can hide 'View in Studio' links."""
        self.setup_mongo_course(course_edit_method='XML')
1404
        result_fragment = self.module.render(STUDENT_VIEW, context=self.default_context)
1405 1406 1407
        self.assertNotIn('View Unit in Studio', result_fragment.content)


1408
@attr(shard=1)
1409 1410 1411
class MixedViewInStudioTest(ViewInStudioTest):
    """Test the 'View in Studio' link visibility in a mixed mongo backed course."""

1412
    MODULESTORE = TEST_DATA_MIXED_MODULESTORE
1413 1414 1415 1416

    def test_view_in_studio_link_mongo_backed(self):
        """Mixed mongo courses that are mongo backed should see 'View in Studio' links."""
        self.setup_mongo_course()
1417
        result_fragment = self.module.render(STUDENT_VIEW, context=self.default_context)
1418 1419 1420 1421 1422
        self.assertIn('View Unit in Studio', result_fragment.content)

    def test_view_in_studio_link_xml_authored(self):
        """Courses that change 'course_edit_method' setting can hide 'View in Studio' links."""
        self.setup_mongo_course(course_edit_method='XML')
1423
        result_fragment = self.module.render(STUDENT_VIEW, context=self.default_context)
1424 1425 1426
        self.assertNotIn('View Unit in Studio', result_fragment.content)


1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
@XBlock.tag("detached")
class DetachedXBlock(XBlock):
    """
    XBlock marked with the 'detached' flag.
    """
    def student_view(self, context=None):  # pylint: disable=unused-argument
        """
        A simple view that returns just enough to test.
        """
        frag = Fragment(u"Hello there!")
        return frag


1440
@attr(shard=1)
1441
@patch.dict('django.conf.settings.FEATURES', {'DISPLAY_DEBUG_INFO_TO_STAFF': True, 'DISPLAY_HISTOGRAMS_TO_STAFF': True})
1442
@patch('courseware.module_render.has_access', Mock(return_value=True, autospec=True))
1443
class TestStaffDebugInfo(SharedModuleStoreTestCase):
1444 1445
    """Tests to verify that Staff Debug Info panel and histograms are displayed to staff."""

1446 1447 1448 1449 1450
    @classmethod
    def setUpClass(cls):
        super(TestStaffDebugInfo, cls).setUpClass()
        cls.course = CourseFactory.create()

1451
    def setUp(self):
1452
        super(TestStaffDebugInfo, self).setUp()
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
        self.user = UserFactory.create()
        self.request = RequestFactory().get('/')
        self.request.user = self.user
        self.request.session = {}

        problem_xml = OptionResponseXMLFactory().build_xml(
            question_text='The correct answer is Correct',
            num_inputs=2,
            weight=2,
            options=['Correct', 'Incorrect'],
            correct_option='Correct'
        )
        self.descriptor = ItemFactory.create(
            category='problem',
            data=problem_xml,
            display_name='Option Response Problem'
        )

        self.location = self.descriptor.location
        self.field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
            self.course.id,
            self.user,
            self.descriptor
        )

    @patch.dict('django.conf.settings.FEATURES', {'DISPLAY_DEBUG_INFO_TO_STAFF': False})
    def test_staff_debug_info_disabled(self):
1480 1481 1482 1483
        module = render.get_module(
            self.user,
            self.request,
            self.location,
Calen Pennington committed
1484
            self.field_data_cache,
1485
        )
1486
        result_fragment = module.render(STUDENT_VIEW)
1487
        self.assertNotIn('Staff Debug', result_fragment.content)
1488

1489 1490 1491 1492 1493 1494
    def test_staff_debug_info_enabled(self):
        module = render.get_module(
            self.user,
            self.request,
            self.location,
            self.field_data_cache,
1495
        )
1496
        result_fragment = module.render(STUDENT_VIEW)
1497 1498
        self.assertIn('Staff Debug', result_fragment.content)

1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
    @XBlock.register_temp_plugin(DetachedXBlock, identifier='detached-block')
    def test_staff_debug_info_disabled_for_detached_blocks(self):
        """Staff markup should not be present on detached blocks."""

        descriptor = ItemFactory.create(
            category='detached-block',
            display_name='Detached Block'
        )
        field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
            self.course.id,
            self.user,
            descriptor
        )
        module = render.get_module(
            self.user,
            self.request,
            descriptor.location,
            field_data_cache,
        )
        result_fragment = module.render(STUDENT_VIEW)
        self.assertNotIn('Staff Debug', result_fragment.content)

1521 1522 1523 1524 1525 1526 1527 1528
    @patch.dict('django.conf.settings.FEATURES', {'DISPLAY_HISTOGRAMS_TO_STAFF': False})
    def test_histogram_disabled(self):
        module = render.get_module(
            self.user,
            self.request,
            self.location,
            self.field_data_cache,
        )
1529
        result_fragment = module.render(STUDENT_VIEW)
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
        self.assertNotIn('histrogram', result_fragment.content)

    def test_histogram_enabled_for_unscored_xmodules(self):
        """Histograms should not display for xmodules which are not scored."""

        html_descriptor = ItemFactory.create(
            category='html',
            data='Here are some course details.'
        )
        field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
            self.course.id,
            self.user,
            self.descriptor
        )
1544
        with patch('openedx.core.lib.xblock_utils.grade_histogram') as mock_grade_histogram:
1545 1546 1547 1548 1549 1550 1551
            mock_grade_histogram.return_value = []
            module = render.get_module(
                self.user,
                self.request,
                html_descriptor.location,
                field_data_cache,
            )
1552
            module.render(STUDENT_VIEW)
1553 1554 1555 1556 1557 1558 1559
            self.assertFalse(mock_grade_histogram.called)

    def test_histogram_enabled_for_scored_xmodules(self):
        """Histograms should display for xmodules which are scored."""

        StudentModuleFactory.create(
            course_id=self.course.id,
1560
            module_state_key=self.location,
1561 1562 1563 1564 1565
            student=UserFactory(),
            grade=1,
            max_grade=1,
            state="{}",
        )
1566
        with patch('openedx.core.lib.xblock_utils.grade_histogram') as mock_grade_histogram:
1567 1568 1569 1570 1571 1572 1573
            mock_grade_histogram.return_value = []
            module = render.get_module(
                self.user,
                self.request,
                self.location,
                self.field_data_cache,
            )
1574
            module.render(STUDENT_VIEW)
1575 1576
            self.assertTrue(mock_grade_histogram.called)

1577

1578
PER_COURSE_ANONYMIZED_DESCRIPTORS = (LTIDescriptor, )
1579

1580 1581
# The "set" here is to work around the bug that load_classes returns duplicates for multiply-delcared classes.
PER_STUDENT_ANONYMIZED_DESCRIPTORS = set(
1582 1583
    class_ for (name, class_) in XModuleDescriptor.load_classes()
    if not issubclass(class_, PER_COURSE_ANONYMIZED_DESCRIPTORS)
1584
)
1585 1586


1587
@attr(shard=1)
1588
@ddt.ddt
1589
class TestAnonymousStudentId(SharedModuleStoreTestCase, LoginEnrollmentTestCase):
1590 1591 1592 1593
    """
    Test that anonymous_student_id is set correctly across a variety of XBlock types
    """

1594 1595 1596 1597 1598 1599
    @classmethod
    def setUpClass(cls):
        super(TestAnonymousStudentId, cls).setUpClass()
        cls.course_key = ToyCourseFactory.create().id
        cls.course = modulestore().get_course(cls.course_key)

1600
    def setUp(self):
1601
        super(TestAnonymousStudentId, self).setUp()
1602 1603
        self.user = UserFactory()

1604
    @patch('courseware.module_render.has_access', Mock(return_value=True, autospec=True))
1605
    def _get_anonymous_id(self, course_id, xblock_class):
1606
        location = course_id.make_usage_key('dummy_category', 'dummy_name')
1607 1608
        descriptor = Mock(
            spec=xblock_class,
1609
            _field_data=Mock(spec=FieldData, name='field_data'),
1610 1611
            location=location,
            static_asset_path=None,
1612
            _runtime=Mock(
1613
                spec=Runtime,
1614
                resources_fs=None,
1615 1616
                mixologist=Mock(_mixins=(), name='mixologist'),
                name='runtime',
1617 1618
            ),
            scope_ids=Mock(spec=ScopeIds),
1619 1620 1621 1622
            name='descriptor',
            _field_data_cache={},
            _dirty_fields={},
            fields={},
1623
            days_early_for_beta=None,
1624
        )
1625
        descriptor.runtime = CombinedSystem(descriptor._runtime, None)  # pylint: disable=protected-access
1626 1627 1628
        # Use the xblock_class's bind_for_student method
        descriptor.bind_for_student = partial(xblock_class.bind_for_student, descriptor)

1629 1630 1631 1632
        if hasattr(xblock_class, 'module_class'):
            descriptor.module_class = xblock_class.module_class

        return render.get_module_for_descriptor_internal(
1633 1634
            user=self.user,
            descriptor=descriptor,
1635
            student_data=Mock(spec=FieldData, name='student_data'),
1636
            course_id=course_id,
1637 1638
            track_function=Mock(name='track_function'),  # Track Function
            xqueue_callback_url_prefix=Mock(name='xqueue_callback_url_prefix'),  # XQueue Callback Url Prefix
1639
            request_token='request_token',
1640
            course=self.course,
1641 1642
        ).xmodule_runtime.anonymous_student_id

1643
    @ddt.data(*PER_STUDENT_ANONYMIZED_DESCRIPTORS)
1644 1645 1646 1647 1648 1649
    def test_per_student_anonymized_id(self, descriptor_class):
        for course_id in ('MITx/6.00x/2012_Fall', 'MITx/6.00x/2013_Spring'):
            self.assertEquals(
                # This value is set by observation, so that later changes to the student
                # id computation don't break old data
                '5afe5d9bb03796557ee2614f5c9611fb',
1650
                self._get_anonymous_id(CourseKey.from_string(course_id), descriptor_class)
1651 1652
            )

1653
    @ddt.data(*PER_COURSE_ANONYMIZED_DESCRIPTORS)
1654 1655 1656 1657 1658
    def test_per_course_anonymized_id(self, descriptor_class):
        self.assertEquals(
            # This value is set by observation, so that later changes to the student
            # id computation don't break old data
            'e3b0b940318df9c14be59acb08e78af5',
1659
            self._get_anonymous_id(SlashSeparatedCourseKey('MITx', '6.00x', '2012_Fall'), descriptor_class)
1660 1661 1662 1663 1664 1665
        )

        self.assertEquals(
            # This value is set by observation, so that later changes to the student
            # id computation don't break old data
            'f82b5416c9f54b5ce33989511bb5ef2e',
1666
            self._get_anonymous_id(SlashSeparatedCourseKey('MITx', '6.00x', '2013_Spring'), descriptor_class)
1667
        )
1668 1669


1670
@attr(shard=1)
1671
@patch('track.views.tracker', autospec=True)
1672
class TestModuleTrackingContext(SharedModuleStoreTestCase):
1673 1674 1675 1676
    """
    Ensure correct tracking information is included in events emitted during XBlock callback handling.
    """

1677 1678 1679 1680 1681
    @classmethod
    def setUpClass(cls):
        super(TestModuleTrackingContext, cls).setUpClass()
        cls.course = CourseFactory.create()

1682
    def setUp(self):
1683 1684
        super(TestModuleTrackingContext, self).setUp()

1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
        self.user = UserFactory.create()
        self.request = RequestFactory().get('/')
        self.request.user = self.user
        self.request.session = {}
        self.course = CourseFactory.create()

        self.problem_xml = OptionResponseXMLFactory().build_xml(
            question_text='The correct answer is Correct',
            num_inputs=2,
            weight=2,
            options=['Correct', 'Incorrect'],
            correct_option='Correct'
        )

    def test_context_contains_display_name(self, mock_tracker):
        problem_display_name = u'Option Response Problem'
Braden MacDonald committed
1701
        module_info = self.handle_callback_and_get_module_info(mock_tracker, problem_display_name)
1702
        self.assertEquals(problem_display_name, module_info['display_name'])
1703

1704 1705 1706 1707 1708 1709
    @XBlockAside.register_temp_plugin(AsideTestType, 'test_aside')
    @patch('xmodule.modulestore.mongo.base.CachingDescriptorSystem.applicable_aside_types',
           lambda self, block: ['test_aside'])
    @patch('lms.djangoapps.lms_xblock.runtime.LmsModuleSystem.applicable_aside_types',
           lambda self, block: ['test_aside'])
    def test_context_contains_aside_info(self, mock_tracker):
1710
        """
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
        Check that related xblock asides populate information in the 'problem_check' event in case
        the 'get_event_context' method is exist
        """
        problem_display_name = u'Test Problem'

        def get_event_context(self, event_type, event):  # pylint: disable=unused-argument
            """
            This method return data that should be associated with the "check_problem" event
            """
            return {'content': 'test1', 'data_field': 'test2'}

        AsideTestType.get_event_context = get_event_context
        context_info = self.handle_callback_and_get_context_info(mock_tracker, problem_display_name)
        self.assertIn('asides', context_info)
        self.assertIn('test_aside', context_info['asides'])
        self.assertIn('content', context_info['asides']['test_aside'])
        self.assertEquals(context_info['asides']['test_aside']['content'], 'test1')
        self.assertIn('data_field', context_info['asides']['test_aside'])
        self.assertEquals(context_info['asides']['test_aside']['data_field'], 'test2')

    def handle_callback_and_get_context_info(self, mock_tracker, problem_display_name=None):
        """
        Creates a fake module, invokes the callback and extracts the 'context'
1734
        metadata from the emitted problem_check event.
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
        """
        descriptor_kwargs = {
            'category': 'problem',
            'data': self.problem_xml
        }
        if problem_display_name:
            descriptor_kwargs['display_name'] = problem_display_name

        descriptor = ItemFactory.create(**descriptor_kwargs)

        render.handle_xblock_callback(
            self.request,
1747 1748
            self.course.id.to_deprecated_string(),
            quote_slashes(descriptor.location.to_deprecated_string()),
1749 1750 1751 1752 1753 1754 1755 1756 1757
            'xmodule_handler',
            'problem_check',
        )

        self.assertEquals(len(mock_tracker.send.mock_calls), 1)
        mock_call = mock_tracker.send.mock_calls[0]
        event = mock_call[1][0]

        self.assertEquals(event['event_type'], 'problem_check')
1758 1759 1760 1761 1762 1763 1764 1765 1766
        return event['context']

    def handle_callback_and_get_module_info(self, mock_tracker, problem_display_name=None):
        """
        Creates a fake module, invokes the callback and extracts the 'module'
        metadata from the emitted problem_check event.
        """
        event = self.handle_callback_and_get_context_info(mock_tracker, problem_display_name)
        return event['module']
1767 1768

    def test_missing_display_name(self, mock_tracker):
Braden MacDonald committed
1769
        actual_display_name = self.handle_callback_and_get_module_info(mock_tracker)['display_name']
1770
        self.assertTrue(actual_display_name.startswith('problem'))
1771

1772 1773 1774 1775 1776 1777 1778 1779
    def test_library_source_information(self, mock_tracker):
        """
        Check that XBlocks that are inherited from a library include the
        information about their library block source in events.
        We patch the modulestore to avoid having to create a library.
        """
        original_usage_key = UsageKey.from_string(u'block-v1:A+B+C+type@problem+block@abcd1234')
        original_usage_version = ObjectId()
Braden MacDonald committed
1780 1781 1782
        mock_get_original_usage = lambda _, key: (original_usage_key, original_usage_version)
        with patch('xmodule.modulestore.mixed.MixedModuleStore.get_block_original_usage', mock_get_original_usage):
            module_info = self.handle_callback_and_get_module_info(mock_tracker)
1783 1784 1785 1786 1787
            self.assertIn('original_usage_key', module_info)
            self.assertEqual(module_info['original_usage_key'], unicode(original_usage_key))
            self.assertIn('original_usage_version', module_info)
            self.assertEqual(module_info['original_usage_version'], unicode(original_usage_version))

1788

1789
@attr(shard=1)
1790 1791 1792 1793 1794 1795 1796 1797 1798
class TestXmoduleRuntimeEvent(TestSubmittingProblems):
    """
    Inherit from TestSubmittingProblems to get functionality that set up a course and problems structure
    """

    def setUp(self):
        super(TestXmoduleRuntimeEvent, self).setUp()
        self.homework = self.add_graded_section_to_course('homework')
        self.problem = self.add_dropdown_to_section(self.homework.location, 'p1', 1)
1799 1800
        self.grade_dict = {'value': 0.18, 'max_value': 32}
        self.delete_dict = {'value': None, 'max_value': None}
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811

    def get_module_for_user(self, user):
        """Helper function to get useful module at self.location in self.course_id for user"""
        mock_request = MagicMock()
        mock_request.user = user
        field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
            self.course.id, user, self.course, depth=2)

        return render.get_module(  # pylint: disable=protected-access
            user,
            mock_request,
1812
            self.problem.location,
1813
            field_data_cache,
1814
        )._xmodule
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824

    def set_module_grade_using_publish(self, grade_dict):
        """Publish the user's grade, takes grade_dict as input"""
        module = self.get_module_for_user(self.student_user)
        module.system.publish(module, 'grade', grade_dict)
        return module

    def test_xmodule_runtime_publish(self):
        """Tests the publish mechanism"""
        self.set_module_grade_using_publish(self.grade_dict)
1825
        student_module = StudentModule.objects.get(student=self.student_user, module_state_key=self.problem.location)
1826 1827 1828 1829 1830 1831 1832
        self.assertEqual(student_module.grade, self.grade_dict['value'])
        self.assertEqual(student_module.max_grade, self.grade_dict['max_value'])

    def test_xmodule_runtime_publish_delete(self):
        """Test deleting the grade using the publish mechanism"""
        module = self.set_module_grade_using_publish(self.grade_dict)
        module.system.publish(module, 'grade', self.delete_dict)
1833
        student_module = StudentModule.objects.get(student=self.student_user, module_state_key=self.problem.location)
1834 1835 1836
        self.assertIsNone(student_module.grade)
        self.assertIsNone(student_module.max_grade)

1837
    @freeze_time(datetime.now().replace(tzinfo=pytz.UTC))
1838
    @patch('lms.djangoapps.grades.signals.handlers.PROBLEM_RAW_SCORE_CHANGED.send')
1839 1840 1841 1842 1843
    def test_score_change_signal(self, send_mock):
        """Test that a Django signal is generated when a score changes"""
        self.set_module_grade_using_publish(self.grade_dict)
        expected_signal_kwargs = {
            'sender': None,
1844 1845 1846
            'raw_possible': self.grade_dict['max_value'],
            'raw_earned': self.grade_dict['value'],
            'weight': None,
1847
            'user_id': self.student_user.id,
1848
            'course_id': unicode(self.course.id),
1849 1850
            'usage_id': unicode(self.problem.location),
            'only_if_higher': None,
1851 1852
            'modified': datetime.now().replace(tzinfo=pytz.UTC),
            'score_db_table': 'csm',
1853 1854 1855
        }
        send_mock.assert_called_with(**expected_signal_kwargs)

1856

1857
@attr(shard=1)
1858 1859 1860 1861 1862 1863 1864 1865 1866
class TestRebindModule(TestSubmittingProblems):
    """
    Tests to verify the functionality of rebinding a module.
    Inherit from TestSubmittingProblems to get functionality that set up a course structure
    """
    def setUp(self):
        super(TestRebindModule, self).setUp()
        self.homework = self.add_graded_section_to_course('homework')
        self.lti = ItemFactory.create(category='lti', parent=self.homework)
1867
        self.problem = ItemFactory.create(category='problem', parent=self.homework)
1868 1869 1870
        self.user = UserFactory.create()
        self.anon_user = AnonymousUser()

1871
    def get_module_for_user(self, user, item=None):
1872 1873 1874 1875 1876 1877
        """Helper function to get useful module at self.location in self.course_id for user"""
        mock_request = MagicMock()
        mock_request.user = user
        field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
            self.course.id, user, self.course, depth=2)

1878 1879 1880
        if item is None:
            item = self.lti

1881 1882 1883
        return render.get_module(  # pylint: disable=protected-access
            user,
            mock_request,
1884
            item.location,
1885
            field_data_cache,
1886
        )._xmodule
1887

1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904
    def test_rebind_module_to_new_users(self):
        module = self.get_module_for_user(self.user, self.problem)

        # Bind the module to another student, which will remove "correct_map"
        # from the module's _field_data_cache and _dirty_fields.
        user2 = UserFactory.create()
        module.descriptor.bind_for_student(module.system, user2.id)

        # XBlock's save method assumes that if a field is in _dirty_fields,
        # then it's also in _field_data_cache. If this assumption
        # doesn't hold, then we get an error trying to bind this module
        # to a third student, since we've removed "correct_map" from
        # _field_data cache, but not _dirty_fields, when we bound
        # this module to the second student. (TNL-2640)
        user3 = UserFactory.create()
        module.descriptor.bind_for_student(module.system, user3.id)

1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
    def test_rebind_noauth_module_to_user_not_anonymous(self):
        """
        Tests that an exception is thrown when rebind_noauth_module_to_user is run from a
        module bound to a real user
        """
        module = self.get_module_for_user(self.user)
        user2 = UserFactory()
        user2.id = 2
        with self.assertRaisesRegexp(
            render.LmsModuleRenderError,
            "rebind_noauth_module_to_user can only be called from a module bound to an anonymous user"
        ):
            self.assertTrue(module.system.rebind_noauth_module_to_user(module, user2))

    def test_rebind_noauth_module_to_user_anonymous(self):
        """
        Tests that get_user_module_for_noauth succeeds when rebind_noauth_module_to_user is run from a
        module bound to AnonymousUser
        """
        module = self.get_module_for_user(self.anon_user)
        user2 = UserFactory()
        user2.id = 2
        module.system.rebind_noauth_module_to_user(module, user2)
        self.assertTrue(module)
        self.assertEqual(module.system.anonymous_student_id, anonymous_id_for_user(user2, self.course.id))
        self.assertEqual(module.scope_ids.user_id, user2.id)
        self.assertEqual(module.descriptor.scope_ids.user_id, user2.id)
1932

1933

1934
@attr(shard=1)
1935 1936
@ddt.ddt
class TestEventPublishing(ModuleStoreTestCase, LoginEnrollmentTestCase):
1937 1938 1939
    """
    Tests of event publishing for both XModules and XBlocks.
    """
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959

    def setUp(self):
        """
        Set up the course and user context
        """
        super(TestEventPublishing, self).setUp()

        self.mock_user = UserFactory()
        self.mock_user.id = 1
        self.request_factory = RequestFactory()

    @ddt.data('xblock', 'xmodule')
    @XBlock.register_temp_plugin(PureXBlock, identifier='xblock')
    @XBlock.register_temp_plugin(EmptyXModuleDescriptor, identifier='xmodule')
    @patch.object(render, 'make_track_function')
    def test_event_publishing(self, block_type, mock_track_function):
        request = self.request_factory.get('')
        request.user = self.mock_user
        course = CourseFactory()
        descriptor = ItemFactory(category=block_type, parent=course)
1960
        field_data_cache = FieldDataCache([course, descriptor], course.id, self.mock_user)  # pylint: disable=no-member
1961 1962 1963 1964 1965 1966 1967 1968 1969
        block = render.get_module(self.mock_user, request, descriptor.location, field_data_cache)

        event_type = 'event_type'
        event = {'event': 'data'}

        block.runtime.publish(block, event_type, event)

        mock_track_function.assert_called_once_with(request)

1970
        mock_track_function.return_value.assert_called_once_with(event_type, event)
1971 1972


1973
@attr(shard=1)
1974
@ddt.ddt
1975
class LMSXBlockServiceBindingTest(SharedModuleStoreTestCase):
1976 1977 1978
    """
    Tests that the LMS Module System (XBlock Runtime) provides an expected set of services.
    """
1979 1980 1981 1982 1983 1984

    @classmethod
    def setUpClass(cls):
        super(LMSXBlockServiceBindingTest, cls).setUpClass()
        cls.course = CourseFactory.create()

1985 1986 1987 1988 1989 1990
    def setUp(self):
        """
        Set up the user and other fields that will be used to instantiate the runtime.
        """
        super(LMSXBlockServiceBindingTest, self).setUp()
        self.user = UserFactory()
1991
        self.student_data = Mock()
1992 1993 1994 1995 1996
        self.track_function = Mock()
        self.xqueue_callback_url_prefix = Mock()
        self.request_token = Mock()

    @XBlock.register_temp_plugin(PureXBlock, identifier='pure')
1997
    @ddt.data("user", "i18n", "fs", "field-data", "bookmarks")
1998 1999 2000 2001 2002 2003 2004
    def test_expected_services_exist(self, expected_service):
        """
        Tests that the 'user', 'i18n', and 'fs' services are provided by the LMS runtime.
        """
        descriptor = ItemFactory(category="pure", parent=self.course)
        runtime, _ = render.get_module_system_for_user(
            self.user,
2005
            self.student_data,
2006 2007 2008 2009
            descriptor,
            self.course.id,
            self.track_function,
            self.xqueue_callback_url_prefix,
2010 2011
            self.request_token,
            course=self.course
2012 2013 2014
        )
        service = runtime.service(descriptor, expected_service)
        self.assertIsNotNone(service)
2015

2016 2017 2018 2019 2020 2021 2022 2023
    def test_beta_tester_fields_added(self):
        """
        Tests that the beta tester fields are set on LMS runtime.
        """
        descriptor = ItemFactory(category="pure", parent=self.course)
        descriptor.days_early_for_beta = 5
        runtime, _ = render.get_module_system_for_user(
            self.user,
2024
            self.student_data,
2025 2026 2027 2028
            descriptor,
            self.course.id,
            self.track_function,
            self.xqueue_callback_url_prefix,
2029 2030
            self.request_token,
            course=self.course
2031 2032
        )

2033 2034 2035
        # pylint: disable=no-member
        self.assertFalse(runtime.user_is_beta_tester)
        self.assertEqual(runtime.days_early_for_beta, 5)
2036

2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063

class PureXBlockWithChildren(PureXBlock):
    """
    Pure XBlock with children to use in tests.
    """
    has_children = True


class EmptyXModuleWithChildren(EmptyXModule):  # pylint: disable=abstract-method
    """
    Empty XModule for testing with no dependencies.
    """
    has_children = True


class EmptyXModuleDescriptorWithChildren(EmptyXModuleDescriptor):  # pylint: disable=abstract-method
    """
    Empty XModule for testing with no dependencies.
    """
    module_class = EmptyXModuleWithChildren
    has_children = True


BLOCK_TYPES = ['xblock', 'xmodule']
USER_NUMBERS = range(2)


2064
@attr(shard=1)
2065
@ddt.ddt
2066
class TestFilteredChildren(SharedModuleStoreTestCase):
2067 2068 2069 2070
    """
    Tests that verify access to XBlock/XModule children work correctly
    even when those children are filtered by the runtime when loaded.
    """
2071 2072 2073 2074 2075 2076

    @classmethod
    def setUpClass(cls):
        super(TestFilteredChildren, cls).setUpClass()
        cls.course = CourseFactory.create()

2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180
    # pylint: disable=attribute-defined-outside-init, no-member
    def setUp(self):
        super(TestFilteredChildren, self).setUp()
        self.users = {number: UserFactory() for number in USER_NUMBERS}

        self._old_has_access = render.has_access
        patcher = patch('courseware.module_render.has_access', self._has_access)
        patcher.start()
        self.addCleanup(patcher.stop)

    @ddt.data(*BLOCK_TYPES)
    @XBlock.register_temp_plugin(PureXBlockWithChildren, identifier='xblock')
    @XBlock.register_temp_plugin(EmptyXModuleDescriptorWithChildren, identifier='xmodule')
    def test_unbound(self, block_type):
        block = self._load_block(block_type)
        self.assertUnboundChildren(block)

    @ddt.data(*itertools.product(BLOCK_TYPES, USER_NUMBERS))
    @ddt.unpack
    @XBlock.register_temp_plugin(PureXBlockWithChildren, identifier='xblock')
    @XBlock.register_temp_plugin(EmptyXModuleDescriptorWithChildren, identifier='xmodule')
    def test_unbound_then_bound_as_descriptor(self, block_type, user_number):
        user = self.users[user_number]
        block = self._load_block(block_type)
        self.assertUnboundChildren(block)
        self._bind_block(block, user)
        self.assertBoundChildren(block, user)

    @ddt.data(*itertools.product(BLOCK_TYPES, USER_NUMBERS))
    @ddt.unpack
    @XBlock.register_temp_plugin(PureXBlockWithChildren, identifier='xblock')
    @XBlock.register_temp_plugin(EmptyXModuleDescriptorWithChildren, identifier='xmodule')
    def test_unbound_then_bound_as_xmodule(self, block_type, user_number):
        user = self.users[user_number]
        block = self._load_block(block_type)
        self.assertUnboundChildren(block)
        self._bind_block(block, user)

        # Validate direct XModule access as well
        if isinstance(block, XModuleDescriptor):
            self.assertBoundChildren(block._xmodule, user)  # pylint: disable=protected-access
        else:
            self.assertBoundChildren(block, user)

    @ddt.data(*itertools.product(BLOCK_TYPES, USER_NUMBERS))
    @ddt.unpack
    @XBlock.register_temp_plugin(PureXBlockWithChildren, identifier='xblock')
    @XBlock.register_temp_plugin(EmptyXModuleDescriptorWithChildren, identifier='xmodule')
    def test_bound_only_as_descriptor(self, block_type, user_number):
        user = self.users[user_number]
        block = self._load_block(block_type)
        self._bind_block(block, user)
        self.assertBoundChildren(block, user)

    @ddt.data(*itertools.product(BLOCK_TYPES, USER_NUMBERS))
    @ddt.unpack
    @XBlock.register_temp_plugin(PureXBlockWithChildren, identifier='xblock')
    @XBlock.register_temp_plugin(EmptyXModuleDescriptorWithChildren, identifier='xmodule')
    def test_bound_only_as_xmodule(self, block_type, user_number):
        user = self.users[user_number]
        block = self._load_block(block_type)
        self._bind_block(block, user)

        # Validate direct XModule access as well
        if isinstance(block, XModuleDescriptor):
            self.assertBoundChildren(block._xmodule, user)  # pylint: disable=protected-access
        else:
            self.assertBoundChildren(block, user)

    def _load_block(self, block_type):
        """
        Instantiate an XBlock of `block_type` with the appropriate set of children.
        """
        self.parent = ItemFactory(category=block_type, parent=self.course)

        # Create a child of each block type for each user
        self.children_for_user = {
            user: [
                ItemFactory(category=child_type, parent=self.parent).scope_ids.usage_id
                for child_type in BLOCK_TYPES
            ]
            for user in self.users.itervalues()
        }

        self.all_children = sum(self.children_for_user.values(), [])

        return modulestore().get_item(self.parent.scope_ids.usage_id)

    def _bind_block(self, block, user):
        """
        Bind `block` to the supplied `user`.
        """
        course_id = self.course.id
        field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
            course_id,
            user,
            block,
        )
        return get_module_for_descriptor(
            user,
            Mock(name='request', user=user),
            block,
            field_data_cache,
            course_id,
2181
            course=self.course
2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201
        )

    def _has_access(self, user, action, obj, course_key=None):
        """
        Mock implementation of `has_access` used to control which blocks
        have access to which children during tests.
        """
        if action != 'load':
            return self._old_has_access(user, action, obj, course_key)

        if isinstance(obj, XBlock):
            key = obj.scope_ids.usage_id
        elif isinstance(obj, UsageKey):
            key = obj

        if key == self.parent.scope_ids.usage_id:
            return True
        return key in self.children_for_user[user]

    def assertBoundChildren(self, block, user):
2202 2203 2204
        """
        Ensure the bound children are indeed children.
        """
2205 2206 2207
        self.assertChildren(block, self.children_for_user[user])

    def assertUnboundChildren(self, block):
2208 2209 2210
        """
        Ensure unbound children are indeed children.
        """
2211 2212 2213
        self.assertChildren(block, self.all_children)

    def assertChildren(self, block, child_usage_ids):
2214 2215 2216
        """
        Used to assert that sets of children are equivalent.
        """
2217
        self.assertEquals(set(child_usage_ids), set(child.scope_ids.usage_id for child in block.get_children()))
2218 2219


2220
@attr(shard=1)
2221 2222 2223 2224 2225
@ddt.ddt
class TestDisabledXBlockTypes(ModuleStoreTestCase):
    """
    Tests that verify disabled XBlock types are not loaded.
    """
2226
    # pylint: disable=no-member
2227 2228
    def setUp(self):
        super(TestDisabledXBlockTypes, self).setUp()
2229
        XBlockConfiguration(name='video', enabled=False).save()
2230 2231 2232 2233 2234

    @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
    def test_get_item(self, default_ms):
        with self.store.default_store(default_ms):
            course = CourseFactory()
2235 2236 2237 2238 2239 2240 2241
            self._verify_descriptor('video', course, 'RawDescriptorWithMixins')

    @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
    def test_dynamic_updates(self, default_ms):
        """Tests that the list of disabled xblocks can dynamically update."""
        with self.store.default_store(default_ms):
            course = CourseFactory()
2242
            item_usage_id = self._verify_descriptor('problem', course, 'CapaDescriptorWithMixins')
2243 2244
            XBlockConfiguration(name='problem', enabled=False).save()

2245 2246 2247 2248 2249 2250 2251 2252
            # First verify that the cached value is used until there is a new request cache.
            self._verify_descriptor('problem', course, 'CapaDescriptorWithMixins', item_usage_id)

            # Now simulate a new request cache.
            self.store.request_cache.data = {}
            self._verify_descriptor('problem', course, 'RawDescriptorWithMixins', item_usage_id)

    def _verify_descriptor(self, category, course, descriptor, item_id=None):
2253 2254 2255
        """
        Helper method that gets an item with the specified category from the
        modulestore and verifies that it has the expected descriptor name.
2256 2257

        Returns the item's usage_id.
2258
        """
2259 2260 2261 2262 2263
        if not item_id:
            item = ItemFactory(category=category, parent=course)
            item_id = item.scope_ids.usage_id

        item = self.store.get_item(item_id)
2264
        self.assertEqual(item.__class__.__name__, descriptor)
2265
        return item_id