test_module_render.py 43.4 KB
Newer Older
1 2 3
"""
Test for lms courseware app, module render unit
"""
4
import ddt
5
from functools import partial
6
from mock import MagicMock, patch, Mock
7 8
import json

9
from django.http import Http404, HttpResponse
Brian Wilson committed
10
from django.core.urlresolvers import reverse
11
from django.conf import settings
12
from django.test.client import RequestFactory
13
from django.test.utils import override_settings
14
from django.contrib.auth.models import AnonymousUser
15

16
from capa.tests.response_xml_factory import OptionResponseXMLFactory
17 18 19
from xblock.field_data import FieldData
from xblock.runtime import Runtime
from xblock.fields import ScopeIds
20
from xblock.core import XBlock
21 22
from xmodule.lti_module import LTIDescriptor
from xmodule.modulestore.django import modulestore
23
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
24
from xmodule.modulestore.tests.factories import ItemFactory, CourseFactory, check_mongo_calls
25
from xmodule.x_module import XModuleDescriptor, STUDENT_VIEW
26
from opaque_keys.edx.locations import SlashSeparatedCourseKey
27

28
from courseware import module_render as render
29
from courseware.courses import get_course_with_access, course_image_url, get_course_info_section
30
from courseware.model_data import FieldDataCache
31
from courseware.models import StudentModule
32
from courseware.tests.factories import StudentModuleFactory, UserFactory, GlobalStaffFactory
33
from courseware.tests.tests import LoginEnrollmentTestCase
34

35
from courseware.tests.modulestore_config import TEST_DATA_MIXED_MODULESTORE
36 37
from courseware.tests.modulestore_config import TEST_DATA_MONGO_MODULESTORE
from courseware.tests.modulestore_config import TEST_DATA_XML_MODULESTORE
38
from courseware.tests.test_submitting_problems import TestSubmittingProblems
39

40
from student.models import anonymous_id_for_user
41
from lms.lib.xblock.runtime import quote_slashes
42
from xmodule.modulestore import ModuleStoreEnum
Jay Zoldak committed
43

Jay Zoldak committed
44

45 46 47 48 49 50 51 52
class PureXBlock(XBlock):
    """
    Pure XBlock to use in tests.
    """
    pass


@ddt.ddt
53 54
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
class ModuleRenderTestCase(ModuleStoreTestCase, LoginEnrollmentTestCase):
55 56 57
    """
    Tests of courseware.module_render
    """
58
    def setUp(self):
59 60 61
        self.course_key = SlashSeparatedCourseKey('edX', 'toy', '2012_Fall')
        self.location = self.course_key.make_usage_key('chapter', 'Overview')
        self.toy_course = modulestore().get_course(self.course_key)
62 63 64 65 66 67 68 69 70 71
        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
72
        self.callback_url = reverse('xqueue_callback', kwargs=dict(course_id=self.course_key.to_deprecated_string(),
73 74 75
                                                                   userid=str(self.mock_user.id),
                                                                   mod_id=self.mock_module.id,
                                                                   dispatch=self.dispatch))
76 77

    def test_get_module(self):
78 79
        self.assertEqual(
            None,
80
            render.get_module('dummyuser', None, 'invalid location', None)
81
        )
82

83 84 85 86 87 88 89 90 91
    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

92
        course = get_course_with_access(self.mock_user, 'load', self.course_key)
93

Calen Pennington committed
94
        field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
95
            self.course_key, self.mock_user, course, depth=2)
96

Chris Dodge committed
97 98 99
        module = render.get_module(
            self.mock_user,
            mock_request,
100
            self.course_key.make_usage_key('html', 'toyjumpto'),
Calen Pennington committed
101
            field_data_cache,
Chris Dodge committed
102
        )
103 104

        # get the rendered HTML output which should have the rewritten link
105
        html = module.render(STUDENT_VIEW).content
106 107 108

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

111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    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
        with patch('courseware.module_render.find_target_student_module') as get_fake_module:
            get_fake_module.return_value = self.mock_module
            # call xqueue_callback with our mocked information
            request = self.request_factory.post(self.callback_url, data)
127
            render.xqueue_callback(request, self.course_key, self.mock_user.id, self.mock_module.id, self.dispatch)
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

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

        with patch('courseware.module_render.find_target_student_module') as get_fake_module:
            get_fake_module.return_value = self.mock_module
            # Test with missing xqueue data
            with self.assertRaises(Http404):
                request = self.request_factory.post(self.callback_url, {})
144
                render.xqueue_callback(request, self.course_key, self.mock_user.id, self.mock_module.id, self.dispatch)
145 146 147 148

            # Test with missing xqueue_header
            with self.assertRaises(Http404):
                request = self.request_factory.post(self.callback_url, data)
149
                render.xqueue_callback(request, self.course_key, self.mock_user.id, self.mock_module.id, self.dispatch)
150

151 152 153 154 155 156 157 158
    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')

159
    def test_anonymous_handle_xblock_callback(self):
160
        dispatch_url = reverse(
161
            'xblock_handler',
162
            args=[
163 164
                self.course_key.to_deprecated_string(),
                quote_slashes(self.course_key.make_usage_key('videosequence', 'Toy_Videos').to_deprecated_string()),
165
                'xmodule_handler',
166 167 168 169
                'goto_position'
            ]
        )
        response = self.client.post(dispatch_url, {'position': 2})
polesye committed
170 171
        self.assertEquals(403, response.status_code)
        self.assertEquals('Unauthenticated', response.content)
172

173 174 175 176 177 178 179 180 181 182 183
    @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)
        render.get_module_for_descriptor(self.mock_user, request, descriptor, field_data_cache, self.toy_course.id)
        render.get_module_for_descriptor(self.mock_user, request, descriptor, field_data_cache, self.toy_course.id)

Jay Zoldak committed
184

185
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
186 187 188 189 190 191
class TestHandleXBlockCallback(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
    Test the handle_xblock_callback function
    """

    def setUp(self):
192 193 194
        self.course_key = SlashSeparatedCourseKey('edX', 'toy', '2012_Fall')
        self.location = self.course_key.make_usage_key('chapter', 'Overview')
        self.toy_course = modulestore().get_course(self.course_key)
195 196 197 198 199 200 201 202 203 204
        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
205 206 207 208 209 210 211 212
        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
            }
        )
213 214 215 216 217 218 219 220 221 222 223 224 225

    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):
226 227
        request = self.request_factory.post('dummy_url', data={'position': 1})
        request.user = self.mock_user
228 229
        with self.assertRaises(Http404):
            render.handle_xblock_callback(
230
                request,
231
                self.course_key.to_deprecated_string(),
232 233 234 235 236 237 238 239 240 241 242 243 244 245
                '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,
246 247
                self.course_key.to_deprecated_string(),
                quote_slashes(self.location.to_deprecated_string()),
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
                'dummy_handler'
            ).content,
            json.dumps({
                'success': 'Submission aborted! Maximum %d files may be submitted at once' %
                           settings.MAX_FILEUPLOADS_PER_INPUT
            })
        )

    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,
266 267
                self.course_key.to_deprecated_string(),
                quote_slashes(self.location.to_deprecated_string()),
268 269 270 271 272 273 274 275 276 277 278 279 280
                '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))
            })
        )

    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,
281 282
            self.course_key.to_deprecated_string(),
            quote_slashes(self.location.to_deprecated_string()),
283 284 285 286 287 288 289 290 291 292 293 294
            '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',
295
                quote_slashes(self.location.to_deprecated_string()),
296 297 298 299 300 301 302 303 304 305
                '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,
306 307
                self.course_key.to_deprecated_string(),
                quote_slashes(self.course_key.make_usage_key('chapter', 'bad_location').to_deprecated_string()),
308 309 310 311 312 313 314 315 316 317
                '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,
318 319
                self.course_key.to_deprecated_string(),
                quote_slashes(self.location.to_deprecated_string()),
320 321 322 323 324 325 326 327 328 329
                '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,
330 331
                self.course_key.to_deprecated_string(),
                quote_slashes(self.location.to_deprecated_string()),
332 333 334 335 336
                'bad_handler',
                'bad_dispatch',
            )


337
@ddt.ddt
338 339
@override_settings(MODULESTORE=TEST_DATA_MONGO_MODULESTORE)
class TestTOC(ModuleStoreTestCase):
Jay Zoldak committed
340
    """Check the Table of Contents for a course"""
341
    def setup_modulestore(self, default_ms, num_finds, num_sends):
342 343 344
        self.course_key = self.create_toy_course()
        self.chapter = 'Overview'
        chapter_url = '%s/%s/%s' % ('/courses', self.course_key, self.chapter)
Jay Zoldak committed
345
        factory = RequestFactory()
346 347
        self.request = factory.get(chapter_url)
        self.request.user = UserFactory()
348
        self.modulestore = self.store._get_modulestore_for_courseid(self.course_key)
349 350 351 352 353 354
        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
                )
355

356 357 358 359 360 361 362 363 364 365 366 367
    # 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
    # Split makes 2 queries to render the toc:
    #     - it loads the active version at the start of the bulk operation
    #     - it loads the course definition for inheritance, because it's outside
    #     the bulk-operation marker that loaded the course descriptor
    @ddt.data((ModuleStoreEnum.Type.mongo, 3, 0, 0), (ModuleStoreEnum.Type.split, 6, 0, 2))
368
    @ddt.unpack
369
    def test_toc_toy_from_chapter(self, default_ms, setup_finds, setup_sends, toc_finds):
370
        with self.store.default_store(default_ms):
371
            self.setup_modulestore(default_ms, setup_finds, setup_sends)
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
            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}],
                          'url_name': 'Overview', 'display_name': u'Overview'},
                         {'active': False, 'sections':
                          [{'url_name': 'toyvideo', 'display_name': 'toyvideo', 'graded': True,
                            'format': '', 'due': None, 'active': False}],
                          'url_name': 'secret:magic', 'display_name': 'secret:magic'}])

387
            with check_mongo_calls(toc_finds):
388 389 390
                actual = render.toc_for_course(
                    self.request.user, self.request, self.toy_course, self.chapter, None, self.field_data_cache
                )
391 392
        for toc_section in expected:
            self.assertIn(toc_section, actual)
Jay Zoldak committed
393

394 395 396 397 398 399 400 401 402 403 404 405
    # 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
    # Split makes 2 queries to render the toc:
    #     - it loads the active version at the start of the bulk operation
    #     - it loads the course definition for inheritance, because it's outside
    #     the bulk-operation marker that loaded the course descriptor
    @ddt.data((ModuleStoreEnum.Type.mongo, 3, 0, 0), (ModuleStoreEnum.Type.split, 6, 0, 2))
406
    @ddt.unpack
407
    def test_toc_toy_from_section(self, default_ms, setup_finds, setup_sends, toc_finds):
408
        with self.store.default_store(default_ms):
409
            self.setup_modulestore(default_ms, setup_finds, setup_sends)
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
            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}],
                          'url_name': 'Overview', 'display_name': u'Overview'},
                         {'active': False, 'sections':
                          [{'url_name': 'toyvideo', 'display_name': 'toyvideo', 'graded': True,
                            'format': '', 'due': None, 'active': False}],
                          'url_name': 'secret:magic', 'display_name': 'secret:magic'}])

426
            with check_mongo_calls(toc_finds):
427
                actual = render.toc_for_course(self.request.user, self.request, self.toy_course, self.chapter, section, self.field_data_cache)
428 429
            for toc_section in expected:
                self.assertIn(toc_section, actual)
430 431


432
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
433 434 435 436 437 438 439 440 441 442 443 444 445
class TestHtmlModifiers(ModuleStoreTestCase):
    """
    Tests to verify that standard modifications to the output of XModule/XBlock
    student_view are taking place
    """
    def setUp(self):
        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>'
446
        self.rewrite_bad_link = '<img src="/static//file.jpg" />'
447 448 449
        self.course_link = '<a href="/course/bar/content">Test course rewrite</a>'
        self.descriptor = ItemFactory.create(
            category='html',
450
            data=self.content_string + self.rewrite_link + self.rewrite_bad_link + self.course_link
451 452
        )
        self.location = self.descriptor.location
Calen Pennington committed
453
        self.field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
454 455 456 457 458 459 460 461 462 463
            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
464
            self.field_data_cache,
465 466
            wrap_xmodule_display=True,
        )
467
        result_fragment = module.render(STUDENT_VIEW)
468

469
        self.assertIn('div class="xblock xblock-student_view xmodule_display xmodule_HtmlModule"', result_fragment.content)
470 471 472 473 474 475

    def test_xmodule_display_wrapper_disabled(self):
        module = render.get_module(
            self.user,
            self.request,
            self.location,
Calen Pennington committed
476
            self.field_data_cache,
477 478
            wrap_xmodule_display=False,
        )
479
        result_fragment = module.render(STUDENT_VIEW)
480

481
        self.assertNotIn('div class="xblock xblock-student_view xmodule_display xmodule_HtmlModule"', result_fragment.content)
482 483 484 485 486 487

    def test_static_link_rewrite(self):
        module = render.get_module(
            self.user,
            self.request,
            self.location,
Calen Pennington committed
488
            self.field_data_cache,
489
        )
490
        result_fragment = module.render(STUDENT_VIEW)
491 492 493 494 495 496 497 498 499

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

500 501 502 503 504
    def test_static_badlink_rewrite(self):
        module = render.get_module(
            self.user,
            self.request,
            self.location,
Calen Pennington committed
505
            self.field_data_cache,
506
        )
507
        result_fragment = module.render(STUDENT_VIEW)
508 509 510 511 512

        self.assertIn(
            '/c4x/{org}/{course}/asset/_file.jpg'.format(
                org=self.course.location.org,
                course=self.course.location.course,
513 514 515 516
            ),
            result_fragment.content
        )

517 518
    def test_static_asset_path_use(self):
        '''
519
        when a course is loaded with do_import_static=False (see xml_importer.py), then
520 521 522 523 524 525 526
        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
527
            self.field_data_cache,
528 529
            static_asset_path="toy_course_dir",
        )
530
        result_fragment = module.render(STUDENT_VIEW)
531 532 533 534 535 536
        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
537
        self.course.static_asset_path = "toy_course_dir"
538 539
        url = course_image_url(self.course)
        self.assertTrue(url.startswith('/static/toy_course_dir/'))
Calen Pennington committed
540
        self.course.static_asset_path = ""
541 542

    def test_get_course_info_section(self):
Calen Pennington committed
543
        self.course.static_asset_path = "toy_course_dir"
544
        get_course_info_section(self.request, self.course, "handouts")
Chris Dodge committed
545
        # NOTE: check handouts output...right now test course seems to have no such content
546 547
        # at least this makes sure get_course_info_section returns without exception

548 549 550 551 552
    def test_course_link_rewrite(self):
        module = render.get_module(
            self.user,
            self.request,
            self.location,
Calen Pennington committed
553
            self.field_data_cache,
554
        )
555
        result_fragment = module.render(STUDENT_VIEW)
556 557 558

        self.assertIn(
            '/courses/{course_id}/bar/content'.format(
559
                course_id=self.course.id.to_deprecated_string()
560 561 562 563
            ),
            result_fragment.content
        )

564

565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
class ViewInStudioTest(ModuleStoreTestCase):
    """Tests for the 'View in Studio' link visiblity."""

    def setUp(self):
        """ Set up the user and request that will be used. """
        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
        )

586
        return render.get_module(
587 588 589 590 591 592 593 594 595 596 597 598 599 600
            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
601
            parent_location=course.location,
602 603
        )

604 605
        child_descriptor = ItemFactory.create(
            category='vertical',
cahrens committed
606
            parent_location=descriptor.location
607 608 609 610
        )

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

cahrens committed
611
        # pylint: disable=W0201
612
        self.child_module = self._get_module(course.id, child_descriptor, child_descriptor.location)
613 614 615 616 617 618

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

623
        self.module = self._get_module(course_key, descriptor, location)
624 625 626 627 628 629 630 631 632 633 634 635


@override_settings(MODULESTORE=TEST_DATA_MONGO_MODULESTORE)
class MongoViewInStudioTest(ViewInStudioTest):
    """Test the 'View in Studio' link visibility in a mongo backed course."""

    def setUp(self):
        super(MongoViewInStudioTest, self).setUp()

    def test_view_in_studio_link_studio_course(self):
        """Regular Studio courses should see 'View in Studio' links."""
        self.setup_mongo_course()
636
        result_fragment = self.module.render(STUDENT_VIEW)
637 638
        self.assertIn('View Unit in Studio', result_fragment.content)

639 640 641 642
    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.
643
        result_fragment = self.module.render(STUDENT_VIEW)
644 645 646 647 648 649 650
        # The single "View Unit in Studio" link should appear before the first xmodule vertical definition.
        parts = result_fragment.content.split('xmodule_VerticalModule')
        self.assertEqual(3, len(parts), "Did not find two vertical modules")
        self.assertIn('View Unit in Studio', parts[0])
        self.assertNotIn('View Unit in Studio', parts[1])
        self.assertNotIn('View Unit in Studio', parts[2])

651 652 653
    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')
654
        result_fragment = self.module.render(STUDENT_VIEW)
655 656 657 658 659 660 661 662 663 664 665 666 667
        self.assertNotIn('View Unit in Studio', result_fragment.content)


@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
class MixedViewInStudioTest(ViewInStudioTest):
    """Test the 'View in Studio' link visibility in a mixed mongo backed course."""

    def setUp(self):
        super(MixedViewInStudioTest, self).setUp()

    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()
668
        result_fragment = self.module.render(STUDENT_VIEW)
669 670 671 672 673
        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')
674
        result_fragment = self.module.render(STUDENT_VIEW)
675 676 677 678 679
        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()
680
        result_fragment = self.module.render(STUDENT_VIEW)
681 682 683 684 685 686 687 688 689 690 691 692 693
        self.assertNotIn('View Unit in Studio', result_fragment.content)


@override_settings(MODULESTORE=TEST_DATA_XML_MODULESTORE)
class XmlViewInStudioTest(ViewInStudioTest):
    """Test the 'View in Studio' link visibility in an xml backed course."""

    def setUp(self):
        super(XmlViewInStudioTest, self).setUp()

    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()
694
        result_fragment = self.module.render(STUDENT_VIEW)
695 696 697
        self.assertNotIn('View Unit in Studio', result_fragment.content)


698 699 700 701 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 732
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
@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):
        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):
733 734 735 736
        module = render.get_module(
            self.user,
            self.request,
            self.location,
Calen Pennington committed
737
            self.field_data_cache,
738
        )
739
        result_fragment = module.render(STUDENT_VIEW)
740
        self.assertNotIn('Staff Debug', result_fragment.content)
741

742 743 744 745 746 747
    def test_staff_debug_info_enabled(self):
        module = render.get_module(
            self.user,
            self.request,
            self.location,
            self.field_data_cache,
748
        )
749
        result_fragment = module.render(STUDENT_VIEW)
750 751
        self.assertIn('Staff Debug', result_fragment.content)

752 753 754 755 756 757 758 759
    @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,
        )
760
        result_fragment = module.render(STUDENT_VIEW)
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
        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
        )
        with patch('xmodule_modifiers.grade_histogram') as mock_grade_histogram:
            mock_grade_histogram.return_value = []
            module = render.get_module(
                self.user,
                self.request,
                html_descriptor.location,
                field_data_cache,
            )
783
            module.render(STUDENT_VIEW)
784 785 786 787 788 789 790
            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,
791
            module_state_key=self.location,
792 793 794 795 796 797 798 799 800 801 802 803 804
            student=UserFactory(),
            grade=1,
            max_grade=1,
            state="{}",
        )
        with patch('xmodule_modifiers.grade_histogram') as mock_grade_histogram:
            mock_grade_histogram.return_value = []
            module = render.get_module(
                self.user,
                self.request,
                self.location,
                self.field_data_cache,
            )
805
            module.render(STUDENT_VIEW)
806 807
            self.assertTrue(mock_grade_histogram.called)

808

809
PER_COURSE_ANONYMIZED_DESCRIPTORS = (LTIDescriptor, )
810

811 812
# The "set" here is to work around the bug that load_classes returns duplicates for multiply-delcared classes.
PER_STUDENT_ANONYMIZED_DESCRIPTORS = set(
813 814
    class_ for (name, class_) in XModuleDescriptor.load_classes()
    if not issubclass(class_, PER_COURSE_ANONYMIZED_DESCRIPTORS)
815
)
816 817


818
@ddt.ddt
819 820 821 822 823 824 825 826 827 828 829
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
class TestAnonymousStudentId(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
    Test that anonymous_student_id is set correctly across a variety of XBlock types
    """

    def setUp(self):
        self.user = UserFactory()

    @patch('courseware.module_render.has_access', Mock(return_value=True))
    def _get_anonymous_id(self, course_id, xblock_class):
830
        location = course_id.make_usage_key('dummy_category', 'dummy_name')
831 832 833 834 835 836 837 838 839 840 841 842
        descriptor = Mock(
            spec=xblock_class,
            _field_data=Mock(spec=FieldData),
            location=location,
            static_asset_path=None,
            runtime=Mock(
                spec=Runtime,
                resources_fs=None,
                mixologist=Mock(_mixins=())
            ),
            scope_ids=Mock(spec=ScopeIds),
        )
843 844 845
        # Use the xblock_class's bind_for_student method
        descriptor.bind_for_student = partial(xblock_class.bind_for_student, descriptor)

846 847 848 849
        if hasattr(xblock_class, 'module_class'):
            descriptor.module_class = xblock_class.module_class

        return render.get_module_for_descriptor_internal(
850 851 852 853 854 855 856
            user=self.user,
            descriptor=descriptor,
            field_data_cache=Mock(spec=FieldDataCache),
            course_id=course_id,
            track_function=Mock(),  # Track Function
            xqueue_callback_url_prefix=Mock(),  # XQueue Callback Url Prefix
            request_token='request_token',
857 858
        ).xmodule_runtime.anonymous_student_id

859
    @ddt.data(*PER_STUDENT_ANONYMIZED_DESCRIPTORS)
860 861 862 863 864 865
    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',
866
                self._get_anonymous_id(SlashSeparatedCourseKey.from_deprecated_string(course_id), descriptor_class)
867 868
            )

869
    @ddt.data(*PER_COURSE_ANONYMIZED_DESCRIPTORS)
870 871 872 873 874
    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',
875
            self._get_anonymous_id(SlashSeparatedCourseKey('MITx', '6.00x', '2012_Fall'), descriptor_class)
876 877 878 879 880 881
        )

        self.assertEquals(
            # This value is set by observation, so that later changes to the student
            # id computation don't break old data
            'f82b5416c9f54b5ce33989511bb5ef2e',
882
            self._get_anonymous_id(SlashSeparatedCourseKey('MITx', '6.00x', '2013_Spring'), descriptor_class)
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


@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
@patch('track.views.tracker')
class TestModuleTrackingContext(ModuleStoreTestCase):
    """
    Ensure correct tracking information is included in events emitted during XBlock callback handling.
    """

    def setUp(self):
        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'
        actual_display_name = self.handle_callback_and_get_display_name_from_event(mock_tracker, problem_display_name)
        self.assertEquals(problem_display_name, actual_display_name)

    def handle_callback_and_get_display_name_from_event(self, mock_tracker, problem_display_name=None):
        """
        Creates a fake module, invokes the callback and extracts the display name from the emitted problem_check event.
        """
        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,
928 929
            self.course.id.to_deprecated_string(),
            quote_slashes(descriptor.location.to_deprecated_string()),
930 931 932 933 934 935 936 937 938 939 940 941 942 943
            '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')
        return event['context']['module']['display_name']

    def test_missing_display_name(self, mock_tracker):
        actual_display_name = self.handle_callback_and_get_display_name_from_event(mock_tracker)
        self.assertTrue(actual_display_name.startswith('problem'))
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967


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,
968
            self.problem.location,
969
            field_data_cache,
970
        )._xmodule
971 972 973 974 975 976 977 978 979 980

    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)
981
        student_module = StudentModule.objects.get(student=self.student_user, module_state_key=self.problem.location)
982 983 984 985 986 987 988
        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)
989
        student_module = StudentModule.objects.get(student=self.student_user, module_state_key=self.problem.location)
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
        self.assertIsNone(student_module.grade)
        self.assertIsNone(student_module.max_grade)


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)
        self.user = UserFactory.create()
        self.anon_user = AnonymousUser()

    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,
1016
            self.lti.location,
1017
            field_data_cache,
1018
        )._xmodule
1019 1020 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

    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)
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057

    @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)