-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Expand file tree
/
Copy pathtest_block_render.py
More file actions
2902 lines (2540 loc) · 113 KB
/
test_block_render.py
File metadata and controls
2902 lines (2540 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
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
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
765
766
767
768
769
770
771
772
773
774
775
776
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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
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
"""
Test for lms courseware app, block render unit
"""
import json
import textwrap
import warnings
from datetime import datetime
from functools import partial
from unittest.mock import MagicMock, Mock, patch
import ddt
import pytest
import pytz
from bson import ObjectId
from completion.models import BlockCompletion # lint-amnesty, pylint: disable=wrong-import-order
from completion.waffle import ENABLE_COMPLETION_TRACKING_SWITCH # lint-amnesty, pylint: disable=wrong-import-order
from django.conf import settings # lint-amnesty, pylint: disable=wrong-import-order
from django.contrib.auth.models import AnonymousUser # lint-amnesty, pylint: disable=wrong-import-order
from django.http import Http404, HttpResponse # lint-amnesty, pylint: disable=wrong-import-order
from django.middleware.csrf import get_token # lint-amnesty, pylint: disable=wrong-import-order
from django.test.client import RequestFactory # lint-amnesty, pylint: disable=wrong-import-order
from django.test.utils import override_settings # lint-amnesty, pylint: disable=wrong-import-order
from django.urls import reverse # lint-amnesty, pylint: disable=wrong-import-order
from edx_proctoring.api import ( # lint-amnesty, pylint: disable=wrong-import-order
create_exam,
create_exam_attempt,
update_attempt_status,
)
from edx_proctoring.runtime import set_runtime_service # lint-amnesty, pylint: disable=wrong-import-order
from edx_proctoring.tests.test_services import ( # lint-amnesty, pylint: disable=wrong-import-order
MockCertificateService,
MockCreditService,
MockGradesService,
)
from edx_toggles.toggles.testutils import override_waffle_switch # lint-amnesty, pylint: disable=wrong-import-order
from edx_when.field_data import DateLookupFieldData # lint-amnesty, pylint: disable=wrong-import-order
from freezegun import freeze_time # lint-amnesty, pylint: disable=wrong-import-order
from milestones.tests.utils import MilestonesTestCaseMixin # lint-amnesty, pylint: disable=wrong-import-order
from opaque_keys.edx.asides import AsideUsageKeyV2 # lint-amnesty, pylint: disable=wrong-import-order
from opaque_keys.edx.keys import CourseKey, UsageKey # lint-amnesty, pylint: disable=wrong-import-order
from pyquery import PyQuery # lint-amnesty, pylint: disable=wrong-import-order
from web_fragments.fragment import Fragment # lint-amnesty, pylint: disable=wrong-import-order
from xblock.completable import CompletableXBlockMixin # lint-amnesty, pylint: disable=wrong-import-order
from xblock.core import XBlock, XBlockAside # lint-amnesty, pylint: disable=wrong-import-order
from xblock.exceptions import NoSuchServiceError
from xblock.field_data import FieldData # lint-amnesty, pylint: disable=wrong-import-order
from xblock.fields import ScopeIds # lint-amnesty, pylint: disable=wrong-import-order
from xblock.runtime import DictKeyValueStore, KvsFieldData # lint-amnesty, pylint: disable=wrong-import-order
from xblock.test.tools import TestRuntime # lint-amnesty, pylint: disable=wrong-import-order
from xblocks_contrib.problem.capa.tests.response_xml_factory import (
OptionResponseXMLFactory, # lint-amnesty, pylint: disable=reimported
)
from common.djangoapps.course_modes.models import CourseMode # lint-amnesty, pylint: disable=reimported
from common.djangoapps.student.models import CourseEnrollment, anonymous_id_for_user
from common.djangoapps.student.tests.factories import (
BetaTesterFactory,
GlobalStaffFactory,
InstructorFactory,
RequestFactoryNoCsrf,
StaffFactory,
UserFactory,
)
from common.djangoapps.xblock_django.constants import (
ATTR_KEY_ANONYMOUS_USER_ID,
ATTR_KEY_DEPRECATED_ANONYMOUS_USER_ID,
ATTR_KEY_USER_IS_BETA_TESTER,
ATTR_KEY_USER_IS_GLOBAL_STAFF,
ATTR_KEY_USER_IS_STAFF,
ATTR_KEY_USER_ROLE,
)
from common.djangoapps.xblock_django.models import XBlockConfiguration
from lms.djangoapps.courseware import block_render as render
from lms.djangoapps.courseware.access_response import AccessResponse
from lms.djangoapps.courseware.block_render import get_block_for_descriptor, hash_resource
from lms.djangoapps.courseware.courses import get_course_info_section, get_course_with_access
from lms.djangoapps.courseware.field_overrides import OverrideFieldData
from lms.djangoapps.courseware.masquerade import CourseMasquerade
from lms.djangoapps.courseware.model_data import FieldDataCache
from lms.djangoapps.courseware.models import StudentModule
from lms.djangoapps.courseware.tests.factories import StudentModuleFactory
from lms.djangoapps.courseware.tests.test_submitting_problems import TestSubmittingProblems
from lms.djangoapps.courseware.tests.tests import LoginEnrollmentTestCase
from lms.djangoapps.lms_xblock.field_data import LmsFieldData
from lms.djangoapps.verify_student.tests.factories import SoftwareSecurePhotoVerificationFactory
from openedx.core.djangoapps.credit.api import set_credit_requirement_status, set_credit_requirements
from openedx.core.djangoapps.credit.models import CreditCourse
from openedx.core.djangoapps.oauth_dispatch.jwt import _create_jwt, create_jwt_for_user
from openedx.core.djangoapps.oauth_dispatch.tests.factories import AccessTokenFactory, ApplicationFactory
from openedx.core.lib.courses import course_image_url
from openedx.core.lib.gating import api as gating_api
from openedx.core.lib.url_utils import quote_slashes
from xmodule.capa_block import ProblemBlock
from xmodule.contentstore.django import contentstore
from xmodule.html_block import AboutBlock, CourseInfoBlock, HtmlBlock, StaticTabBlock
from xmodule.lti_block import LTIBlock
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import XBlockI18nService, modulestore
from xmodule.modulestore.tests.django_utils import (
TEST_DATA_SPLIT_MODULESTORE,
ModuleStoreTestCase,
SharedModuleStoreTestCase,
upload_file_to_course,
)
from xmodule.modulestore.tests.factories import ( # lint-amnesty, pylint: disable=wrong-import-order
BlockFactory,
CourseFactory,
ToyCourseFactory,
check_mongo_calls,
)
from xmodule.modulestore.tests.test_asides import AsideTestType # lint-amnesty, pylint: disable=wrong-import-order
from xmodule.services import RebindUserServiceError
from xmodule.video_block import VideoBlock # lint-amnesty, pylint: disable=wrong-import-order
from xmodule.x_module import STUDENT_VIEW, ModuleStoreRuntime, XModuleMixin # lint-amnesty, pylint: disable=wrong-import-order
TEST_DATA_DIR = settings.COMMON_TEST_DATA_ROOT
@XBlock.needs('fs')
@XBlock.needs('mako')
@XBlock.needs('user')
@XBlock.needs('verification')
@XBlock.needs('proctoring')
@XBlock.needs('milestones')
@XBlock.needs('credit')
@XBlock.needs('bookmarks')
@XBlock.needs('gating')
@XBlock.needs('grade_utils')
@XBlock.needs('user_state')
@XBlock.needs('content_type_gating')
@XBlock.needs('cache')
@XBlock.needs('sandbox')
@XBlock.needs('replace_urls')
@XBlock.needs('rebind_user')
@XBlock.needs('completion')
@XBlock.needs('i18n')
@XBlock.needs('library_tools')
@XBlock.needs('partitions')
@XBlock.needs('settings')
@XBlock.needs('user_tags')
@XBlock.needs('badging')
@XBlock.needs('teams')
@XBlock.needs('teams_configuration')
@XBlock.needs('call_to_action')
class PureXBlock(XBlock):
"""
Pure XBlock to use in tests.
"""
pass # lint-amnesty, pylint: disable=unnecessary-pass
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
}
)
class StubCompletableXBlock(CompletableXBlockMixin):
"""
This XBlock exists to test completion storage.
"""
@XBlock.json_handler
def complete(self, json_data, suffix): # pylint: disable=unused-argument
"""
Mark the block's completion value using the completion API.
"""
return self.runtime.publish( # lint-amnesty, pylint: disable=no-member
self,
'completion',
{'completion': json_data['completion']},
)
@XBlock.json_handler
def progress(self, json_data, suffix): # pylint: disable=unused-argument
"""
Mark the block as complete using the deprecated progress interface.
New code should use the completion event instead.
"""
return self.runtime.publish(self, 'progress', {}) # lint-amnesty, pylint: disable=no-member
class XBlockWithoutCompletionAPI(XBlock):
"""
This XBlock exists to test completion storage for xblocks
that don't support completion API but do emit progress signal.
"""
@XBlock.json_handler
def progress(self, json_data, suffix): # pylint: disable=unused-argument
"""
Mark the block as complete using the deprecated progress interface.
New code should use the completion event instead.
"""
return self.runtime.publish(self, 'progress', {})
@ddt.ddt
class BlockRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase):
"""
Tests of courseware.block_render
"""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.course_key = ToyCourseFactory.create().id
cls.toy_course = modulestore().get_course(cls.course_key)
# 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.
def setUp(self):
"""
Set up the course and user context
"""
super().setUp()
OverrideFieldData.provider_classes = None
self.mock_user = UserFactory()
self.mock_user.id = 1
self.request_factory = RequestFactoryNoCsrf()
# Construct a mock block for the modulestore to return
self.mock_block = MagicMock()
self.mock_block.id = 1
self.dispatch = 'score_update'
# Construct a 'standard' xqueue_callback url
self.callback_url = reverse(
'xqueue_callback',
kwargs=dict(
course_id=str(self.course_key),
userid=str(self.mock_user.id),
mod_id=self.mock_block.id,
dispatch=self.dispatch
)
)
def tearDown(self):
OverrideFieldData.provider_classes = None
super().tearDown()
def test_get_block(self):
assert render.get_block('dummyuser', None, 'invalid location', None) is None
def test_block_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
course = get_course_with_access(self.mock_user, 'load', self.course_key)
field_data_cache = FieldDataCache.cache_for_block_descendents(
self.course_key, self.mock_user, course, depth=2)
block = render.get_block(
self.mock_user,
mock_request,
self.course_key.make_usage_key('html', 'toyjumpto'),
field_data_cache,
)
# get the rendered HTML output which should have the rewritten link
html = block.render(STUDENT_VIEW).content
# See if the url got rewritten to the target link
# note if the URL mapping changes then this assertion will break
assert '/courses/' + str(self.course_key) + '/jump_to_id/vertical_test' in html
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 block
with patch('lms.djangoapps.courseware.block_render.load_single_xblock', return_value=self.mock_block):
# call xqueue_callback with our mocked information
request = self.request_factory.post(self.callback_url, data)
render.xqueue_callback(
request,
str(self.course_key),
self.mock_user.id,
self.mock_block.id,
self.dispatch
)
# Verify that handle ajax is called with the correct data
request.POST._mutable = True # lint-amnesty, pylint: disable=protected-access
request.POST['queuekey'] = fake_key
self.mock_block.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('lms.djangoapps.courseware.block_render.load_single_xblock', return_value=self.mock_block):
# Test with missing xqueue data
with pytest.raises(Http404):
request = self.request_factory.post(self.callback_url, {})
render.xqueue_callback(
request,
str(self.course_key),
self.mock_user.id,
self.mock_block.id,
self.dispatch
)
# Test with missing xqueue_header
with pytest.raises(Http404):
request = self.request_factory.post(self.callback_url, data)
render.xqueue_callback(
request,
str(self.course_key),
self.mock_user.id,
self.mock_block.id,
self.dispatch
)
def _get_dispatch_url(self):
"""Helper to get dispatch URL for testing xblock callback."""
return reverse(
'xblock_handler',
args=[
str(self.course_key),
quote_slashes(str(self.course_key.make_usage_key('sequential', 'Toy_Videos'))),
'xmodule_handler',
'goto_position'
]
)
def test_anonymous_get_xblock_callback(self):
"""Test that anonymous GET is allowed."""
dispatch_url = self._get_dispatch_url()
response = self.client.get(dispatch_url)
assert 200 == response.status_code
def test_anonymous_post_xblock_callback(self):
"""Test that anonymous POST is not allowed."""
dispatch_url = self._get_dispatch_url()
response = self.client.post(dispatch_url, {'position': 2})
# https://openedx.atlassian.net/browse/LEARNER-7131
assert 'Unauthenticated' == response.content.decode('utf-8')
assert 403 == response.status_code
def test_session_authentication(self):
""" Test that the xblock endpoint supports session authentication."""
self.client.login(username=self.mock_user.username, password=self.TEST_PASSWORD)
dispatch_url = self._get_dispatch_url()
response = self.client.post(dispatch_url)
assert 200 == response.status_code
def test_oauth_authentication(self):
""" Test that the xblock endpoint supports OAuth authentication."""
dispatch_url = self._get_dispatch_url()
access_token = AccessTokenFactory(user=self.mock_user, application=ApplicationFactory()).token
headers = {'HTTP_AUTHORIZATION': 'Bearer ' + access_token}
response = self.client.post(dispatch_url, {}, **headers)
assert 200 == response.status_code
def test_jwt_authentication(self):
""" Test that the xblock endpoint supports JWT authentication."""
dispatch_url = self._get_dispatch_url()
token = create_jwt_for_user(self.mock_user)
headers = {'HTTP_AUTHORIZATION': 'JWT ' + token}
response = self.client.post(dispatch_url, {}, **headers)
assert 200 == response.status_code
def test_jwt_authentication_with_restricted_application(self):
"""Test that the XBlock endpoint disallows JWT authentication with restricted applications."""
def _mock_create_restricted_jwt(*args, **kwargs):
"""Pass an additional argument to `_create_jwt` without modifying the signature of `create_jwt_for_user`."""
kwargs['is_restricted'] = True
return _create_jwt(*args, **kwargs)
with patch('openedx.core.djangoapps.oauth_dispatch.jwt._create_jwt', _mock_create_restricted_jwt):
token = create_jwt_for_user(self.mock_user)
dispatch_url = self._get_dispatch_url()
headers = {'HTTP_AUTHORIZATION': 'JWT ' + token}
response = self.client.get(dispatch_url, {}, **headers)
assert 403 == response.status_code
response = self.client.post(dispatch_url, {}, **headers)
assert 403 == response.status_code
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=self.TEST_PASSWORD)
dispatch_url = self._get_dispatch_url()
response = self.client.post(dispatch_url)
assert 200 == response.status_code
assert json.loads(response.content.decode('utf-8')) == {'success': True}
response = self.client.post(dispatch_url, {'position': ''})
assert 200 == response.status_code
assert json.loads(response.content.decode('utf-8')) == {'success': True}
response = self.client.post(dispatch_url, {'position': '-1'})
assert 200 == response.status_code
assert json.loads(response.content.decode('utf-8')) == {'success': True}
response = self.client.post(dispatch_url, {'position': "string"})
assert 200 == response.status_code
assert json.loads(response.content.decode('utf-8')) == {'success': True}
response = self.client.post(dispatch_url, {'position': "Φυσικά"})
assert 200 == response.status_code
assert json.loads(response.content.decode('utf-8')) == {'success': True}
response = self.client.post(dispatch_url, {'position': ''})
assert 200 == response.status_code
assert json.loads(response.content.decode('utf-8')) == {'success': True}
@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()
block = BlockFactory(category=block_type, parent=course)
field_data_cache = FieldDataCache([self.toy_course, block], self.toy_course.id, self.mock_user)
# This is verifying that caching doesn't cause an error during get_block_for_descriptor, which
# is why it calls the method twice identically.
render.get_block_for_descriptor(
self.mock_user,
request,
block,
field_data_cache,
self.toy_course.id,
course=self.toy_course
)
render.get_block_for_descriptor(
self.mock_user,
request,
block,
field_data_cache,
self.toy_course.id,
course=self.toy_course
)
@override_settings(FIELD_OVERRIDE_PROVIDERS=(
'lms.djangoapps.courseware.student_field_overrides.IndividualStudentOverrideProvider',
))
@patch(
'xmodule.modulestore.xml.XMLImportingModuleStoreRuntime.applicable_aside_types',
lambda self, block: ['test_aside']
)
@patch('xmodule.modulestore.split_mongo.runtime.SplitModuleStoreRuntime.applicable_aside_types',
lambda self, block: ['test_aside'])
@XBlockAside.register_temp_plugin(AsideTestType, 'test_aside')
@ddt.data('regular', 'test_aside')
def test_rebind_different_users(self, block_category):
"""
This tests the rebinding a block to a student does not result
in overly nested _field_data.
"""
def create_aside(item, block_type):
"""
Helper function to create aside
"""
key_store = DictKeyValueStore()
field_data = KvsFieldData(key_store)
runtime = TestRuntime(services={'field-data': field_data})
def_id = runtime.id_generator.create_definition(block_type)
usage_id = AsideUsageKeyV2(runtime.id_generator.create_usage(def_id), "aside")
aside = AsideTestType(scope_ids=ScopeIds('user', block_type, def_id, usage_id), runtime=runtime)
aside.content = '%s_new_value11' % block_type
aside.data_field = '%s_new_value12' % block_type
aside.has_score = False
modulestore().update_item(item, self.mock_user.id, asides=[aside])
return item
request = self.request_factory.get('')
request.user = self.mock_user
course = CourseFactory.create()
block = BlockFactory(category="html", parent=course)
if block_category == 'test_aside':
block = create_aside(block, "test_aside")
field_data_cache = FieldDataCache(
[course, block], course.id, self.mock_user
)
# grab what _field_data was originally set to
original_field_data = block._field_data # lint-amnesty, pylint: disable=no-member, protected-access
render.get_block_for_descriptor(
self.mock_user, request, block, field_data_cache, course.id, course=course
)
# check that block.runtime.service(block, 'field-data-unbound') is the same as the original
# _field_data, but now _field_data as been reset.
assert block.runtime.service(block, 'field-data-unbound') is original_field_data
assert block.runtime.service(block, 'field-data-unbound') is not block._field_data # pylint: disable=protected-access, line-too-long
# now bind this block to a few other students
for user in [UserFactory(), UserFactory(), self.mock_user]:
render.get_block_for_descriptor(
user,
request,
block,
field_data_cache,
course.id,
course=course
)
# _field_data should now be wrapped by LmsFieldData
# pylint: disable=protected-access
assert isinstance(block._field_data, LmsFieldData) # lint-amnesty, pylint: disable=no-member
# the LmsFieldData should now wrap OverrideFieldData
assert isinstance(block._field_data._authored_data._source, OverrideFieldData) # lint-amnesty, pylint: disable=no-member, line-too-long
# the OverrideFieldData should point to the date FieldData
assert isinstance(block._field_data._authored_data._source.fallback, DateLookupFieldData) # lint-amnesty, pylint: disable=no-member, line-too-long
assert block._field_data._authored_data._source.fallback._defaults \
is block.runtime.service(block, 'field-data-unbound')
def test_hash_resource(self):
"""
Ensure that the resource hasher works and does not fail on unicode,
decoded or otherwise.
"""
resources = ['ASCII text', '❄ I am a special snowflake.', "❄ So am I, but I didn't tell you."]
assert hash_resource(resources) == '50c2ae79fbce9980e0803848914b0a09'
@ddt.ddt
class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCase):
"""
Test the handle_xblock_callback function
"""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.course_key = ToyCourseFactory.create().id
cls.toy_course = modulestore().get_course(cls.course_key)
def setUp(self):
super().setUp()
self.location = self.course_key.make_usage_key('chapter', 'Overview')
self.mock_user = UserFactory.create()
self.request_factory = RequestFactoryNoCsrf()
# Construct a mock block for the modulestore to return
self.mock_block = MagicMock()
self.mock_block.id = 1
self.dispatch = 'score_update'
# Construct a 'standard' xqueue_callback url
self.callback_url = reverse(
'xqueue_callback', kwargs={
'course_id': str(self.course_key),
'userid': str(self.mock_user.id),
'mod_id': self.mock_block.id,
'dispatch': self.dispatch
}
)
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 make_xblock_callback_response(self, request_data, course, block, handler):
"""
Prepares an xblock callback request and returns response to it.
"""
request = self.request_factory.post(
'/',
data=json.dumps(request_data),
content_type='application/json',
)
request.user = self.mock_user
response = render.handle_xblock_callback(
request,
str(course.id),
quote_slashes(str(block.scope_ids.usage_id)),
handler,
'',
)
return response
def test_invalid_csrf_token(self):
"""
Verify that invalid CSRF token is rejected.
"""
request = RequestFactory().post('dummy_url', data={'position': 1})
csrf_token = get_token(request)
request._post = {'csrfmiddlewaretoken': f'{csrf_token}-dummy'} # pylint: disable=protected-access
request.user = self.mock_user
request.COOKIES[settings.CSRF_COOKIE_NAME] = csrf_token
response = render.handle_xblock_callback(
request,
str(self.course_key),
quote_slashes(str(self.location)),
'xmodule_handler',
'goto_position',
)
assert 403 == response.status_code
def test_valid_csrf_token(self):
"""
Verify that valid CSRF token is accepted.
"""
request = RequestFactory().post('dummy_url', data={'position': 1})
csrf_token = get_token(request)
request._post = {'csrfmiddlewaretoken': csrf_token} # pylint: disable=protected-access
request.user = self.mock_user
request.COOKIES[settings.CSRF_COOKIE_NAME] = csrf_token
response = render.handle_xblock_callback(
request,
str(self.course_key),
quote_slashes(str(self.location)),
'xmodule_handler',
'goto_position',
)
assert 200 == response.status_code
def test_invalid_location(self):
request = self.request_factory.post('dummy_url', data={'position': 1})
request.user = self.mock_user
with pytest.raises(Http404):
render.handle_xblock_callback(
request,
str(self.course_key),
'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
assert render.handle_xblock_callback(request, str(self.course_key), quote_slashes(str(self.location)), 'dummy_handler').content.decode('utf-8') == json.dumps({'success': (f'Submission aborted! Maximum {settings.MAX_FILEUPLOADS_PER_INPUT:d} files may be submitted at once')}, indent=2) # pylint: disable=line-too-long
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
assert render.handle_xblock_callback(request, str(self.course_key), quote_slashes(str(self.location)), 'dummy_handler').content.decode('utf-8') == json.dumps({'success': ('Submission aborted! Your file "%s" is too large (max size: %d MB)' % (inputfile.name, (settings.STUDENT_FILEUPLOAD_MAX_SIZE / (1000 ** 2))))}, indent=2) # pylint: disable=line-too-long
def test_xblock_dispatch(self):
request = self.request_factory.post('dummy_url', data={'position': 1})
request.user = self.mock_user
response = render.handle_xblock_callback(
request,
str(self.course_key),
quote_slashes(str(self.location)),
'xmodule_handler',
'goto_position',
)
assert isinstance(response, HttpResponse)
def test_bad_course_id(self):
request = self.request_factory.post('dummy_url')
request.user = self.mock_user
with pytest.raises(Http404):
render.handle_xblock_callback(
request,
'bad_course_id',
quote_slashes(str(self.location)),
'xmodule_handler',
'goto_position',
)
def test_bad_location(self):
request = self.request_factory.post('dummy_url')
request.user = self.mock_user
with pytest.raises(Http404):
render.handle_xblock_callback(
request,
str(self.course_key),
quote_slashes(str(self.course_key.make_usage_key('chapter', 'bad_location'))),
'xmodule_handler',
'goto_position',
)
def test_bad_xblock_dispatch(self):
request = self.request_factory.post('dummy_url')
request.user = self.mock_user
with pytest.raises(Http404):
render.handle_xblock_callback(
request,
str(self.course_key),
quote_slashes(str(self.location)),
'xmodule_handler',
'bad_dispatch',
)
def test_missing_handler(self):
request = self.request_factory.post('dummy_url')
request.user = self.mock_user
with pytest.raises(Http404):
render.handle_xblock_callback(
request,
str(self.course_key),
quote_slashes(str(self.location)),
'bad_handler',
'bad_dispatch',
)
@XBlock.register_temp_plugin(GradedStatelessXBlock, identifier='stateless_scorer')
def test_score_without_student_state(self):
course = CourseFactory.create()
block = BlockFactory.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,
str(course.id),
quote_slashes(str(block.scope_ids.usage_id)),
'set_score',
'',
)
assert response.status_code == 200
student_module = StudentModule.objects.get(
student=self.mock_user,
module_state_key=block.scope_ids.usage_id,
)
assert student_module.grade == 0.75
assert student_module.max_grade == 1
@ddt.data(
('complete', {'completion': 0.625}),
('progress', {}),
)
@ddt.unpack
@XBlock.register_temp_plugin(StubCompletableXBlock, identifier='comp')
def test_completion_events_with_completion_disabled(self, signal, data):
with override_waffle_switch(ENABLE_COMPLETION_TRACKING_SWITCH, False):
course = CourseFactory.create()
block = BlockFactory.create(category='comp', parent=course)
request = self.request_factory.post(
'/',
data=json.dumps(data),
content_type='application/json',
)
request.user = self.mock_user
with patch('completion.models.BlockCompletionManager.submit_completion') as mock_complete:
render.handle_xblock_callback(
request,
str(course.id),
quote_slashes(str(block.scope_ids.usage_id)),
signal,
'',
)
mock_complete.assert_not_called()
assert not BlockCompletion.objects.filter(block_key=block.scope_ids.usage_id).exists()
@XBlock.register_temp_plugin(StubCompletableXBlock, identifier='comp')
def test_completion_signal_for_completable_xblock(self):
with override_waffle_switch(ENABLE_COMPLETION_TRACKING_SWITCH, True):
course = CourseFactory.create()
block = BlockFactory.create(category='comp', parent=course)
response = self.make_xblock_callback_response(
{'completion': 0.625}, course, block, 'complete'
)
assert response.status_code == 200
completion = BlockCompletion.objects.get(block_key=block.scope_ids.usage_id)
assert completion.completion == 0.625
@XBlock.register_temp_plugin(StubCompletableXBlock, identifier='comp')
@ddt.data((True, True), (False, False),)
@ddt.unpack
def test_aside(self, is_xblock_aside, is_get_aside_called):
"""
test get_aside_from_xblock called
"""
course = CourseFactory.create()
block = BlockFactory.create(category='comp', parent=course)
request = self.request_factory.post(
'/',
data=json.dumps({'completion': 0.625}),
content_type='application/json',
)
request.user = self.mock_user
def get_usage_key():
"""return usage key"""
return (
quote_slashes(str(AsideUsageKeyV2(block.scope_ids.usage_id, "aside")))
if is_xblock_aside
else str(block.scope_ids.usage_id)
)
with patch(
'lms.djangoapps.courseware.block_render.is_xblock_aside',
return_value=is_xblock_aside
), patch(
'lms.djangoapps.courseware.block_render.get_aside_from_xblock'
) as mocked_get_aside_from_xblock, patch(
'lms.djangoapps.courseware.block_render.webob_to_django_response'
) as mocked_webob_to_django_response:
render.handle_xblock_callback(
request,
str(course.id),
get_usage_key(),
'complete',
'',
)
assert mocked_webob_to_django_response.called is True
assert mocked_get_aside_from_xblock.called is is_get_aside_called
def test_aside_invalid_usage_id(self):
"""
test aside work when invalid usage id
"""
course = CourseFactory.create()
request = self.request_factory.post(
'/',
data=json.dumps({'completion': 0.625}),
content_type='application/json',
)
request.user = self.mock_user
with patch(
'lms.djangoapps.courseware.block_render.is_xblock_aside',
return_value=True
), self.assertRaises(Http404):
render.handle_xblock_callback(
request,
str(course.id),
"foo@bar",
'complete',
'',
)
@XBlock.register_temp_plugin(StubCompletableXBlock, identifier='comp')
def test_progress_signal_ignored_for_completable_xblock(self):
with override_waffle_switch(ENABLE_COMPLETION_TRACKING_SWITCH, True):
course = CourseFactory.create()
block = BlockFactory.create(category='comp', parent=course)
response = self.make_xblock_callback_response(
{}, course, block, 'progress'
)
assert response.status_code == 200
assert not BlockCompletion.objects.filter(block_key=block.scope_ids.usage_id).exists()
@XBlock.register_temp_plugin(XBlockWithoutCompletionAPI, identifier='no_comp')
def test_progress_signal_processed_for_xblock_without_completion_api(self):
with override_waffle_switch(ENABLE_COMPLETION_TRACKING_SWITCH, True):
course = CourseFactory.create()
block = BlockFactory.create(category='no_comp', parent=course)
response = self.make_xblock_callback_response(
{}, course, block, 'progress'
)
assert response.status_code == 200
completion = BlockCompletion.objects.get(block_key=block.scope_ids.usage_id)
assert completion.completion == 1.0
@XBlock.register_temp_plugin(StubCompletableXBlock, identifier='comp')
def test_skip_handlers_for_masquerading_staff(self):
with override_waffle_switch(ENABLE_COMPLETION_TRACKING_SWITCH, True):
course = CourseFactory.create()
block = BlockFactory.create(category='comp', parent=course)
request = self.request_factory.post(
'/',
data=json.dumps({'completion': 0.8}),
content_type='application/json',
)
request.user = self.mock_user
request.session = {}
request.user.real_user = GlobalStaffFactory.create()
request.user.real_user.masquerade_settings = CourseMasquerade(course.id, user_name="jem")
with patch('xmodule.services.is_masquerading_as_specific_student') as mock_masq:
mock_masq.return_value = True
response = render.handle_xblock_callback(
request,
str(course.id),
quote_slashes(str(block.scope_ids.usage_id)),
'complete',
'',
)
mock_masq.assert_called()
assert response.status_code == 200
with pytest.raises(BlockCompletion.DoesNotExist):
BlockCompletion.objects.get(block_key=block.scope_ids.usage_id)
@XBlock.register_temp_plugin(GradedStatelessXBlock, identifier='stateless_scorer')
@patch('xmodule.services.grades_signals.SCORE_PUBLISHED.send')
def test_anonymous_user_not_be_graded(self, mock_score_signal):
course = CourseFactory.create()
block_kwargs = {
'category': 'problem',
}
request = self.request_factory.get('/')
request.user = AnonymousUser()
block = BlockFactory.create(**block_kwargs)
render.handle_xblock_callback(
request,
str(course.id),
quote_slashes(str(block.location)),
'xmodule_handler',
'problem_check',
)
assert not mock_score_signal.called
@ddt.data(
# See seq_block.py for the definition of these handlers
('get_completion', True), # has the 'will_recheck_access' attribute set to True
('goto_position', False), # does not set it
)
@ddt.unpack
@patch('lms.djangoapps.courseware.block_render.get_block_for_descriptor', wraps=get_block_for_descriptor)
def test_will_recheck_access_handler_attribute(self, handler, will_recheck_access, mock_get_block):
"""Confirm that we pay attention to any 'will_recheck_access' attributes on handler methods"""
course = CourseFactory.create()
block_kwargs = {
'category': 'sequential',
'parent': course,
}
block = BlockFactory.create(**block_kwargs)
usage_id = str(block.location)
# Send no special parameters, which will be invalid, but we don't care
request = self.request_factory.post('/', data='{}', content_type='application/json')
request.user = self.mock_user
render.handle_xblock_callback(request, str(course.id), usage_id, handler)
assert mock_get_block.call_count == 2
assert mock_get_block.call_args[1]['will_recheck_access'] == will_recheck_access
@ddt.ddt
@patch.dict('django.conf.settings.FEATURES', {'ENABLE_XBLOCK_VIEW_ENDPOINT': True})
class TestXBlockView(SharedModuleStoreTestCase, LoginEnrollmentTestCase):
"""
Test the handle_xblock_callback function
"""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.course_key = ToyCourseFactory.create().id