-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Expand file tree
/
Copy pathtest_contentstore.py
More file actions
2191 lines (1785 loc) · 96 KB
/
test_contentstore.py
File metadata and controls
2191 lines (1785 loc) · 96 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
# lint-amnesty, pylint: disable=missing-module-docstring
# TODO: Rewrite several of these assertions so that they check the output of the REST or Python
# APIs rather than parsing HTML from the deprecated legacy frontend pages. In particular, any
# test case using override_waffle_flag(toggles.LEGACY_STUDIO_*, True) will need to be fixed.
# Part of https://github.com/openedx/edx-platform/issues/36275.
import copy
import re
import shutil
from datetime import timedelta
from functools import wraps
from json import loads
from textwrap import dedent
from unittest import SkipTest, mock
from uuid import uuid4
import ddt
from django.conf import settings
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
from edx_toggles.toggles.testutils import override_waffle_flag, override_waffle_switch
from edxval.api import create_video, get_videos_for_course
from fs.osfs import OSFS
from lxml import etree
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import AssetKey, CourseKey, UsageKey
from opaque_keys.edx.locations import CourseLocator
from path import Path as path
from cms.djangoapps.contentstore import toggles
from cms.djangoapps.contentstore.config import waffle
from cms.djangoapps.contentstore.tests.utils import AjaxEnabledTestClient, CourseTestCase, get_url, parse_json
from cms.djangoapps.contentstore.utils import delete_course, reverse_course_url, reverse_url
from cms.djangoapps.contentstore.views.component import ADVANCED_COMPONENT_TYPES
from common.djangoapps.course_action_state.managers import CourseActionStateItemNotFoundError
from common.djangoapps.course_action_state.models import CourseRerunState, CourseRerunUIStateManager
from common.djangoapps.student import auth
from common.djangoapps.student.models import CourseEnrollment
from common.djangoapps.student.roles import CourseCreatorRole, CourseInstructorRole
from openedx.core.djangoapps.django_comment_common.utils import are_permissions_roles_seeded
from openedx.core.lib.tempdir import mkdtemp_clean
from xmodule.capa_block import ProblemBlock
from xmodule.contentstore.content import StaticContent
from xmodule.contentstore.django import contentstore
from xmodule.contentstore.utils import empty_asset_trashcan, restore_asset_from_trashcan
from xmodule.course_block import CourseBlock, Textbook
from xmodule.exceptions import InvalidVersionError
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.exceptions import ItemNotFoundError
from xmodule.modulestore.inheritance import own_metadata
from xmodule.modulestore.split_mongo import BlockKey
from xmodule.modulestore.tests.django_utils import TEST_DATA_SPLIT_MODULESTORE
from xmodule.modulestore.tests.factories import BlockFactory, CourseFactory, check_mongo_calls
from xmodule.modulestore.xml_exporter import export_course_to_xml
from xmodule.modulestore.xml_importer import import_course_from_xml, perform_xlint
from xmodule.seq_block import SequenceBlock
from xmodule.video_block import VideoBlock
TEST_DATA_CONTENTSTORE = copy.deepcopy(settings.CONTENTSTORE)
TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex # noqa: UP031
TEST_DATA_DIR = settings.COMMON_TEST_DATA_ROOT
def requires_pillow_jpeg(func):
"""
A decorator to indicate that the function requires JPEG support for Pillow,
otherwise it cannot be run
"""
@wraps(func)
def decorated_func(*args, **kwargs):
"""
Execute the function if we have JPEG support in Pillow.
"""
try:
from PIL import Image
except ImportError:
raise SkipTest("Pillow is not installed (or not found)") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if not getattr(Image.core, "jpeg_decoder", False):
raise SkipTest("Pillow cannot open JPEG files")
return func(*args, **kwargs)
return decorated_func
@override_settings(CONTENTSTORE=TEST_DATA_CONTENTSTORE)
class ContentStoreTestCase(CourseTestCase):
"""
Base class for Content Store Test Cases
"""
MODULESTORE = TEST_DATA_SPLIT_MODULESTORE
class ImportRequiredTestCases(ContentStoreTestCase):
"""
Tests which legitimately need to import a course
"""
def test_no_static_link_rewrites_on_import(self):
course_items = import_course_from_xml(
self.store, self.user.id, TEST_DATA_DIR, ['toy'], create_if_not_present=True
)
course = course_items[0]
handouts_usage_key = course.id.make_usage_key('course_info', 'handouts')
handouts = self.store.get_item(handouts_usage_key)
self.assertIn('/static/', handouts.data) # noqa: PT009
handouts_usage_key = course.id.make_usage_key('html', 'toyhtml')
handouts = self.store.get_item(handouts_usage_key)
self.assertIn('/static/', handouts.data) # noqa: PT009
def test_xlint_fails(self):
err_cnt = perform_xlint(TEST_DATA_DIR, ['toy'])
self.assertGreater(err_cnt, 0) # noqa: PT009
def test_invalid_asset_overwrite(self):
"""
Tests that an asset with invalid displayname can be overwritten if multiple assets have same displayname.
It Verifies that:
During import, if ('/') or ('\') is present in displayname of an asset, it is replaced with underscores '_'.
Export does not fail when an asset has '/' in its displayname. If the converted display matches with
any other asset, then it will be replaced.
Asset name in XML: "/invalid\\displayname/subs-esLhHcdKGWvKs.srt"
"""
content_store = contentstore()
expected_displayname = '_invalid_displayname_subs-esLhHcdKGWvKs.srt'
import_course_from_xml(
self.store,
self.user.id,
TEST_DATA_DIR,
['import_draft_order'],
static_content_store=content_store,
verbose=True,
create_if_not_present=True
)
# Verify the course has imported successfully
course = self.store.get_course(self.store.make_course_key(
'test_org',
'import_draft_order',
'import_draft_order'
))
self.assertIsNotNone(course) # noqa: PT009
# Add a new asset in the course, and make sure to name it such that it overwrite the one existing
# asset in the course. (i.e. _invalid_displayname_subs-esLhHcdKGWvKs.srt)
asset_key = course.id.make_asset_key('asset', 'sample_asset.srt')
content = StaticContent(
asset_key, expected_displayname, 'application/text', b'test',
)
content_store.save(content)
# Get & verify that course actually has two assets
assets, count = content_store.get_all_content_for_course(course.id)
self.assertEqual(count, 2) # noqa: PT009
# Verify both assets have similar `displayname` after saving.
for asset in assets:
self.assertEqual(asset['displayname'], expected_displayname) # noqa: PT009
# Test course export does not fail
root_dir = path(mkdtemp_clean())
print(f'Exporting to tempdir = {root_dir}')
export_course_to_xml(self.store, content_store, course.id, root_dir, 'test_export')
filesystem = OSFS(str(root_dir / 'test_export/static'))
exported_static_files = filesystem.listdir('/')
# Verify that asset have been overwritten during export.
self.assertEqual(len(exported_static_files), 1) # noqa: PT009
self.assertTrue(filesystem.exists(expected_displayname)) # noqa: PT009
self.assertEqual(exported_static_files[0], expected_displayname) # noqa: PT009
# Remove exported course
shutil.rmtree(root_dir)
def test_about_overrides(self):
"""
This test case verifies that a course can use specialized override for about data,
e.g. /about/Fall_2012/effort.html
while there is a base definition in /about/effort.html
"""
course_items = import_course_from_xml(
self.store, self.user.id, TEST_DATA_DIR, ['toy'], create_if_not_present=True
)
course_key = course_items[0].id
effort = self.store.get_item(course_key.make_usage_key('about', 'effort'))
self.assertEqual(effort.data, '6 hours') # noqa: PT009
# this one should be in a non-override folder
effort = self.store.get_item(course_key.make_usage_key('about', 'end_date'))
self.assertEqual(effort.data, 'TBD') # noqa: PT009
@requires_pillow_jpeg
def test_asset_import(self):
"""
This test validates that an image asset is imported and a thumbnail was generated for a .gif
"""
content_store = contentstore()
import_course_from_xml(
self.store, self.user.id, TEST_DATA_DIR, ['toy'], static_content_store=content_store, verbose=True,
create_if_not_present=True
)
course = self.store.get_course(self.store.make_course_key('edX', 'toy', '2012_Fall'))
self.assertIsNotNone(course) # noqa: PT009
# make sure we have some assets in our contentstore
all_assets, __ = content_store.get_all_content_for_course(course.id)
self.assertGreater(len(all_assets), 0) # noqa: PT009
# make sure we have some thumbnails in our contentstore
all_thumbnails = content_store.get_all_content_thumbnails_for_course(course.id)
self.assertGreater(len(all_thumbnails), 0) # noqa: PT009
location = AssetKey.from_string('asset-v1:edX+toy+2012_Fall+type@asset+block@just_a_test.jpg')
content = content_store.find(location)
self.assertIsNotNone(content) # noqa: PT009
self.assertIsNotNone(content.thumbnail_location) # noqa: PT009
thumbnail = content_store.find(content.thumbnail_location)
self.assertIsNotNone(thumbnail) # noqa: PT009
def test_course_info_updates_import_export(self):
"""
Test that course info updates are imported and exported with all content fields ('data', 'items')
"""
content_store = contentstore()
data_dir = TEST_DATA_DIR
courses = import_course_from_xml(
self.store, self.user.id, data_dir, ['course_info_updates'],
static_content_store=content_store, verbose=True, create_if_not_present=True
)
course = courses[0]
self.assertIsNotNone(course) # noqa: PT009
course_updates = self.store.get_item(course.id.make_usage_key('course_info', 'updates'))
self.assertIsNotNone(course_updates) # noqa: PT009
# check that course which is imported has files 'updates.html' and 'updates.items.json'
filesystem = OSFS(str(data_dir + '/course_info_updates/info'))
self.assertTrue(filesystem.exists('updates.html')) # noqa: PT009
self.assertTrue(filesystem.exists('updates.items.json')) # noqa: PT009
# verify that course info update module has same data content as in data file from which it is imported
# check 'data' field content
with filesystem.open('updates.html', 'r') as course_policy:
on_disk = course_policy.read()
self.assertEqual(course_updates.data, on_disk) # noqa: PT009
# check 'items' field content
with filesystem.open('updates.items.json', 'r') as course_policy:
on_disk = loads(course_policy.read())
self.assertEqual(course_updates.items, on_disk) # noqa: PT009
# now export the course to a tempdir and test that it contains files 'updates.html' and 'updates.items.json'
# with same content as in course 'info' directory
root_dir = path(mkdtemp_clean())
print(f'Exporting to tempdir = {root_dir}')
export_course_to_xml(self.store, content_store, course.id, root_dir, 'test_export')
# check that exported course has files 'updates.html' and 'updates.items.json'
filesystem = OSFS(str(root_dir / 'test_export/info'))
self.assertTrue(filesystem.exists('updates.html')) # noqa: PT009
self.assertTrue(filesystem.exists('updates.items.json')) # noqa: PT009
# verify that exported course has same data content as in course_info_update module
with filesystem.open('updates.html', 'r') as grading_policy:
on_disk = grading_policy.read()
self.assertEqual(on_disk, course_updates.data) # noqa: PT009
with filesystem.open('updates.items.json', 'r') as grading_policy:
on_disk = loads(grading_policy.read())
self.assertEqual(on_disk, course_updates.items) # noqa: PT009
def test_rewrite_nonportable_links_on_import(self):
content_store = contentstore()
import_course_from_xml(
self.store, self.user.id, TEST_DATA_DIR, ['toy'],
static_content_store=content_store, create_if_not_present=True
)
# first check a static asset link
course_key = self.store.make_course_key('edX', 'toy', '2012_Fall')
html_block_location = course_key.make_usage_key('html', 'nonportable')
html_block = self.store.get_item(html_block_location)
self.assertIn('/static/foo.jpg', html_block.data) # noqa: PT009
# then check a intra courseware link
html_block_location = course_key.make_usage_key('html', 'nonportable_link')
html_block = self.store.get_item(html_block_location)
self.assertIn('/jump_to_id/nonportable_link', html_block.data) # noqa: PT009
def verify_content_existence(self, store, root_dir, course_id, dirname, category_name, filename_suffix=''): # lint-amnesty, pylint: disable=missing-function-docstring
filesystem = OSFS(root_dir / 'test_export')
self.assertTrue(filesystem.exists(dirname)) # noqa: PT009
items = store.get_items(course_id, qualifiers={'category': category_name})
for item in items:
filesystem = OSFS(root_dir / ('test_export/' + dirname))
self.assertTrue(filesystem.exists(item.location.block_id + filename_suffix)) # noqa: PT009
def test_export_course_with_metadata_only_video(self):
content_store = contentstore()
import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['toy'], create_if_not_present=True)
course_id = self.store.make_course_key('edX', 'toy', '2012_Fall')
# create a new video block and add it as a child to a vertical
# this re-creates a bug whereby since the video template doesn't have
# anything in 'data' field, the export was blowing up
verticals = self.store.get_items(course_id, qualifiers={'category': 'vertical'})
self.assertGreater(len(verticals), 0) # noqa: PT009
parent = verticals[0]
BlockFactory.create(parent_location=parent.location, category="video", display_name="untitled")
root_dir = path(mkdtemp_clean())
print(f'Exporting to tempdir = {root_dir}')
# export out to a tempdir
export_course_to_xml(self.store, content_store, course_id, root_dir, 'test_export')
shutil.rmtree(root_dir)
def test_export_course_with_metadata_only_word_cloud(self):
"""
Similar to `test_export_course_with_metadata_only_video`.
"""
content_store = contentstore()
import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['word_cloud'], create_if_not_present=True)
course_id = self.store.make_course_key('HarvardX', 'ER22x', '2013_Spring')
verticals = self.store.get_items(course_id, qualifiers={'category': 'vertical'})
self.assertGreater(len(verticals), 0) # noqa: PT009
parent = verticals[0]
BlockFactory.create(parent_location=parent.location, category="word_cloud", display_name="untitled")
root_dir = path(mkdtemp_clean())
print(f'Exporting to tempdir = {root_dir}')
# export out to a tempdir
export_course_to_xml(self.store, content_store, course_id, root_dir, 'test_export')
shutil.rmtree(root_dir)
def test_import_after_renaming_xml_data(self):
"""
Test that import works fine on split mongo after renaming the blocks url.
"""
split_store = modulestore()._get_modulestore_by_type(ModuleStoreEnum.Type.split) # pylint: disable=W0212
import_course_from_xml(
split_store, self.user.id, TEST_DATA_DIR,
['course_before_rename'],
create_if_not_present=True
)
course_after_rename = import_course_from_xml(
split_store, self.user.id, TEST_DATA_DIR,
['course_after_rename'],
create_if_not_present=True
)
all_items = split_store.get_items(course_after_rename[0].id, qualifiers={'category': 'chapter'})
renamed_chapter = [item for item in all_items if item.location.block_id == 'renamed_chapter'][0]
self.assertIsNotNone(renamed_chapter.published_on) # noqa: PT009
self.assertIsNotNone(renamed_chapter.parent) # noqa: PT009
self.assertIn(renamed_chapter.location, course_after_rename[0].children) # noqa: PT009
original_chapter = [item for item in all_items
if item.location.block_id == 'b9870b9af59841a49e6e02765d0e3bbf'][0]
self.assertIsNone(original_chapter.published_on) # noqa: PT009
self.assertIsNone(original_chapter.parent) # noqa: PT009
self.assertNotIn(original_chapter.location, course_after_rename[0].children) # noqa: PT009
def test_empty_data_roundtrip(self):
"""
Test that an empty `data` field is preserved through
export/import.
"""
content_store = contentstore()
import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['toy'], create_if_not_present=True)
course_id = self.store.make_course_key('edX', 'toy', '2012_Fall')
verticals = self.store.get_items(course_id, qualifiers={'category': 'vertical'})
self.assertGreater(len(verticals), 0) # noqa: PT009
parent = verticals[0]
# Create a block, and ensure that its `data` field is empty
word_cloud = BlockFactory.create(
parent_location=parent.location, category="word_cloud", display_name="untitled")
del word_cloud.data
self.assertEqual(word_cloud.data, '') # noqa: PT009
# Export the course
root_dir = path(mkdtemp_clean())
export_course_to_xml(self.store, content_store, course_id, root_dir, 'test_roundtrip')
# Reimport and get the video back
import_course_from_xml(self.store, self.user.id, root_dir)
imported_word_cloud = self.store.get_item(course_id.make_usage_key('word_cloud', 'untitled'))
# It should now contain empty data
self.assertEqual(imported_word_cloud.data, '') # noqa: PT009
def test_html_export_roundtrip(self):
"""
Test that a course which has HTML that has style formatting is preserved in export/import
"""
content_store = contentstore()
import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['toy'], create_if_not_present=True)
course_id = self.store.make_course_key('edX', 'toy', '2012_Fall')
# Export the course
root_dir = path(mkdtemp_clean())
export_course_to_xml(self.store, content_store, course_id, root_dir, 'test_roundtrip')
# Reimport and get the video back
import_course_from_xml(self.store, self.user.id, root_dir, create_if_not_present=True)
# get the sample HTML with styling information
html_block = self.store.get_item(course_id.make_usage_key('html', 'with_styling'))
self.assertIn('<p style="font:italic bold 72px/30px Georgia, serif; color: red; ">', html_block.data) # noqa: PT009 # pylint: disable=line-too-long
# get the sample HTML with just a simple <img> tag information
html_block = self.store.get_item(course_id.make_usage_key('html', 'just_img'))
self.assertIn('<img src="/static/foo_bar.jpg" />', html_block.data) # noqa: PT009
def test_export_course_without_content_store(self):
# Create toy course
course_items = import_course_from_xml(
self.store, self.user.id, TEST_DATA_DIR, ['toy'], create_if_not_present=True
)
course_id = course_items[0].id
root_dir = path(mkdtemp_clean())
print(f'Exporting to tempdir = {root_dir}')
export_course_to_xml(self.store, None, course_id, root_dir, 'test_export_no_content_store')
# Delete the course from module store and reimport it
self.store.delete_course(course_id, self.user.id)
import_course_from_xml(
self.store, self.user.id, root_dir, ['test_export_no_content_store'],
static_content_store=None,
target_id=course_id,
create_if_not_present=True
)
# Verify reimported course
items = self.store.get_items(
course_id,
qualifiers={
'name': 'vertical_sequential',
}
)
self.assertEqual(len(items), 1) # noqa: PT009
def test_export_course_no_xml_attributes(self):
"""
Test that a block without an `xml_attributes` attr will still be
exported successfully
"""
content_store = contentstore()
import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['toy'], create_if_not_present=True)
course_id = self.store.make_course_key('edX', 'toy', '2012_Fall')
verticals = self.store.get_items(course_id, qualifiers={'category': 'vertical'})
vertical = verticals[0]
# create OpenAssessmentBlock:
open_assessment = BlockFactory.create(
parent_location=vertical.location,
category="openassessment",
display_name="untitled",
)
# convert it to draft
draft_open_assessment = self.store.convert_to_draft(
open_assessment.location, self.user.id
)
# note that it has no `xml_attributes` attribute
self.assertFalse(hasattr(draft_open_assessment, "xml_attributes")) # noqa: PT009
# export should still complete successfully
root_dir = path(mkdtemp_clean())
export_course_to_xml(
self.store,
content_store,
course_id,
root_dir,
'test_no_xml_attributes'
)
@ddt.ddt
class MiscCourseTests(ContentStoreTestCase):
"""
Tests that rely on the toy courses.
"""
def setUp(self):
super().setUp()
# save locs not items b/c the items won't have the subsequently created children in them until refetched
self.chapter_loc = self.store.create_child(
self.user.id, self.course.location, 'chapter', 'test_chapter'
).location
self.seq_loc = self.store.create_child(
self.user.id, self.chapter_loc, 'sequential', 'test_seq'
).location
self.vert_loc = self.store.create_child(self.user.id, self.seq_loc, 'vertical', 'test_vert').location
# now create some things quasi like the toy course had
self.problem = self.store.create_child(
self.user.id, self.vert_loc, 'problem', 'test_problem', fields={
"data": "<problem>Test</problem>"
}
)
self.store.create_child(
self.user.id, self.vert_loc, 'video', fields={
"youtube_id_0_75": "JMD_ifUUfsU",
"youtube_id_1_0": "OEoXaMPEzfM",
"youtube_id_1_25": "AKqURZnYqpk",
"youtube_id_1_5": "DYpADpL7jAY",
"name": "sample_video",
}
)
self.store.create_child(
self.user.id, self.vert_loc, 'video', fields={
"youtube_id_0_75": "JMD_ifUUfsU",
"youtube_id_1_0": "OEoXaMPEzfM",
"youtube_id_1_25": "AKqURZnYqpk",
"youtube_id_1_5": "DYpADpL7jAY",
"name": "truncated_video",
"end_time": timedelta(hours=10),
}
)
self.store.create_child(
self.user.id, self.vert_loc, 'poll_question', fields={
"name": "T1_changemind_poll_foo_2",
"display_name": "Change your answer",
"question": "Have you changed your mind?",
"answers": [{"id": "yes", "text": "Yes"}, {"id": "no", "text": "No"}],
}
)
self.course = self.store.publish(self.course.location, self.user.id)
def check_components_on_page(self, component_types, expected_types):
"""
Ensure that the right types end up on the page.
component_types is the list of advanced components.
expected_types is the list of elements that should appear on the page.
expected_types and component_types should be similar, but not
exactly the same -- for example, 'video' in
component_types should cause 'Video' to be present.
"""
self.course.advanced_modules = component_types
self.store.update_item(self.course, self.user.id)
# just pick one vertical
resp = self.client.get_html(get_url('container_handler', self.vert_loc))
for expected in expected_types:
self.assertContains(resp, expected)
@override_waffle_flag(toggles.LEGACY_STUDIO_UNIT_EDITOR, True)
@ddt.data("<script>alert(1)</script>", "alert('hi')", "</script><script>alert(1)</script>")
def test_container_handler_xss_prevent(self, malicious_code):
"""
Test that XSS attack is prevented
"""
resp = self.client.get_html(get_url('container_handler', self.vert_loc) + '?action=' + malicious_code)
# Test that malicious code does not appear in html
self.assertNotContains(resp, malicious_code)
@override_waffle_flag(toggles.LEGACY_STUDIO_UNIT_EDITOR, True)
def test_advanced_components_in_edit_unit(self):
# This could be made better, but for now let's just assert that we see the advanced modules mentioned in the
# page response HTML
self.check_components_on_page(
ADVANCED_COMPONENT_TYPES,
['Word cloud', 'Annotation', 'split_test'],
)
@ddt.data('/Fake/asset/displayname', '\\Fake\\asset\\displayname')
def test_export_on_invalid_displayname(self, invalid_displayname):
""" Tests that assets with invalid 'displayname' does not cause export to fail """
content_store = contentstore()
exported_asset_name = '_Fake_asset_displayname'
# Create an asset with slash `invalid_displayname` '
asset_key = self.course.id.make_asset_key('asset', "fake_asset.txt")
content = StaticContent(
asset_key, invalid_displayname, 'application/text', b'test',
)
content_store.save(content)
# Verify that the course has only one asset and it has been added with an invalid asset name.
assets, count = content_store.get_all_content_for_course(self.course.id)
self.assertEqual(count, 1) # noqa: PT009
display_name = assets[0]['displayname']
self.assertEqual(display_name, invalid_displayname) # noqa: PT009
# Now export the course to a tempdir and test that it contains assets. The export should pass
root_dir = path(mkdtemp_clean())
print(f'Exporting to tempdir = {root_dir}')
export_course_to_xml(self.store, content_store, self.course.id, root_dir, 'test_export')
filesystem = OSFS(root_dir / 'test_export/static')
exported_static_files = filesystem.listdir('/')
# Verify that only single asset has been exported with the expected asset name.
self.assertTrue(filesystem.exists(exported_asset_name)) # noqa: PT009
self.assertEqual(len(exported_static_files), 1) # noqa: PT009
# Remove tempdir
shutil.rmtree(root_dir)
@mock.patch(
'lms.djangoapps.ccx.modulestore.CCXModulestoreWrapper.get_item',
mock.Mock(return_value=mock.Mock(children=[]))
)
def test_export_with_orphan_vertical(self):
"""
Tests that, export does not fail when a parent xblock does not have draft child xblock
information but the draft child xblock has parent information.
"""
# Make an existing unit a draft
self.problem = self.store.unpublish(self.problem.location, self.user.id)
root_dir = path(mkdtemp_clean())
export_course_to_xml(self.store, None, self.course.id, root_dir, 'test_export')
# Verify that problem is exported in the drafts. This is expected because we are
# mocking get_item to for drafts. Expect no draft is exported.
# Specifically get_item is used in `xmodule.modulestore.xml_exporter._export_drafts`
export_draft_dir = OSFS(root_dir / 'test_export/drafts')
self.assertEqual(len(export_draft_dir.listdir('/')), 0) # noqa: PT009
# Remove tempdir
shutil.rmtree(root_dir)
def test_assets_overwrite(self):
""" Tests that assets will similar 'displayname' will be overwritten during export """
content_store = contentstore()
asset_displayname = 'Fake_asset.txt'
# Create two assets with similar 'displayname'
for i in range(2):
asset_path = f'sample_asset_{i}.txt'
asset_key = self.course.id.make_asset_key('asset', asset_path)
content = StaticContent(
asset_key, asset_displayname, 'application/text', b'test',
)
content_store.save(content)
# Fetch & verify course assets to be equal to 2.
assets, count = content_store.get_all_content_for_course(self.course.id)
self.assertEqual(count, 2) # noqa: PT009
# Verify both assets have similar 'displayname' after saving.
for asset in assets:
self.assertEqual(asset['displayname'], asset_displayname) # noqa: PT009
# Now export the course to a tempdir and test that it contains assets.
root_dir = path(mkdtemp_clean())
print(f'Exporting to tempdir = {root_dir}')
export_course_to_xml(self.store, content_store, self.course.id, root_dir, 'test_export')
# Verify that asset have been overwritten during export.
filesystem = OSFS(root_dir / 'test_export/static')
exported_static_files = filesystem.listdir('/')
self.assertTrue(filesystem.exists(asset_displayname)) # noqa: PT009
self.assertEqual(len(exported_static_files), 1) # noqa: PT009
# Remove tempdir
shutil.rmtree(root_dir)
@override_waffle_flag(toggles.LEGACY_STUDIO_UNIT_EDITOR, True)
def test_advanced_components_require_two_clicks(self):
self.check_components_on_page(['word_cloud'], ['Word cloud'])
@override_waffle_flag(toggles.LEGACY_STUDIO_UNIT_EDITOR, True)
def test_edit_unit(self):
"""Verifies rendering the editor in all the verticals in the given test course"""
self._check_verticals([self.vert_loc])
def _get_draft_counts(self, item): # lint-amnesty, pylint: disable=missing-function-docstring
cnt = 1 if not self.store.has_published_version(item) else 0
for child in item.get_children():
cnt = cnt + self._get_draft_counts(child)
return cnt
def test_get_items(self):
"""
This verifies a bug we had where the None setting in get_items() meant 'wildcard'
Unfortunately, None = published for the revision field, so get_items() would return
both draft and non-draft copies.
"""
self.problem = self.store.unpublish(self.problem.location, self.user.id)
# Query get_items() and find the html item. This should just return back a single item (not 2).
direct_store_items = self.store.get_items(
self.course.id, revision=ModuleStoreEnum.RevisionOption.published_only
)
items_from_direct_store = [item for item in direct_store_items if item.location == self.problem.location]
self.assertEqual(len(items_from_direct_store), 0) # noqa: PT009
# Fetch from the draft store.
draft_store_items = self.store.get_items(
self.course.id, revision=ModuleStoreEnum.RevisionOption.draft_only
)
items_from_draft_store = [item for item in draft_store_items if item.location == self.problem.location]
self.assertEqual(len(items_from_draft_store), 1) # noqa: PT009
def test_draft_metadata(self):
"""
This verifies a bug we had where inherited metadata was getting written to the
block as 'own-metadata' when publishing. Also verifies the metadata inheritance is
properly computed
"""
# refetch course so it has all the children correct
course = self.store.update_item(self.course, self.user.id)
course.graceperiod = timedelta(days=1, hours=5, minutes=59, seconds=59)
course = self.store.update_item(course, self.user.id)
problem = self.store.get_item(self.problem.location)
self.assertEqual(problem.graceperiod, course.graceperiod) # noqa: PT009
self.assertNotIn('graceperiod', own_metadata(problem)) # noqa: PT009
self.store.convert_to_draft(problem.location, self.user.id)
# refetch to check metadata
problem = self.store.get_item(problem.location)
self.assertEqual(problem.graceperiod, course.graceperiod) # noqa: PT009
self.assertNotIn('graceperiod', own_metadata(problem)) # noqa: PT009
# publish block
self.store.publish(problem.location, self.user.id)
# refetch to check metadata
problem = self.store.get_item(problem.location)
self.assertEqual(problem.graceperiod, course.graceperiod) # noqa: PT009
self.assertNotIn('graceperiod', own_metadata(problem)) # noqa: PT009
# put back in draft and change metadata and see if it's now marked as 'own_metadata'
self.store.convert_to_draft(problem.location, self.user.id)
problem = self.store.get_item(problem.location)
new_graceperiod = timedelta(hours=1)
self.assertNotIn('graceperiod', own_metadata(problem)) # noqa: PT009
problem.graceperiod = new_graceperiod
# Save the data that we've just changed to the underlying
# MongoKeyValueStore before we update the mongo datastore.
problem.save()
self.assertIn('graceperiod', own_metadata(problem)) # noqa: PT009
self.assertEqual(problem.graceperiod, new_graceperiod) # noqa: PT009
self.store.update_item(problem, self.user.id)
# read back to make sure it reads as 'own-metadata'
problem = self.store.get_item(problem.location)
self.assertIn('graceperiod', own_metadata(problem)) # noqa: PT009
self.assertEqual(problem.graceperiod, new_graceperiod) # noqa: PT009
# republish
self.store.publish(problem.location, self.user.id)
# and re-read and verify 'own-metadata'
self.store.convert_to_draft(problem.location, self.user.id)
problem = self.store.get_item(problem.location)
self.assertIn('graceperiod', own_metadata(problem)) # noqa: PT009
self.assertEqual(problem.graceperiod, new_graceperiod) # noqa: PT009
def test_get_depth_with_drafts(self):
# make sure no draft items have been returned
num_drafts = self._get_draft_counts(self.course)
self.assertEqual(num_drafts, 0) # noqa: PT009
# put into draft
self.problem = self.store.unpublish(self.problem.location, self.user.id)
# make sure we can query that item and verify that it is a draft
draft_problem = self.store.get_item(self.problem.location)
self.assertEqual(self.store.has_published_version(draft_problem), False) # noqa: PT009
# now requery with depth
course = self.store.get_course(self.course.id, depth=None)
# make sure just one draft item have been returned
num_drafts = self._get_draft_counts(course)
self.assertEqual(num_drafts, 1) # noqa: PT009
@mock.patch('xmodule.course_block.requests.get')
def test_import_textbook_as_content_element(self, mock_get):
mock_get.return_value.text = dedent("""
<?xml version="1.0"?><table_of_contents>
<entry page="5" page_label="ii" name="Table of Contents"/>
</table_of_contents>
""").strip()
self.course.textbooks = [Textbook("Textbook", "https://s3.amazonaws.com/edx-textbooks/guttag_computation_v3/")]
course = self.store.update_item(self.course, self.user.id)
self.assertGreater(len(course.textbooks), 0) # noqa: PT009
def test_import_polls(self):
items = self.store.get_items(self.course.id, qualifiers={'category': 'poll_question'})
self.assertGreater(len(items), 0) # noqa: PT009
# check that there's actually content in the 'question' field
self.assertGreater(len(items[0].question), 0) # noqa: PT009
def test_module_preview_in_whitelist(self):
"""
Tests the ajax callback to render an XBlock
"""
with override_settings(COURSES_WITH_UNSAFE_CODE=[str(self.course.id)]):
# also try a custom response which will trigger the 'is this course in whitelist' logic
resp = self.client.get_json(
get_url('xblock_view_handler', self.vert_loc, kwargs={'view_name': 'container_preview'})
)
self.assertEqual(resp.status_code, 200) # noqa: PT009
vertical = self.store.get_item(self.vert_loc)
for child in vertical.children:
self.assertContains(resp, str(child))
def test_delete(self):
# make sure the parent points to the child object which is to be deleted
# need to refetch chapter b/c at the time it was assigned it had no children
chapter = self.store.get_item(self.chapter_loc)
self.assertIn(self.seq_loc, chapter.children) # noqa: PT009
self.client.delete(get_url('xblock_handler', self.seq_loc))
with self.assertRaises(ItemNotFoundError): # noqa: PT027
self.store.get_item(self.seq_loc)
chapter = self.store.get_item(self.chapter_loc)
# make sure the parent no longer points to the child object which was deleted
self.assertNotIn(self.seq_loc, chapter.children) # noqa: PT009
def test_asset_delete_and_restore(self):
"""
This test will exercise the soft delete/restore functionality of the assets
"""
asset_key = self._delete_asset_in_course()
# now try to find it in store, but they should not be there any longer
content = contentstore().find(asset_key, throw_on_not_found=False)
self.assertIsNone(content) # noqa: PT009
# now try to find it and the thumbnail in trashcan - should be in there
content = contentstore('trashcan').find(asset_key, throw_on_not_found=False)
self.assertIsNotNone(content) # noqa: PT009
# let's restore the asset
restore_asset_from_trashcan(str(asset_key))
# now try to find it in courseware store, and they should be back after restore
content = contentstore('trashcan').find(asset_key, throw_on_not_found=False)
self.assertIsNotNone(content) # noqa: PT009
def _delete_asset_in_course(self):
"""
Helper method for:
1) importing course from xml
2) finding asset in course (verifying non-empty)
3) computing thumbnail location of asset
4) deleting the asset from the course
"""
asset_key = self.course.id.make_asset_key('asset', 'sample_static.html')
content = StaticContent(
asset_key, "Fake asset", "application/text", b"test",
)
contentstore().save(content)
# go through the website to do the delete, since the soft-delete logic is in the view
url = reverse_course_url(
'assets_handler',
self.course.id,
kwargs={'asset_key_string': str(asset_key)}
)
resp = self.client.delete(url)
self.assertEqual(resp.status_code, 204) # noqa: PT009
return asset_key
def test_empty_trashcan(self):
"""
This test will exercise the emptying of the asset trashcan
"""
self._delete_asset_in_course()
# make sure there's something in the trashcan
all_assets, __ = contentstore('trashcan').get_all_content_for_course(self.course.id)
self.assertGreater(len(all_assets), 0) # noqa: PT009
# empty the trashcan
empty_asset_trashcan([self.course.id])
# make sure trashcan is empty
all_assets, count = contentstore('trashcan').get_all_content_for_course(self.course.id)
self.assertEqual(len(all_assets), 0) # noqa: PT009
self.assertEqual(count, 0) # noqa: PT009
def test_illegal_draft_crud_ops(self):
chapter = self.store.get_item(self.chapter_loc)
chapter.data = 'chapter data'
self.store.update_item(chapter, self.user.id)
with self.assertRaises(InvalidVersionError): # noqa: PT027
self.store.unpublish(self.chapter_loc, self.user.id)
def test_bad_contentstore_request(self):
"""
Test that user get proper responses for urls with invalid url or
asset/course key
"""
resp = self.client.get_html('asset-v1:CDX+123123+2012_Fall+type@asset+block@&invalid.png')
self.assertEqual(resp.status_code, 404) # noqa: PT009
resp = self.client.get_html('asset-v1:CDX+123123+2012_Fall+type@[email protected]')
self.assertEqual(resp.status_code, 404) # noqa: PT009
@override_waffle_switch(waffle.ENABLE_ACCESSIBILITY_POLICY_PAGE, active=False)
def test_disabled_accessibility_page(self):
"""
Test that accessibility page returns 404 when waffle switch is disabled
"""
resp = self.client.get_html('/accessibility')
self.assertEqual(resp.status_code, 404) # noqa: PT009
def test_delete_course(self):
"""
This test creates a course, makes a draft item, and deletes the course. This will also assert that the
draft content is also deleted
"""
# add an asset
asset_key = self.course.id.make_asset_key('asset', 'sample_static.html')
content = StaticContent(
asset_key, "Fake asset", "application/text", b"test",
)
contentstore().save(content)
assets, count = contentstore().get_all_content_for_course(self.course.id)
self.assertGreater(len(assets), 0) # noqa: PT009
self.assertGreater(count, 0) # noqa: PT009
self.store.unpublish(self.vert_loc, self.user.id)
# delete the course
self.store.delete_course(self.course.id, self.user.id)
# assert that there's absolutely no non-draft blocks in the course
# this should also include all draft items
with self.assertRaises(ItemNotFoundError): # noqa: PT027
self.store.get_items(self.course.id)
# assert that all content in the asset library is keeped
# in case the course is later restored.
assets, count = contentstore().get_all_content_for_course(self.course.id)
self.assertGreater(len(assets), 0) # noqa: PT009
self.assertGreater(count, 0) # noqa: PT009
def test_course_handouts_rewrites(self):
"""
Test that the xblock_handler rewrites static handout links
"""
handouts = self.store.create_item(
self.user.id, self.course.id, 'course_info', 'handouts', fields={
"data": "<a href='/static/handouts/sample_handout.txt'>Sample</a>",