Skip to content
test_calendar.py 30.5 KiB
Newer Older
Dong Zhuang's avatar
Dong Zhuang committed
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
from __future__ import division

__copyright__ = "Copyright (C) 2018 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 pytz
import json
import datetime

from django.test import TestCase
from django.utils.timezone import now, timedelta

from relate.utils import as_local_time

from course.models import Event

from tests.base_test_mixins import (
    SingleCourseTestMixin, MockAddMessageMixing, HackRepoMixin)
from tests.utils import mock
from tests import factories
from tests.constants import DATE_TIME_PICKER_TIME_FORMAT


class CreateRecurringEventsTest(SingleCourseTestMixin,
                                MockAddMessageMixing, TestCase):
    """test course.calendar.create_recurring_events"""
    default_event_kind = "lecture"

    def get_create_recurring_events_url(self, course_identifier=None):
        course_identifier = course_identifier or self.get_default_course_identifier()
        return self.get_course_view_url(
            "relate-create_recurring_events", course_identifier)

    def get_create_recurring_events_view(self, course_identifier=None,
                                         force_login_instructor=True):
        course_identifier = course_identifier or self.get_default_course_identifier()
        if not force_login_instructor:
            user = self.get_logged_in_user()
        else:
            user = self.instructor_participation.user

        with self.temporarily_switch_to_user(user):
            return self.c.get(
                self.get_create_recurring_events_url(course_identifier))

    def post_create_recurring_events_view(self, data, course_identifier=None,
                                          force_login_instructor=True):
        course_identifier = course_identifier or self.get_default_course_identifier()
        if not force_login_instructor:
            user = self.get_logged_in_user()
        else:
            user = self.instructor_participation.user

        with self.temporarily_switch_to_user(user):
            return self.c.post(
                self.get_create_recurring_events_url(course_identifier), data)

    def get_post_create_recur_evt_data(
            self, op="submit", starting_ordinal=None, **kwargs):
        data = {
            "kind": self.default_event_kind,
            "time": now().replace(tzinfo=None).strftime(
                DATE_TIME_PICKER_TIME_FORMAT),
            "interval": "weekly",
            "count": 5,
            op: ''
        }

        if starting_ordinal:
            data["starting_ordinal"] = starting_ordinal

        data.update(kwargs)
        return data

    def test_not_authenticated(self):
        with self.temporarily_switch_to_user(None):
            resp = self.get_create_recurring_events_view(
                force_login_instructor=False)
            self.assertEqual(resp.status_code, 302)

            resp = self.post_create_recurring_events_view(
                data={}, force_login_instructor=False)
            self.assertEqual(resp.status_code, 302)

    def test_no_pperm(self):
        with self.temporarily_switch_to_user(self.student_participation.user):
            resp = self.get_create_recurring_events_view(
                force_login_instructor=False)
            self.assertEqual(resp.status_code, 403)

            resp = self.post_create_recurring_events_view(
                data={}, force_login_instructor=False)
            self.assertEqual(resp.status_code, 403)

    def test_get_success(self):
        resp = self.get_create_recurring_events_view()
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Event.objects.count(), 0)

    def test_post_form_not_valid(self):
        with mock.patch(
                "course.calendar.RecurringEventForm.is_valid"
        ) as mock_form_valid:
            mock_form_valid.return_value = False
            resp = self.post_create_recurring_events_view(
                data=self.get_post_create_recur_evt_data())
            self.assertEqual(resp.status_code, 200)

    def test_post_success_starting_ordinal_specified(self):
        resp = self.post_create_recurring_events_view(
            data=self.get_post_create_recur_evt_data(starting_ordinal=4))
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Event.objects.count(), 5)
        self.assertListEqual(
            list(Event.objects.values_list("ordinal", flat=True)),
            [4, 5, 6, 7, 8])

        t = None
        for evt in Event.objects.all():
            if t is None:
                t = evt.time
                continue
            else:
                self.assertEqual(evt.time - t, datetime.timedelta(weeks=1))
                t = evt.time

    def test_post_success_starting_ordinal_not_specified(self):
        resp = self.post_create_recurring_events_view(
            data=self.get_post_create_recur_evt_data())
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Event.objects.count(), 5)
        self.assertListEqual(
            list(Event.objects.values_list("ordinal", flat=True)),
            [1, 2, 3, 4, 5])

    def test_post_event_already_exists_starting_ordinal_specified(self):
        factories.EventFactory(
            course=self.course, kind=self.default_event_kind, ordinal=7)
        resp = self.post_create_recurring_events_view(
            data=self.get_post_create_recur_evt_data(starting_ordinal=4))
        self.assertEqual(resp.status_code, 200)

        # not created
        self.assertEqual(Event.objects.count(), 1)

        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(
            "EventAlreadyExists: 'lecture 7' already exists. "
            "No events created.")

    def test_post_event_already_exists_starting_ordinal_not_specified(self):
        factories.EventFactory(
            course=self.course, kind=self.default_event_kind, ordinal=4)
        resp = self.post_create_recurring_events_view(
            data=self.get_post_create_recur_evt_data())
        self.assertEqual(resp.status_code, 200)

        # created and ordinal is not None
        self.assertEqual(
            Event.objects.filter(
                kind=self.default_event_kind, ordinal__isnull=False).count(), 6)

        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith("Events created.")

    def test_unknown_error(self):
        error_msg = "my unknown error"
        with mock.patch(
                "course.calendar._create_recurring_events_backend"
        ) as mock_create_evt_backend:
            mock_create_evt_backend.side_effect = RuntimeError(error_msg)
            resp = self.post_create_recurring_events_view(
                data=self.get_post_create_recur_evt_data(starting_ordinal=4))
            self.assertEqual(resp.status_code, 200)

        # not created
        self.assertEqual(Event.objects.count(), 0)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(
            "RuntimeError: %s. No events created." % error_msg)

    def test_duration_in_minutes(self):
        resp = self.post_create_recurring_events_view(
            data=self.get_post_create_recur_evt_data(
                starting_ordinal=4, duration_in_minutes=20))
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Event.objects.count(), 5)
        self.assertListEqual(
            list(Event.objects.values_list("ordinal", flat=True)),
            [4, 5, 6, 7, 8])

        t = None
        for evt in Event.objects.all():
            self.assertEqual(evt.end_time - evt.time, timedelta(minutes=20))
            if t is None:
                t = evt.time
                continue
            else:
                self.assertEqual(evt.time - t, datetime.timedelta(weeks=1))
                t = evt.time

    def test_interval_biweekly(self):
        resp = self.post_create_recurring_events_view(
            data=self.get_post_create_recur_evt_data(
                starting_ordinal=4, interval="biweekly"))
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Event.objects.count(), 5)
        self.assertListEqual(
            list(Event.objects.values_list("ordinal", flat=True)),
            [4, 5, 6, 7, 8])

        t = None
        for evt in Event.objects.all():
            if t is None:
                t = evt.time
                continue
            else:
                self.assertEqual(evt.time - t, datetime.timedelta(weeks=2))
                t = evt.time


class RenumberEventsTest(SingleCourseTestMixin,
                         MockAddMessageMixing, TestCase):
    """test course.calendar.create_recurring_events"""
    default_event_kind = "lecture"

    def get_renumber_events_events_url(self, course_identifier=None):
        course_identifier = course_identifier or self.get_default_course_identifier()
        return self.get_course_view_url(
            "relate-renumber_events", course_identifier)

    def get_renumber_events_view(self, course_identifier=None,
                                 force_login_instructor=True):
        course_identifier = course_identifier or self.get_default_course_identifier()
        if not force_login_instructor:
            user = self.get_logged_in_user()
        else:
            user = self.instructor_participation.user

        with self.temporarily_switch_to_user(user):
            return self.c.get(
                self.get_renumber_events_events_url(course_identifier))

    def post_renumber_events_view(self, data, course_identifier=None,
                                  force_login_instructor=True):
        course_identifier = course_identifier or self.get_default_course_identifier()
        if not force_login_instructor:
            user = self.get_logged_in_user()
        else:
            user = self.instructor_participation.user

        with self.temporarily_switch_to_user(user):
            return self.c.post(
                self.get_renumber_events_events_url(course_identifier), data)

    def get_post_renumber_evt_data(
            self, starting_ordinal, kind=None, op="submit", **kwargs):

        data = {
            "kind": kind or self.default_event_kind,
            "starting_ordinal": starting_ordinal}

        if starting_ordinal:
            data["starting_ordinal"] = starting_ordinal

        data.update(kwargs)
        return data

    @classmethod
    def setUpTestData(cls):  # noqa
        super(RenumberEventsTest, cls).setUpTestData()
        times = []
        now_time = now()
        for i in range(5):
            times.append(now_time)
            now_time += timedelta(weeks=1)
            factories.EventFactory(
                kind=cls.default_event_kind, ordinal=i * 2 + 1, time=now_time)

        cls.evt1, cls.evt2, cls.evt3, cls.evt4, cls.evt5 = Event.objects.all()

        for i in range(2):
            factories.EventFactory(
                kind="another_kind", ordinal=i * 3 + 1, time=now_time)
            now_time += timedelta(weeks=1)

        cls.evt_another_kind1, cls.evt_another_kind2 = (
            Event.objects.filter(kind="another_kind"))
        cls.evt_another_kind1_ordinal = cls.evt_another_kind1.ordinal
        cls.evt_another_kind2_ordinal = cls.evt_another_kind2.ordinal

    def setUp(self):
        super(RenumberEventsTest, self).setUp()
        self.evt1.refresh_from_db()
        self.evt2.refresh_from_db()
        self.evt3.refresh_from_db()
        self.evt4.refresh_from_db()
        self.evt5.refresh_from_db()

    def test_not_authenticated(self):
        with self.temporarily_switch_to_user(None):
            resp = self.get_renumber_events_view(
                force_login_instructor=False)
            self.assertEqual(resp.status_code, 302)

            resp = self.post_renumber_events_view(data={},
                                                  force_login_instructor=False)
            self.assertEqual(resp.status_code, 302)

    def test_no_pperm(self):
        with self.temporarily_switch_to_user(self.student_participation.user):
            resp = self.get_renumber_events_view(
                force_login_instructor=False)
            self.assertEqual(resp.status_code, 403)

            resp = self.post_renumber_events_view(data={},
                                                  force_login_instructor=False)
            self.assertEqual(resp.status_code, 403)

    def test_get_success(self):
        resp = self.get_renumber_events_view()
        self.assertEqual(resp.status_code, 200)

    def test_post_form_not_valid(self):
        with mock.patch(
                "course.calendar.RenumberEventsForm.is_valid"
        ) as mock_form_valid:
            mock_form_valid.return_value = False

            resp = self.post_renumber_events_view(
                data=self.get_post_renumber_evt_data(starting_ordinal=3))
            self.assertEqual(resp.status_code, 200)

        all_default_evts = Event.objects.filter(kind=self.default_event_kind)
        self.assertEqual(all_default_evts.count(), 5)
        self.assertListEqual(
            list(all_default_evts.values_list("ordinal", flat=True)),
            [1, 3, 5, 7, 9])

        t = None
        for evt in all_default_evts:
            if t is None:
                t = evt.time
                continue
            else:
                self.assertEqual(evt.time - t, datetime.timedelta(weeks=1))
                t = evt.time

        # other events also not affected
        self.evt_another_kind1.refresh_from_db()
        self.evt_another_kind2.refresh_from_db()
        self.assertEqual(
            self.evt_another_kind1.ordinal, self.evt_another_kind1_ordinal)
        self.assertEqual(
            self.evt_another_kind2.ordinal, self.evt_another_kind2_ordinal)

    def test_post_success(self):
        resp = self.post_renumber_events_view(
            data=self.get_post_renumber_evt_data(starting_ordinal=3))
        self.assertEqual(resp.status_code, 200)
        all_pks = list(Event.objects.values_list("pk", flat=True))

        # originally 1, 3, 5, 7, 9, now 3, 4, 5, 6, 7

        all_default_evts = Event.objects.filter(kind=self.default_event_kind)
        self.assertEqual(all_default_evts.count(), 5)
        self.assertListEqual(
            list(all_default_evts.values_list("ordinal", flat=True)),
            [3, 4, 5, 6, 7])

        t = None
        for evt in all_default_evts:
            if t is None:
                t = evt.time
                continue
            else:
                self.assertEqual(evt.time - t, datetime.timedelta(weeks=1))
                t = evt.time

        # other events not affected
        self.evt_another_kind1.refresh_from_db()
        self.evt_another_kind2.refresh_from_db()
        self.assertEqual(
            self.evt_another_kind1.ordinal, self.evt_another_kind1_ordinal)
        self.assertEqual(
            self.evt_another_kind2.ordinal, self.evt_another_kind2_ordinal)

        # no new objects created
        self.assertListEqual(
            list(Event.objects.values_list("pk", flat=True)), all_pks)

        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith("Events renumbered.")

    def test_renumber_non_existing_events(self):
        all_pks = list(Event.objects.values_list("pk", flat=True))

        resp = self.post_renumber_events_view(
            data=self.get_post_renumber_evt_data(
                kind="foo_kind", starting_ordinal=3))
        self.assertEqual(resp.status_code, 200)

        # nothing changed
        all_default_evts = Event.objects.filter(kind=self.default_event_kind)
        self.assertListEqual(
            list(all_default_evts.values_list("ordinal", flat=True)),
            [1, 3, 5, 7, 9])

        # no new objects created
        self.assertListEqual(
            list(Event.objects.values_list("pk", flat=True)), all_pks)

        # other events also not affected
        self.evt_another_kind1.refresh_from_db()
        self.evt_another_kind2.refresh_from_db()
        self.assertEqual(
            self.evt_another_kind1.ordinal, self.evt_another_kind1_ordinal)
        self.assertEqual(
            self.evt_another_kind2.ordinal, self.evt_another_kind2_ordinal)

        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith("No events found.")


class ViewCalendarTest(SingleCourseTestMixin, HackRepoMixin, TestCase):
    """test course.calendar.view_calendar"""

    default_faked_now = datetime.datetime(2019, 1, 1, tzinfo=pytz.UTC)
    default_event_time = default_faked_now - timedelta(hours=12)
    default_event_kind = "lecture"

    def setUp(self):
        super(ViewCalendarTest, self).setUp()
        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)

        self.addCleanup(factories.EventFactory.reset_sequence)

    def get_course_calender_view(self, course_identifier=None):
        course_identifier = course_identifier or self.get_default_course_identifier()
        return self.c.get(self.get_course_calender_url(course_identifier))

    def switch_to_fake_commit_sha(self):
        self.course.active_git_commit_sha = "my_fake_commit_sha_for_events"
        self.course.events_file = "events.yml"
        self.course.save()

    def test_no_pperm(self):
        with mock.patch(
                "course.utils.CoursePageContext.has_permission"
        ) as mock_has_pperm:
            mock_has_pperm.return_value = False
            resp = self.get_course_calender_view()
            self.assertEqual(resp.status_code, 403)

    def test_neither_events_nor_event_file(self):
        self.mock_get_now_or_fake_time.return_value = self.default_faked_now
        resp = self.get_course_calender_view()
        self.assertEqual(resp.status_code, 200)
        self.assertResponseContextEqual(resp, "events_json", '[]')
        self.assertResponseContextEqual(resp, "event_info_list", [])
        self.assertResponseContextEqual(
            resp, "default_date", self.default_faked_now.date().isoformat())

    def test_no_event_file(self):
        factories.EventFactory(
            kind=self.default_event_kind, course=self.course,
            time=self.default_event_time)
        factories.EventFactory(
            kind=self.default_event_kind, course=self.course,
            time=self.default_event_time + timedelta(hours=1))

        resp = self.get_course_calender_view()
        self.assertEqual(resp.status_code, 200)

        events_json = json.loads(resp.context["events_json"])
        self.assertEqual(len(events_json), 2)
        self.assertDictEqual(
            events_json[0],
            {'id': 1, 'start': self.default_event_time.isoformat(),
             'allDay': False,
             'title': 'lecture 0'})
        self.assertDictEqual(
            events_json[1],
            {'id': 2,
             'start': (self.default_event_time + timedelta(hours=1)).isoformat(),
             'allDay': False,
             'title': 'lecture 1'})

        self.assertResponseContextEqual(resp, "event_info_list", [])

    def test_hidden_event_not_shown(self):
        factories.EventFactory(
            kind=self.default_event_kind, course=self.course,
            time=self.default_event_time)
        factories.EventFactory(
            kind=self.default_event_kind, course=self.course,
            shown_in_calendar=False,
            time=self.default_event_time + timedelta(hours=1))

        resp = self.get_course_calender_view()
        self.assertEqual(resp.status_code, 200)

        events_json = json.loads(resp.context["events_json"])
        self.assertEqual(len(events_json), 1)
        self.assertDictEqual(
            events_json[0],
            {'id': 1, 'start': self.default_event_time.isoformat(),
             'allDay': False,
             'title': 'lecture 0'})
        self.assertResponseContextEqual(resp, "event_info_list", [])

    def test_event_has_end_time(self):
        factories.EventFactory(
            kind=self.default_event_kind, course=self.course,
            time=self.default_event_time,
            end_time=self.default_event_time + timedelta(hours=1))
        resp = self.get_course_calender_view()
        self.assertEqual(resp.status_code, 200)

        events_json = json.loads(resp.context["events_json"])
        self.assertEqual(len(events_json), 1)
        event_json = events_json[0]
        self.assertDictEqual(
            event_json,
            {'id': 1, 'start': self.default_event_time.isoformat(),
             'allDay': False,
             'title': 'lecture 0',
             'end': (self.default_event_time + timedelta(hours=1)).isoformat(),
             })

        self.assertResponseContextEqual(resp, "event_info_list", [])

    def test_event_course_finished(self):
        self.mock_get_now_or_fake_time.return_value = self.default_faked_now
        self.course.end_date = (self.default_faked_now - timedelta(weeks=1)).date()
        self.course.save()

        resp = self.get_course_calender_view()
        self.assertEqual(resp.status_code, 200)

        self.assertResponseContextEqual(resp, "events_json", '[]')
        self.assertResponseContextEqual(resp, "event_info_list", [])
        self.assertResponseContextEqual(
            resp, "default_date", self.course.end_date.isoformat())

    def test_event_course_not_finished(self):
        self.mock_get_now_or_fake_time.return_value = self.default_faked_now
        self.course.end_date = (self.default_faked_now + timedelta(weeks=1)).date()
        self.course.save()

        resp = self.get_course_calender_view()
        self.assertEqual(resp.status_code, 200)

        self.assertResponseContextEqual(resp, "events_json", '[]')
        self.assertResponseContextEqual(resp, "event_info_list", [])
        self.assertResponseContextEqual(
            resp, "default_date", self.default_faked_now.date().isoformat())

    def test_events_file_no_events(self):
        # make sure it works
        self.switch_to_fake_commit_sha()

        resp = self.get_course_calender_view()

        self.assertResponseContextEqual(resp, "events_json", '[]')
        self.assertResponseContextEqual(resp, "event_info_list", [])

    def test_events_file_with_events_test1(self):
        self.switch_to_fake_commit_sha()

        # lecture 1
        lecture1_start_time = self.default_event_time - timedelta(weeks=1)
        factories.EventFactory(
            kind=self.default_event_kind, course=self.course,
            time=lecture1_start_time, ordinal=1)

        # lecture 2
        factories.EventFactory(
            kind=self.default_event_kind, course=self.course,
            time=self.default_event_time, ordinal=2)

        resp = self.get_course_calender_view()

        events_json = json.loads(resp.context["events_json"])
        self.assertEqual(len(events_json), 2)
        self.assertDictEqual(
            events_json[0],
            {'id': 2, 'start': self.default_event_time.isoformat(),
             'allDay': False,
             'title': 'Lecture 2'})

        self.assertDictEqual(
            events_json[1],
            {'id': 1,
             'color': "red",
             'start': lecture1_start_time.isoformat(),
             'allDay': False,
             'title': 'Alternative title for lecture 1',
             'url': '#event-1'
             })

        event_info_list = resp.context["event_info_list"]

        # lecture 2 doesn't create an EventInfo object
        self.assertEqual(len(event_info_list), 1)

        # check the attributes of EventInfo of lecture 1
        evt_info_dict = event_info_list[0].__dict__
        evt_description = evt_info_dict.pop("description")

        self.assertDictEqual(
            evt_info_dict,
            {"id": 1, "human_title": "Alternative title for lecture 1",
             "start_time": lecture1_start_time,
             "end_time": None})

        # make sure markup_to_html is called
        self.assertIn(
            'href="/course/test-course/flow/prequiz-linear-algebra/start/',
            evt_description)

    def test_events_file_with_events_test2(self):
        self.switch_to_fake_commit_sha()

        self.mock_get_now_or_fake_time.return_value = (
                self.default_event_time + timedelta(minutes=5))

        # lecture 2
        factories.EventFactory(
            kind=self.default_event_kind, course=self.course,
            time=self.default_event_time, ordinal=2)

        # lecture 3
        lecture3_start_time = self.default_event_time + timedelta(weeks=1)
        factories.EventFactory(
            kind=self.default_event_kind, course=self.course,
            time=lecture3_start_time, ordinal=3)

        # test event
        test_start_time = self.default_event_time + timedelta(minutes=1)
        factories.EventFactory(
            kind="test", course=self.course, all_day=True,
            time=test_start_time,
            ordinal=None)

        resp = self.get_course_calender_view()

        events_json = json.loads(resp.context["events_json"])
        self.assertEqual(len(events_json), 3)

        self.assertDictEqual(
            events_json[0],
            {'id': 2, 'start': (lecture3_start_time).isoformat(),
             'allDay': False,
             'title': 'Lecture 3'})

        self.assertDictEqual(
            events_json[1],
            {'id': 1, 'start': self.default_event_time.isoformat(),
             'allDay': False,
             'title': 'Lecture 2',
             'url': '#event-1'})

        self.assertDictEqual(
            events_json[2],
            {'id': 3, 'start': test_start_time.isoformat(),
             'allDay': True,
             'title': 'test'})

        event_info_list = resp.context["event_info_list"]

        # only lecture 2 create an EventInfo object
        self.assertEqual(len(event_info_list), 1)

        # check the attributes of EventInfo of lecture 1
        evt_info_dict = event_info_list[0].__dict__
        evt_description = evt_info_dict.pop("description")

        self.assertDictEqual(
            evt_info_dict,
            {"id": 1, "human_title": "Lecture 2",
             "start_time": self.default_event_time,
             "end_time": None})

        self.assertIn(
            'Can you see this?',
            evt_description)

        # lecture 2's description exceeded show_description_until
        self.mock_get_now_or_fake_time.return_value = (
                lecture3_start_time + timedelta(minutes=5))

        # no EventInfo object
        resp = self.get_course_calender_view()
        self.assertResponseContextEqual(resp, "event_info_list", [])

    def test_events_file_with_events_test3(self):
        self.switch_to_fake_commit_sha()

        exam_end_time = self.default_event_time + timedelta(hours=2)
        factories.EventFactory(
            kind="exam", course=self.course,
            ordinal=None,
            time=self.default_event_time,
            end_time=exam_end_time)

        resp = self.get_course_calender_view()

        events_json = json.loads(resp.context["events_json"])
        self.assertEqual(len(events_json), 1)

        self.assertDictEqual(
            events_json[0],
            {'id': 1,
             'start': self.default_event_time.isoformat(),
             'allDay': False,
             'title': 'Exam',
             'color': 'red',
             'end': exam_end_time.isoformat()})

        self.assertResponseContextEqual(resp, "event_info_list", [])

    def test_all_day_event(self):
        self.switch_to_fake_commit_sha()

        # lecture 2, no end_time
        lecture2_start_time = datetime.datetime(2019, 1, 1, tzinfo=pytz.UTC)

        self.mock_get_now_or_fake_time.return_value = (
                lecture2_start_time + timedelta(minutes=5))

        lecture2_evt = factories.EventFactory(
            kind=self.default_event_kind, course=self.course,
            all_day=True,
            time=lecture2_start_time, ordinal=2)

        # lecture 3
        lecture3_start_time = lecture2_start_time + timedelta(weeks=1)
        factories.EventFactory(
            kind=self.default_event_kind, course=self.course,
            time=lecture3_start_time, ordinal=3)

        resp = self.get_course_calender_view()

        events_json = json.loads(resp.context["events_json"])
        self.assertEqual(len(events_json), 2)

        self.assertDictEqual(
            events_json[1],
            {'id': 1, 'start': lecture2_start_time.isoformat(),
             'allDay': True,
             'title': 'Lecture 2',
             'url': '#event-1'})

        # now we add end_time of lecture 2 evt to a time which is not midnight
        lecture2_end_time = lecture2_start_time + timedelta(hours=18)
        lecture2_evt.end_time = lecture2_end_time
        lecture2_evt.save()

        resp = self.get_course_calender_view()

        events_json = json.loads(resp.context["events_json"])
        self.assertEqual(len(events_json), 2)

        self.assertDictEqual(
            events_json[1],
            {'id': 1, 'start': lecture2_start_time.isoformat(),
             'allDay': True,
             'title': 'Lecture 2',
             'url': '#event-1',
             'end': lecture2_end_time.isoformat()
             })

        # now we update end_time of lecture 2 evt to midnight
        while True:
            local_t = as_local_time(lecture2_end_time)
            end_midnight = datetime.time(tzinfo=local_t.tzinfo)
            if local_t.time() == end_midnight:
                lecture2_evt.end_time = lecture2_end_time
                lecture2_evt.save()
                break

            lecture2_end_time += timedelta(hours=1)

        resp = self.get_course_calender_view()

        events_json = json.loads(resp.context["events_json"])
        self.assertEqual(len(events_json), 2)

        self.assertDictEqual(
            events_json[1],
            {'id': 1, 'start': lecture2_start_time.isoformat(),
             'allDay': True,
             'title': 'Lecture 2',
             'url': '#event-1',
             'end': lecture2_end_time.isoformat()
             })

# vim: fdm=marker