-
Notifications
You must be signed in to change notification settings - Fork 227
Expand file tree
/
Copy pathtest_core.py
More file actions
1369 lines (1091 loc) · 50.9 KB
/
Copy pathtest_core.py
File metadata and controls
1369 lines (1091 loc) · 50.9 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
"""
Tests the fundamentals of XBlocks including - but not limited to -
metaclassing, field access, caching, serialization, and bulk saves.
"""
# Allow accessing protected members for testing purposes
# pylint: disable=protected-access
from datetime import datetime
import json
import re
import unittest
from unittest.mock import patch, MagicMock, Mock
import ddt
import pytest
from opaque_keys.edx.locator import LibraryUsageLocatorV2, LibraryLocatorV2
from webob import Response
from xblock.core import Blocklike, XBlock
from xblock.exceptions import (
XBlockSaveError,
KeyValueMultiSaveError,
JsonHandlerError,
DisallowedFileError,
FieldDataDeprecationWarning,
)
from xblock.fields import Dict, Float, Integer, List, Set, Field, Scope, ScopeIds, String
from xblock.field_data import FieldData, DictFieldData
from xblock.runtime import Runtime
from xblock.test.tools import (
WarningTestMixin,
TestRuntime,
)
def test_field_access():
class FieldTester(XBlock):
"""Test XBlock for field access testing"""
field_a = Integer(scope=Scope.settings)
field_b = Integer(scope=Scope.content, default=10)
field_c = Integer(scope=Scope.user_state, default=42)
float_a = Float(scope=Scope.settings, default=5.8)
float_b = Float(scope=Scope.settings)
field_data = DictFieldData({'field_a': 5, 'float_a': 6.1, 'field_x': 15})
field_tester = FieldTester(TestRuntime(services={'field-data': field_data}), scope_ids=Mock())
# Verify that the fields have been set
assert field_tester.field_a == 5
assert field_tester.field_b == 10
assert field_tester.field_c == 42
assert field_tester.float_a == 6.1
assert field_tester.float_b is None
assert not hasattr(field_tester, 'field_x')
# Set two of the fields.
field_tester.field_a = 20
field_tester.float_a = 20.5
# field_a should be updated in the cache, but /not/ in the underlying db.
assert field_tester.field_a == 20
assert field_tester.float_a == 20.5
assert field_data.get(field_tester, 'field_a') == 5
assert field_data.get(field_tester, 'float_a') == 6.1
# save the XBlock
field_tester.save()
# verify that the fields have been updated correctly
assert field_tester.field_a == 20
assert field_tester.float_a == 20.5
# Now, field_a should be updated in the underlying db
assert field_data.get(field_tester, 'field_a') == 20
assert field_data.get(field_tester, 'float_a') == 20.5
assert field_tester.field_b == 10
assert field_tester.field_c == 42
assert field_tester.float_b is None
# Deletes happen immediately (do not require a save)
del field_tester.field_a
del field_tester.float_a
# After delete, we should find default values in the cache
assert field_tester.field_a is None
assert field_tester.float_a == 5.8
# But the fields should not actually be present in the underlying kvstore
with pytest.raises(KeyError):
field_data.get(field_tester, 'field_a')
assert not field_data.has(field_tester, 'field_a')
with pytest.raises(KeyError):
field_data.get(field_tester, 'float_a')
assert not field_data.has(field_tester, 'float_a')
def test_list_field_access():
# Check that lists are correctly saved when not directly set
class FieldTester(XBlock):
"""Test XBlock for field access testing"""
field_a = List(scope=Scope.settings)
field_b = List(scope=Scope.content, default=[1, 2, 3])
field_c = List(scope=Scope.content, default=[4, 5, 6])
field_d = List(scope=Scope.settings)
field_data = DictFieldData({'field_a': [200], 'field_b': [11, 12, 13]})
field_tester = FieldTester(TestRuntime(services={'field-data': field_data}), scope_ids=Mock(spec=ScopeIds))
# Check initial values have been set properly
assert [200] == field_tester.field_a
assert [11, 12, 13] == field_tester.field_b
assert [4, 5, 6] == field_tester.field_c
assert [] == field_tester.field_d
# Update the fields
field_tester.field_a.append(1)
field_tester.field_b.append(14)
field_tester.field_c.append(7)
field_tester.field_d.append(1)
# The fields should be update in the cache, but /not/ in the underlying kvstore.
assert [200, 1] == field_tester.field_a
assert [11, 12, 13, 14] == field_tester.field_b
assert [4, 5, 6, 7] == field_tester.field_c
assert [1] == field_tester.field_d
# Examine model data directly
# Caveat: there's not a clean way to copy the originally provided values for `field_a` and `field_b`
# when we instantiate the XBlock. So, the values for those two in both `field_data` and `_field_data_cache`
# point at the same object. Thus, `field_a` and `field_b` actually have the correct values in
# `field_data` right now. `field_c` does not, because it has never been written to the `field_data`.
assert not field_data.has(field_tester, 'field_c')
assert not field_data.has(field_tester, 'field_d')
# save the XBlock
field_tester.save()
# verify that the fields have been updated correctly
assert [200, 1] == field_tester.field_a
assert [11, 12, 13, 14] == field_tester.field_b
assert [4, 5, 6, 7] == field_tester.field_c
assert [1] == field_tester.field_d
# Now, the fields should be updated in the underlying kvstore
assert [200, 1] == field_data.get(field_tester, 'field_a')
assert [11, 12, 13, 14] == field_data.get(field_tester, 'field_b')
assert [4, 5, 6, 7] == field_data.get(field_tester, 'field_c')
assert [1] == field_data.get(field_tester, 'field_d')
def test_set_field_access():
# Check that sets are correctly saved when not directly set
class FieldTester(XBlock):
"""Test XBlock for field access testing"""
field_a = Set(scope=Scope.settings)
field_b = Set(scope=Scope.content, default=[1, 2, 3])
field_c = Set(scope=Scope.content, default=[4, 5, 6])
field_d = Set(scope=Scope.settings)
field_tester = FieldTester(MagicMock(), DictFieldData({'field_a': [200], 'field_b': [11, 12, 13]}), Mock())
# Check initial values have been set properly
assert {200} == field_tester.field_a
assert {11, 12, 13} == field_tester.field_b
assert {4, 5, 6} == field_tester.field_c
assert set() == field_tester.field_d
# Update the fields
field_tester.field_a.add(1)
field_tester.field_b.add(14)
field_tester.field_c.remove(5)
field_tester.field_d.add(1)
# The fields should be update in the cache, but /not/ in the underlying kvstore.
assert {200, 1} == field_tester.field_a
assert {11, 12, 13, 14} == field_tester.field_b
assert {4, 6} == field_tester.field_c
assert {1} == field_tester.field_d
# Examine model data directly
# Caveat: there's not a clean way to copy the originally provided values for `field_a` and `field_b`
# when we instantiate the XBlock. So, the values for those two in both `_field_data` and `_field_data_cache`
# point at the same object. Thus, `field_a` and `field_b` actually have the correct values in
# `_field_data` right now. `field_c` does not, because it has never been written to the `_field_data`.
assert not field_tester._field_data.has(field_tester, 'field_c')
assert not field_tester._field_data.has(field_tester, 'field_d')
# save the XBlock
field_tester.save()
# verify that the fields have been updated correctly
assert {200, 1} == field_tester.field_a
assert {11, 12, 13, 14} == field_tester.field_b
assert {4, 6} == field_tester.field_c
assert {1} == field_tester.field_d
# Now, the fields should be updated in the underlying kvstore
assert {200, 1} == field_tester._field_data.get(field_tester, 'field_a')
assert {11, 12, 13, 14} == field_tester._field_data.get(field_tester, 'field_b')
assert {4, 6} == field_tester._field_data.get(field_tester, 'field_c')
assert {1} == field_tester._field_data.get(field_tester, 'field_d')
def test_shared_block_base_defaults():
"""
Test default values and static methods provided by the SharedBlockBase class.
"""
class DefaultsTester(XBlock):
pass
defaults_tester = DefaultsTester(
TestRuntime(services={'field-data': DictFieldData({})}),
scope_ids=Mock(spec=ScopeIds)
)
# Testing the default static method return values of SharedBlockBase
assert defaults_tester.get_resources_dir() == ''
assert defaults_tester.get_public_dir() == 'public'
assert defaults_tester.get_i18n_js_namespace() is None
class CustomizedValuesTester(XBlock):
resources_dir = 'custom_resource_dir'
public_dir = 'another_public_dir'
i18n_js_namespace = 'CustomizedValuesTesterI18N'
customized_values_tester = CustomizedValuesTester(
TestRuntime(services={'field-data': DictFieldData({})}),
scope_ids=Mock(spec=ScopeIds),
)
# Testing the customized static method return values of SharedBlockBase
assert customized_values_tester.get_resources_dir() == 'custom_resource_dir'
assert customized_values_tester.get_public_dir() == 'another_public_dir'
assert customized_values_tester.get_i18n_js_namespace() == 'CustomizedValuesTesterI18N'
def test_mutable_none_values():
# Check that fields with values intentionally set to None
# save properly.
class FieldTester(XBlock):
"""Test XBlock for field access testing"""
field_a = List(scope=Scope.settings)
field_b = List(scope=Scope.settings)
field_c = List(scope=Scope.content, default=None)
field_tester = FieldTester(
TestRuntime(services={'field-data': DictFieldData({'field_a': None})}),
scope_ids=Mock(spec=ScopeIds)
)
# Set fields b & c to None
field_tester.field_b = None
field_tester.field_c = None
# Save our changes
field_tester.save()
# Access the fields without modifying them. Want to call `__get__`, not `__set__`,
# because `__get__` marks only mutable fields as dirty.
_test_get = field_tester.field_a
_test_get = field_tester.field_b
_test_get = field_tester.field_c
# The previous accesses will mark the fields as dirty (via __get__)
assert len(field_tester._dirty_fields) == 3 # pylint: disable=W0212
# However, the fields should not ACTUALLY be marked as fields that need to be saved.
assert len(field_tester._get_fields_to_save()) == 0 # pylint: disable=W0212
def test_dict_field_access():
# Check that dicts are correctly saved when not directly set
class FieldTester(XBlock):
"""Test XBlock for field access testing"""
field_a = Dict(scope=Scope.settings)
field_b = Dict(scope=Scope.content, default={'a': 1, 'b': 2, 'c': 3})
field_c = Dict(scope=Scope.content, default={'a': 4, 'b': 5, 'c': 6})
field_d = Dict(scope=Scope.settings)
field_data = DictFieldData({
'field_a': {'a': 200},
'field_b': {'a': 11, 'b': 12, 'c': 13}
})
field_tester = FieldTester(
TestRuntime(services={'field-data': field_data}),
None,
Mock()
)
# Check initial values have been set properly
assert {'a': 200} == field_tester.field_a
assert {'a': 11, 'b': 12, 'c': 13} == field_tester.field_b
assert {'a': 4, 'b': 5, 'c': 6} == field_tester.field_c
assert {} == field_tester.field_d
# Update the fields
field_tester.field_a['a'] = 250
field_tester.field_b['d'] = 14
field_tester.field_c['a'] = 0
field_tester.field_d['new'] = 'value'
# The fields should be update in the cache, but /not/ in the underlying kvstore.
assert {'a': 250} == field_tester.field_a
assert {'a': 11, 'b': 12, 'c': 13, 'd': 14} == field_tester.field_b
assert {'a': 0, 'b': 5, 'c': 6} == field_tester.field_c
assert {'new': 'value'} == field_tester.field_d
# Examine model data directly
# Caveat: there's not a clean way to copy the originally provided values for `field_a` and `field_b`
# when we instantiate the XBlock. So, the values for those two in both `field_data` and `_field_data_cache`
# point at the same object. Thus, `field_a` and `field_b` actually have the correct values in
# `field_data` right now. `field_c` does not, because it has never been written to the `field_data`.
assert not field_data.has(field_tester, 'field_c')
assert not field_data.has(field_tester, 'field_d')
field_tester.save()
# verify that the fields have been updated correctly
assert {'a': 250} == field_tester.field_a
assert {'a': 11, 'b': 12, 'c': 13, 'd': 14} == field_tester.field_b
assert {'a': 0, 'b': 5, 'c': 6} == field_tester.field_c
assert {'new': 'value'} == field_tester.field_d
# Now, the fields should be updated in the underlying kvstore
assert {'a': 250} == field_data.get(field_tester, 'field_a')
assert {'a': 11, 'b': 12, 'c': 13, 'd': 14} == field_data.get(field_tester, 'field_b')
assert {'a': 0, 'b': 5, 'c': 6} == field_data.get(field_tester, 'field_c')
assert {'new': 'value'} == field_data.get(field_tester, 'field_d')
def test_default_values():
# Check that values that are deleted are restored to their default values
class FieldTester(XBlock):
"""Test XBlock for field access testing"""
dic1 = Dict(scope=Scope.settings)
dic2 = Dict(scope=Scope.content, default={'a': 1, 'b': 2, 'c': 3})
list1 = List(scope=Scope.settings)
list2 = List(scope=Scope.content, default=[1, 2, 3])
field_data = DictFieldData({'dic1': {'a': 200}, 'list1': ['a', 'b']})
field_tester = FieldTester(TestRuntime(services={'field-data': field_data}), scope_ids=Mock(spec=ScopeIds))
assert {'a': 200} == field_tester.dic1
assert {'a': 1, 'b': 2, 'c': 3} == field_tester.dic2
assert ['a', 'b'] == field_tester.list1
assert [1, 2, 3] == field_tester.list2
# Modify the fields & save
field_tester.dic1.popitem()
field_tester.dic2.clear()
field_tester.list1.pop()
field_tester.list2.remove(2)
field_tester.save()
# Test that after save, new values exist and fields are present in the underlying kvstore
assert {} == field_tester.dic1
assert {} == field_tester.dic2
assert ['a'] == field_tester.list1
assert [1, 3] == field_tester.list2
for fname in ['dic1', 'dic2', 'list1', 'list2']:
assert field_data.has(field_tester, fname)
# Now delete each field
del field_tester.dic1
del field_tester.dic2
del field_tester.list1
del field_tester.list2
# Test that default values return after a delete, but fields not actually
# in the underlying kvstore
# Defaults not explicitly set
assert {} == field_tester.dic1
assert [] == field_tester.list1
# Defaults explicitly set
assert {'a': 1, 'b': 2, 'c': 3} == field_tester.dic2
assert [1, 2, 3] == field_tester.list2
for fname in ['dic1', 'dic2', 'list1', 'list2']:
assert not field_data.has(field_tester, fname)
def test_json_field_access():
# Check that values are correctly converted to and from json in accessors.
class Date(Field):
"""Date needs to convert between JSON-compatible persistence and a datetime object"""
def from_json(self, value):
"""Convert a string representation of a date to a datetime object"""
return datetime.strptime(value, "%m/%d/%Y")
def to_json(self, value):
"""Convert a datetime object to a string"""
return value.strftime("%m/%d/%Y")
class FieldTester(Blocklike):
"""Toy class for field access testing"""
field_a = Date(scope=Scope.settings)
field_b = Date(scope=Scope.content, default=datetime(2013, 4, 1))
field_tester = FieldTester(
runtime=TestRuntime(services={'field-data': DictFieldData({})}),
scope_ids=MagicMock(spec=ScopeIds)
)
# Check initial values
assert field_tester.field_a is None
assert datetime(2013, 4, 1) == field_tester.field_b
# Test no default specified
field_tester.field_a = datetime(2013, 1, 2)
assert datetime(2013, 1, 2) == field_tester.field_a
del field_tester.field_a
assert field_tester.field_a is None
# Test default explicitly specified
field_tester.field_b = datetime(2013, 1, 2)
assert datetime(2013, 1, 2) == field_tester.field_b
del field_tester.field_b
assert datetime(2013, 4, 1) == field_tester.field_b
def test_defaults_not_shared():
class FieldTester(XBlock):
"""Toy class for field access testing"""
field_a = List(scope=Scope.settings)
field_tester_a = FieldTester(TestRuntime(services={'field-data': DictFieldData({})}), scope_ids=Mock(spec=ScopeIds))
field_tester_b = FieldTester(TestRuntime(services={'field-data': DictFieldData({})}), scope_ids=Mock(spec=ScopeIds))
field_tester_a.field_a.append(1)
assert [1] == field_tester_a.field_a
assert [] == field_tester_b.field_a
# Write out the data
field_tester_a.save()
# Double check that write didn't do something weird
assert [1] == field_tester_a.field_a
assert [] == field_tester_b.field_a
def test_object_identity():
# Check that values that are modified are what is returned
class FieldTester(Blocklike):
"""Toy class for field access testing"""
field_a = List(scope=Scope.settings)
def mock_default(block, name):
"""
Raising KeyError emulates no attribute found, which causes
proper default value to be used after field is deleted.
"""
raise KeyError
# Make sure that field_data always returns a different object
# each time it's actually queried, so that the caching is
# doing the work to maintain object identity.
field_data = MagicMock(spec=FieldData)
field_data.get = lambda block, name, default=None: [name]
field_data.default = mock_default
field_tester = FieldTester(
runtime=TestRuntime(services={'field-data': field_data}),
scope_ids=MagicMock(spec=ScopeIds)
)
value = field_tester.field_a
assert value == field_tester.field_a
# Changing the field in place matches a previously fetched value
field_tester.field_a.append(1)
assert value == field_tester.field_a
# Changing the previously-fetched value also changes the value returned by the field:
value.append(2)
assert value == field_tester.field_a
# Deletion restores the default value. In the case of a List with
# no default defined, this is the empty list.
del field_tester.field_a
assert [] == field_tester.field_a
def test_caching_is_per_instance():
# Test that values cached for one instance do not appear on another
class FieldTester(Blocklike):
"""Toy class for field access testing"""
field_a = List(scope=Scope.settings)
field_data = MagicMock(spec=FieldData)
field_data.get = lambda block, name, default=None: [name]
# Same field_data used in different objects should result
# in separately-cached values, so that changing a value
# in one instance doesn't affect values stored in others.
field_tester_a = FieldTester(
runtime=TestRuntime(services={'field-data': field_data}),
scope_ids=MagicMock(spec=ScopeIds)
)
field_tester_b = FieldTester(
runtime=TestRuntime(services={'field-data': field_data}),
scope_ids=MagicMock(spec=ScopeIds)
)
value = field_tester_a.field_a
assert value == field_tester_a.field_a
field_tester_a.field_a.append(1)
assert value == field_tester_a.field_a
assert value != field_tester_b.field_a
def test_field_serialization():
# Some Fields can define their own serialization mechanisms.
# This test ensures that we are using them properly.
class CustomField(Field):
"""
Specify a custom field that defines its own serialization
"""
def from_json(self, value):
return value['value']
def to_json(self, value):
return {'value': value}
class FieldTester(XBlock):
"""Test XBlock for field serialization testing"""
field = CustomField()
field_data = DictFieldData({
'field': {'value': 4}
})
field_tester = FieldTester(
TestRuntime(services={'field-data': field_data}),
None,
Mock(),
)
assert field_tester.field == 4
field_tester.field = 5
field_tester.save()
assert {'value': 5} == field_data.get(field_tester, 'field')
def test_class_tags():
xblock = XBlock(None, None, None)
assert xblock._class_tags == set() # pylint: disable=comparison-with-callable
class Sub1Block(XBlock):
"""Toy XBlock"""
sub1block = Sub1Block(None, None, None)
assert sub1block._class_tags == set() # pylint: disable=comparison-with-callable
@XBlock.tag("cat dog")
class Sub2Block(Sub1Block):
"""Toy XBlock"""
sub2block = Sub2Block(None, None, None)
assert sub2block._class_tags == {"cat", "dog"} # pylint: disable=comparison-with-callable
class Sub3Block(Sub2Block):
"""Toy XBlock"""
sub3block = Sub3Block(None, None, None)
assert sub3block._class_tags == {"cat", "dog"} # pylint: disable=comparison-with-callable
@XBlock.tag("mixin")
class MixinBlock(XBlock):
"""Toy XBlock"""
class Sub4Block(MixinBlock, Sub3Block):
"""Toy XBlock"""
sub4block = Sub4Block(None, None, None)
assert sub4block._class_tags == { # pylint: disable=comparison-with-callable
"cat", "dog", "mixin"
}
def test_loading_tagged_classes():
@XBlock.tag("thetag")
class HasTag1(XBlock):
"""Toy XBlock"""
class HasTag2(HasTag1):
"""Toy XBlock"""
class HasntTag(XBlock):
"""Toy XBlock"""
the_classes = [('hastag1', HasTag1), ('hastag2', HasTag2), ('hasnttag', HasntTag)]
tagged_classes = [('hastag1', HasTag1), ('hastag2', HasTag2)]
with patch('xblock.core.XBlock.load_classes', return_value=the_classes):
assert set(XBlock.load_tagged_classes('thetag')) == set(tagged_classes)
def setup_save_failure(set_many):
"""
Set up tests for when there's a save error in the underlying KeyValueStore
"""
field_data = MagicMock(spec=FieldData)
field_data.get = lambda block, name, default=None: 99
field_data.set_many = set_many
class FieldTester(XBlock):
"""
Test XBlock with three fields
"""
field_a = Integer(scope=Scope.settings)
field_b = Integer(scope=Scope.content, default=10)
field_c = Integer(scope=Scope.user_state, default=42)
field_tester = FieldTester(TestRuntime(services={'field-data': field_data}), scope_ids=Mock(spec=ScopeIds))
return field_tester
def test_xblock_save_one():
# Mimics a save failure when we only manage to save one of the values
def fake_set_many(block, update_dict):
"""Mock update method that throws a KeyValueMultiSaveError indicating
that only one field was correctly saved."""
raise KeyValueMultiSaveError([next(iter(update_dict))])
field_tester = setup_save_failure(fake_set_many)
field_tester.field_a = 20
field_tester.field_b = 40
field_tester.field_c = 60
with pytest.raises(XBlockSaveError) as save_error:
# This call should raise an XBlockSaveError
field_tester.save()
# Verify that the correct data is getting stored by the error
assert len(save_error.value.saved_fields) == 1
assert len(save_error.value.dirty_fields) == 2
def test_xblock_save_failure_none():
# Mimics a save failure when we don't manage to save any of the values
def fake_set_many(block, update_dict):
"""Mock update method that throws a KeyValueMultiSaveError indicating
that no fields were correctly saved."""
raise KeyValueMultiSaveError([])
field_tester = setup_save_failure(fake_set_many)
field_tester.field_a = 20
field_tester.field_b = 30
field_tester.field_c = 40
with pytest.raises(XBlockSaveError) as save_error:
# This call should raise an XBlockSaveError
field_tester.save()
# Verify that the correct data is getting stored by the error
assert len(save_error.value.saved_fields) == 0
assert len(save_error.value.dirty_fields) == 3
def test_xblock_write_then_delete():
# Tests that setting a field, then deleting it later, doesn't
# cause an erroneous write of the originally set value after
# a call to `XBlock.save`
class FieldTester(XBlock):
"""Test XBlock with two fields"""
field_a = Integer(scope=Scope.settings)
field_b = Integer(scope=Scope.content, default=10)
field_data = DictFieldData({'field_a': 5})
field_tester = FieldTester(TestRuntime(services={'field-data': field_data}), scope_ids=Mock(spec=ScopeIds))
# Verify that the fields have been set correctly
assert field_tester.field_a == 5
assert field_tester.field_b == 10
# Set the fields to new values
field_tester.field_a = 20
field_tester.field_b = 20
# Assert that we've correctly cached the value of both fields to the newly set values.
assert field_tester.field_a == 20
assert field_tester.field_b == 20
# Before saving, delete all the fields. Deletes are performed immediately for now,
# so the field should immediately not be present in the field_data after the delete.
# However, we copy the default values into the cache, so after the delete we expect the
# cached values to be the default values, but the fields to be removed from the field_data.
del field_tester.field_a
del field_tester.field_b
# Assert that we're now finding the right cached values - these should be the default values
# that the fields have from the class since we've performed a delete, and XBlock.__delete__
# inserts the default values into the cache as an optimization.
assert field_tester.field_a is None
assert field_tester.field_b == 10
# Perform explicit save
field_tester.save()
# Now that we've done the save, double-check that we still have the correct cached values (the defaults)
assert field_tester.field_a is None
assert field_tester.field_b == 10
# Additionally assert that in the model data, we don't have any values actually set for these fields.
# Basically, we want to ensure that the `save` didn't overwrite anything in the actual field_data
# Note this test directly accessess field_data and is thus somewhat fragile.
assert not field_data.has(field_tester, 'field_a')
assert not field_data.has(field_tester, 'field_b')
def test_get_mutable_mark_dirty():
"""
Ensure that accessing a mutable field type does not mark it dirty
if the field has never been set. If the field has been set, ensure
that it is set to dirty.
"""
class MutableTester(XBlock):
"""Test class with mutable fields."""
list_field = List(default=[])
mutable_test = MutableTester(TestRuntime(services={'field-data': DictFieldData({})}), scope_ids=Mock(spec=ScopeIds))
# Test get/set with a default value.
assert len(mutable_test._dirty_fields) == 0
_test_get = mutable_test.list_field
assert len(mutable_test._dirty_fields) == 1
mutable_test.list_field = []
assert len(mutable_test._dirty_fields) == 1
# Now test after having explicitly set the field.
mutable_test.save()
# _dirty_fields shouldn't be cleared here
assert len(mutable_test._dirty_fields) == 1
_test_get = mutable_test.list_field
assert len(mutable_test._dirty_fields) == 1
def test_change_mutable_default():
"""
Ensure that mutating the default value for a field causes
the changes to be saved, and doesn't corrupt other instances
"""
class MutableTester(XBlock):
"""Test class with mutable fields."""
list_field = List()
field_data_a = DictFieldData({})
mutable_test_a = MutableTester(TestRuntime(services={'field-data': field_data_a}), scope_ids=Mock(spec=ScopeIds))
field_data_b = DictFieldData({})
mutable_test_b = MutableTester(TestRuntime(services={'field-data': field_data_b}), scope_ids=Mock(spec=ScopeIds))
# Saving without changing the default value shouldn't write to field_data
mutable_test_a.list_field # pylint: disable=W0104
mutable_test_a.save()
with pytest.raises(KeyError):
field_data_a.get(mutable_test_a, 'list_field')
mutable_test_a.list_field.append(1)
mutable_test_a.save()
assert [1] == field_data_a.get(mutable_test_a, 'list_field')
with pytest.raises(KeyError):
field_data_b.get(mutable_test_b, 'list_field')
def test_handle_shortcut():
runtime = Mock(spec=['handle'])
scope_ids = Mock(spec=[])
request = Mock(spec=[])
block = XBlock(runtime, None, scope_ids)
block.handle('handler_name', request)
runtime.handle.assert_called_with(block, 'handler_name', request, '')
runtime.handle.reset_mock()
block.handle('handler_name', request, 'suffix')
runtime.handle.assert_called_with(block, 'handler_name', request, 'suffix')
def test_services_decorators():
class NoServicesBlock(XBlock):
"""XBlock requesting no services"""
no_services_block = NoServicesBlock(None, None, None)
assert not NoServicesBlock._services_requested
assert not no_services_block._services_requested
@XBlock.needs("n")
@XBlock.wants("w")
class ServiceUsingBlock(XBlock):
"""XBlock using some services."""
service_using_block = ServiceUsingBlock(None, scope_ids=Mock())
assert ServiceUsingBlock._services_requested == {
'n': 'need', 'w': 'want'
}
assert service_using_block._services_requested == { # pylint: disable=comparison-with-callable
'n': 'need', 'w': 'want'
}
def test_services_decorators_with_inheritance():
@XBlock.needs("n1")
@XBlock.wants("w1")
class ServiceUsingBlock(XBlock):
"""XBlock using some services."""
@XBlock.needs("n2")
@XBlock.wants("w2")
class SubServiceUsingBlock(ServiceUsingBlock):
"""Does this class properly inherit services from ServiceUsingBlock?"""
sub_service_using_block = SubServiceUsingBlock(None, scope_ids=Mock())
assert sub_service_using_block.service_declaration("n1") == "need"
assert sub_service_using_block.service_declaration("w1") == "want"
assert sub_service_using_block.service_declaration("n2") == "need"
assert sub_service_using_block.service_declaration("w2") == "want"
assert sub_service_using_block.service_declaration("field-data") == "need"
assert sub_service_using_block.service_declaration("xx") is None
def test_cached_parent():
class HasParent(XBlock):
"""
Dummy empty class
"""
runtime = TestRuntime(services={'field-data': DictFieldData({})})
runtime.get_block = Mock()
block = HasParent(runtime, scope_ids=Mock(spec=ScopeIds))
# block has no parent yet, and we don't need to call the runtime to find
# that out.
assert block.get_parent() is None
assert not runtime.get_block.called
# Set a parent id for the block. Get the parent. Now we have one, and we
# used runtime.get_block to get it.
block.parent = "some_parent_id"
parent = block.get_parent()
assert parent is not None
assert runtime.get_block.called
# Get the parent again. It will be the same parent, and we didn't call the
# runtime.
runtime.get_block.reset_mock()
parent2 = block.get_parent()
assert parent2 is parent
assert not runtime.get_block.called
def test_json_handler_basic():
test_self = Mock()
test_data = {"foo": "bar", "baz": "quux"}
test_data_json = ['{"foo": "bar", "baz": "quux"}', '{"baz": "quux", "foo": "bar"}']
test_suffix = "suff"
test_request = Mock(method="POST", body=test_data_json[0].encode('utf-8'))
@XBlock.json_handler
def test_func(self, request, suffix):
assert self == test_self
assert request == test_data
assert suffix == test_suffix
return request
response = test_func(test_self, test_request, test_suffix)
assert response.status_code == 200
assert response.body.decode('utf-8') in test_data_json
assert response.content_type == "application/json"
def test_json_handler_invalid_json():
test_request = Mock(method="POST", body=b"{")
@XBlock.json_handler
def test_func(self, request, suffix): # pylint: disable=unused-argument
return {}
response = test_func(Mock(), test_request, "dummy_suffix")
# pylint: disable=no-member
assert response.status_code == 400
assert json.loads(response.body.decode('utf-8')) == {"error": "Invalid JSON"}
assert response.content_type == "application/json"
def test_json_handler_get():
test_request = Mock(method="GET")
@XBlock.json_handler
def test_func(self, request, suffix): # pylint: disable=unused-argument
return {}
response = test_func(Mock(), test_request, "dummy_suffix")
# pylint: disable=no-member
assert response.status_code == 405
assert json.loads(response.body.decode('utf-8')) == {"error": "Method must be POST"}
assert list(response.allow) == ["POST"]
def test_json_handler_empty_request():
test_request = Mock(method="POST", body=b"")
@XBlock.json_handler
def test_func(self, request, suffix): # pylint: disable=unused-argument
return {}
response = test_func(Mock(), test_request, "dummy_suffix")
# pylint: disable=no-member
assert response.status_code == 400
assert json.loads(response.body.decode('utf-8')) == {"error": "Invalid JSON"}
assert response.content_type == "application/json"
def test_json_handler_error():
test_status_code = 418
test_message = "I'm a teapot"
test_request = Mock(method="POST", body=b"{}")
@XBlock.json_handler
def test_func(self, request, suffix):
raise JsonHandlerError(test_status_code, test_message)
response = test_func(Mock(), test_request, "dummy_suffix")
assert response.status_code == test_status_code
assert json.loads(response.body.decode('utf-8')) == {"error": test_message}
assert response.content_type == "application/json"
def test_json_handler_return_response():
test_request = Mock(method="POST", body=b"{}")
@XBlock.json_handler
def test_func(self, request, suffix): # pylint: disable=unused-argument
return Response(body="not JSON", status=418, content_type="text/plain")
response = test_func(Mock(), test_request, "dummy_suffix")
assert response.ubody == "not JSON"
assert response.status_code == 418
assert response.content_type == "text/plain"
def test_json_handler_return_unicode():
test_request = Mock(method="POST", body=b'["foo", "bar"]')
@XBlock.json_handler
def test_func(self, request, suffix): # pylint: disable=unused-argument
return Response(request=request)
response = test_func(Mock(), test_request, "dummy_suffix")
for request_part in response.request: # pylint: disable=not-an-iterable
assert isinstance(request_part, str)
@ddt.ddt
class OpenLocalResourceTest(unittest.TestCase):
"""Tests of `open_local_resource`."""
class LoadableXBlock(XBlock):
"""Just something to load resources from."""
class UnloadableXBlock(XBlock):
"""Just something to load resources from."""
resources_dir = None
def stub_open_resource(self, uri):
"""Act like xblock.core.Blocklike._open_resource, for testing."""
return "!" + uri + "!"
@ddt.data(
"public/hey.js",
"public/sub/hey.js",
"public/js/vendor/jNotify.jQuery.min.js",
"public/something.foo", # Unknown file extension is fine
"public/a/long/PATH/no-problem=here$123.ext",
"public/\N{SNOWMAN}.js",
)
def test_open_good_local_resource(self, uri):
loadable = self.LoadableXBlock(None, scope_ids=Mock())
with patch('xblock.core.Blocklike._open_resource', self.stub_open_resource):
assert loadable.open_local_resource(uri) == "!" + uri + "!"
assert loadable.open_local_resource(uri.encode('utf-8')) == "!" + uri + "!"
@ddt.data(
b"public/hey.js",
b"public/sub/hey.js",
b"public/js/vendor/jNotify.jQuery.min.js",
b"public/something.foo", # Unknown file extension is fine
b"public/a/long/PATH/no-problem=here$123.ext",
"public/\N{SNOWMAN}.js".encode(),
)
def test_open_good_local_resource_binary(self, uri):
loadable = self.LoadableXBlock(None, scope_ids=Mock())
with patch('xblock.core.Blocklike._open_resource', self.stub_open_resource):
assert loadable.open_local_resource(uri) == "!" + uri.decode('utf-8') + "!"
@ddt.data(
"public/../secret.js",
"public/.git/secret.js",
"static/secret.js",
"../public/no-no.bad",
"image.png",