forked from openedx/edx-platform
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtest_capa_block.py
3307 lines (2767 loc) · 140 KB
/
test_capa_block.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
"""
Tests of the Capa XModule
"""
# pylint: disable=invalid-name
import datetime
import json
import os
import random
import textwrap
import unittest
from unittest.mock import DEFAULT, Mock, patch, PropertyMock
import pytest
import ddt
import requests
import webob
from codejail.safe_exec import SafeExecException
from django.test import override_settings
from django.utils.encoding import smart_str
from lms.djangoapps.courseware.user_state_client import XBlockUserState
from lxml import etree
from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator
from pytz import UTC
from webob.multidict import MultiDict
from xblock.field_data import DictFieldData
from xblock.fields import ScopeIds
from xblock.scorable import Score
import xmodule
from xmodule.capa import responsetypes
from xmodule.capa.correctmap import CorrectMap
from xmodule.capa.responsetypes import LoncapaProblemError, ResponseError, StudentInputError
from xmodule.capa.xqueue_interface import XQueueInterface
from xmodule.capa_block import ComplexEncoder, ProblemBlock
from xmodule.tests import DATA_DIR
from ..capa_block import RANDOMIZATION, SHOWANSWER
from . import get_test_system
class CapaFactory:
"""
A helper class to create problem blocks with various parameters for testing.
"""
sample_problem_xml = textwrap.dedent("""\
<?xml version="1.0"?>
<problem>
<text>
<p>What is pi, to two decimal places?</p>
</text>
<numericalresponse answer="3.14">
<textline math="1" size="30"/>
</numericalresponse>
</problem>
""")
num = 0
@classmethod
def next_num(cls):
cls.num += 1
return cls.num
@classmethod
def input_key(cls, response_num=2, input_num=1):
"""
Return the input key to use when passing GET parameters
"""
return "input_" + cls.answer_key(response_num, input_num)
@classmethod
def answer_key(cls, response_num=2, input_num=1):
"""
Return the key stored in the capa problem answer dict
"""
return ("%s_%d_%d" % ("-".join(['i4x', 'edX', 'capa_test', 'problem', 'SampleProblem%d' % cls.num]),
response_num, input_num))
@classmethod
def create(cls, attempts=None, problem_state=None, correct=False, xml=None, override_get_score=True,
render_template=None, **kwargs):
"""
All parameters are optional, and are added to the created problem if specified.
Arguments:
graceperiod:
due:
max_attempts:
showanswer:
force_save_button:
rerandomize: all strings, as specified in the policy for the problem
problem_state: a dict to be serialized into the instance_state of the block.
attempts: also added to instance state. Will be converted to an int.
render_template: pass function or Mock for testing
"""
location = BlockUsageLocator(
CourseLocator("edX", "capa_test", "2012_Fall", deprecated=True),
"problem",
f"SampleProblem{cls.next_num()}",
deprecated=True,
)
if xml is None:
xml = cls.sample_problem_xml
field_data = {'data': xml}
field_data.update(kwargs)
if problem_state is not None:
field_data.update(problem_state)
if attempts is not None:
# converting to int here because I keep putting "0" and "1" in the tests
# since everything else is a string.
field_data['attempts'] = int(attempts)
system = get_test_system(
course_id=location.course_key,
user_is_staff=kwargs.get('user_is_staff', False),
render_template=render_template or Mock(return_value="<div>Test Template HTML</div>"),
)
block = ProblemBlock(
system,
DictFieldData(field_data),
ScopeIds(None, 'problem', location, location),
)
assert block.lcp
if override_get_score:
if correct:
# TODO: probably better to actually set the internal state properly, but...
block.score = Score(raw_earned=1, raw_possible=1)
else:
block.score = Score(raw_earned=0, raw_possible=1)
block.graded = 'False'
block.weight = 1
return block
class CapaFactoryWithFiles(CapaFactory):
"""
A factory for creating a Capa problem with files attached.
"""
sample_problem_xml = textwrap.dedent("""\
<problem>
<coderesponse queuename="BerkeleyX-cs188x">
<!-- actual filenames here don't matter for server-side tests,
they are only acted upon in the browser. -->
<filesubmission
points="25"
allowed_files="prog1.py prog2.py prog3.py"
required_files="prog1.py prog2.py prog3.py"
/>
<codeparam>
<answer_display>
If you're having trouble with this Project,
please refer to the Lecture Slides and attend office hours.
</answer_display>
<grader_payload>{"project": "p3"}</grader_payload>
</codeparam>
</coderesponse>
<customresponse>
<text>
If you worked with a partner, enter their username or email address. If you
worked alone, enter None.
</text>
<textline points="0" size="40" correct_answer="Your partner's username or 'None'"/>
<answer type="loncapa/python">
correct=['correct']
s = str(submission[0]).strip()
if submission[0] == '':
correct[0] = 'incorrect'
</answer>
</customresponse>
</problem>
""")
@ddt.ddt
class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=missing-class-docstring
def setUp(self):
super().setUp()
now = datetime.datetime.now(UTC)
day_delta = datetime.timedelta(days=1)
self.yesterday_str = str(now - day_delta)
self.today_str = str(now)
self.tomorrow_str = str(now + day_delta)
# in the capa grace period format, not in time delta format
self.two_day_delta_str = "2 days"
def test_import(self):
block = CapaFactory.create()
assert block.get_score().raw_earned == 0
other_block = CapaFactory.create()
assert block.get_score().raw_earned == 0
assert block.url_name != other_block.url_name, 'Factory should be creating unique names for each problem'
def test_correct(self):
"""
Check that the factory creates correct and incorrect problems properly.
"""
block = CapaFactory.create()
assert block.get_score().raw_earned == 0
other_block = CapaFactory.create(correct=True)
assert other_block.get_score().raw_earned == 1
def test_get_score(self):
"""
Tests the internals of get_score. In keeping with the ScorableXBlock spec,
Capa blocks store their score independently of the LCP internals, so it must
be explicitly updated.
"""
student_answers = {'1_2_1': 'abcd'}
correct_map = CorrectMap(answer_id='1_2_1', correctness="correct", npoints=0.9)
block = CapaFactory.create(correct=True, override_get_score=False)
block.lcp.correct_map = correct_map
block.lcp.student_answers = student_answers
assert block.get_score().raw_earned == 0.0
block.set_score(block.score_from_lcp(block.lcp))
assert block.get_score().raw_earned == 0.9
other_correct_map = CorrectMap(answer_id='1_2_1', correctness="incorrect", npoints=0.1)
other_block = CapaFactory.create(correct=False, override_get_score=False)
other_block.lcp.correct_map = other_correct_map
other_block.lcp.student_answers = student_answers
assert other_block.get_score().raw_earned == 0.0
other_block.set_score(other_block.score_from_lcp(other_block.lcp))
assert other_block.get_score().raw_earned == 0.1
def test_showanswer_default(self):
"""
Make sure the show answer logic does the right thing.
"""
# default, no due date, showanswer 'closed', so problem is open, and show_answer
# not visible.
problem = CapaFactory.create()
assert not problem.answer_available()
@ddt.data(
(requests.exceptions.ReadTimeout, (1, 'failed to read from the server')),
(requests.exceptions.ConnectionError, (1, 'cannot connect to server')),
)
@ddt.unpack
def test_xqueue_request_exception(self, exception, result):
"""
Makes sure that platform will raise appropriate exception in case of
connect/read timeout(s) to request to xqueue
"""
xqueue_interface = XQueueInterface("http://example.com/xqueue", Mock())
with patch.object(xqueue_interface.session, 'post', side_effect=exception):
# pylint: disable = protected-access
response = xqueue_interface._http_post('http://some/fake/url', {})
assert response == result
def test_showanswer_attempted(self):
problem = CapaFactory.create(showanswer='attempted')
assert not problem.answer_available()
problem.attempts = 1
assert problem.answer_available()
@ddt.data(
# If show_correctness=always, Answer is visible after attempted
({'showanswer': 'attempted', 'max_attempts': '1', 'show_correctness': 'always', }, False, True),
# If show_correctness=never, Answer is never visible
({'showanswer': 'attempted', 'max_attempts': '1', 'show_correctness': 'never', }, False, False),
# If show_correctness=past_due, answer is not visible before due date
({'showanswer': 'attempted', 'show_correctness': 'past_due', 'max_attempts': '1', 'due': 'tomorrow_str', },
False, False),
# If show_correctness=past_due, answer is visible after due date
({'showanswer': 'attempted', 'show_correctness': 'past_due', 'max_attempts': '1', 'due': 'yesterday_str', },
True, True))
@ddt.unpack
def test_showanswer_hide_correctness(self, problem_data, answer_available_no_attempt,
answer_available_after_attempt):
"""
Ensure that the answer will not be shown when correctness is being hidden.
"""
if 'due' in problem_data:
problem_data['due'] = getattr(self, problem_data['due'])
problem = CapaFactory.create(**problem_data)
assert problem.answer_available() == answer_available_no_attempt
problem.attempts = 1
assert problem.answer_available() == answer_available_after_attempt
def test_showanswer_closed(self):
# can see after attempts used up, even with due date in the future
used_all_attempts = CapaFactory.create(showanswer='closed',
max_attempts="1",
attempts="1",
due=self.tomorrow_str)
assert used_all_attempts.answer_available()
# can see after due date
after_due_date = CapaFactory.create(showanswer='closed',
max_attempts="1",
attempts="0",
due=self.yesterday_str)
assert after_due_date.answer_available()
# can't see because attempts left
attempts_left_open = CapaFactory.create(showanswer='closed',
max_attempts="1",
attempts="0",
due=self.tomorrow_str)
assert not attempts_left_open.answer_available()
# Can't see because grace period hasn't expired
still_in_grace = CapaFactory.create(showanswer='closed',
max_attempts="1",
attempts="0",
due=self.yesterday_str,
graceperiod=self.two_day_delta_str)
assert not still_in_grace.answer_available()
def test_showanswer_correct_or_past_due(self):
"""
With showanswer="correct_or_past_due" should show answer after the answer is correct
or after the problem is closed for everyone--e.g. after due date + grace period.
"""
# can see because answer is correct, even with due date in the future
answer_correct = CapaFactory.create(showanswer='correct_or_past_due',
max_attempts="1",
attempts="0",
due=self.tomorrow_str,
correct=True)
assert answer_correct.answer_available()
# can see after due date, even when answer isn't correct
past_due_date = CapaFactory.create(showanswer='correct_or_past_due',
max_attempts="1",
attempts="0",
due=self.yesterday_str)
assert past_due_date.answer_available()
# can also see after due date when answer _is_ correct
past_due_date_correct = CapaFactory.create(showanswer='correct_or_past_due',
max_attempts="1",
attempts="0",
due=self.yesterday_str,
correct=True)
assert past_due_date_correct.answer_available()
# Can't see because grace period hasn't expired and answer isn't correct
still_in_grace = CapaFactory.create(showanswer='correct_or_past_due',
max_attempts="1",
attempts="1",
due=self.yesterday_str,
graceperiod=self.two_day_delta_str)
assert not still_in_grace.answer_available()
def test_showanswer_past_due(self):
"""
With showanswer="past_due" should only show answer after the problem is closed
for everyone--e.g. after due date + grace period.
"""
# can't see after attempts used up, even with due date in the future
used_all_attempts = CapaFactory.create(showanswer='past_due',
max_attempts="1",
attempts="1",
due=self.tomorrow_str)
assert not used_all_attempts.answer_available()
# can see after due date
past_due_date = CapaFactory.create(showanswer='past_due',
max_attempts="1",
attempts="0",
due=self.yesterday_str)
assert past_due_date.answer_available()
# can't see because attempts left
attempts_left_open = CapaFactory.create(showanswer='past_due',
max_attempts="1",
attempts="0",
due=self.tomorrow_str)
assert not attempts_left_open.answer_available()
# Can't see because grace period hasn't expired, even though have no more
# attempts.
still_in_grace = CapaFactory.create(showanswer='past_due',
max_attempts="1",
attempts="1",
due=self.yesterday_str,
graceperiod=self.two_day_delta_str)
assert not still_in_grace.answer_available()
def test_showanswer_after_attempts_with_max(self):
"""
Button should not be visible when attempts < required attempts.
Even with max attempts set, the show answer button should only
show up after the user has attempted answering the question for
the requisite number of times, i.e `attempts_before_showanswer_button`
"""
problem = CapaFactory.create(
showanswer='after_attempts',
attempts='2',
attempts_before_showanswer_button='3',
max_attempts='5',
)
assert not problem.answer_available()
def test_showanswer_after_attempts_no_max(self):
"""
Button should not be visible when attempts < required attempts.
Even when max attempts is NOT set, the answer should still
only be available after the student has attempted the
problem at least `attempts_before_showanswer_button` times
"""
problem = CapaFactory.create(
showanswer='after_attempts',
attempts='2',
attempts_before_showanswer_button='3',
)
assert not problem.answer_available()
def test_showanswer_after_attempts_used_all_attempts(self):
"""
Button should be visible even after all attempts are used up.
As long as the student has attempted the question for
the requisite number of times, then the show ans. button is
visible even after they have exhausted their attempts.
"""
problem = CapaFactory.create(
showanswer='after_attempts',
attempts_before_showanswer_button='2',
max_attempts='3',
attempts='3',
due=self.tomorrow_str,
)
assert problem.answer_available()
def test_showanswer_after_attempts_past_due_date(self):
"""
Show Answer button should be visible even after the due date.
As long as the student has attempted the problem for the requisite
number of times, the answer should be available past the due date.
"""
problem = CapaFactory.create(
showanswer='after_attempts',
attempts_before_showanswer_button='2',
attempts='2',
due=self.yesterday_str,
)
assert problem.answer_available()
def test_showanswer_after_attempts_still_in_grace(self):
"""
If attempts > required attempts, ans. is available in grace period.
As long as the user has attempted for the requisite # of times,
the show answer button is visible throughout the grace period.
"""
problem = CapaFactory.create(
showanswer='after_attempts',
after_attempts='3',
attempts='4',
due=self.yesterday_str,
graceperiod=self.two_day_delta_str,
)
assert problem.answer_available()
def test_showanswer_after_attempts_large(self):
"""
If required attempts > max attempts then required attempts = max attempts.
Ensure that if attempts_before_showanswer_button > max_attempts,
the button should show up after all attempts are used up,
i.e after_attempts falls back to max_attempts
"""
problem = CapaFactory.create(
showanswer='after_attempts',
attempts_before_showanswer_button='5',
max_attempts='3',
attempts='3',
)
assert problem.answer_available()
def test_showanswer_after_attempts_zero(self):
"""
Button should always be visible if required min attempts = 0.
If attempts_before_showanswer_button = 0, then the show answer
button should be visible at all times.
"""
problem = CapaFactory.create(
showanswer='after_attempts',
attempts_before_showanswer_button='0',
attempts='0',
)
assert problem.answer_available()
def test_showanswer_finished(self):
"""
With showanswer="finished" should show answer after the problem is closed,
or after the answer is correct.
"""
# can see after attempts used up, even with due date in the future
used_all_attempts = CapaFactory.create(showanswer='finished',
max_attempts="1",
attempts="1",
due=self.tomorrow_str)
assert used_all_attempts.answer_available()
# can see after due date
past_due_date = CapaFactory.create(showanswer='finished',
max_attempts="1",
attempts="0",
due=self.yesterday_str)
assert past_due_date.answer_available()
# can't see because attempts left and wrong
attempts_left_open = CapaFactory.create(showanswer='finished',
max_attempts="1",
attempts="0",
due=self.tomorrow_str)
assert not attempts_left_open.answer_available()
# _can_ see because attempts left and right
correct_ans = CapaFactory.create(showanswer='finished',
max_attempts="1",
attempts="0",
due=self.tomorrow_str,
correct=True)
assert correct_ans.answer_available()
# Can see even though grace period hasn't expired, because have no more
# attempts.
still_in_grace = CapaFactory.create(showanswer='finished',
max_attempts="1",
attempts="1",
due=self.yesterday_str,
graceperiod=self.two_day_delta_str)
assert still_in_grace.answer_available()
def test_showanswer_answered(self):
"""
Tests that with showanswer="answered" should show answer after the problem is correctly answered.
It should *NOT* show answer if the answer is incorrect.
"""
# Can not see "Show Answer" when student answer is wrong
answer_wrong = CapaFactory.create(
showanswer=SHOWANSWER.ANSWERED,
max_attempts="1",
attempts="0",
due=self.tomorrow_str,
correct=False
)
assert not answer_wrong.answer_available()
# Expect to see "Show Answer" when answer is correct
answer_correct = CapaFactory.create(
showanswer=SHOWANSWER.ANSWERED,
max_attempts="1",
attempts="0",
due=self.tomorrow_str,
correct=True
)
assert answer_correct.answer_available()
@ddt.data('', 'other-value')
def test_show_correctness_other(self, show_correctness):
"""
Test that correctness is visible if show_correctness is not set to one of the values
from SHOW_CORRECTNESS constant.
"""
problem = CapaFactory.create(show_correctness=show_correctness)
assert problem.correctness_available()
def test_show_correctness_default(self):
"""
Test that correctness is visible by default.
"""
problem = CapaFactory.create()
assert problem.correctness_available()
def test_show_correctness_never(self):
"""
Test that correctness is hidden when show_correctness turned off.
"""
problem = CapaFactory.create(show_correctness='never')
assert not problem.correctness_available()
@ddt.data(
# Correctness not visible if due date in the future, even after using up all attempts
({'show_correctness': 'past_due', 'max_attempts': '1', 'attempts': '1', 'due': 'tomorrow_str', }, False),
# Correctness visible if due date in the past
({'show_correctness': 'past_due', 'max_attempts': '1', 'attempts': '0', 'due': 'yesterday_str', }, True),
# Correctness not visible if due date in the future
({'show_correctness': 'past_due', 'max_attempts': '1', 'attempts': '0', 'due': 'tomorrow_str', }, False),
# Correctness not visible because grace period hasn't expired,
# even after using up all attempts
({'show_correctness': 'past_due', 'max_attempts': '1', 'attempts': '1', 'due': 'yesterday_str',
'graceperiod': 'two_day_delta_str', }, False))
@ddt.unpack
def test_show_correctness_past_due(self, problem_data, expected_result):
"""
Test that with show_correctness="past_due", correctness will only be visible
after the problem is closed for everyone--e.g. after due date + grace period.
"""
problem_data['due'] = getattr(self, problem_data['due'])
if 'graceperiod' in problem_data:
problem_data['graceperiod'] = getattr(self, problem_data['graceperiod'])
problem = CapaFactory.create(**problem_data)
assert problem.correctness_available() == expected_result
def test_closed(self):
# Attempts < Max attempts --> NOT closed
block = CapaFactory.create(max_attempts="1", attempts="0")
assert not block.closed()
# Attempts < Max attempts --> NOT closed
block = CapaFactory.create(max_attempts="2", attempts="1")
assert not block.closed()
# Attempts = Max attempts --> closed
block = CapaFactory.create(max_attempts="1", attempts="1")
assert block.closed()
# Attempts > Max attempts --> closed
block = CapaFactory.create(max_attempts="1", attempts="2")
assert block.closed()
# Max attempts = 0 --> closed
block = CapaFactory.create(max_attempts="0", attempts="2")
assert block.closed()
# Past due --> closed
block = CapaFactory.create(max_attempts="1", attempts="0",
due=self.yesterday_str)
assert block.closed()
@patch.object(ProblemBlock, 'course_end_date', new_callable=PropertyMock)
def test_closed_for_archive(self, mock_course_end_date):
# Utility to create a datetime object in the past
def past_datetime(days):
return (datetime.datetime.now(UTC) - datetime.timedelta(days=days))
# Utility to create a datetime object in the future
def future_datetime(days):
return (datetime.datetime.now(UTC) + datetime.timedelta(days=days))
block = CapaFactory.create(max_attempts="1", attempts="0")
# For active courses without graceperiod
mock_course_end_date.return_value = future_datetime(10)
assert not block.closed()
# For archive courses without graceperiod
mock_course_end_date.return_value = past_datetime(10)
assert block.closed()
# For active courses with graceperiod
mock_course_end_date.return_value = future_datetime(10)
block.graceperiod = datetime.timedelta(days=2)
assert not block.closed()
# For archive courses with graceperiod
mock_course_end_date.return_value = past_datetime(2)
block.graceperiod = datetime.timedelta(days=3)
assert not block.closed()
def test_parse_get_params(self):
# Valid GET param dict
# 'input_5' intentionally left unset,
valid_get_dict = MultiDict({
'input_1': 'test',
'input_1_2': 'test',
'input_1_2_3': 'test',
'input_[]_3': 'test',
'input_4': None,
'input_6': 5
})
result = ProblemBlock.make_dict_of_responses(valid_get_dict)
# Expect that we get a dict with "input" stripped from key names
# and that we get the same values back
for key in result.keys(): # lint-amnesty, pylint: disable=consider-iterating-dictionary
original_key = "input_" + key
assert original_key in valid_get_dict, ('Output dict should have key %s' % original_key)
assert valid_get_dict[original_key] == result[key]
# Valid GET param dict with list keys
# Each tuple represents a single parameter in the query string
valid_get_dict = MultiDict((('input_2[]', 'test1'), ('input_2[]', 'test2')))
result = ProblemBlock.make_dict_of_responses(valid_get_dict)
assert '2' in result
assert ['test1', 'test2'] == result['2']
# If we use [] at the end of a key name, we should always
# get a list, even if there's just one value
valid_get_dict = MultiDict({'input_1[]': 'test'})
result = ProblemBlock.make_dict_of_responses(valid_get_dict)
assert result['1'] == ['test']
# If we have no underscores in the name, then the key is invalid
invalid_get_dict = MultiDict({'input': 'test'})
with pytest.raises(ValueError):
result = ProblemBlock.make_dict_of_responses(invalid_get_dict)
# Two equivalent names (one list, one non-list)
# One of the values would overwrite the other, so detect this
# and raise an exception
invalid_get_dict = MultiDict({'input_1[]': 'test 1',
'input_1': 'test 2'})
with pytest.raises(ValueError):
result = ProblemBlock.make_dict_of_responses(invalid_get_dict)
def test_submit_problem_correct(self):
block = CapaFactory.create(attempts=1)
# Simulate that all answers are marked correct, no matter
# what the input is, by patching CorrectMap.is_correct()
# Also simulate rendering the HTML
with patch('xmodule.capa.correctmap.CorrectMap.is_correct') as mock_is_correct:
with patch('xmodule.capa_block.ProblemBlock.get_problem_html') as mock_html:
mock_is_correct.return_value = True
mock_html.return_value = "Test HTML"
# Check the problem
get_request_dict = {CapaFactory.input_key(): '3.14'}
result = block.submit_problem(get_request_dict)
# Expect that the problem is marked correct
assert result['success'] == 'correct'
# Expect that we get the (mocked) HTML
assert result['contents'] == 'Test HTML'
# Expect that the number of attempts is incremented by 1
assert block.attempts == 2
# and that this was considered attempt number 2 for grading purposes
assert block.lcp.context['attempt'] == 2
def test_submit_problem_incorrect(self):
block = CapaFactory.create(attempts=0)
# Simulate marking the input incorrect
with patch('xmodule.capa.correctmap.CorrectMap.is_correct') as mock_is_correct:
mock_is_correct.return_value = False
# Check the problem
get_request_dict = {CapaFactory.input_key(): '0'}
result = block.submit_problem(get_request_dict)
# Expect that the problem is marked correct
assert result['success'] == 'incorrect'
# Expect that the number of attempts is incremented by 1
assert block.attempts == 1
# and that this is considered the first attempt
assert block.lcp.context['attempt'] == 1
def test_submit_problem_closed(self):
block = CapaFactory.create(attempts=3)
# Problem closed -- cannot submit
# Simulate that ProblemBlock.closed() always returns True
with patch('xmodule.capa_block.ProblemBlock.closed') as mock_closed:
mock_closed.return_value = True
with pytest.raises(xmodule.exceptions.NotFoundError):
get_request_dict = {CapaFactory.input_key(): '3.14'}
block.submit_problem(get_request_dict)
# Expect that number of attempts NOT incremented
assert block.attempts == 3
@ddt.data(
RANDOMIZATION.ALWAYS,
'true'
)
def test_submit_problem_resubmitted_with_randomize(self, rerandomize):
# Randomize turned on
block = CapaFactory.create(rerandomize=rerandomize, attempts=0)
# Simulate that the problem is completed
block.done = True
# Expect that we cannot submit
with pytest.raises(xmodule.exceptions.NotFoundError):
get_request_dict = {CapaFactory.input_key(): '3.14'}
block.submit_problem(get_request_dict)
# Expect that number of attempts NOT incremented
assert block.attempts == 0
@ddt.data(
RANDOMIZATION.NEVER,
'false',
RANDOMIZATION.PER_STUDENT
)
def test_submit_problem_resubmitted_no_randomize(self, rerandomize):
# Randomize turned off
block = CapaFactory.create(rerandomize=rerandomize, attempts=0, done=True)
# Expect that we can submit successfully
get_request_dict = {CapaFactory.input_key(): '3.14'}
result = block.submit_problem(get_request_dict)
assert result['success'] == 'correct'
# Expect that number of attempts IS incremented, still same attempt
assert block.attempts == 1
assert block.lcp.context['attempt'] == 1
def test_submit_problem_queued(self):
block = CapaFactory.create(attempts=1)
# Simulate that the problem is queued
multipatch = patch.multiple(
'xmodule.capa.capa_problem.LoncapaProblem',
is_queued=DEFAULT,
get_recentmost_queuetime=DEFAULT
)
with multipatch as values:
values['is_queued'].return_value = True
values['get_recentmost_queuetime'].return_value = datetime.datetime.now(UTC)
get_request_dict = {CapaFactory.input_key(): '3.14'}
result = block.submit_problem(get_request_dict)
# Expect an AJAX alert message in 'success'
assert 'You must wait' in result['success']
# Expect that the number of attempts is NOT incremented
assert block.attempts == 1
@patch.object(XQueueInterface, '_http_post')
def test_submit_problem_with_files(self, mock_xqueue_post):
# Check a problem with uploaded files, using the submit_problem API.
# pylint: disable=protected-access
# The files we'll be uploading.
fnames = ["prog1.py", "prog2.py", "prog3.py"]
fpaths = [os.path.join(DATA_DIR, "capa", fname) for fname in fnames]
fileobjs = [open(fpath) for fpath in fpaths]
for fileobj in fileobjs:
self.addCleanup(fileobj.close)
block = CapaFactoryWithFiles.create()
# Mock the XQueueInterface post method
mock_xqueue_post.return_value = (0, "ok")
# Create a request dictionary for submit_problem.
get_request_dict = {
CapaFactoryWithFiles.input_key(response_num=2): fileobjs,
CapaFactoryWithFiles.input_key(response_num=3): 'None',
}
block.submit_problem(get_request_dict)
# pylint: disable=line-too-long
# _http_post is called like this:
# _http_post(
# 'http://example.com/xqueue/xqueue/submit/',
# {
# 'xqueue_header': '{"lms_key": "df34fb702620d7ae892866ba57572491", "lms_callback_url": "/", "queue_name": "BerkeleyX-cs188x"}',
# 'xqueue_body': '{"student_info": "{\\"anonymous_student_id\\": \\"student\\", \\"submission_time\\": \\"20131117183318\\"}", "grader_payload": "{\\"project\\": \\"p3\\"}", "student_response": ""}',
# },
# files={
# path(u'/home/ned/edx/edx-platform/common/test/data/uploads/asset.html'):
# <open file u'/home/ned/edx/edx-platform/common/test/data/uploads/asset.html', mode 'r' at 0x49c5f60>,
# path(u'/home/ned/edx/edx-platform/common/test/data/uploads/image.jpg'):
# <open file u'/home/ned/edx/edx-platform/common/test/data/uploads/image.jpg', mode 'r' at 0x49c56f0>,
# path(u'/home/ned/edx/edx-platform/common/test/data/uploads/textbook.pdf'):
# <open file u'/home/ned/edx/edx-platform/common/test/data/uploads/textbook.pdf', mode 'r' at 0x49c5a50>,
# },
# )
# pylint: enable=line-too-long
assert mock_xqueue_post.call_count == 1
_, kwargs = mock_xqueue_post.call_args
self.assertCountEqual(fpaths, list(kwargs['files'].keys()))
for fpath, fileobj in kwargs['files'].items():
assert fpath == fileobj.name
@patch.object(XQueueInterface, '_http_post')
def test_submit_problem_with_files_as_xblock(self, mock_xqueue_post):
# Check a problem with uploaded files, using the XBlock API.
# pylint: disable=protected-access
# The files we'll be uploading.
fnames = ["prog1.py", "prog2.py", "prog3.py"]
fpaths = [os.path.join(DATA_DIR, "capa", fname) for fname in fnames]
fileobjs = [open(fpath) for fpath in fpaths]
for fileobj in fileobjs:
self.addCleanup(fileobj.close)
block = CapaFactoryWithFiles.create()
# Mock the XQueueInterface post method
mock_xqueue_post.return_value = (0, "ok")
# Create a webob Request with the files uploaded.
post_data = []
for fname, fileobj in zip(fnames, fileobjs):
post_data.append((CapaFactoryWithFiles.input_key(response_num=2), (fname, fileobj)))
post_data.append((CapaFactoryWithFiles.input_key(response_num=3), 'None'))
request = webob.Request.blank("/some/fake/url", POST=post_data, content_type='multipart/form-data')
block.handle('xmodule_handler', request, 'problem_check')
assert mock_xqueue_post.call_count == 1
_, kwargs = mock_xqueue_post.call_args
self.assertCountEqual(fnames, list(kwargs['files'].keys()))
for fpath, fileobj in kwargs['files'].items():
assert fpath == fileobj.name
def test_submit_problem_error(self):
# Try each exception that capa_block should handle
exception_classes = [StudentInputError,
LoncapaProblemError,
ResponseError]
for exception_class in exception_classes:
# Create the block
block = CapaFactory.create(attempts=1, user_is_staff=False)
# Simulate answering a problem that raises the exception
with patch('xmodule.capa.capa_problem.LoncapaProblem.grade_answers') as mock_grade:
mock_grade.side_effect = exception_class('test error')
get_request_dict = {CapaFactory.input_key(): '3.14'}
result = block.submit_problem(get_request_dict)
# Expect an AJAX alert message in 'success'
expected_msg = 'test error'
assert expected_msg == result['success']
# Expect that the number of attempts is NOT incremented
assert block.attempts == 1
# but that this was considered attempt number 2 for grading purposes
assert block.lcp.context['attempt'] == 2
def test_submit_problem_error_with_codejail_exception(self):
# Try each exception that capa_block should handle
exception_classes = [StudentInputError,
LoncapaProblemError,
ResponseError]
for exception_class in exception_classes:
# Create the block
block = CapaFactory.create(attempts=1, user_is_staff=False)
# Simulate a codejail exception "Exception: Couldn't execute jailed code"
with patch('xmodule.capa.capa_problem.LoncapaProblem.grade_answers') as mock_grade:
try:
raise ResponseError(
'Couldn\'t execute jailed code: stdout: \'\', '
'stderr: \'Traceback (most recent call last):\\n'
' File "jailed_code", line 15, in <module>\\n'
' exec code in g_dict\\n File "<string>", line 67, in <module>\\n'
' File "<string>", line 65, in check_func\\n'
'Exception: Couldn\'t execute jailed code\\n\' with status code: 1', )
except ResponseError as err:
mock_grade.side_effect = exception_class(str(err))
get_request_dict = {CapaFactory.input_key(): '3.14'}
result = block.submit_problem(get_request_dict)
# Expect an AJAX alert message in 'success' without the text of the stack trace
expected_msg = 'Couldn\'t execute jailed code'
assert expected_msg == result['success']
# Expect that the number of attempts is NOT incremented
assert block.attempts == 1
# but that this was considered the second attempt for grading purposes
assert block.lcp.context['attempt'] == 2
@override_settings(DEBUG=True)
def test_submit_problem_other_errors(self):
"""
Test that errors other than the expected kinds give an appropriate message.
See also `test_submit_problem_error` for the "expected kinds" or errors.