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

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

29
from capa.tests.response_xml_factory import OptionResponseXMLFactory
30
from courseware import module_render as render
31
from courseware.courses import get_course_with_access, course_image_url, get_course_info_section
32
from courseware.field_overrides import OverrideFieldData
33
from courseware.model_data import FieldDataCache
34
from courseware.module_render import hash_resource, get_module_for_descriptor
35
from courseware.models import StudentModule
36
from courseware.tests.factories import StudentModuleFactory, UserFactory, GlobalStaffFactory
37
from courseware.tests.tests import LoginEnrollmentTestCase
38 39
from courseware.tests.test_submitting_problems import TestSubmittingProblems
from lms.djangoapps.lms_xblock.runtime import quote_slashes
40
from lms.djangoapps.lms_xblock.field_data import LmsFieldData
41
from student.models import anonymous_id_for_user
42
from xmodule.modulestore.tests.django_utils import (
Ned Batchelder committed
43 44
    TEST_DATA_MIXED_TOY_MODULESTORE,
    TEST_DATA_XML_MODULESTORE,
45 46
)
from xmodule.lti_module import LTIDescriptor
47
from xmodule.modulestore import ModuleStoreEnum
48 49 50
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import ItemFactory, CourseFactory, check_mongo_calls
51
from xmodule.x_module import XModuleDescriptor, XModule, STUDENT_VIEW, CombinedSystem
52

53 54 55 56 57 58 59 60 61 62 63 64 65 66
from openedx.core.djangoapps.credit.models import CreditCourse
from openedx.core.djangoapps.credit.api import (
    set_credit_requirements,
    set_credit_requirement_status
)

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

67
TEST_DATA_DIR = settings.COMMON_TEST_DATA_ROOT
Jay Zoldak committed
68

Jay Zoldak committed
69

70 71 72 73
@XBlock.needs("field-data")
@XBlock.needs("i18n")
@XBlock.needs("fs")
@XBlock.needs("user")
74 75 76 77 78 79 80
class PureXBlock(XBlock):
    """
    Pure XBlock to use in tests.
    """
    pass


81 82 83 84
class EmptyXModule(XModule):  # pylint: disable=abstract-method
    """
    Empty XModule for testing with no dependencies.
    """
85 86 87
    pass


88 89 90 91
class EmptyXModuleDescriptor(XModuleDescriptor):  # pylint: disable=abstract-method
    """
    Empty XModule for testing with no dependencies.
    """
92 93 94
    module_class = EmptyXModule


95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
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
            }
        )


116
@attr('shard_1')
117
@ddt.ddt
118
class ModuleRenderTestCase(ModuleStoreTestCase, LoginEnrollmentTestCase):
119 120 121
    """
    Tests of courseware.module_render
    """
122 123
    # 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.
124
    def setUp(self):
125 126 127 128 129 130
        """
        Set up the course and user context
        """
        super(ModuleRenderTestCase, self).setUp()

        self.course_key = self.create_toy_course()
131
        self.toy_course = modulestore().get_course(self.course_key)
132 133 134 135 136 137 138 139 140 141
        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
142 143 144 145 146 147 148 149 150
        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
            )
        )
151 152

    def test_get_module(self):
153 154
        self.assertEqual(
            None,
155
            render.get_module('dummyuser', None, 'invalid location', None)
156
        )
157

158 159 160 161 162 163 164 165 166
    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

167
        course = get_course_with_access(self.mock_user, 'load', self.course_key)
168

Calen Pennington committed
169
        field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
170
            self.course_key, self.mock_user, course, depth=2)
171

Chris Dodge committed
172 173 174
        module = render.get_module(
            self.mock_user,
            mock_request,
175
            self.course_key.make_usage_key('html', 'toyjumpto'),
Calen Pennington committed
176
            field_data_cache,
Chris Dodge committed
177
        )
178 179

        # get the rendered HTML output which should have the rewritten link
180
        html = module.render(STUDENT_VIEW).content
181 182 183

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

186 187 188 189 190 191 192 193 194 195 196 197
    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
198
        with patch('courseware.module_render.load_single_xblock', return_value=self.mock_module):
199 200
            # call xqueue_callback with our mocked information
            request = self.request_factory.post(self.callback_url, data)
201 202 203 204 205 206 207
            render.xqueue_callback(
                request,
                unicode(self.course_key),
                self.mock_user.id,
                self.mock_module.id,
                self.dispatch
            )
208 209 210 211 212 213 214 215 216 217 218

        # 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',
        }

219
        with patch('courseware.module_render.load_single_xblock', return_value=self.mock_module):
220 221 222
            # Test with missing xqueue data
            with self.assertRaises(Http404):
                request = self.request_factory.post(self.callback_url, {})
223 224 225 226 227 228 229
                render.xqueue_callback(
                    request,
                    unicode(self.course_key),
                    self.mock_user.id,
                    self.mock_module.id,
                    self.dispatch
                )
230 231 232 233

            # Test with missing xqueue_header
            with self.assertRaises(Http404):
                request = self.request_factory.post(self.callback_url, data)
234 235 236 237 238 239 240
                render.xqueue_callback(
                    request,
                    unicode(self.course_key),
                    self.mock_user.id,
                    self.mock_module.id,
                    self.dispatch
                )
241

242 243 244 245 246 247 248 249
    def test_get_score_bucket(self):
        self.assertEquals(render.get_score_bucket(0, 10), 'incorrect')
        self.assertEquals(render.get_score_bucket(1, 10), 'partial')
        self.assertEquals(render.get_score_bucket(10, 10), 'correct')
        # get_score_bucket calls error cases 'incorrect'
        self.assertEquals(render.get_score_bucket(11, 10), 'incorrect')
        self.assertEquals(render.get_score_bucket(-1, 10), 'incorrect')

250
    def test_anonymous_handle_xblock_callback(self):
251
        dispatch_url = reverse(
252
            'xblock_handler',
253
            args=[
254 255
                self.course_key.to_deprecated_string(),
                quote_slashes(self.course_key.make_usage_key('videosequence', 'Toy_Videos').to_deprecated_string()),
256
                'xmodule_handler',
257 258 259 260
                'goto_position'
            ]
        )
        response = self.client.post(dispatch_url, {'position': 2})
polesye committed
261 262
        self.assertEquals(403, response.status_code)
        self.assertEquals('Unauthenticated', response.content)
263

264 265 266 267 268 269 270 271 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
    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})

302 303 304 305 306 307 308 309
    @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)
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
        # 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
        )
328

329
    @override_settings(FIELD_OVERRIDE_PROVIDERS=(
330 331
        'ccx.overrides.CustomCoursesForEdxOverrideProvider',
    ))
332 333 334 335 336 337 338
    def test_rebind_different_users_ccx(self):
        """
        This tests the rebinding a descriptor to a student does not result
        in overly nested _field_data when CCX is enabled.
        """
        request = self.request_factory.get('')
        request.user = self.mock_user
339
        course = CourseFactory.create(enable_ccx=True)
340 341 342

        descriptor = ItemFactory(category='html', parent=course)
        field_data_cache = FieldDataCache(
343
            [course, descriptor], course.id, self.mock_user
344 345 346 347 348 349
        )

        # 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(
350
            self.mock_user, request, descriptor, field_data_cache, course.id, course=course
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
        )

        # 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,
366 367
                course.id,
                course=course
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
            )

        # _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
        )

388 389 390 391 392 393 394 395
    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
396

397
@attr('shard_1')
398 399 400 401 402 403
class TestHandleXBlockCallback(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
    Test the handle_xblock_callback function
    """

    def setUp(self):
404 405 406
        super(TestHandleXBlockCallback, self).setUp()

        self.course_key = self.create_toy_course()
407 408
        self.location = self.course_key.make_usage_key('chapter', 'Overview')
        self.toy_course = modulestore().get_course(self.course_key)
409
        self.mock_user = UserFactory.create()
410 411 412 413 414 415 416 417
        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
418 419 420 421 422 423 424 425
        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
            }
        )
426 427 428 429 430 431 432 433 434 435 436 437 438

    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):
439 440
        request = self.request_factory.post('dummy_url', data={'position': 1})
        request.user = self.mock_user
441 442
        with self.assertRaises(Http404):
            render.handle_xblock_callback(
443
                request,
444
                self.course_key.to_deprecated_string(),
445 446 447 448 449 450 451 452 453 454 455 456 457 458
                '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,
459 460
                self.course_key.to_deprecated_string(),
                quote_slashes(self.location.to_deprecated_string()),
461 462 463 464 465
                'dummy_handler'
            ).content,
            json.dumps({
                'success': 'Submission aborted! Maximum %d files may be submitted at once' %
                           settings.MAX_FILEUPLOADS_PER_INPUT
466
            }, indent=2)
467 468 469 470 471 472 473 474 475 476 477 478
        )

    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,
479 480
                self.course_key.to_deprecated_string(),
                quote_slashes(self.location.to_deprecated_string()),
481 482 483 484 485
                '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))
486
            }, indent=2)
487 488 489 490 491 492 493
        )

    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,
494 495
            self.course_key.to_deprecated_string(),
            quote_slashes(self.location.to_deprecated_string()),
496 497 498 499 500 501 502 503 504 505 506 507
            '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',
508
                quote_slashes(self.location.to_deprecated_string()),
509 510 511 512 513 514 515 516 517 518
                '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,
519 520
                self.course_key.to_deprecated_string(),
                quote_slashes(self.course_key.make_usage_key('chapter', 'bad_location').to_deprecated_string()),
521 522 523 524 525 526 527 528 529 530
                '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,
531 532
                self.course_key.to_deprecated_string(),
                quote_slashes(self.location.to_deprecated_string()),
533 534 535 536 537 538 539 540 541 542
                '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,
543 544
                self.course_key.to_deprecated_string(),
                quote_slashes(self.location.to_deprecated_string()),
545 546 547 548
                'bad_handler',
                'bad_dispatch',
            )

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
    @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)

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
    @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)
597
        doc = PyQuery(content['html'])
598
        self.assertEquals(len(doc('div.xblock-student_view-videosequence')), 1)
599

600

601
@attr('shard_1')
602
@ddt.ddt
603
class TestTOC(ModuleStoreTestCase):
Jay Zoldak committed
604
    """Check the Table of Contents for a course"""
605
    def setup_modulestore(self, default_ms, num_finds, num_sends):
606 607 608
        self.course_key = self.create_toy_course()
        self.chapter = 'Overview'
        chapter_url = '%s/%s/%s' % ('/courses', self.course_key, self.chapter)
Jay Zoldak committed
609
        factory = RequestFactory()
610 611
        self.request = factory.get(chapter_url)
        self.request.user = UserFactory()
612
        self.modulestore = self.store._get_modulestore_for_courselike(self.course_key)  # pylint: disable=protected-access, attribute-defined-outside-init
613 614 615 616 617 618
        with self.modulestore.bulk_operations(self.course_key):
            with check_mongo_calls(num_finds, num_sends):
                self.toy_course = self.store.get_course(self.toy_loc, depth=2)
                self.field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
                    self.toy_loc, self.request.user, self.toy_course, depth=2
                )
619

620 621 622 623 624 625 626
    # 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
627
    # Split makes 5 queries to render the toc:
628
    #     - it loads the active version at the start of the bulk operation
629
    #     - it loads 4 definitions, because it instantiates 4 VideoModules
630
    #       each of which access a Scope.content field in __init__
631
    @ddt.data((ModuleStoreEnum.Type.mongo, 3, 0, 0), (ModuleStoreEnum.Type.split, 6, 0, 5))
632
    @ddt.unpack
633
    def test_toc_toy_from_chapter(self, default_ms, setup_finds, setup_sends, toc_finds):
634
        with self.store.default_store(default_ms):
635
            self.setup_modulestore(default_ms, setup_finds, setup_sends)
636

637 638 639 640 641 642 643 644 645
            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}],
646
                          'url_name': 'Overview', 'display_name': u'Overview', 'display_id': u'overview'},
647 648 649
                         {'active': False, 'sections':
                          [{'url_name': 'toyvideo', 'display_name': 'toyvideo', 'graded': True,
                            'format': '', 'due': None, 'active': False}],
650
                          'url_name': 'secret:magic', 'display_name': 'secret:magic', 'display_id': 'secretmagic'}])
651

652
            course = self.store.get_course(self.toy_course.id, depth=2)
653
            with check_mongo_calls(toc_finds):
654
                actual = render.toc_for_course(
655
                    self.request.user, self.request, course, self.chapter, None, self.field_data_cache
656
                )
657 658
        for toc_section in expected:
            self.assertIn(toc_section, actual)
Jay Zoldak committed
659

660 661 662 663 664 665 666
    # 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
667
    # Split makes 5 queries to render the toc:
668
    #     - it loads the active version at the start of the bulk operation
669
    #     - it loads 4 definitions, because it instantiates 4 VideoModules
670
    #       each of which access a Scope.content field in __init__
671
    @ddt.data((ModuleStoreEnum.Type.mongo, 3, 0, 0), (ModuleStoreEnum.Type.split, 6, 0, 5))
672
    @ddt.unpack
673
    def test_toc_toy_from_section(self, default_ms, setup_finds, setup_sends, toc_finds):
674
        with self.store.default_store(default_ms):
675
            self.setup_modulestore(default_ms, setup_finds, setup_sends)
676 677 678 679 680 681 682 683 684 685
            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}],
686
                          'url_name': 'Overview', 'display_name': u'Overview', 'display_id': u'overview'},
687 688 689
                         {'active': False, 'sections':
                          [{'url_name': 'toyvideo', 'display_name': 'toyvideo', 'graded': True,
                            'format': '', 'due': None, 'active': False}],
690
                          'url_name': 'secret:magic', 'display_name': 'secret:magic', 'display_id': 'secretmagic'}])
691

692
            with check_mongo_calls(toc_finds):
693
                actual = render.toc_for_course(
694
                    self.request.user, self.request, self.toy_course, self.chapter, section, self.field_data_cache
695
                )
696 697
            for toc_section in expected:
                self.assertIn(toc_section, actual)
698 699


700
@attr('shard_1')
701
@ddt.ddt
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
@patch.dict('django.conf.settings.FEATURES', {'ENABLE_PROCTORED_EXAMS': True})
class TestProctoringRendering(ModuleStoreTestCase):
    """Check the Table of Contents for a course"""
    def setUp(self):
        """
        Set up the initial mongo datastores
        """
        super(TestProctoringRendering, self).setUp()
        self.course_key = self.create_toy_course()
        self.chapter = 'Overview'
        chapter_url = '%s/%s/%s' % ('/courses', self.course_key, self.chapter)
        factory = RequestFactory()
        self.request = factory.get(chapter_url)
        self.request.user = UserFactory()
        self.modulestore = self.store._get_modulestore_for_courselike(self.course_key)  # pylint: disable=protected-access, attribute-defined-outside-init
        with self.modulestore.bulk_operations(self.course_key):
            self.toy_course = self.store.get_course(self.toy_loc, depth=2)
            self.field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
                self.toy_loc, self.request.user, self.toy_course, depth=2
            )

    @ddt.data(
        ('honor', False, None, None),
        (
            'honor',
            True,
            'eligible',
            {
                'status': 'eligible',
                'short_description': 'Ungraded Practice Exam',
732
                'suggested_icon': '',
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
                'in_completed_state': False
            }
        ),
        (
            'honor',
            True,
            'submitted',
            {
                'status': 'submitted',
                'short_description': 'Practice Exam Completed',
                'suggested_icon': 'fa-check',
                'in_completed_state': True
            }
        ),
        (
            'honor',
            True,
            'error',
            {
                'status': 'error',
                'short_description': 'Practice Exam Failed',
                'suggested_icon': 'fa-exclamation-triangle',
                'in_completed_state': True
            }
        ),
        (
            'verified',
            False,
            None,
            {
                'status': 'eligible',
                'short_description': 'Proctored Option Available',
765
                'suggested_icon': 'fa-pencil-square-o',
766 767 768 769 770 771 772 773 774 775
                'in_completed_state': False
            }
        ),
        (
            'verified',
            False,
            'declined',
            {
                'status': 'declined',
                'short_description': 'Taking As Open Exam',
776
                'suggested_icon': 'fa-pencil-square-o',
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
                'in_completed_state': False
            }
        ),
        (
            'verified',
            False,
            'submitted',
            {
                'status': 'submitted',
                'short_description': 'Pending Session Review',
                'suggested_icon': 'fa-spinner fa-spin',
                'in_completed_state': True
            }
        ),
        (
            'verified',
            False,
            'verified',
            {
                'status': 'verified',
                'short_description': 'Passed Proctoring',
                'suggested_icon': 'fa-check',
                'in_completed_state': True
            }
        ),
        (
            'verified',
            False,
            'rejected',
            {
                'status': 'rejected',
                'short_description': 'Failed Proctoring',
                'suggested_icon': 'fa-exclamation-triangle',
                'in_completed_state': True
            }
        ),
        (
            'verified',
            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)

        actual = render.toc_for_course(
            self.request.user,
            self.request,
            self.toy_course,
            self.chapter,
            'Toy_Videos',
            self.field_data_cache
        )
        section_actual = self._find_section(actual, 'Overview', 'Toy_Videos')

        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)

    @ddt.data(
        (
            'honor',
            True,
            None,
854
            'Try a proctored exam',
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
            True
        ),
        (
            'honor',
            True,
            'submitted',
            'You have submitted this practice proctored exam',
            False
        ),
        (
            'honor',
            True,
            'error',
            'There was a problem with your practice proctoring session',
            True
        ),
        (
            'verified',
            False,
            None,
875
            'This exam is proctored',
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
            False
        ),
        (
            'verified',
            False,
            'submitted',
            'You have submitted this proctored exam for review',
            True
        ),
        (
            'verified',
            False,
            'verified',
            'Your proctoring session was reviewed and passed all requirements',
            False
        ),
        (
            'verified',
            False,
            'rejected',
            'Your proctoring session was reviewed and did not pass requirements',
            True
        ),
        (
            'verified',
            False,
            'error',
            'There was a problem with your proctoring session',
            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(
                self.request.user.username,
                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
        sequence.is_proctored_enabled = True
        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)

        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


@attr('shard_1')
@ddt.ddt
1023 1024 1025 1026 1027 1028
class TestHtmlModifiers(ModuleStoreTestCase):
    """
    Tests to verify that standard modifications to the output of XModule/XBlock
    student_view are taking place
    """
    def setUp(self):
1029
        super(TestHtmlModifiers, self).setUp()
1030 1031 1032 1033 1034 1035 1036
        self.user = UserFactory.create()
        self.request = RequestFactory().get('/')
        self.request.user = self.user
        self.request.session = {}
        self.course = CourseFactory.create()
        self.content_string = '<p>This is the content<p>'
        self.rewrite_link = '<a href="/static/foo/content">Test rewrite</a>'
1037
        self.rewrite_bad_link = '<img src="/static//file.jpg" />'
1038 1039 1040
        self.course_link = '<a href="/course/bar/content">Test course rewrite</a>'
        self.descriptor = ItemFactory.create(
            category='html',
1041
            data=self.content_string + self.rewrite_link + self.rewrite_bad_link + self.course_link
1042 1043
        )
        self.location = self.descriptor.location
Calen Pennington committed
1044
        self.field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
            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
1055
            self.field_data_cache,
1056 1057
            wrap_xmodule_display=True,
        )
1058
        result_fragment = module.render(STUDENT_VIEW)
1059

1060
        self.assertEquals(len(PyQuery(result_fragment.content)('div.xblock.xblock-student_view.xmodule_HtmlModule')), 1)
1061 1062 1063 1064 1065 1066

    def test_xmodule_display_wrapper_disabled(self):
        module = render.get_module(
            self.user,
            self.request,
            self.location,
Calen Pennington committed
1067
            self.field_data_cache,
1068 1069
            wrap_xmodule_display=False,
        )
1070
        result_fragment = module.render(STUDENT_VIEW)
1071

1072
        self.assertNotIn('div class="xblock xblock-student_view xmodule_display xmodule_HtmlModule"', result_fragment.content)
1073 1074 1075 1076 1077 1078

    def test_static_link_rewrite(self):
        module = render.get_module(
            self.user,
            self.request,
            self.location,
Calen Pennington committed
1079
            self.field_data_cache,
1080
        )
1081
        result_fragment = module.render(STUDENT_VIEW)
1082 1083 1084 1085 1086 1087 1088 1089 1090

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

1091 1092 1093 1094 1095
    def test_static_badlink_rewrite(self):
        module = render.get_module(
            self.user,
            self.request,
            self.location,
Calen Pennington committed
1096
            self.field_data_cache,
1097
        )
1098
        result_fragment = module.render(STUDENT_VIEW)
1099 1100 1101 1102 1103

        self.assertIn(
            '/c4x/{org}/{course}/asset/_file.jpg'.format(
                org=self.course.location.org,
                course=self.course.location.course,
1104 1105 1106 1107
            ),
            result_fragment.content
        )

1108 1109
    def test_static_asset_path_use(self):
        '''
1110
        when a course is loaded with do_import_static=False (see xml_importer.py), then
1111 1112 1113 1114 1115 1116 1117
        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
1118
            self.field_data_cache,
1119 1120
            static_asset_path="toy_course_dir",
        )
1121
        result_fragment = module.render(STUDENT_VIEW)
1122 1123 1124 1125 1126 1127
        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
1128
        self.course.static_asset_path = "toy_course_dir"
1129 1130
        url = course_image_url(self.course)
        self.assertTrue(url.startswith('/static/toy_course_dir/'))
Calen Pennington committed
1131
        self.course.static_asset_path = ""
1132

1133 1134
    @override_settings(DEFAULT_COURSE_ABOUT_IMAGE_URL='test.png')
    @override_settings(STATIC_URL='static/')
1135 1136 1137
    @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
    def test_course_image_for_split_course(self, store):
        """
1138 1139
        for split courses if course_image is empty then course_image_url will be
        the default image url defined in settings
1140 1141 1142 1143 1144
        """
        self.course = CourseFactory.create(default_store=store)
        self.course.course_image = ''

        url = course_image_url(self.course)
1145
        self.assertEqual('static/test.png', url)
1146

1147
    def test_get_course_info_section(self):
Calen Pennington committed
1148
        self.course.static_asset_path = "toy_course_dir"
1149
        get_course_info_section(self.request, self.course, "handouts")
Chris Dodge committed
1150
        # NOTE: check handouts output...right now test course seems to have no such content
1151 1152
        # at least this makes sure get_course_info_section returns without exception

1153 1154 1155 1156 1157
    def test_course_link_rewrite(self):
        module = render.get_module(
            self.user,
            self.request,
            self.location,
Calen Pennington committed
1158
            self.field_data_cache,
1159
        )
1160
        result_fragment = module.render(STUDENT_VIEW)
1161 1162 1163

        self.assertIn(
            '/courses/{course_id}/bar/content'.format(
1164
                course_id=self.course.id.to_deprecated_string()
1165 1166 1167 1168
            ),
            result_fragment.content
        )

1169

1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
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


1186
@attr('shard_1')
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
@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
1211
            course=course
1212 1213 1214 1215 1216 1217 1218
        )
        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)


1219 1220 1221 1222 1223
class ViewInStudioTest(ModuleStoreTestCase):
    """Tests for the 'View in Studio' link visiblity."""

    def setUp(self):
        """ Set up the user and request that will be used. """
1224
        super(ViewInStudioTest, self).setUp()
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
        self.staff_user = GlobalStaffFactory.create()
        self.request = RequestFactory().get('/')
        self.request.user = self.staff_user
        self.request.session = {}
        self.module = None

    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
        )

1241
        return render.get_module(
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
            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
1256
            parent_location=course.location,
1257 1258
        )

1259 1260
        child_descriptor = ItemFactory.create(
            category='vertical',
cahrens committed
1261
            parent_location=descriptor.location
1262 1263 1264 1265
        )

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

1266
        # pylint: disable=attribute-defined-outside-init
1267
        self.child_module = self._get_module(course.id, child_descriptor, child_descriptor.location)
1268 1269 1270 1271 1272 1273

    def setup_xml_course(self):
        """
        Define the XML backed course to use.
        Toy courses are already loaded in XML and mixed modulestores.
        """
1274 1275 1276
        course_key = SlashSeparatedCourseKey('edX', 'toy', '2012_Fall')
        location = course_key.make_usage_key('chapter', 'Overview')
        descriptor = modulestore().get_item(location)
1277

1278
        self.module = self._get_module(course_key, descriptor, location)
1279 1280


1281
@attr('shard_1')
1282 1283 1284 1285 1286 1287
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()
1288
        result_fragment = self.module.render(STUDENT_VIEW)
1289 1290
        self.assertIn('View Unit in Studio', result_fragment.content)

1291 1292 1293 1294
    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.
1295
        result_fragment = self.module.render(STUDENT_VIEW)
1296
        # The single "View Unit in Studio" link should appear before the first xmodule vertical definition.
1297 1298
        parts = result_fragment.content.split('data-block-type="vertical"')
        self.assertEqual(3, len(parts), "Did not find two vertical blocks")
1299 1300 1301 1302
        self.assertIn('View Unit in Studio', parts[0])
        self.assertNotIn('View Unit in Studio', parts[1])
        self.assertNotIn('View Unit in Studio', parts[2])

1303 1304 1305
    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')
1306
        result_fragment = self.module.render(STUDENT_VIEW)
1307 1308 1309
        self.assertNotIn('View Unit in Studio', result_fragment.content)


1310
@attr('shard_1')
1311 1312 1313
class MixedViewInStudioTest(ViewInStudioTest):
    """Test the 'View in Studio' link visibility in a mixed mongo backed course."""

1314
    MODULESTORE = TEST_DATA_MIXED_TOY_MODULESTORE
1315 1316 1317 1318

    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()
1319
        result_fragment = self.module.render(STUDENT_VIEW)
1320 1321 1322 1323 1324
        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')
1325
        result_fragment = self.module.render(STUDENT_VIEW)
1326 1327 1328 1329 1330
        self.assertNotIn('View Unit in Studio', result_fragment.content)

    def test_view_in_studio_link_xml_backed(self):
        """Course in XML only modulestore should not see 'View in Studio' links."""
        self.setup_xml_course()
1331
        result_fragment = self.module.render(STUDENT_VIEW)
1332 1333 1334
        self.assertNotIn('View Unit in Studio', result_fragment.content)


1335
@attr('shard_1')
1336 1337
class XmlViewInStudioTest(ViewInStudioTest):
    """Test the 'View in Studio' link visibility in an xml backed course."""
1338
    MODULESTORE = TEST_DATA_XML_MODULESTORE
1339 1340 1341 1342

    def test_view_in_studio_link_xml_backed(self):
        """Course in XML only modulestore should not see 'View in Studio' links."""
        self.setup_xml_course()
1343
        result_fragment = self.module.render(STUDENT_VIEW)
1344 1345 1346
        self.assertNotIn('View Unit in Studio', result_fragment.content)


1347
@attr('shard_1')
1348 1349 1350 1351 1352 1353
@patch.dict('django.conf.settings.FEATURES', {'DISPLAY_DEBUG_INFO_TO_STAFF': True, 'DISPLAY_HISTOGRAMS_TO_STAFF': True})
@patch('courseware.module_render.has_access', Mock(return_value=True))
class TestStaffDebugInfo(ModuleStoreTestCase):
    """Tests to verify that Staff Debug Info panel and histograms are displayed to staff."""

    def setUp(self):
1354
        super(TestStaffDebugInfo, self).setUp()
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
        self.user = UserFactory.create()
        self.request = RequestFactory().get('/')
        self.request.user = self.user
        self.request.session = {}
        self.course = CourseFactory.create()

        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):
1383 1384 1385 1386
        module = render.get_module(
            self.user,
            self.request,
            self.location,
Calen Pennington committed
1387
            self.field_data_cache,
1388
        )
1389
        result_fragment = module.render(STUDENT_VIEW)
1390
        self.assertNotIn('Staff Debug', result_fragment.content)
1391

1392 1393 1394 1395 1396 1397
    def test_staff_debug_info_enabled(self):
        module = render.get_module(
            self.user,
            self.request,
            self.location,
            self.field_data_cache,
1398
        )
1399
        result_fragment = module.render(STUDENT_VIEW)
1400 1401
        self.assertIn('Staff Debug', result_fragment.content)

1402 1403 1404 1405 1406 1407 1408 1409
    @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,
        )
1410
        result_fragment = module.render(STUDENT_VIEW)
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
        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
        )
1425
        with patch('openedx.core.lib.xblock_utils.grade_histogram') as mock_grade_histogram:
1426 1427 1428 1429 1430 1431 1432
            mock_grade_histogram.return_value = []
            module = render.get_module(
                self.user,
                self.request,
                html_descriptor.location,
                field_data_cache,
            )
1433
            module.render(STUDENT_VIEW)
1434 1435 1436 1437 1438 1439 1440
            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,
1441
            module_state_key=self.location,
1442 1443 1444 1445 1446
            student=UserFactory(),
            grade=1,
            max_grade=1,
            state="{}",
        )
1447
        with patch('openedx.core.lib.xblock_utils.grade_histogram') as mock_grade_histogram:
1448 1449 1450 1451 1452 1453 1454
            mock_grade_histogram.return_value = []
            module = render.get_module(
                self.user,
                self.request,
                self.location,
                self.field_data_cache,
            )
1455
            module.render(STUDENT_VIEW)
1456 1457
            self.assertTrue(mock_grade_histogram.called)

1458

1459
PER_COURSE_ANONYMIZED_DESCRIPTORS = (LTIDescriptor, )
1460

1461 1462
# The "set" here is to work around the bug that load_classes returns duplicates for multiply-delcared classes.
PER_STUDENT_ANONYMIZED_DESCRIPTORS = set(
1463 1464
    class_ for (name, class_) in XModuleDescriptor.load_classes()
    if not issubclass(class_, PER_COURSE_ANONYMIZED_DESCRIPTORS)
1465
)
1466 1467


1468
@attr('shard_1')
1469
@ddt.ddt
1470 1471 1472 1473 1474 1475
class TestAnonymousStudentId(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
    Test that anonymous_student_id is set correctly across a variety of XBlock types
    """

    def setUp(self):
1476
        super(TestAnonymousStudentId, self).setUp(create_user=False)
1477
        self.user = UserFactory()
1478 1479
        self.course_key = self.create_toy_course()
        self.course = modulestore().get_course(self.course_key)
1480 1481 1482

    @patch('courseware.module_render.has_access', Mock(return_value=True))
    def _get_anonymous_id(self, course_id, xblock_class):
1483
        location = course_id.make_usage_key('dummy_category', 'dummy_name')
1484 1485
        descriptor = Mock(
            spec=xblock_class,
1486
            _field_data=Mock(spec=FieldData, name='field_data'),
1487 1488
            location=location,
            static_asset_path=None,
1489
            _runtime=Mock(
1490
                spec=Runtime,
1491
                resources_fs=None,
1492 1493
                mixologist=Mock(_mixins=(), name='mixologist'),
                name='runtime',
1494 1495
            ),
            scope_ids=Mock(spec=ScopeIds),
1496 1497 1498 1499
            name='descriptor',
            _field_data_cache={},
            _dirty_fields={},
            fields={},
1500
            days_early_for_beta=None,
1501
        )
1502
        descriptor.runtime = CombinedSystem(descriptor._runtime, None)  # pylint: disable=protected-access
1503 1504 1505
        # Use the xblock_class's bind_for_student method
        descriptor.bind_for_student = partial(xblock_class.bind_for_student, descriptor)

1506 1507 1508 1509
        if hasattr(xblock_class, 'module_class'):
            descriptor.module_class = xblock_class.module_class

        return render.get_module_for_descriptor_internal(
1510 1511
            user=self.user,
            descriptor=descriptor,
1512
            student_data=Mock(spec=FieldData, name='student_data'),
1513
            course_id=course_id,
1514 1515
            track_function=Mock(name='track_function'),  # Track Function
            xqueue_callback_url_prefix=Mock(name='xqueue_callback_url_prefix'),  # XQueue Callback Url Prefix
1516
            request_token='request_token',
1517
            course=self.course,
1518 1519
        ).xmodule_runtime.anonymous_student_id

1520
    @ddt.data(*PER_STUDENT_ANONYMIZED_DESCRIPTORS)
1521 1522 1523 1524 1525 1526
    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',
1527
                self._get_anonymous_id(CourseKey.from_string(course_id), descriptor_class)
1528 1529
            )

1530
    @ddt.data(*PER_COURSE_ANONYMIZED_DESCRIPTORS)
1531 1532 1533 1534 1535
    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',
1536
            self._get_anonymous_id(SlashSeparatedCourseKey('MITx', '6.00x', '2012_Fall'), descriptor_class)
1537 1538 1539 1540 1541 1542
        )

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


1547
@attr('shard_1')
1548 1549 1550 1551 1552 1553 1554
@patch('track.views.tracker')
class TestModuleTrackingContext(ModuleStoreTestCase):
    """
    Ensure correct tracking information is included in events emitted during XBlock callback handling.
    """

    def setUp(self):
1555 1556
        super(TestModuleTrackingContext, self).setUp()

1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
        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
1573
        module_info = self.handle_callback_and_get_module_info(mock_tracker, problem_display_name)
1574
        self.assertEquals(problem_display_name, module_info['display_name'])
1575

Braden MacDonald committed
1576
    def handle_callback_and_get_module_info(self, mock_tracker, problem_display_name=None):
1577
        """
1578 1579
        Creates a fake module, invokes the callback and extracts the 'module'
        metadata from the emitted problem_check event.
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
        """
        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,
1592 1593
            self.course.id.to_deprecated_string(),
            quote_slashes(descriptor.location.to_deprecated_string()),
1594 1595 1596 1597 1598 1599 1600 1601 1602
            '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')
1603
        return event['context']['module']
1604 1605

    def test_missing_display_name(self, mock_tracker):
Braden MacDonald committed
1606
        actual_display_name = self.handle_callback_and_get_module_info(mock_tracker)['display_name']
1607
        self.assertTrue(actual_display_name.startswith('problem'))
1608

1609 1610 1611 1612 1613 1614 1615 1616
    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
1617 1618 1619
        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)
1620 1621 1622 1623 1624
            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))

1625

1626
@attr('shard_1')
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
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)
        self.grade_dict = {'value': 0.18, 'max_value': 32, 'user_id': self.student_user.id}
        self.delete_dict = {'value': None, 'max_value': None, 'user_id': self.student_user.id}

    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,
1649
            self.problem.location,
1650
            field_data_cache,
1651
        )._xmodule
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661

    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)
1662
        student_module = StudentModule.objects.get(student=self.student_user, module_state_key=self.problem.location)
1663 1664 1665 1666 1667 1668 1669
        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)
1670
        student_module = StudentModule.objects.get(student=self.student_user, module_state_key=self.problem.location)
1671 1672 1673
        self.assertIsNone(student_module.grade)
        self.assertIsNone(student_module.max_grade)

1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
    @patch('courseware.module_render.SCORE_CHANGED.send')
    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,
            'points_possible': self.grade_dict['max_value'],
            'points_earned': self.grade_dict['value'],
            'user_id': self.student_user.id,
            'course_id': unicode(self.course.id),
            'usage_id': unicode(self.problem.location)
        }
        send_mock.assert_called_with(**expected_signal_kwargs)

1688

1689
@attr('shard_1')
1690 1691 1692 1693 1694 1695 1696 1697 1698
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)
1699
        self.problem = ItemFactory.create(category='problem', parent=self.homework)
1700 1701 1702
        self.user = UserFactory.create()
        self.anon_user = AnonymousUser()

1703
    def get_module_for_user(self, user, item=None):
1704 1705 1706 1707 1708 1709
        """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)

1710 1711 1712
        if item is None:
            item = self.lti

1713 1714 1715
        return render.get_module(  # pylint: disable=protected-access
            user,
            mock_request,
1716
            item.location,
1717
            field_data_cache,
1718
        )._xmodule
1719

1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
    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)

1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
    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)
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774

    @patch('courseware.module_render.make_psychometrics_data_update_handler')
    @patch.dict(settings.FEATURES, {'ENABLE_PSYCHOMETRICS': True})
    def test_psychometrics_anonymous(self, psycho_handler):
        """
        Make sure that noauth modules with anonymous users don't have
        the psychometrics callback bound.
        """
        module = self.get_module_for_user(self.anon_user)
        module.system.rebind_noauth_module_to_user(module, self.anon_user)
        self.assertFalse(psycho_handler.called)
1775 1776


1777
@attr('shard_1')
1778 1779
@ddt.ddt
class TestEventPublishing(ModuleStoreTestCase, LoginEnrollmentTestCase):
1780 1781 1782
    """
    Tests of event publishing for both XModules and XBlocks.
    """
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802

    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)
1803
        field_data_cache = FieldDataCache([course, descriptor], course.id, self.mock_user)  # pylint: disable=no-member
1804 1805 1806 1807 1808 1809 1810 1811 1812
        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)

1813
        mock_track_function.return_value.assert_called_once_with(event_type, event)
1814 1815


1816
@attr('shard_1')
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
@ddt.ddt
class LMSXBlockServiceBindingTest(ModuleStoreTestCase):
    """
    Tests that the LMS Module System (XBlock Runtime) provides an expected set of services.
    """
    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()
1828
        self.student_data = Mock()
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
        self.course = CourseFactory.create()
        self.track_function = Mock()
        self.xqueue_callback_url_prefix = Mock()
        self.request_token = Mock()

    @XBlock.register_temp_plugin(PureXBlock, identifier='pure')
    @ddt.data("user", "i18n", "fs", "field-data")
    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,
1843
            self.student_data,
1844 1845 1846 1847
            descriptor,
            self.course.id,
            self.track_function,
            self.xqueue_callback_url_prefix,
1848 1849
            self.request_token,
            course=self.course
1850 1851 1852
        )
        service = runtime.service(descriptor, expected_service)
        self.assertIsNotNone(service)
1853

1854 1855 1856 1857 1858 1859 1860 1861
    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,
1862
            self.student_data,
1863 1864 1865 1866
            descriptor,
            self.course.id,
            self.track_function,
            self.xqueue_callback_url_prefix,
1867 1868
            self.request_token,
            course=self.course
1869 1870 1871 1872 1873
        )

        self.assertFalse(getattr(runtime, u'user_is_beta_tester'))
        self.assertEqual(getattr(runtime, u'days_early_for_beta'), 5)

1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900

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)


1901
@attr('shard_1')
1902 1903 1904 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 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
@ddt.ddt
class TestFilteredChildren(ModuleStoreTestCase):
    """
    Tests that verify access to XBlock/XModule children work correctly
    even when those children are filtered by the runtime when loaded.
    """
    # 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.course = CourseFactory()

        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,
2013
            course=self.course
2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
        )

    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):
2034 2035 2036
        """
        Ensure the bound children are indeed children.
        """
2037 2038 2039
        self.assertChildren(block, self.children_for_user[user])

    def assertUnboundChildren(self, block):
2040 2041 2042
        """
        Ensure unbound children are indeed children.
        """
2043 2044 2045
        self.assertChildren(block, self.all_children)

    def assertChildren(self, block, child_usage_ids):
2046 2047 2048
        """
        Used to assert that sets of children are equivalent.
        """
2049
        self.assertEquals(set(child_usage_ids), set(child.scope_ids.usage_id for child in block.get_children()))
2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072


@attr('shard_1')
@ddt.ddt
class TestDisabledXBlockTypes(ModuleStoreTestCase):
    """
    Tests that verify disabled XBlock types are not loaded.
    """
    # pylint: disable=attribute-defined-outside-init, no-member
    def setUp(self):
        super(TestDisabledXBlockTypes, self).setUp()

        for store in self.store.modulestores:
            store.disabled_xblock_types = ('combinedopenended', 'peergrading', 'video')

    @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
    def test_get_item(self, default_ms):
        with self.store.default_store(default_ms):
            course = CourseFactory()
            for block_type in ('peergrading', 'combinedopenended', 'video'):
                item = ItemFactory(category=block_type, parent=course)
                item = self.store.get_item(item.scope_ids.usage_id)
                self.assertEqual(item.__class__.__name__, 'RawDescriptorWithMixins')