Newer
Older
__copyright__ = "Copyright (C) 2014 Andreas Kloeckner, Zesheng Wang, Dong Zhuang"
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import datetime
import pytz
import unittest
from django.test import TestCase, override_settings
from django import http
from django.urls import reverse
from django.utils.timezone import now, timedelta
from course.models import ExamTicket, FlowSession
from course import constants, exam
from tests.constants import (
DATE_TIME_PICKER_TIME_FORMAT)
from tests.base_test_mixins import (
SingleCourseTestMixin, MockAddMessageMixing, SingleCoursePageTestMixin)
from tests.utils import mock, reload_urlconf
from tests import factories
class GenTicketCodeTest(unittest.TestCase):
"""test exam.gen_ticket_code"""
def test_unique(self):
code = set()
for i in range(10):
code.add(exam.gen_ticket_code())
self.assertEqual(len(code), 10)
class ExamTestMixin(SingleCourseTestMixin, MockAddMessageMixing):
force_login_student_for_each_test = False
default_faked_now = datetime.datetime(2019, 1, 1, tzinfo=pytz.UTC)
default_valid_start_time = default_faked_now
default_valid_end_time = default_valid_start_time + timedelta(hours=3)
@classmethod
def setUpTestData(cls): # noqa
cls.add_user_permission(
cls.instructor_participation.user, "can_issue_exam_tickets",
model=ExamTicket)
cls.exam = factories.ExamFactory(course=cls.course)
def setUp(self):
self.c.force_login(self.instructor_participation.user)
fake_get_now_or_fake_time = mock.patch(
"course.views.get_now_or_fake_time")
self.mock_get_now_or_fake_time = fake_get_now_or_fake_time.start()
self.mock_get_now_or_fake_time.return_value = now()
self.addCleanup(fake_get_now_or_fake_time.stop)
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
def get_post_data(self, **kwargs):
data = {
"user": self.student_participation.user.pk,
"exam": self.exam.pk,
"valid_start_time": (
self.default_valid_start_time.strftime(
DATE_TIME_PICKER_TIME_FORMAT)),
"valid_end_time": (
self.default_valid_end_time.strftime(
DATE_TIME_PICKER_TIME_FORMAT))}
data.update(kwargs)
return data
class IssueExamTicketTest(ExamTestMixin, TestCase):
"""test exam.issue_exam_ticket
"""
def get_issue_exam_ticket_url(self):
from django.urls import reverse
return reverse("relate-issue_exam_ticket")
def get_issue_exam_ticket_view(self):
return self.c.get(self.get_issue_exam_ticket_url())
def post_issue_exam_ticket_view(self, data):
return self.c.post(self.get_issue_exam_ticket_url(), data)
def test_not_authenticated(self):
with self.temporarily_switch_to_user(None):
resp = self.get_issue_exam_ticket_view()
self.assertEqual(resp.status_code, 403)
resp = self.post_issue_exam_ticket_view(data={})
self.assertEqual(resp.status_code, 403)
self.assertEqual(ExamTicket.objects.count(), 0)
def test_no_pperm(self):
with self.temporarily_switch_to_user(self.student_participation.user):
resp = self.get_issue_exam_ticket_view()
self.assertEqual(resp.status_code, 403)
resp = self.post_issue_exam_ticket_view(data={})
self.assertEqual(resp.status_code, 403)
self.assertEqual(ExamTicket.objects.count(), 0)
def test_get_success(self):
resp = self.get_issue_exam_ticket_view()
self.assertEqual(resp.status_code, 200)
self.assertEqual(ExamTicket.objects.count(), 0)
def test_post_success(self):
self.mock_get_now_or_fake_time.return_value = self.default_faked_now
resp = self.post_issue_exam_ticket_view(data=self.get_post_data())
self.assertFormErrorLoose(resp, None)
self.assertEqual(resp.status_code, 200)
self.assertEqual(ExamTicket.objects.count(), 1)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith("Ticket issued for", reset=False)
self.assertAddMessageCalledWith("The ticket code is")
def test_form_invalid(self):
self.mock_get_now_or_fake_time.return_value = self.default_faked_now
with mock.patch("course.exam.IssueTicketForm.is_valid") as mock_is_valid:
mock_is_valid.return_value = False
resp = self.post_issue_exam_ticket_view(data=self.get_post_data())
self.assertFormErrorLoose(resp, None)
self.assertEqual(resp.status_code, 200)
self.assertEqual(ExamTicket.objects.count(), 0)
def test_participation_not_match(self):
self.mock_get_now_or_fake_time.return_value = self.default_faked_now
another_exam = factories.ExamFactory(
course=factories.CourseFactory(identifier="another-course"))
resp = self.post_issue_exam_ticket_view(
data=self.get_post_data(exam=another_exam.pk))
self.assertFormErrorLoose(resp, None)
self.assertEqual(resp.status_code, 200)
self.assertEqual(ExamTicket.objects.count(), 0)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith("User is not enrolled in course.")
def test_revoke_revoke_prior_ticket(self):
self.mock_get_now_or_fake_time.return_value = self.default_faked_now
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
prior_ticket = factories.ExamTicketFactory(
exam=self.exam,
participation=self.student_participation,
state=constants.exam_ticket_states.valid)
resp = self.post_issue_exam_ticket_view(
data=self.get_post_data(revoke_prior=True))
self.assertFormErrorLoose(resp, None)
self.assertEqual(resp.status_code, 200)
self.assertEqual(ExamTicket.objects.count(), 2)
prior_ticket.refresh_from_db()
self.assertEqual(prior_ticket.state, constants.exam_ticket_states.revoked)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith("Ticket issued for", reset=False)
self.assertAddMessageCalledWith("The ticket code is")
class BatchIssueExamTicketsTest(ExamTestMixin, TestCase):
def get_batch_issue_exam_ticket_url(self, course_identifier=None):
course_identifier = course_identifier or self.get_default_course_identifier()
return self.get_course_view_url(
"relate-batch_issue_exam_tickets",
course_identifier=course_identifier)
def get_batch_issue_exam_ticket_view(self):
return self.c.get(self.get_batch_issue_exam_ticket_url())
def post_batch_issue_exam_ticket_view(self, data):
return self.c.post(self.get_batch_issue_exam_ticket_url(), data)
def get_post_data(self, **kwargs):
data = super().get_post_data()
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
del data["user"]
data["format"] = "{{ tickets }}{{checkin_uri}}"
data.update(kwargs)
return data
def test_not_authenticated(self):
with self.temporarily_switch_to_user(None):
resp = self.get_batch_issue_exam_ticket_view()
self.assertEqual(resp.status_code, 403)
resp = self.post_batch_issue_exam_ticket_view(data={})
self.assertEqual(resp.status_code, 403)
self.assertEqual(ExamTicket.objects.count(), 0)
def test_no_pperm(self):
with self.temporarily_switch_to_user(self.student_participation.user):
resp = self.get_batch_issue_exam_ticket_view()
self.assertEqual(resp.status_code, 403)
resp = self.post_batch_issue_exam_ticket_view(data={})
self.assertEqual(resp.status_code, 403)
self.assertEqual(ExamTicket.objects.count(), 0)
def test_get_success(self):
resp = self.get_batch_issue_exam_ticket_view()
self.assertEqual(resp.status_code, 200)
self.assertEqual(ExamTicket.objects.count(), 0)
def test_form_invalid(self):
with mock.patch("course.exam.BatchIssueTicketsForm.is_valid"
) as mock_is_valid:
mock_is_valid.return_value = False
resp = self.post_batch_issue_exam_ticket_view(data=self.get_post_data())
self.assertEqual(resp.status_code, 200)
self.assertEqual(ExamTicket.objects.count(), 0)
def test_template_syntax_error(self):
with mock.patch("course.content.markup_to_html") as mock_mth:
from jinja2 import TemplateSyntaxError
mock_mth.side_effect = TemplateSyntaxError(
lineno=10, message=b"my error")
resp = self.post_batch_issue_exam_ticket_view(data=self.get_post_data())
self.assertEqual(resp.status_code, 200)
self.assertEqual(ExamTicket.objects.count(), 0)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith("Template rendering failed")
def test_unknown_error(self):
with mock.patch("course.content.markup_to_html") as mock_mth:
mock_mth.side_effect = RuntimeError("my error")
resp = self.post_batch_issue_exam_ticket_view(data=self.get_post_data())
self.assertEqual(resp.status_code, 200)
self.assertEqual(ExamTicket.objects.count(), 0)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith("Template rendering failed")
def test_post_success(self):
factories.ParticipationFactory(course=self.course)
factories.ParticipationFactory(
course=self.course, status=constants.participation_status.dropped)
resp = self.post_batch_issue_exam_ticket_view(
data=self.get_post_data())
self.assertEqual(resp.status_code, 200)
self.assertFormErrorLoose(resp, None)
self.assertEqual(ExamTicket.objects.count(), 4)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith("4 tickets issued.")
def test_revoke_revoke_prior_ticket(self):
prior_ticket = factories.ExamTicketFactory(
exam=self.exam,
participation=self.student_participation,
state=constants.exam_ticket_states.valid)
resp = self.post_batch_issue_exam_ticket_view(
data=self.get_post_data(revoke_prior=True))
self.assertFormErrorLoose(resp, None)
self.assertEqual(resp.status_code, 200)
self.assertEqual(ExamTicket.objects.count(), 4)
prior_ticket.refresh_from_db()
self.assertEqual(prior_ticket.state, constants.exam_ticket_states.revoked)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith("3 tickets issued.")
@override_settings(RELATE_TICKET_MINUTES_VALID_AFTER_USE=120)
class CheckExamTicketTest(ExamTestMixin, TestCase):
def setUp(self):
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
self.exam.refresh_from_db()
self.now = now()
self.facilities = frozenset([])
self.exam.no_exams_after = self.now + timedelta(days=1)
self.exam.no_exams_before = self.now - timedelta(days=2)
self.exam.save()
self.ticket = factories.ExamTicketFactory(
exam=self.exam, participation=self.student_participation,
state=constants.exam_ticket_states.valid,
usage_time=self.now + timedelta(minutes=100),
valid_start_time=self.now - timedelta(minutes=20),
valid_end_time=self.now + timedelta(minutes=100),
)
def test_object_not_found(self):
result, msg = exam.check_exam_ticket(
username="abcd",
code=self.ticket.code,
now_datetime=self.now,
facilities=self.facilities)
self.assertFalse(result)
self.assertEqual(msg, "User name or ticket code not recognized.")
def test_ticket_not_usable(self):
result, msg = exam.check_exam_ticket(
username=self.student_participation.user.username,
code=self.ticket.code,
now_datetime=self.now,
facilities=self.facilities)
self.assertTrue(result, msg=msg)
self.ticket.state = constants.exam_ticket_states.revoked
self.ticket.save()
result, msg = exam.check_exam_ticket(
username=self.student_participation.user.username,
code=self.ticket.code,
now_datetime=self.now,
facilities=self.facilities)
self.assertFalse(result, msg=msg)
self.assertEqual(
msg, "Ticket is not in usable state. (Has it been revoked?)")
def test_ticket_expired(self):
self.ticket.usage_time = self.now - timedelta(days=1)
self.ticket.state = constants.exam_ticket_states.used
self.ticket.save()
result, msg = exam.check_exam_ticket(
username=self.student_participation.user.username,
code=self.ticket.code,
now_datetime=self.now,
facilities=self.facilities)
self.assertFalse(result, msg=msg)
self.assertEqual(msg, "Ticket has exceeded its validity period.")
def test_ticket_not_active(self):
self.exam.active = False
self.exam.save()
result, msg = exam.check_exam_ticket(
username=self.student_participation.user.username,
code=self.ticket.code,
now_datetime=self.now,
facilities=self.facilities)
self.assertFalse(result, msg=msg)
self.assertEqual(msg, "Exam is not active.")
def test_not_started(self):
result, msg = exam.check_exam_ticket(
username=self.student_participation.user.username,
code=self.ticket.code,
now_datetime=self.now - timedelta(days=5),
facilities=self.facilities)
self.assertFalse(result, msg=msg)
self.assertEqual(msg, "Exam has not started yet.")
def test_ended(self):
result, msg = exam.check_exam_ticket(
username=self.student_participation.user.username,
code=self.ticket.code,
now_datetime=self.now + timedelta(days=5),
facilities=self.facilities)
self.assertFalse(result, msg=msg)
self.assertEqual(msg, "Exam has ended.")
def test_restrict_to_facility(self):
self.ticket.restrict_to_facility = "my_fa1"
self.ticket.save()
result, msg = exam.check_exam_ticket(
username=self.student_participation.user.username,
code=self.ticket.code,
now_datetime=self.now,
facilities=frozenset(["my_fa2"]))
self.assertFalse(result, msg=msg)
self.assertEqual(
msg, "Exam ticket requires presence in facility 'my_fa1'.")
result, msg = exam.check_exam_ticket(
username=self.student_participation.user.username,
code=self.ticket.code,
now_datetime=self.now,
facilities=None)
self.assertFalse(result, msg=msg)
self.assertEqual(
msg, "Exam ticket requires presence in facility 'my_fa1'.")
result, msg = exam.check_exam_ticket(
username=self.student_participation.user.username,
code=self.ticket.code,
now_datetime=self.now,
facilities=self.facilities)
self.assertFalse(result, msg=msg)
self.assertEqual(
msg, "Exam ticket requires presence in facility 'my_fa1'.")
result, msg = exam.check_exam_ticket(
username=self.student_participation.user.username,
code=self.ticket.code,
now_datetime=self.now,
facilities=frozenset(["my_fa1", "my_fa2"]))
self.assertTrue(result, msg=msg)
def test_not_yet_valid(self):
result, msg = exam.check_exam_ticket(
username=self.student_participation.user.username,
code=self.ticket.code,
now_datetime=self.ticket.valid_start_time - timedelta(minutes=1),
facilities=self.facilities)
self.assertFalse(result, msg=msg)
self.assertEqual(
msg, "Exam ticket is not yet valid.")
def test_expired(self):
result, msg = exam.check_exam_ticket(
username=self.student_participation.user.username,
code=self.ticket.code,
now_datetime=self.ticket.valid_end_time + timedelta(minutes=1),
facilities=self.facilities)
self.assertFalse(result, msg=msg)
self.assertEqual(
msg, "Exam ticket has expired.")
class ExamTicketBackendTest(ExamTestMixin, TestCase):
def setUp(self):
self.backend = exam.ExamTicketBackend()
def test_not_authenticate(self):
with mock.patch("course.exam.check_exam_ticket") as mock_check_ticket:
mock_check_ticket.return_value = False, "msg"
self.assertIsNone(self.backend.authenticate("foo", "bar"))
def test_get_user(self):
self.assertEqual(
self.backend.get_user(self.instructor_participation.user.pk),
self.instructor_participation.user)
self.assertIsNone(self.backend.get_user(100))
class IsFromExamsOnlyFacilityTest(unittest.TestCase):
"""test exam.is_from_exams_only_facility"""
def setUp(self):
self.requset = mock.MagicMock()
self.requset.relate_facilities = ["fa1", "fa2"]
fake_get_facilities_config = mock.patch(
"course.utils.get_facilities_config")
self.mock_get_facilities_config = fake_get_facilities_config.start()
self.addCleanup(fake_get_facilities_config.stop)
def test_true(self):
self.mock_get_facilities_config.return_value = {
"fa1": {"exams_only": False, "ip_range": "foo"},
"fa2": {"exams_only": True, "ip_range": "bar"}}
self.assertTrue(exam.is_from_exams_only_facility(self.requset))
def test_false(self):
self.mock_get_facilities_config.return_value = dict()
self.assertFalse(exam.is_from_exams_only_facility(self.requset))
def test_false_2(self):
self.mock_get_facilities_config.return_value = {
"fa1": {"exams_only": False, "ip_range": "foo"},
"fa3": {"exams_only": True, "ip_range": "bar"}}
self.assertFalse(exam.is_from_exams_only_facility(self.requset))
class GetLoginExamTicketTest(ExamTestMixin, TestCase):
"""test exam.get_login_exam_ticket"""
def setUp(self):
self.ticket = factories.ExamTicketFactory(
exam=self.exam, participation=self.student_participation,
state=constants.exam_ticket_states.valid)
self.request = mock.MagicMock()
def test_none(self):
self.request.session = {}
self.assertIsNone(exam.get_login_exam_ticket(self.request))
def test_object_does_not_exist(self):
self.request.session = {
"relate_exam_ticket_pk_used_for_login": 100
}
with self.assertRaises(ExamTicket.DoesNotExist):
exam.get_login_exam_ticket(self.request)
def test_get(self):
self.request.session = {
"relate_exam_ticket_pk_used_for_login": self.ticket.pk
}
self.assertEqual(exam.get_login_exam_ticket(self.request), self.ticket)
class CheckInForExamTest(ExamTestMixin, TestCase):
force_login_student_for_each_test = True
def setUp(self):
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
self.ticket = factories.ExamTicketFactory(
exam=self.exam, participation=self.student_participation,
state=constants.exam_ticket_states.valid)
self.instructor_ticket = factories.ExamTicketFactory(
exam=self.exam, participation=self.instructor_participation,
state=constants.exam_ticket_states.valid)
fake_check_exam_ticket = mock.patch("course.exam.check_exam_ticket")
self.mock_check_exam_ticket = fake_check_exam_ticket.start()
self.addCleanup(fake_check_exam_ticket.stop)
def get_check_in_for_exam_url(self):
return reverse("relate-check_in_for_exam")
def get_check_in_for_exam_view(self):
return self.c.get(self.get_check_in_for_exam_url())
def post_check_in_for_exam_view(self, data):
return self.c.post(self.get_check_in_for_exam_url(), data)
def get_post_data(self, **kwargs):
data = {
"username": self.student_participation.user.username,
"code": self.ticket.code
}
data.update(kwargs)
return data
def test_get(self):
resp = self.get_check_in_for_exam_view()
self.assertEqual(resp.status_code, 200)
self.assertEqual(self.ticket.state, constants.exam_ticket_states.valid)
def test_login_success(self):
self.mock_check_exam_ticket.return_value = True, "hello"
resp = self.post_check_in_for_exam_view(
self.get_post_data())
self.assertEqual(resp.status_code, 302)
self.ticket.refresh_from_db()
self.assertEqual(self.ticket.state, constants.exam_ticket_states.used)
def test_login_failure(self):
self.mock_check_exam_ticket.return_value = False, "what's wrong?"
resp = self.post_check_in_for_exam_view(
self.get_post_data())
self.assertEqual(resp.status_code, 200)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith("what's wrong?")
self.assertEqual(self.ticket.state, constants.exam_ticket_states.valid)
def test_form_invalid(self):
with mock.patch("course.exam.ExamCheckInForm.is_valid"
) as mock_is_valid:
mock_is_valid.return_value = False
resp = self.post_check_in_for_exam_view(data=self.get_post_data())
self.assertEqual(resp.status_code, 200)
self.assertEqual(self.ticket.state, constants.exam_ticket_states.valid)
def test_login_though_ticket_not_valid(self):
self.ticket.state = constants.exam_ticket_states.used
self.ticket.save()
self.mock_check_exam_ticket.return_value = True, "hello"
resp = self.post_check_in_for_exam_view(
self.get_post_data())
self.assertEqual(resp.status_code, 302)
self.assertEqual(self.ticket.state, constants.exam_ticket_states.used)
def test_pretend_facility(self):
with self.temporarily_switch_to_user(self.instructor_participation.user):
session = self.c.session
fa = ["my_falicity_1"]
session["relate_pretend_facilities"] = fa
session.save()
self.mock_check_exam_ticket.return_value = True, "hello"
resp = self.post_check_in_for_exam_view(
self.get_post_data(
username=self.instructor_participation.user.username,
code=self.instructor_ticket.code
))
self.assertEqual(resp.status_code, 302)
self.assertIn(frozenset(fa), self.mock_check_exam_ticket.call_args[0])
self.assertEqual(
self.c.session["relate_pretend_facilities"], fa)
self.assertEqual(
self.c.session["relate_exam_ticket_pk_used_for_login"],
self.instructor_ticket.pk)
self.instructor_ticket.refresh_from_db()
self.assertEqual(self.instructor_ticket.state,
constants.exam_ticket_states.used)
class ListAvailableExamsTest(ExamTestMixin, TestCase):
def setUp(self):
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
self.ticket = factories.ExamTicketFactory(
exam=self.exam, participation=self.student_participation,
state=constants.exam_ticket_states.valid)
self.instructor_ticket = factories.ExamTicketFactory(
exam=self.exam, participation=self.instructor_participation,
state=constants.exam_ticket_states.valid)
def get_list_available_exams_url(self):
return reverse("relate-list_available_exams")
def get_list_available_view(self):
return self.c.get(self.get_list_available_exams_url())
def test_not_authenticated(self):
with self.temporarily_switch_to_user(None):
resp = self.get_list_available_view()
exams = resp.context["exams"]
self.assertEqual(exams.count(), 0)
def test_not_found(self):
self.exam.no_exams_after = now() - timedelta(days=1)
self.exam.no_exams_before = now() - timedelta(days=2)
self.exam.save()
with self.temporarily_switch_to_user(self.student_participation.user):
resp = self.get_list_available_view()
exams = resp.context["exams"]
self.assertEqual(exams.count(), 0)
def test_found(self):
self.exam.no_exams_after = now() + timedelta(days=1)
self.exam.no_exams_before = now() - timedelta(days=2)
self.exam.save()
with self.temporarily_switch_to_user(self.student_participation.user):
resp = self.get_list_available_view()
exams = resp.context["exams"]
self.assertEqual(exams.count(), 1)
class ExamFacilityMiddlewareTest(SingleCoursePageTestMixin,
MockAddMessageMixing, TestCase):
"""Integration tests for exam.ExamFacilityMiddleware"""
def setUp(self):
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
fake_is_from_exams_only_facility = mock.patch(
"course.exam.is_from_exams_only_facility")
self.mock_is_from_exams_only_facility = (
fake_is_from_exams_only_facility.start())
self.mock_is_from_exams_only_facility.return_value = True
self.addCleanup(fake_is_from_exams_only_facility.stop)
def test_not_exams_only_facility(self):
self.mock_is_from_exams_only_facility.return_value = False
resp = self.c.get(self.course_page_url)
self.assertEqual(resp.status_code, 200)
def test_exams_only_facility(self):
resp = self.c.get(self.course_page_url)
self.assertRedirects(
resp, reverse("relate-list_available_exams"),
fetch_redirect_response=False)
def test_exams_only_facility_not_authenticated(self):
with self.temporarily_switch_to_user(None):
resp = self.c.get(self.course_page_url)
self.assertRedirects(
resp, reverse("relate-sign_in_choice"),
fetch_redirect_response=False)
def test_already_locked_down(self):
fs = factories.FlowSessionFactory(
participation=self.student_participation, flow_id=self.flow_id)
session = self.c.session
session["relate_session_locked_to_exam_flow_session_pk"] = fs.pk
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
session.save()
resp = self.c.get(self.course_page_url)
self.assertRedirects(
resp, self.get_view_start_flow_url(self.flow_id),
fetch_redirect_response=False)
def test_ok_views(self):
# we only test ta participation
from course.auth import make_sign_in_key
# make sign in key for a user
u = factories.UserFactory(
first_name="foo", last_name="bar",
status=constants.user_status.unconfirmed)
sign_in_key = make_sign_in_key(u)
u.sign_in_key = sign_in_key
u.save()
self.c.force_login(self.ta_participation.user)
my_session = factories.FlowSessionFactory(
participation=self.ta_participation, flow_id=self.flow_id)
with override_settings(RELATE_SIGN_IN_BY_USERNAME_ENABLED=True):
for url, args, kwargs, code_or_redirect in [
("relate-sign_in_choice", [], {}, 200),
("relate-sign_in_by_email", [], {}, 200),
("relate-sign_in_stage2_with_token",
[u.pk, sign_in_key], {}, "/"),
("relate-sign_in_by_user_pw", [], {}, 200),
("relate-impersonate", [], {}, 200),
# because not we are testing get, while stop_impersonating view
# doesn't allow get, if it return 403 instead of 302
# we think it passed test.
("relate-stop_impersonating", [], {}, 403),
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
("relate-check_in_for_exam", [], {}, 200),
("relate-list_available_exams", [], {}, 200),
("relate-view_start_flow", [],
{"course_identifier": self.course.identifier,
"flow_id": self.flow_id}, 200),
("relate-view_resume_flow", [],
{"course_identifier": self.course.identifier,
"flow_session_id": my_session.pk},
self.get_page_url_by_ordinal(0, flow_session_id=my_session.pk)),
("relate-user_profile", [], {}, 200),
("relate-logout", [], {}, "/"),
("relate-set_pretend_facilities", [], {}, 200),
]:
with self.subTest(url=url):
if "sign_in" in url:
switch_to = None
else:
switch_to = self.ta_participation.user
with self.temporarily_switch_to_user(switch_to):
resp = self.c.get(reverse(url, args=args, kwargs=kwargs))
try:
code = int(code_or_redirect)
self.assertEqual(resp.status_code, code)
except ValueError:
self.assertRedirects(
resp, code_or_redirect,
fetch_redirect_response=False)
def test_ok_with_saml2_views(self):
with override_settings(RELATE_SIGN_IN_BY_SAML2_ENABLED=True):
reload_urlconf()
with self.temporarily_switch_to_user(None):
# 'Settings' object has no attribute 'SAML_CONFIG'
# with that error raised, we can confirm it is actually
# requesting the view
with self.assertRaises(AttributeError):
self.c.get(reverse("saml2_login"))
def test_ok_with_select2_views(self):
# test by using the select2 widget of impersonating form
with self.temporarily_switch_to_user(self.ta_participation.user):
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
field_id = self.get_select2_field_id_from_response(resp)
# With no search term, should display all impersonatable users
term = None
resp = self.select2_get_request(field_id=field_id, term=term)
self.assertEqual(resp.status_code, 200)
def test_ok_issue_exam_ticket_view_with_pperm(self):
tup = (
(self.student_participation.user, 302),
(self.ta_participation.user, 302),
(self.superuser, 200),)
for user, status_code in tup:
with self.subTest(user=user):
with self.temporarily_switch_to_user(user):
resp = self.c.get(reverse("relate-issue_exam_ticket"))
self.assertEqual(resp.status_code, status_code)
def test_not_ok_view_flow_page(self):
fs = factories.FlowSessionFactory(
participation=self.student_participation, flow_id=self.flow_id)
resp = self.c.get(self.get_page_url_by_ordinal(0, flow_session_id=fs.pk))
self.assertRedirects(
resp, reverse("relate-list_available_exams"),
fetch_redirect_response=False)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith(
"Access to flows in an exams-only facility "
"is only granted if the flow is locked down. "
"To do so, add 'lock_down_as_exam_session' to "
"your flow's access permissions.")
class ExamLockdownMiddlewareTest(SingleCoursePageTestMixin,
MockAddMessageMixing, TestCase):
"""Integration tests for exam.ExamLockdownMiddleware
"""
@classmethod
def setUpTestData(cls): # noqa
super(SingleCoursePageTestMixin, cls).setUpTestData()
cls.start_flow(cls.flow_id)
cls.fs = FlowSession.objects.last()
def setUp(self):
self.fs.refresh_from_db()
def tweak_session_to_lock_down(self, flow_session_id=None):
session = self.c.session
session["relate_session_locked_to_exam_flow_session_pk"] = (
flow_session_id or FlowSession.objects.last().pk)
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
session.save()
def test_relate_exam_lockdown(self):
"""make sure when not locked down, request.relate_exam_lockdown is True"""
# not locked down
with mock.patch("course.views.render") as mock_render:
mock_render.return_value = http.HttpResponse("hello")
self.c.get("/")
request_obj = mock_render.call_args[0][0]
self.assertTrue(hasattr(request_obj, "relate_exam_lockdown"))
self.assertFalse(request_obj.relate_exam_lockdown)
# add lock down to the session
self.tweak_session_to_lock_down()
with mock.patch("course.utils.render") as mock_render:
mock_render.return_value = http.HttpResponse("hello")
resp = self.c.get("/")
self.assertRedirects(
resp,
self.get_view_start_flow_url(self.flow_id))
request_obj = mock_render.call_args[0][0]
self.assertTrue(hasattr(request_obj, "relate_exam_lockdown"))
self.assertTrue(request_obj.relate_exam_lockdown)
def test_lock_down_session_does_not_exist(self):
"""lock down to a session which does not exist"""
self.tweak_session_to_lock_down(flow_session_id=100)
resp = self.c.get("/")
self.assertEqual(resp.status_code, 403)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith(
"Error while processing exam lockdown: "
"flow session not found.")
def test_ok_views(self):
# we only test student participation user
from course.auth import make_sign_in_key
# make sign in key for a user
u = factories.UserFactory(
first_name="foo", last_name="bar",
status=constants.user_status.unconfirmed)
sign_in_key = make_sign_in_key(u)
u.sign_in_key = sign_in_key
u.save()
with override_settings(RELATE_SIGN_IN_BY_USERNAME_ENABLED=True):
for url, args, kwargs, code_or_redirect in [
# 403, because these file do not have "in_exam" access permission
("relate-get_repo_file", [], {
"course_identifier": self.course.identifier,
"commit_sha": self.course.active_git_commit_sha,
"path": "images/cc.png"}, 403),
("relate-get_current_repo_file", [], {
"course_identifier": self.course.identifier,
"path": "pdfs/sample.pdf"}, 403),
("relate-check_in_for_exam", [], {}, 200),
("relate-list_available_exams", [], {}, 200),
("relate-sign_in_choice", [], {}, 200),
("relate-sign_in_by_email", [], {}, 200),
("relate-sign_in_stage2_with_token",
[u.pk, sign_in_key], {}, "/"),
("relate-sign_in_by_user_pw", [], {}, 200),
("relate-user_profile", [], {}, 200),
("relate-logout", [], {}, "/"),
]:
with self.subTest(url=url):
if "sign_in" in url:
switch_to = None
else:
switch_to = self.student_participation.user
with self.temporarily_switch_to_user(switch_to):
self.tweak_session_to_lock_down()
resp = self.c.get(reverse(url, args=args, kwargs=kwargs))
try:
code = int(code_or_redirect)
self.assertEqual(resp.status_code, code)
except ValueError:
self.assertRedirects(
resp, code_or_redirect,
fetch_redirect_response=False)
def test_ok_with_saml2_views(self):
with override_settings(RELATE_SIGN_IN_BY_SAML2_ENABLED=True):
reload_urlconf()
with self.temporarily_switch_to_user(None):
self.tweak_session_to_lock_down()
# 'Settings' object has no attribute 'SAML_CONFIG'
# with that error raised, we can confirm it is actually
# requesting the view
with self.assertRaises(AttributeError):
self.c.get(reverse("saml2_login"))
self.assertAddMessageCallCount(0)
def test_ok_with_select2_views(self):
# There's curently no views using select2 when locked down.
# Here we are testing by using link from the select2 widget of
# impersonating form
with self.temporarily_switch_to_user(self.ta_participation.user):
resp = self.get_impersonate_view()
field_id = self.get_select2_field_id_from_response(resp)
# With no search term, should display all impersonatable users
term = None
self.tweak_session_to_lock_down()
resp = self.select2_get_request(field_id=field_id, term=term)
self.assertEqual(resp.status_code, 200)
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
def test_flow_page_related_view_ok(self):
for url, args, kwargs, code_or_redirect in [
("relate-view_resume_flow", [],
{"course_identifier": self.course.identifier,
"flow_session_id": self.fs.pk},
self.get_page_url_by_ordinal(0, flow_session_id=self.fs.pk)),
("relate-view_flow_page", [],
{"course_identifier": self.course.identifier,
"flow_session_id": self.fs.pk,
"page_ordinal": 0}, 200),
("relate-update_expiration_mode", [],
{"course_identifier": self.course.identifier,
"flow_session_id": self.fs.pk},
400), # this view doesn't allow get
("relate-update_page_bookmark_state", [],
{"course_identifier": self.course.identifier,
"flow_session_id": self.fs.pk, "page_ordinal": 0},
400), # this view doesn't allow get
("relate-finish_flow_session_view", [],
{"course_identifier": self.course.identifier,
"flow_session_id": self.fs.pk}, 200),
]:
with self.subTest(url=url):
self.tweak_session_to_lock_down()
resp = self.c.get(reverse(url, args=args, kwargs=kwargs))
try:
code = int(code_or_redirect)
self.assertEqual(resp.status_code, code)
except ValueError:
self.assertRedirects(
resp, code_or_redirect,
fetch_redirect_response=False)
def test_flow_page_related_view_not_ok(self):
another_flow_id = "jinja-yaml"
self.start_flow(flow_id=another_flow_id)
another_fs = FlowSession.objects.get(flow_id=another_flow_id)
for url, args, kwargs, code_or_redirect in [
("relate-view_resume_flow", [],
{"course_identifier": self.course.identifier,
"flow_session_id": another_fs.pk},
self.get_view_start_flow_url(self.flow_id)),
("relate-view_flow_page", [],
{"course_identifier": self.course.identifier,
"flow_session_id": another_fs.pk, "page_ordinal": 0},
self.get_view_start_flow_url(self.flow_id)),
("relate-update_expiration_mode", [],
{"course_identifier": self.course.identifier,
"flow_session_id": another_fs.pk},
self.get_view_start_flow_url(self.flow_id)),
("relate-update_page_bookmark_state", [],
{"course_identifier": self.course.identifier,
"flow_session_id": another_fs.pk, "page_ordinal": 0},
self.get_view_start_flow_url(self.flow_id)),
("relate-finish_flow_session_view", [],
{"course_identifier": self.course.identifier,
"flow_session_id": another_fs.pk},
self.get_view_start_flow_url(self.flow_id)),
]:
with self.subTest(url=url):
self.tweak_session_to_lock_down()
resp = self.c.get(reverse(url, args=args, kwargs=kwargs))
try:
code = int(code_or_redirect)