This repository has been archived by the owner on Jul 13, 2022. It is now read-only.
/
xblock_module.py
1613 lines (1308 loc) · 64.1 KB
/
xblock_module.py
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
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Functional tests for modules/upload/upload.py."""
__author__ = 'jorr@google.com (John Orr)'
from cStringIO import StringIO
import os
import re
import urllib
import urlparse
from xml.etree import cElementTree
from controllers import sites
from controllers import utils
import html5lib
from models import config
from models import courses
from models import transforms
import models.models as m_models
from modules.xblock_module import dbmodels
from modules.xblock_module import xblock_module
from tools.etl import etl
import xblock
from xblock import fragment
from tests.functional import actions
from tests.functional import test_classes
from google.appengine.api import files
from google.appengine.api import namespace_manager
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import ndb
THUMBS_ENTRY_POINT = 'thumbs = thumbs:ThumbsBlock'
def insert_thumbs_block():
rt = xblock_module.Runtime(MockHandler(), is_admin=True)
usage_id = parse_xml_string(rt, '<thumbs/>')
data = {'description': 'an xblock', 'usage_id': usage_id}
root_usage = xblock_module.RootUsageDto(None, data)
return xblock_module.RootUsageDao.save(root_usage)
def parse_html_string(html_doc):
parser = html5lib.HTMLParser(
tree=html5lib.treebuilders.getTreeBuilder('etree', cElementTree),
namespaceHTMLElements=False)
return parser.parse(html_doc)
@ndb.toplevel
def parse_xml_string(rt, xml_str, dry_run=False):
return rt.parse_xml_string(xml_str, None, dry_run=dry_run)
class MockHandler(object):
def canonicalize_url(self, location):
return '/new_course' + location
class TestBase(actions.TestBase):
def setUp(self):
super(TestBase, self).setUp()
# Whitelist the thumbs block for testing
if THUMBS_ENTRY_POINT not in xblock_module.XBLOCK_WHITELIST:
xblock_module.XBLOCK_WHITELIST.append(THUMBS_ENTRY_POINT)
def tearDown(self):
if THUMBS_ENTRY_POINT in xblock_module.XBLOCK_WHITELIST:
xblock_module.XBLOCK_WHITELIST.remove(THUMBS_ENTRY_POINT)
xblock.core.XBlock._plugin_cache = None # pylint: disable=protected-access
super(TestBase, self).tearDown()
class DataMigrationTests(TestBase):
"""Functional tests for data migration with import and ETL."""
def setUp(self):
super(DataMigrationTests, self).setUp()
self.old_namespace = namespace_manager.get_namespace()
def tearDown(self):
namespace_manager.set_namespace(self.old_namespace)
super(DataMigrationTests, self).tearDown()
def test_course_import(self):
"""Confirm course import preserves XBlock data."""
sites.setup_courses('course:/a::ns_a, course:/b::ns_b, course:/:/')
app_context_a, app_context_b, _ = sites.get_all_courses()
course_b = courses.Course(None, app_context=app_context_b)
# Switch to Course A and insert a CB XBlock usage
namespace_manager.set_namespace('ns_a')
rt = xblock_module.Runtime(MockHandler(), is_admin=True)
usage_id = parse_xml_string(rt, '<html>Text</html>')
data = {'description': 'an xblock', 'usage_id': usage_id}
root_usage = xblock_module.RootUsageDto(None, data)
key = xblock_module.RootUsageDao.save(root_usage)
# Switch to Course B and import
namespace_manager.set_namespace('ns_b')
self.assertEqual(0, len(xblock_module.RootUsageDao.get_all()))
errors = []
course_b.import_from(app_context_a, errors)
if errors:
raise Exception(errors)
# Confirm the import worked
self.assertEqual(1, len(xblock_module.RootUsageDao.get_all()))
root_usage = xblock_module.RootUsageDao.load(key)
rt = xblock_module.Runtime(MockHandler())
block = rt.get_block(root_usage.usage_id)
self.assertEqual('html', block.xml_element_name())
self.assertEqual('Text', block.content)
def test_etl_roundtrip(self):
"""Confirm that XBlock data can be exported and imported with ETL."""
sites.setup_courses('course:/a::ns_a, course:/b::ns_b, course:/:/')
# Switch to Course A and insert a CB XBlock usage
namespace_manager.set_namespace('ns_a')
rt = xblock_module.Runtime(MockHandler(), is_admin=True)
usage_id = parse_xml_string(rt, '<html>Text</html>')
data = {'description': 'an xblock', 'usage_id': usage_id}
root_usage = xblock_module.RootUsageDto(None, data)
key = xblock_module.RootUsageDao.save(root_usage)
# Switch to Course B and confirm there's no XBlock data yet
namespace_manager.set_namespace('ns_b')
self.assertEqual(0, len(xblock_module.RootUsageDao.get_all()))
# Download course data from Course A with ETL
archive_path = os.path.join(self.test_tempdir, 'archive.zip')
args = etl.PARSER.parse_args([
etl._MODE_DOWNLOAD, etl._TYPE_COURSE, # pylint: disable=protected-access
'--archive_path', archive_path, '/a', 'mycourse', 'localhost:8080'])
etl.main(args, environment_class=test_classes.FakeEnvironment)
# Upload the archive zip file into Course B with ETL
args = etl.PARSER.parse_args([
etl._MODE_UPLOAD, etl._TYPE_COURSE, # pylint: disable=protected-access
'--archive_path', archive_path, '/b', 'mycourse', 'localhost:8080'])
etl.main(args, environment_class=test_classes.FakeEnvironment)
# Confirm the XBlock data was migrated correctly
self.assertEqual(1, len(xblock_module.RootUsageDao.get_all()))
root_usage = xblock_module.RootUsageDao.load(key)
rt = xblock_module.Runtime(MockHandler())
block = rt.get_block(root_usage.usage_id)
self.assertEqual('html', block.xml_element_name())
self.assertEqual('Text', block.content)
class KeyValueEntitySanitizationTests(TestBase):
""" Tests that ETL's data sanitization methods are implemented correctly."""
def get_key(self, scope, user_id, block_scope_id, field_name):
xblock_key = xblock.runtime.KeyValueStore.Key(
scope=scope,
user_id=user_id,
block_scope_id=block_scope_id,
field_name=field_name)
key_str = xblock_module.store.key_string(xblock_key)
db_key = db.Key.from_path('KeyValueEntity', key_str)
return db_key
def transform(self, x):
return 'tr_' + x
def test_safe_key_transforms_keys_with_user_id(self):
orig_key = self.get_key(
xblock.fields.Scope.user_state, '1234567890',
'0d40c9be8e254416b4782bf8e19a538f', 'my_field')
safe_key = dbmodels.KeyValueEntity.safe_key(orig_key, self.transform)
self.assertEquals(
'usage.0d40c9be8e254416b4782bf8e19a538f.tr_1234567890.my_field',
safe_key.name())
def test_safe_key_does_not_transform_keys_without_user_id(self):
orig_key = self.get_key(
xblock.fields.Scope.content, None,
'0d40c9be8e254416b4782bf8e19a538f', 'my_field')
safe_key = dbmodels.KeyValueEntity.safe_key(orig_key, self.transform)
self.assertEquals(
'definition.0d40c9be8e254416b4782bf8e19a538f.my_field',
safe_key.name())
def test_safe_key_rejects_malformed_keys(self):
# Key is not an xblock key
bad_key = db.Key.from_path('KeyValueEntity', 'totally_bad_key')
with self.assertRaises(AssertionError):
safe_key = dbmodels.KeyValueEntity.safe_key(bad_key, self.transform)
# Key has too few components
bad_key = db.Key.from_path(
'KeyValueEntity',
'usage.0d40c9be8e254416b4782bf8e19a538f')
with self.assertRaises(AssertionError):
safe_key = dbmodels.KeyValueEntity.safe_key(bad_key, self.transform)
# Key has too many components
bad_key = db.Key.from_path(
'KeyValueEntity',
'usage.0d40c9be8e254416b4782bf8e19a538f.1234567890.my_field.goes_on')
with self.assertRaises(AssertionError):
safe_key = dbmodels.KeyValueEntity.safe_key(bad_key, self.transform)
# Key has unrecognized first component
bad_key = db.Key.from_path(
'KeyValueEntity',
'unrecognized.0d40c9be8e254416b4782bf8e19a538f.1234567890.my_field')
with self.assertRaises(AssertionError):
safe_key = dbmodels.KeyValueEntity.safe_key(bad_key, self.transform)
# Key has unrecognized second component (not a hex string)
bad_key = db.Key.from_path(
'KeyValueEntity',
'usage.not_hex_string.1234567890.my_field')
with self.assertRaises(AssertionError):
safe_key = dbmodels.KeyValueEntity.safe_key(bad_key, self.transform)
# Key has unrecognized second component (hex string, but not 32 chars)
bad_key = db.Key.from_path(
'KeyValueEntity',
'usage.0123456789abcdef0123456789abcde.1234567890.my_field')
with self.assertRaises(AssertionError):
safe_key = dbmodels.KeyValueEntity.safe_key(bad_key, self.transform)
def test_for_export_transforms_value_for_student_data(self):
key = self.get_key(
xblock.fields.Scope.user_state, '1234567890',
'0d40c9be8e254416b4782bf8e19a538f', 'my_field')
orig_model = dbmodels.KeyValueEntity(key=key, data='{"value": 1}')
safe_model = orig_model.for_export(self.transform)
self.assertEquals('tr_{"value": 1}', safe_model.data)
def test_for_export_does_not_transform_value_for_non_student_data(self):
key = self.get_key(
xblock.fields.Scope.content, None,
'0d40c9be8e254416b4782bf8e19a538f', 'my_field')
orig_model = dbmodels.KeyValueEntity(key=key, data='{"value": 1}')
safe_model = orig_model.for_export(self.transform)
self.assertEquals('{"value": 1}', safe_model.data)
def test_for_export_rejects_entity_with_bad_key(self):
# Key has too few components
bad_key = db.Key.from_path(
'KeyValueEntity',
'usage.0d40c9be8e254416b4782bf8e19a538f')
orig_model = dbmodels.KeyValueEntity(key=bad_key, data='{"value": 1}')
with self.assertRaises(AssertionError):
safe_model = orig_model.for_export(self.transform)
class EventEntitySanitizationTests(TestBase):
"""Tests that ETL's data sanitization methods are implemented correctly."""
def transform(self, x):
return 'tr_' + x
def test_non_xblock_events_are_unaffected(self):
orig_event = m_models.EventEntity(
key=db.Key.from_path('EventEntity', 23),
source='some-event',
user_id='1234567890',
data='something happened')
safe_event = orig_event.for_export(self.transform)
self.assertEquals('something happened', safe_event.data)
def test_whitelisted_xblock_events_are_unaffected(self):
orig_event = m_models.EventEntity(
key=db.Key.from_path('EventEntity', 23),
source='xblock-event',
user_id='1234567890',
data=transforms.dumps({
'usage': '0123456789abcdef0123456789abcdef',
'type': 'sequential',
'event': {'position': 1}}))
safe_event = orig_event.for_export(self.transform)
safe_data = transforms.loads(safe_event.data)
self.assertEquals('0123456789abcdef0123456789abcdef', safe_data['usage'])
self.assertEquals('sequential', safe_data['type'])
self.assertEquals({'position': 1}, safe_data['event'])
def test_non_whitelisted_xblock_events_are_transformed(self):
orig_event = m_models.EventEntity(
key=db.Key.from_path('EventEntity', 23),
source='xblock-event',
user_id='1234567890',
data=transforms.dumps({
'usage': '0123456789abcdef0123456789abcdef',
'type': 'problem',
'event': {'value': 1}}))
safe_event = orig_event.for_export(self.transform)
safe_data = transforms.loads(safe_event.data)
self.assertEquals('0123456789abcdef0123456789abcdef', safe_data['usage'])
self.assertEquals('problem', safe_data['type'])
self.assertEquals('tr_{"value": 1}', safe_data['event'])
def test_tag_xblock_events_are_sanitized(self):
orig_event = m_models.EventEntity(
key=db.Key.from_path('EventEntity', 23),
source='tag-xblock-event',
user_id='1234567890',
data=transforms.dumps({
'event': 'xblock-problem',
'message': 'Problem Checked',
'location': 'http://my.app/new_course/unit?unit=1&lesson=3',
'data': {
'problem_id': 'X',
'answers': 'input_X_2_1=1'}}))
safe_event = orig_event.for_export(self.transform)
safe_data = transforms.loads(safe_event.data)
self.assertEquals(safe_data, {
'event': 'xblock-problem',
'message': 'tr_Problem Checked',
'location': 'http://my.app/new_course/unit?unit=1&lesson=3',
'data': 'tr_{"problem_id": "X", "answers": "input_X_2_1=1"}'})
class RuntimeTestCase(TestBase):
"""Functional tests for the XBlock runtime."""
def test_runtime_exports_blocks_with_ids(self):
"""The XBlock runtime should include block ids in XML exports."""
rt = xblock_module.Runtime(MockHandler(), is_admin=True)
usage_id = parse_xml_string(rt, '<html>text</html>')
xml = '<html usage_id="%s">text</html>' % usage_id
block = rt.get_block(usage_id)
xml_buffer = StringIO()
rt.export_to_xml(block, xml_buffer)
self.assertIn(xml, xml_buffer.getvalue())
def test_runtime_updates_blocks_with_ids(self):
"""The workbench should update blocks in place when they have ids."""
rt = xblock_module.Runtime(MockHandler(), is_admin=True)
usage_id = parse_xml_string(rt, '<html>foo</html>')
self.assertEqual('foo', rt.get_block(usage_id).content)
xml = '<html usage_id="%s">bar</html>' % usage_id
new_usage_id = parse_xml_string(rt, xml)
self.assertEqual(usage_id, new_usage_id)
self.assertEqual('bar', rt.get_block(usage_id).content)
def test_runtime_removes_orphaned_blocks_on_update(self):
"""Remove a child on block update and see it removed in datastore."""
block_with_child_xml = """
<vertical usage_id="vertical_id">
<html usage_id="html_id">text</html>
</vertical>"""
block_without_child_xml = """
<vertical usage_id="vertical_id">
</vertical>"""
rt = xblock_module.Runtime(MockHandler(), is_admin=True)
parse_xml_string(rt, block_with_child_xml)
vertical = rt.get_block('vertical_id')
self.assertEqual(1, len(vertical.children))
# Merge in same vertical, with html block deleted and check it is
# deleted from the block tree
rt = xblock_module.Runtime(MockHandler(), is_admin=True)
parse_xml_string(rt, block_without_child_xml)
vertical = rt.get_block('vertical_id')
self.assertEqual(0, len(vertical.children))
# However the html block is not deleted from the datastore, just
# unlinked from the content tree.
html = rt.get_block('html_id')
self.assertEqual('html', html.xml_element_name())
self.assertEqual('text', html.content)
def test_runtime_should_import_blocks_with_specified_ids(self):
"""The workbench shouild create a new block with a given id."""
rt = xblock_module.Runtime(MockHandler(), is_admin=True)
parse_xml_string(rt, '<html usage_id="my_usage_id">foo</html>')
block = rt.get_block('my_usage_id')
self.assertEqual('html', block.xml_element_name())
self.assertEqual('foo', block.content)
def test_rendered_blocks_have_js_dependencies_included(self):
rt = xblock_module.Runtime(MockHandler(), is_admin=True)
usage_id = parse_xml_string(rt, '<thumbs/>')
rt = xblock_module.Runtime(MockHandler(), student_id='s23')
block = rt.get_block(usage_id)
frag = rt.render(block, 'student_view')
self.assertIn('js/vendor/jquery.min.js', frag.foot_html())
self.assertIn('js/vendor/jquery.cookie.js', frag.foot_html())
self.assertIn('js/runtime/1.js', frag.foot_html())
def test_handler_url(self):
xsrf_token = utils.XsrfTokenManager.create_xsrf_token(
xblock_module.XBLOCK_XSRF_TOKEN_NAME)
rt = xblock_module.Runtime(MockHandler(), is_admin=True)
usage_id = parse_xml_string(rt, '<thumbs/>')
rt = xblock_module.Runtime(MockHandler(), student_id='s23')
block = rt.get_block(usage_id)
url = urlparse.urlparse(rt.handler_url(block, 'vote'))
self.assertEqual('/new_course/modules/xblock_module/handler', url.path)
query = urlparse.parse_qs(url.query)
self.assertEqual(block.scope_ids.usage_id, query['usage'][0])
self.assertEqual('vote', query['handler'][0])
self.assertEqual(xsrf_token, query['xsrf_token'][0])
def test_runtime_prevents_student_writes_to_non_student_fields(self):
rt = xblock_module.Runtime(MockHandler(), is_admin=True)
usage_id = parse_xml_string(rt, '<html>Test</html>')
# Load the block in student role
rt = xblock_module.Runtime(MockHandler(), student_id='s23')
block = rt.get_block(usage_id)
self.assertEqual('Test', block.content)
block.content = 'Something else'
try:
block.save()
self.fail('Expected InvalidScopeError')
except xblock.exceptions.InvalidScopeError:
pass # Expected exception
# Load the block in admin role
rt = xblock_module.Runtime(MockHandler(), is_admin=True)
block = rt.get_block(usage_id)
block.content = 'Something else'
block.save() # No exception
def test_runtime_prevents_loading_of_non_whitelisted_blocks(self):
rt = xblock_module.Runtime(MockHandler(), is_admin=True)
# Loading thumbs block succeeds when it is whitelisted
unused_usage_id = parse_xml_string(rt, '<thumbs/>')
# Loading thumbs block fails when it is not whitelisted
xblock_module.XBLOCK_WHITELIST.remove(THUMBS_ENTRY_POINT)
xblock.core.XBlock._plugin_cache = None # pylint: disable=protected-access
try:
unused_usage_id = parse_xml_string(rt, '<thumbs/>')
self.fail('Expected ForbiddenXBlockError')
except xblock_module.ForbiddenXBlockError:
pass # Expected exception
def test_publish_logs_events(self):
student_id = 'the_student'
rt = xblock_module.Runtime(
MockHandler(), student_id=student_id, is_admin=True)
usage_id = parse_xml_string(rt, '<html>Test</html>')
block = rt.get_block(usage_id)
xblock_event_data = {'data': 1234}
rt.publish(block, xblock_event_data)
expected_event_data = {
'usage': usage_id,
'type': 'html',
'event': xblock_event_data}
event = m_models.EventEntity.all().fetch(1)[0]
self.assertEqual(student_id, event.user_id)
self.assertEqual('xblock-event', event.source)
self.assertEqual(expected_event_data, transforms.loads(event.data))
def test_publish_does_not_log_events_when_tag_events_disabled(self):
try:
config.Registry.test_overrides[
utils.CAN_PERSIST_TAG_EVENTS.name] = False
student_id = 'the_student'
rt = xblock_module.Runtime(
MockHandler(), student_id=student_id, is_admin=True)
usage_id = parse_xml_string(rt, '<html>Test</html>')
block = rt.get_block(usage_id)
xblock_event_data = {'data': 1234}
rt.publish(block, xblock_event_data)
events = m_models.EventEntity.all().fetch(1)
self.assertEqual(0, len(events))
finally:
config.Registry.test_overrides[
utils.CAN_PERSIST_TAG_EVENTS.name] = True
class XBlockActionHandlerTestCase(TestBase):
"""Functional tests for the XBlock callback handler."""
def test_post(self):
actions.login('user@example.com')
rt = xblock_module.Runtime(MockHandler(), is_admin=True)
usage_id = parse_xml_string(rt, '<thumbs/>')
self.assertEqual(0, rt.get_block(usage_id).upvotes)
xsrf_token = utils.XsrfTokenManager.create_xsrf_token(
xblock_module.XBLOCK_XSRF_TOKEN_NAME)
params = {
'usage': usage_id,
'handler': 'vote',
'xsrf_token': xsrf_token}
response = self.post(
'%s?%s' % (xblock_module.HANDLER_URI, urllib.urlencode(params)),
'{"voteType":"up"}', {})
self.assertEqual('{"down": 0, "up": 1}', response.body)
self.assertEqual(1, rt.get_block(usage_id).upvotes)
def test_post_bad_xsrf_rejected(self):
"""Callbacks with bad XSRF token should be rejected."""
actions.login('user@example.com')
rt = xblock_module.Runtime(MockHandler(), is_admin=True)
usage_id = parse_xml_string(rt, '<thumbs/>')
params = {
'usage': usage_id,
'handler': 'vote',
'xsrf_token': 'bad_token'}
response = self.testapp.post(
'%s?%s' % (xblock_module.HANDLER_URI, urllib.urlencode(params)),
'{"vote_type":"up"}', {},
expect_errors=True)
self.assertEqual(400, response.status_int)
class GuestUserTestCase(TestBase):
"""Functional tests for the handling of logged-in and guest users."""
def setUp(self):
super(GuestUserTestCase, self).setUp()
actions.login('user@example.com', is_admin=True)
config.Registry.test_overrides[utils.CAN_PERSIST_TAG_EVENTS.name] = True
# Create a course in namespace "test"
sites.setup_courses('course:/test::ns_test, course:/:/')
self.old_namespace = namespace_manager.get_namespace()
namespace_manager.set_namespace('ns_test')
actions.login('admin@example.com', is_admin=True)
# Add an xblock containing a seqeunce of html blocks
rt = xblock_module.Runtime(MockHandler(), is_admin=True)
self.usage_id = parse_xml_string(
rt, '<sequential><html>1</html><html>2</html></sequential>')
data = {'description': 'an xblock', 'usage_id': self.usage_id}
root_usage = xblock_module.RootUsageDto(None, data)
root_usage_id = xblock_module.RootUsageDao.save(root_usage)
# Add a unit and a lesson to the course
app_context = sites.get_all_courses()[0]
self.course = courses.Course(None, app_context=app_context)
self.unit = self.course.add_unit()
self.unit.now_available = True
self.lesson = self.course.add_lesson(self.unit)
# The lesson displays the xblock
self.lesson.now_available = True
self.lesson.objectives = '<xblock root_id="%s"/>' % root_usage_id
# Make the course available.
self.get_environ_old = sites.ApplicationContext.get_environ
def get_environ_new(cxt):
environ = self.get_environ_old(cxt)
environ['course']['now_available'] = True
return environ
sites.ApplicationContext.get_environ = get_environ_new
self.course.save()
# Ensure the user is logged out
actions.logout()
def tearDown(self):
namespace_manager.set_namespace(self.old_namespace)
sites.ApplicationContext.get_environ = self.get_environ_old
super(GuestUserTestCase, self).tearDown()
def _get_xblock_in_lesson(self):
lesson_uri = '/test/unit?unit=%s&lesson=%s' % (
self.unit.unit_id, self.lesson.lesson_id)
response = self.get(lesson_uri)
root = parse_html_string(response.body)
sequence_elt = root.find(
'.//*[@class="gcb-lesson-content"]/div/div/div[@class="xblock"]')
self.assertEqual('sequential', sequence_elt.attrib['data-block-type'])
self.assertEqual(self.usage_id, sequence_elt.attrib['data-usage'])
return sequence_elt
def _post_tab_position(self, xsrf_token, position):
params = {
'usage': self.usage_id,
'handler': 'on_select',
'xsrf_token': xsrf_token}
response = self.testapp.post(
'/test%s?%s' % (
xblock_module.HANDLER_URI, urllib.urlencode(params)),
'{"position":%s}' % position, {})
self.assertEqual('{"position": %s}' % position, response.body)
def _extract_position(self, sequence_elt):
return int(sequence_elt.find(
'./div[@class="sequence_block"]').attrib['data-position'])
def assert_guest_user(self):
# The guest user can view the page
sequence_elt = self._get_xblock_in_lesson()
xsrf_token = sequence_elt.attrib['data-xsrf-token']
self.assertEqual(0, self._extract_position(sequence_elt))
# The response has a coookie with a temporary user id
session_cookie = self.testapp.cookies['cb-guest-session']
self.assertRegexpMatches(session_cookie, r'^[0-9a-f]{32}$')
# Click on the second tab
self._post_tab_position(xsrf_token, 1)
# Cookie hasn't changed
self.assertEqual(
session_cookie, self.testapp.cookies['cb-guest-session'])
# Reload the page, and expect that the selected tab will have changed
sequence_elt = self._get_xblock_in_lesson()
self.assertEqual(1, self._extract_position(sequence_elt))
# There was an event recorded
student_id = 'guest-%s' % session_cookie
event = m_models.EventEntity.all().fetch(1)[0]
self.assertEqual(student_id, event.user_id)
# The state is stored under temp student_id
rt = xblock_module.Runtime(MockHandler(), student_id=student_id)
self.assertEqual(1, rt.get_block(self.usage_id).position)
def test_user_not_in_session_is_guest_user(self):
self.assertIsNone(users.get_current_user())
self.assert_guest_user()
def test_unregistered_user_in_session_is_guest_user(self):
actions.login('user@example.com')
self.assert_guest_user()
def test_registered_user_is_not_guest(self):
actions.login('user@example.com')
m_models.Student.add_new_student_for_current_user('User', None)
student_id = users.get_current_user().user_id()
self.assertIsNotNone(student_id)
# The user can view the page
sequence_elt = self._get_xblock_in_lesson()
xsrf_token = sequence_elt.attrib['data-xsrf-token']
self.assertEqual(0, self._extract_position(sequence_elt))
# The response has no session cookie
self.assertNotIn('cb-guest-session', self.testapp.cookies)
# Click on the second tab
self._post_tab_position(xsrf_token, 1)
# Still no session cookie
self.assertNotIn('cb-guest-session', self.testapp.cookies)
# Reload the page, and expect that the selected tab will have changed
sequence_elt = self._get_xblock_in_lesson()
self.assertEqual(1, self._extract_position(sequence_elt))
# There was an event recorded
event = m_models.EventEntity.all().fetch(1)[0]
self.assertEqual(student_id, event.user_id)
# The state is stored under student_id
rt = xblock_module.Runtime(MockHandler(), student_id=student_id)
self.assertEqual(1, rt.get_block(self.usage_id).position)
class RootUsageTestCase(TestBase):
"""Functional tests for the root usage DAO and DTO."""
def test_root_usage_properties(self):
data = {'description': 'an xblock', 'usage_id': '123'}
root_usage = xblock_module.RootUsageDto(None, data)
self.assertEqual('an xblock', root_usage.description)
self.assertEqual('123', root_usage.usage_id)
def test_root_usage_crud(self):
data = {'description': 'an xblock', 'usage_id': '123'}
root_usage = xblock_module.RootUsageDto(None, data)
root_usage_id = xblock_module.RootUsageDao.save(root_usage)
self.assertTrue(root_usage_id is not None)
root_usage = xblock_module.RootUsageDto(root_usage_id, None)
root_usage = xblock_module.RootUsageDao.load(root_usage_id)
self.assertEqual(data, root_usage.dict)
xblock_module.RootUsageDao.delete(root_usage)
root_usage = xblock_module.RootUsageDao.load(root_usage_id)
self.assertIsNone(root_usage)
class XBlockEditorTestCase(TestBase):
"""Functional tests for the XBlock editor in the dashboard."""
def setUp(self):
super(XBlockEditorTestCase, self).setUp()
self.base = '/test'
sites.setup_courses('course:/test::ns_test, course:/:/')
self.old_namespace = namespace_manager.get_namespace()
namespace_manager.set_namespace('ns_test')
actions.login('admin@example.com', is_admin=True)
def tearDown(self):
namespace_manager.set_namespace(self.old_namespace)
super(XBlockEditorTestCase, self).tearDown()
def test_xblock_section_present_in_assets(self):
response = self.get('dashboard?action=assets')
self.assertIn('<h3>XBlocks</h3>', response.body)
self.assertNotIn('an xblock', response.body)
insert_thumbs_block()
response = self.get('dashboard?action=assets')
self.assertIn('an xblock', response.body)
def test_add_xblock_editor_present(self):
response = self.get('dashboard?action=assets')
self.assertIn(
'href="dashboard?action=add_xblock">Add XBlock</a>', response.body)
response = self.get('dashboard?action=add_xblock')
self.assertIn('Add XBlock', response.body)
def test_import_xblock_button(self):
"""Import button present if class empty, absent if it has content."""
def get_import_button():
root = parse_html_string(self.get('dashboard?action=assets').body)
return root.find('.//*[@id="gcb-main-content"]/a[1]')
button = get_import_button()
self.assertEquals('Import', button.text)
self.assertEquals(
'dashboard?action=import_xblock', button.attrib['href'])
# Add some content to the class. Import should not appear now.
app_context = sites.get_all_courses()[0]
course = courses.Course(None, app_context=app_context)
unused_unit = course.add_unit()
course.save()
button = get_import_button()
self.assertEquals('Merge', button.text)
self.assertEquals(
'dashboard?action=import_xblock', button.attrib['href'])
def test_edit_xblock_editor_present(self):
root_usage_id = insert_thumbs_block()
editor_url = 'dashboard?action=edit_xblock&key=%s' % root_usage_id
response = self.get('dashboard?action=assets')
self.assertIn('href="%s">[Edit]</a>' % editor_url, response.body)
response = self.get(editor_url)
self.assertIn('Edit XBlock', response.body)
def test_editor_and_import_unavailable_when_module_disabled(self):
xblock_module.custom_module.disable()
response = self.get('dashboard?action=assets')
self.assertNotIn('<h3>XBlocks</h3>', response.body)
self.assertNotIn(
'href="dashboard?action=add_xblock">Add XBlock</a>', response.body)
self.assertNotIn(
'href="dashboard?action=import_xblock">Import</a>', response.body)
self.assertNotIn('dashboard?action=edit_xblock', response.body)
xblock_module.custom_module.enable()
class XBlockEditorRESTHandlerTestCase(TestBase):
"""Functional tests for the dashboard XBlock editor's REST handler."""
def setUp(self):
super(XBlockEditorRESTHandlerTestCase, self).setUp()
actions.login('admin@example.com', is_admin=True)
self.xsrf_token = utils.XsrfTokenManager.create_xsrf_token(
xblock_module.XBlockEditorRESTHandler.XSRF_TOKEN)
@classmethod
def get_request(
cls, xsrf_token, description='html block',
xml='<html>test html</html>'):
request = {
'key': '',
'payload': transforms.dumps({
'xml': xml,
'description': description}),
'xsrf_token': xsrf_token}
return {'request': transforms.dumps(request)}
def get_xsrf_token(self):
return utils.XsrfTokenManager.create_xsrf_token(
xblock_module.XBlockEditorRESTHandler.XSRF_TOKEN)
def delete(self, url, **kwargs):
url = self.canonicalize(url)
response = self.testapp.delete(url, **kwargs)
return self.hook_response(response)
def test_get(self):
root_usage_id = insert_thumbs_block()
response = self.get('rest/xblock?key=%s' % root_usage_id)
resp_dict = transforms.loads(response.body)
self.assertEqual(200, resp_dict['status'])
self.assertEqual('Success', resp_dict['message'])
self.assertIsNotNone(resp_dict['xsrf_token'])
payload = transforms.loads(resp_dict['payload'])
self.assertEqual('an xblock', payload['description'])
self.assertIn('<thumbs usage_id=', payload['xml'])
def test_get_fails_without_login(self):
actions.logout()
root_usage_id = insert_thumbs_block()
response = self.get('rest/xblock?key=%s' % root_usage_id)
resp_dict = transforms.loads(response.body)
self.assertEqual(401, resp_dict['status'])
def test_put(self):
"""Test the happy case of PUT accepting and inserting XBlock XML."""
response = self.put('rest/xblock', self.get_request(self.xsrf_token))
resp_dict = transforms.loads(response.body)
self.assertEqual(200, resp_dict['status'])
self.assertEqual('Saved.', resp_dict['message'])
payload = transforms.loads(resp_dict['payload'])
root_usage_id = payload['key']
self.assertIsNotNone(root_usage_id)
# Confirm the block was stored
root_usage = xblock_module.RootUsageDao.load(root_usage_id)
block = xblock_module.Runtime(
MockHandler()).get_block(root_usage.usage_id)
self.assertEqual('test html', block.content)
def test_put_fails_with_bad_xsrf_token(self):
response = self.put('rest/xblock', self.get_request('bad_token'))
resp_dict = transforms.loads(response.body)
self.assertEqual(403, resp_dict['status'])
def test_put_fails_without_login(self):
actions.logout()
xsrf_token = self.get_xsrf_token()
response = self.put('rest/xblock', self.get_request(xsrf_token))
resp_dict = transforms.loads(response.body)
self.assertEqual(401, resp_dict['status'])
def test_put_fails_without_description(self):
response = self.put(
'rest/xblock', self.get_request(self.xsrf_token, description=''))
resp_dict = transforms.loads(response.body)
self.assertEqual(412, resp_dict['status'])
self.assertEqual('Missing description field', resp_dict['message'])
def test_put_fails_with_invalid_xml(self):
response = self.put(
'rest/xblock', self.get_request(self.xsrf_token, xml='<html'))
resp_dict = transforms.loads(response.body)
self.assertEqual(412, resp_dict['status'])
def test_put_fails_with_empty_xml(self):
response = self.put(
'rest/xblock', self.get_request(self.xsrf_token, xml=''))
resp_dict = transforms.loads(response.body)
self.assertEqual(412, resp_dict['status'])
def test_delete(self):
root_usage_id = insert_thumbs_block()
params = {
'xsrf_token': self.xsrf_token,
'key': root_usage_id}
response = self.delete('rest/xblock?%s' % urllib.urlencode(params))
resp_dict = transforms.loads(response.body)
self.assertEqual(200, resp_dict['status'])
self.assertEqual('Deleted.', resp_dict['message'])
# Confirm deletion took place
self.assertIsNone(xblock_module.RootUsageDao.load(root_usage_id))
def test_delete_fails_with_bad_xsrf_token(self):
root_usage_id = insert_thumbs_block()
params = {
'xsrf_token': 'bad_xsrf_token',
'key': root_usage_id}
response = self.delete('rest/xblock?%s' % urllib.urlencode(params))
resp_dict = transforms.loads(response.body)
self.assertEqual(403, resp_dict['status'])
def test_delete_fails_without_login(self):
actions.logout()
root_usage_id = insert_thumbs_block()
params = {
'xsrf_token': self.get_xsrf_token(),
'key': root_usage_id}
response = self.delete('rest/xblock?%s' % urllib.urlencode(params))
resp_dict = transforms.loads(response.body)
self.assertEqual(401, resp_dict['status'])
class XBlockArchiveRESTHandlerTestCase(TestBase):
"""Functional tests for the XBlock archive importer REST handler."""
def setUp(self):
super(XBlockArchiveRESTHandlerTestCase, self).setUp()
self.testbed.init_blobstore_stub()
self.testbed.init_files_stub()
self.base = '/test'
sites.setup_courses('course:/test::ns_test, course:/:/')
self.old_namespace = namespace_manager.get_namespace()
namespace_manager.set_namespace('ns_test')
actions.login('admin@example.com', is_admin=True)
self.xsrf_token = utils.XsrfTokenManager.create_xsrf_token(
xblock_module.XBlockArchiveRESTHandler.XSRF_TOKEN)
def tearDown(self):
namespace_manager.set_namespace(self.old_namespace)
super(XBlockArchiveRESTHandlerTestCase, self).tearDown()
def get_request(self, xsrf_token=None, upload=None, dry_run=False):
xsrf_token = xsrf_token or self.xsrf_token
filename = upload.filename if upload else ''
request = {
'key': '',
'payload': transforms.dumps({
'file': filename,
'dry_run': dry_run}),
'xsrf_token': xsrf_token}
return {
'request': transforms.dumps(request),
'file': upload}
def get_response_dict(self, response_str):
response_xml = cElementTree.XML(response_str)
response_dict = {}
for child in response_xml:
response_dict[child.tag] = child.text
return response_dict
def test_rest_handler_provides_upload_and_poller_url(self):
response = self.get('rest/xblock_archive')
resp_dict = transforms.loads(response.body)
self.assertEqual(200, resp_dict['status'])
payload = transforms.loads(resp_dict['payload'])
self.assertTrue(
payload['upload_url'].startswith('http://localhost/_ah/upload/'))
self.assertEquals(
'/test/rest/xblock_archive_progress', payload['poller_url'])
def test_post_fails_with_bad_xsrf_token(self):
response = self.post(
'rest/xblock_archive', self.get_request(xsrf_token='bad_token'))
resp_dict = transforms.loads(response.body)
self.assertEqual(403, resp_dict['status'])
def test_post_fails_without_login(self):
actions.logout()
response = self.post(
'rest/xblock_archive', self.get_request(), expect_errors=True)
self.assertEqual(404, response.status_int)
def test_post_fails_with_missing_attachment(self):
response = self.post('rest/xblock_archive', self.get_request())
resp_dict = self.get_response_dict(response.body)
self.assertEqual('403', resp_dict['status'])
self.assertEqual('No file specified.', resp_dict['message'])
def test_post_fails_with_malformed_tar_gz_file(self):
blob_key = self._store_in_blobstore('abc')
app_context = sites.get_app_context_for_namespace('ns_test')
job = xblock_module.XBlockArchiveJob(app_context, blob_key=blob_key)
resp_dict = job.run()
self.assertFalse(resp_dict['success'])
self.assertIn('Unable to read the archive file', resp_dict['message'])