Пример #1
0
 def _setUpVeterisSubsite(self):
     main = getPage("/home/")
     home = Page(slug="veteris", title="Veteris Council")
     main.add_child(instance=home)
     home.save_revision().publish()
     activities = Page(slug="activities", title="Veteris Calendar")
     home.add_child(instance=activities)
     activities.save_revision().publish()
     Site.objects.create(hostname='veteris.joy.test',
                         root_page_id=home.id,
                         is_default_site=False)
     events = CalendarPage(owner=self.user,
                           slug="veteris-events",
                           title="Veteris Events")
     home.add_child(instance=events)
     events.save_revision().publish()
     committee = RecurringEventPage(owner=self.user,
                                    slug="veteris-committee",
                                    title="Committee Meeting",
                                    repeat=Recurrence(
                                        dtstart=dt.date(1970, 1, 5),
                                        freq=MONTHLY,
                                        byweekday=[MO],
                                        until=dt.date(1978, 8, 7)),
                                    time_from=dt.time(14),
                                    time_to=dt.time(15))
     events.add_child(instance=committee)
     committee.save_revision().publish()
Пример #2
0
class TestTZ(TestCase):
    def setUp(self):
        self.home = Page.objects.get(slug='home')
        self.user = User.objects.create_user('i', '*****@*****.**', 's3(r3t')
        self.calendar = CalendarPage(owner=self.user,
                                     slug="events",
                                     title="Events")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()
        self.event = RecurringEventPage(slug="test-meeting",
                                        title="Test Meeting",
                                        repeat=Recurrence(
                                            dtstart=dt.date(1989, 1, 1),
                                            freq=WEEKLY,
                                            byweekday=[MO, WE, FR]),
                                        time_from=dt.time(13, 30),
                                        time_to=dt.time(16),
                                        tz=pytz.timezone("US/Eastern"))
        self.calendar.add_child(instance=self.event)
        self.cancellation = CancellationPage(
            owner=self.user,
            overrides=self.event,
            except_date=dt.date(1989, 2, 1),
            cancellation_title="Meeting Cancelled",
            cancellation_details="Cancelled due to lack of interest")
        self.event.add_child(instance=self.cancellation)
        self.cancellation.save_revision().publish()

    @timezone.override("Australia/Sydney")
    @freeze_timetz("1989-02-02T06:00:00+11:00")
    def testCurrentLocalDt(self):
        when = self.cancellation._current_datetime_from
        self.assertEqual(when.tzinfo.zone, "Australia/Sydney")
        self.assertEqual(when.time(), dt.time(5, 30))
        self.assertEqual(when.date(), dt.date(1989, 2, 2))

    @timezone.override("Australia/Sydney")
    @freeze_timetz("1989-02-02T06:00:00+11:00")
    def testFutureLocalDt(self):
        when = self.cancellation._future_datetime_from
        self.assertIsNone(when)

    @timezone.override("Australia/Sydney")
    def testPastLocalDt(self):
        when = self.cancellation._past_datetime_from
        self.assertEqual(when.tzinfo.zone, "Australia/Sydney")
        self.assertEqual(when.time(), dt.time(5, 30))
        self.assertEqual(when.date(), dt.date(1989, 2, 2))

    @timezone.override("Australia/Sydney")
    @freeze_timetz("1989-10-01T21:00:00+11:00")
    def testCopyFieldsFromParent(self):
        self.assertEqual(self.event.next_date, dt.date(1989, 10, 3))
        cancellation = CancellationPage(owner=self.user)
        cancellation._copyFieldsFromParent(self.event)
        self.assertEqual(cancellation.overrides, self.event)
        self.assertEqual(cancellation.except_date, dt.date(1989, 10, 2))
Пример #3
0
class TestMultiday(TestCase):
    def setUp(self):
        self.home = Page.objects.get(slug='home')
        self.user = User.objects.create_user('i', '*****@*****.**', 's3(r3t')
        self.calendar = CalendarPage(owner=self.user,
                                     slug="schedule",
                                     title="Schedule")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()
        self.event = MultidayRecurringEventPage(
            slug="test-session",
            title="Test Session",
            repeat=Recurrence(dtstart=dt.date(2018, 1, 8),
                              freq=WEEKLY,
                              byweekday=[MO],
                              until=dt.date(2018, 4, 25)),
            num_days=3,
            time_from=dt.time(10),
            time_to=dt.time(12, 30))
        self.calendar.add_child(instance=self.event)
        self.info = ExtraInfoPage(owner=self.user,
                                  overrides=self.event,
                                  except_date=dt.date(2018, 2, 12),
                                  extra_title="System Demo",
                                  extra_information="<h3>System Demo</h3>")
        self.event.add_child(instance=self.info)
        self.info.save_revision().publish()

    def testStatusFinished(self):
        self.assertEqual(self.info.status, "finished")
        self.assertEqual(self.info.status_text, "This event has finished.")

    @freeze_timetz("2018-02-13 14:00:00")
    def testStatusStarted(self):
        self.assertEqual(self.info.status, "started")
        self.assertEqual(self.info.status_text, "This event has started.")

    def testWhen(self):
        self.assertEqual(
            self.info.when, "Monday 12th of February 2018 for 3 days "
            "starting at 10am finishing at 12:30pm")

    def testAt(self):
        self.assertEqual(self.info.at.strip(), "10am")

    @freeze_timetz("2018-02-13 17:00:00")
    def testCurrentDt(self):
        self.assertEqual(self.info._current_datetime_from,
                         datetimetz(2018, 2, 12, 10, 0))

    @freeze_timetz("2018-02-13 14:00:00")
    def testFutureDt(self):
        self.assertIsNone(self.info._future_datetime_from)

    def testPastDt(self):
        self.assertEqual(self.info._past_datetime_from,
                         datetimetz(2018, 2, 12, 10, 0))
Пример #4
0
 def testMainSiteAnotherCalendar(self):
     calendar = CalendarPage(
         owner=self.user,
         slug="events",
         title="Events",
     )
     self.main.add_child(instance=calendar)
     calendar.save_revision().publish()
     self.assertFalse(CalendarPage.can_create_at(self.main))
Пример #5
0
class Test40Day(TestCase):
    def setUp(self):
        self.user = User.objects.create_user('i', '*****@*****.**', 's3cr3t')
        self.calendar = CalendarPage(owner=self.user,
                                     slug="events",
                                     title="Events")
        Page.objects.get(slug='home').add_child(instance=self.calendar)
        self.calendar.save()
        self.calendar.save_revision().publish()
        self.event = MultidayRecurringEventPage(
            owner=self.user,
            slug="ice-festival",
            title="Ice Festival",
            repeat=Recurrence(dtstart=dt.date(2000, 12, 25),
                              until=dt.date(2020, 1, 31),
                              freq=YEARLY,
                              bymonth=12,
                              byweekday=MO(4)),
            num_days=40)
        self.calendar.add_child(instance=self.event)
        self.event.save_revision().publish()

    def testGetEventsByDay(self):
        events = MultidayRecurringEventPage.events.byDay(
            dt.date(2020, 1, 1), dt.date(2020, 1, 31))
        self.assertEqual(len(events), 31)
        evod = events[0]
        self.assertEqual(evod.date, dt.date(2020, 1, 1))
        self.assertEqual(len(evod.days_events), 0)
        self.assertEqual(len(evod.continuing_events), 1)
        thisEvent = evod.continuing_events[0]
        self.assertEqual(thisEvent.title, "Ice Festival")
        evod = events[10]
        self.assertEqual(evod.date, dt.date(2020, 1, 11))
        self.assertEqual(len(evod.continuing_events), 1)
        thisEvent = evod.continuing_events[0]
        self.assertEqual(thisEvent.title, "Ice Festival")

    def testStatus(self):
        with freeze_timetz("2019-12-20 13:00:00"):
            self.assertEqual(self.event.status_text, "")
        with freeze_timetz("2020-01-02 13:00:00"):
            self.assertEqual(self.event.status_text, "This event has started.")
        with freeze_timetz("2020-02-03 17:00:00"):
            self.assertEqual(self.event.status_text,
                             "These events have finished.")

    def testAt(self):
        self.assertEqual(self.event.at.strip(), "")

    @freeze_timetz("2035-04-03 10:00:00")
    def testNextDate(self):
        self.assertEqual(self.event.next_date, None)

    @freeze_timetz("2035-04-03 10:00:00")
    def testPrevDate(self):
        self.assertEqual(self.event.prev_date, dt.date(2019, 12, 23))
class TestPageForm(TestCase):
    Form = ExtCancellationPage.get_edit_handler().get_form_class()

    def setUp(self):
        self.home = Page.objects.get(slug='home')
        self.user = User.objects.create_user('i', '*****@*****.**', 's3(r3t')
        self.calendar = CalendarPage(owner=self.user,
                                     slug="events",
                                     title="Events")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()
        self.event = RecurringEventPage(slug="committee-meeting",
                                        title="Committee Meeting",
                                        repeat=Recurrence(
                                            dtstart=dt.date(2017, 1, 1),
                                            freq=MONTHLY,
                                            byweekday=[MO(1), MO(3)]),
                                        time_from=dt.time(13),
                                        time_to=dt.time(15, 30))
        self.calendar.add_child(instance=self.event)
        self.shutdown = ExtCancellationPage(
            owner=self.user,
            overrides=self.event,
            cancelled_from_date=dt.date(2020, 3, 2),
            cancelled_to_date=dt.date(2020, 3, 6))
        self.event.add_child(instance=self.shutdown)
        self.shutdown.save_revision().publish()

    def testValid(self):
        page = ExtCancellationPage(owner=self.user)
        form = self.Form(
            {
                'overrides': self.event,
                'cancelled_from_date': "2020-03-10"
            },
            instance=page,
            parent_page=self.event)
        self.assertTrue(form.is_valid())  # is_valid() calls full_clean()
        self.assertDictEqual(form.errors, {})

    def testExceptionAlreadyExists(self):
        page = ExtCancellationPage(owner=self.user)
        form = self.Form(
            {
                'overrides': self.event,
                'cancelled_from_date': "2020-03-02"
            },
            instance=page,
            parent_page=self.event)
        self.assertFalse(form.is_valid())
        self.assertDictEqual(
            form.errors, {
                'cancelled_from_date':
                ['There is already an extended cancellation for then']
            })
Пример #7
0
class TestPageFormDeutsche(TestCase):
    Form = ExtraInfoPage.get_edit_handler().get_form_class()

    def setUp(self):
        translation.activate('de')
        self.home = Page.objects.get(slug='home')
        self.user = User.objects.create_user('i', '*****@*****.**', 's3(r3t')
        self.calendar = CalendarPage(owner=self.user,
                                     slug="ereignisse",
                                     title="Ereignisse")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()
        self.event = RecurringEventPage(slug="meeting",
                                        title="Testen Sie Meeting",
                                        repeat=Recurrence(
                                            dtstart=dt.date(1988, 1, 1),
                                            freq=WEEKLY,
                                            byweekday=[MO, WE, FR]),
                                        time_from=dt.time(13),
                                        time_to=dt.time(15, 30))
        self.calendar.add_child(instance=self.event)
        self.info = ExtraInfoPage(owner=self.user,
                                  overrides=self.event,
                                  except_date=dt.date(1999, 1, 5),
                                  extra_title="Freitag",
                                  extra_information="Besonderer Freitag")
        self.event.add_child(instance=self.info)
        self.info.save_revision().publish()

    def tearDown(self):
        translation.deactivate()

    def testExceptionAlreadyExists(self):
        page = ExtraInfoPage(owner=self.user)
        form = self.Form(
            {
                'overrides': self.event,
                'except_date': "1999-01-05",
                'extra_title': "Es ist Freitag",
                'extra_information': rich_text("Besonderer spezieller Freitag")
            },
            instance=page,
            parent_page=self.event)
        self.assertFalse(form.is_valid())
        self.assertDictEqual(
            form.errors, {
                'except_date':
                ['Dieses Datum enthält bereits zusätzliche information']
            })
Пример #8
0
 def setUp(self):
     self.user = User.objects.create_user('i', '*****@*****.**', 's3(r3t')
     calendar = CalendarPage(owner=self.user,
                             slug="events",
                             title="Events",
                             default_view="L")
     Page.objects.get(slug='home').add_child(instance=calendar)
     calendar.save_revision().publish()
     event = SimpleEventPage(owner=self.user,
                             slug="tree-planting",
                             title="Tree Planting",
                             date=dt.date(2011, 6, 5),
                             time_from=dt.time(9, 30),
                             time_to=dt.time(11, 0))
     calendar.add_child(instance=event)
     event.save_revision().publish()
Пример #9
0
 def setUp(self):
     translation.activate('fr')
     self.user = User.objects.create_superuser('i', '*****@*****.**', 's3(r3t')
     calendar = CalendarPage(owner=self.user,
                             slug="calendrier",
                             title="Calendrier")
     Page.objects.get(slug='home').add_child(instance=calendar)
     calendar.save_revision().publish()
     event = SimpleEventPage(owner=self.user,
                             slug="plantation-d-arbres",
                             title="Plantation d'arbres",
                             date=dt.date(2011, 6, 5),
                             time_from=dt.time(9, 30),
                             time_to=dt.time(11, 0))
     calendar.add_child(instance=event)
     event.save_revision().publish()
Пример #10
0
 def _setUpNovaSubsite(self):
     main = getPage("/home/")
     home = Page(slug="nova", title="Nova Homepage")
     main.add_child(instance=home)
     home.save_revision().publish()
     activities = Page(slug="activities", title="Nova Activities")
     home.add_child(instance=activities)
     activities.save_revision().publish()
     Site.objects.create(hostname='nova.joy.test',
                         root_page_id=home.id,
                         is_default_site=False)
     events = CalendarPage(owner=self.user,
                           slug="nova-events",
                           title="Nova Events")
     home.add_child(instance=events)
     events.save_revision().publish()
     committee = RecurringEventPage(owner=self.user,
                                    slug="executive-meeting",
                                    title="Executive Committee Meeting",
                                    repeat=Recurrence(dtstart=dt.date(
                                        1984, 8, 5),
                                                      freq=WEEKLY,
                                                      byweekday=[TH]),
                                    time_from=dt.time(13),
                                    time_to=dt.time(15))
     events.add_child(instance=committee)
     committee.save_revision().publish()
     event = SimpleEventPage(owner=self.user,
                             slug="rubbish-blitz",
                             title="Rubbish Blitz",
                             date=dt.date(1984, 9, 13),
                             time_from=dt.time(12, 30),
                             time_to=dt.time(17))
     events.add_child(instance=event)
     event.save_revision().publish()
     cancellation = CancellationPage(
         owner=self.user,
         slug="1984-09-13-cancellation",
         title="Cancellation for Thursday 13th of September",
         overrides=committee,
         except_date=dt.date(1984, 9, 13),
         cancellation_title="Meeting Cancelled",
         cancellation_details="The committee will be at "
         "the working bee")
     committee.add_child(instance=cancellation)
     cancellation.save_revision().publish()
Пример #11
0
 def testCalendarMixture(self):
     general = GeneralCalendarPage(owner=self.user,
                                   slug="events1",
                                   title="Events")
     self.main.add_child(instance=general)
     general.save_revision().publish()
     self.assertTrue(CalendarPage.can_create_at(self.main))
     calendar = CalendarPage(owner=self.user,
                             slug="events2",
                             title="Events")
     self.main.add_child(instance=calendar)
     calendar.save_revision().publish()
     self.assertTrue(SpecificCalendarPage.can_create_at(self.main))
     specific = SpecificCalendarPage(owner=self.user,
                                     slug="events3",
                                     title="Events")
     self.main.add_child(instance=specific)
     specific.save_revision().publish()
Пример #12
0
class TestPageForm(TestCase):
    Form = ExtraInfoPage.get_edit_handler().get_form_class()

    def setUp(self):
        self.home = Page.objects.get(slug='home')
        self.user = User.objects.create_user('i', '*****@*****.**', 's3(r3t')
        self.calendar = CalendarPage(owner=self.user,
                                     slug="events",
                                     title="Events")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()
        self.event = RecurringEventPage(slug="test-meeting",
                                        title="Test Meeting",
                                        repeat=Recurrence(
                                            dtstart=dt.date(1988, 1, 1),
                                            freq=WEEKLY,
                                            byweekday=[MO, WE, FR]),
                                        time_from=dt.time(13),
                                        time_to=dt.time(15, 30))
        self.calendar.add_child(instance=self.event)
        self.info = ExtraInfoPage(owner=self.user,
                                  overrides=self.event,
                                  except_date=dt.date(1999, 1, 5),
                                  extra_title="Fri-day",
                                  extra_information="Special Friday")
        self.event.add_child(instance=self.info)
        self.info.save_revision().publish()

    def testExceptionAlreadyExists(self):
        page = ExtraInfoPage(owner=self.user)
        form = self.Form(
            {
                'overrides': self.event,
                'except_date': "1999-01-05",
                'extra_title': "It's Friday",
                'extra_information': rich_text("Special Special Friday")
            },
            instance=page,
            parent_page=self.event)
        self.assertFalse(form.is_valid())
        self.assertDictEqual(
            form.errors,
            {'except_date': ['That date already has extra information']})
Пример #13
0
 def testAssimilatedSave(self):
     user = User.objects.create_user('i', '*****@*****.**', 's3cr3t')
     calendar = CalendarPage(owner=user, slug="events", title="Events")
     home = Page.objects.get(slug='home')
     home.add_child(instance=calendar)
     calendar.save_revision().publish()
     event = MEP(owner=user,
                 slug="allnighter",
                 title="All Night",
                 date_from=dt.date(2012, 12, 31),
                 date_to=dt.date(2013, 1, 1),
                 time_from=dt.time(23),
                 time_to=dt.time(3))
     calendar.add_child(instance=event)
     event.save_revision().publish()
     MEP.base_form_class = NewPageForm
     Form = MEP.get_edit_handler().get_form_class()
     form = Form(instance=event, parent_page=calendar)
     page = form.save()
     self.assertEqual(page.owner.username, "buck")
Пример #14
0
class TestCalendarPageForm(TestCase):
    def setUp(self):
        self.user = User.objects.create_superuser('i', '*****@*****.**', 's3(r3t')
        self.request = RequestFactory().get("/test")
        self.request.user = self.user
        self.request.session = {}
        self.home = Page.objects.get(slug='home')
        self.page = CalendarPage(owner=self.user,
                                 slug="events",
                                 title="Events")
        self.home.add_child(instance=self.page)
        self.page.save_revision().publish()

    def testImportPanel(self):
        CalendarPageForm.registerImportHandler(Mock())
        panel = CalendarPage.settings_panels[-1]
        self.assertFalse(panel._show())
        panel.instance = self.page
        panel.request = self.request
        self.assertFalse(panel._show())
        setattr(self.page, '__joyous_edit_request', self.request)
        self.assertTrue(panel._show())
        delattr(self.page, '__joyous_edit_request')

    def testSave(self):
        Form = get_form_for_model(CalendarPage, form_class=CalendarPageForm)
        setattr(self.page, '__joyous_edit_request', self.request)
        form = Form(instance=self.page, parent_page=self.home)
        handler = Mock()
        CalendarPageForm.registerImportHandler(handler)
        form.cleaned_data = {'utc2local': True, 'upload': "FILE"}
        form.save()
        handler.load.assert_called_with(self.page,
                                        self.request,
                                        "FILE",
                                        utc2local=True)
Пример #15
0
class TestFeed(TestCase):
    @freeze_time("2016-03-24")
    def setUp(self):
        imgFile = get_test_image_file()
        imgFile.name = "logo.png"
        self.img = Image.objects.create(title="Logo", file=imgFile)
        imgName = os.path.splitext(os.path.basename(self.img.file.name))[0]
        self.rendName = "{}.width-350.format-png.png".format(imgName)
        Site.objects.update(hostname="joy.test")
        self.home = Page.objects.get(slug='home')
        self.user = User.objects.create_user('i', '*****@*****.**', 's3(R3t')
        self.requestFactory = RequestFactory()
        self.calendar = CalendarPage(owner = self.user,
                                     slug  = "events",
                                     title = "Events")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()
        self.event = RecurringEventPage(owner = self.user,
                                        slug  = "workshop",
                                        title = "Workshop",
                                        image = self.img,
                                        repeat    = Recurrence(dtstart=dt.date(2017,1,1),
                                                               freq=MONTHLY,
                                                               byweekday=[TU(1)],
                                                               until=dt.date(2017,12,26)))
        self.calendar.add_child(instance=self.event)
        self.event.save_revision().publish()
        self.handler = RssHandler()

    def tearDown(self):
        self.img.file.delete(False)
        for rend in self.img.renditions.all():
            rend.file.delete(False)

    def _getRequest(self, path="/"):
        request = self.requestFactory.get(path)
        request.user = self.user
        request.site = self.home.get_site()
        request.session = {}
        request._messages = FallbackStorage(request)
        request.POST = request.POST.copy()
        request.POST['action-publish'] = "action-publish"
        return request

    @freeze_time("2016-12-02")
    def testServe(self):
        response = self.handler.serve(self.calendar,
                                      self._getRequest("/events/"))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.get('Content-Type'), "application/xml; charset=utf-8")
        self.assertIn(b'<?xml version=\'1.0\' encoding=\'UTF-8\'?>', response.content)
        soup = BeautifulSoup(response.content, "xml")
        channel = soup.channel
        self.assertEqual(channel.title.string, "Events")
        self.assertEqual(channel.description.string, "Events")
        self.assertEqual(channel.link.string, "http://joy.test/events/")
        self.assertEqual(channel.generator.string, "ls.joyous")
        self.assertEqual(len(channel("image")), 1)
        image = channel.image
        self.assertEqual(image.url.string, "http://joy.test/static/joyous/img/logo.png")
        self.assertEqual(image.title.string, "Events")
        self.assertEqual(image.link.string, "http://joy.test/events/")
        self.assertEqual(channel.lastBuildDate.string, "Fri, 02 Dec 2016 00:00:00 +0000")
        self.assertEqual(len(channel("item")), 1)
        item = channel.item
        self.assertEqual(item.title.string, "Workshop")
        self.assertEqual(item.link.string, "http://joy.test/events/workshop/")
        self.assertEqual(item.enclosure.decode(),
                         '<enclosure length="773" type="image/png" '
                         'url="http://joy.test/media/images/{}"/>'.format(self.rendName))
        self.assertEqual(item.description.decode(), """<description>\n\n\n
  &lt;div class="joy-ev-when joy-field"&gt;
    The first Tuesday of the month (until 26 December 2017)
  &lt;/div&gt;\n
  &lt;div class="joy-ev-next-on joy-field"&gt;
    Next on Tuesday 3rd of January 2017 
  &lt;/div&gt;\n\n\n\n
&lt;div class="rich-text"&gt;&lt;/div&gt;\n</description>""")
        self.assertEqual(item.guid.get("isPermaLink"), "true")
        self.assertEqual(item.guid.string, "http://joy.test/events/workshop/")
        self.assertEqual(item.pubDate.string, "Thu, 24 Mar 2016 00:00:00 +0000")

    def testServeUnsupported(self):
        response = self.handler.serve(self.event,
                                      self._getRequest("/events/workshop"))
        self.assertIsNone(response)

    @freeze_time("2016-03-25")
    def testServeExtraInfo(self):
        info = ExtraInfoPage(owner = self.user,
                             overrides = self.event,
                             except_date = dt.date(2017,2,7),
                             extra_title = "System Demo",
                             extra_information = "<h3>System Demo</h3>")
        self.event.add_child(instance=info)
        info.save_revision().publish()
        response = self.handler.serve(self.calendar,
                                      self._getRequest("/events/"))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.get('Content-Type'), "application/xml; charset=utf-8")
        soup = BeautifulSoup(response.content, "xml")
        channel = soup.channel
        self.assertEqual(channel.title.string, "Events")
        self.assertEqual(len(channel("item")), 2)
        item = channel("item")[1]
        self.assertEqual(item.title.string, "System Demo")
        self.assertEqual(item.link.string, "http://joy.test/events/workshop/2017-02-07-extra-info/")
        self.assertEqual(item.enclosure.decode(),
                         '<enclosure length="773" type="image/png" '
                         'url="http://joy.test/media/images/{}"/>'.format(self.rendName))
        self.assertEqual(item.description.decode(), """<description>\n\n\n
  &lt;div class="joy-ev-when joy-field"&gt;
    Tuesday 7th of February 2017
  &lt;/div&gt;\n\n\n\n
&lt;div class="rich-text"&gt;&lt;h3&gt;System Demo&lt;/h3&gt;&lt;/div&gt;
&lt;div class="rich-text"&gt;&lt;/div&gt;\n</description>""")
        self.assertEqual(item.guid.get("isPermaLink"), "true")
        self.assertEqual(item.guid.string, "http://joy.test/events/workshop/2017-02-07-extra-info/")
        self.assertEqual(item.pubDate.string, "Fri, 25 Mar 2016 00:00:00 +0000")

    @freeze_time("2016-03-26")
    def testServePostponement(self):
        imgFile = get_test_image_file(filename="logo2.png", colour="red")
        newLogo = Image.objects.create(title="Logo", file=imgFile)
        imgName = os.path.splitext(os.path.basename(newLogo.file.name))[0]
        newLogoRender = "{}.width-350.format-png.png".format(imgName)
        postponement = PostponementPage(owner = self.user,
                                        overrides = self.event,
                                        except_date = dt.date(2017,4,4),
                                        image = newLogo,
                                        cancellation_title   = "Workshop Postponed",
                                        cancellation_details = "Workshop will take place next week",
                                        postponement_title   = "Workshop",
                                        date      = dt.date(2017, 4, 11),
                                        details   = "Interesting stuff")
        self.event.add_child(instance=postponement)
        postponement.save_revision().publish()
        response = self.handler.serve(self.calendar,
                                      self._getRequest("/events/"))
        self.assertEqual(response.status_code, 200)
        soup = BeautifulSoup(response.content, "xml")
        channel = soup.channel
        self.assertEqual(channel.title.string, "Events")
        self.assertEqual(len(channel("item")), 3)
        item1 = channel("item")[1]
        self.assertEqual(item1.title.string, "Workshop Postponed")
        self.assertEqual(item1.link.string, "http://joy.test/events/workshop/2017-04-04-postponement/from/")
        self.assertEqual(item1.enclosure.decode(),
                         '<enclosure length="773" type="image/png" '
                         'url="http://joy.test/media/images/{}"/>'.format(self.rendName))
        self.assertEqual(item1.description.decode(), """<description>\n\n\n
  &lt;div class="joy-ev-when joy-field"&gt;
    Tuesday 4th of April 2017
  &lt;/div&gt;\n\n\n\n
&lt;div class="rich-text"&gt;Workshop will take place next week&lt;/div&gt;\n</description>""")
        self.assertEqual(item1.guid.get("isPermaLink"), "true")
        self.assertEqual(item1.guid.string, "http://joy.test/events/workshop/2017-04-04-postponement/from/")
        self.assertEqual(item1.pubDate.string, "Sat, 26 Mar 2016 00:00:00 +0000")
        item2 = channel("item")[2]
        self.assertEqual(item2.title.string, "Workshop")
        self.assertEqual(item2.link.string, "http://joy.test/events/workshop/2017-04-04-postponement/")
        self.assertEqual(item2.enclosure.decode(),
                         '<enclosure length="773" type="image/png" '
                         'url="http://joy.test/media/images/{}"/>'.format(newLogoRender))
        self.assertEqual(item2.description.decode(), """<description>\n\n\n
  &lt;div class="joy-ev-when joy-field"&gt;
    Tuesday 11th of April 2017
  &lt;/div&gt;\n
  &lt;div class="joy-ev-from-when joy-field"&gt;
    Postponed from Tuesday 4th of April 2017
  &lt;/div&gt;\n\n\n\n
&lt;div class="rich-text"&gt;Interesting stuff&lt;/div&gt;\n</description>""")
        self.assertEqual(item2.guid.get("isPermaLink"), "true")
        self.assertEqual(item2.guid.string, "http://joy.test/events/workshop/2017-04-04-postponement/")
        self.assertEqual(item2.pubDate.string, "Sat, 26 Mar 2016 00:00:00 +0000")

    @freeze_time("2016-03-27")
    def testServeCancellation(self):
        cancellation = CancellationPage(owner = self.user,
                                        overrides = self.event,
                                        except_date = dt.date(2017,5,2),
                                        cancellation_title   = "Workshop Cancelled",
                                        cancellation_details = "No workshop this month")
        self.event.add_child(instance=cancellation)
        cancellation.save_revision().publish()
        response = self.handler.serve(self.calendar,
                                      self._getRequest("/events/"))
        self.assertEqual(response.status_code, 200)
        soup = BeautifulSoup(response.content, "xml")
        channel = soup.channel
        self.assertEqual(channel.title.string, "Events")
        self.assertEqual(len(channel("item")), 2)
        item = channel("item")[1]
        self.assertEqual(item.title.string, "Workshop Cancelled")
        self.assertEqual(item.link.string, "http://joy.test/events/workshop/2017-05-02-cancellation/")
        self.assertEqual(item.enclosure.decode(),
                         '<enclosure length="773" type="image/png" '
                         'url="http://joy.test/media/images/{}"/>'.format(self.rendName))
        self.assertEqual(item.description.decode(), """<description>\n\n\n
  &lt;div class="joy-ev-when joy-field"&gt;
    Tuesday 2nd of May 2017
  &lt;/div&gt;\n\n\n\n
&lt;div class="rich-text"&gt;No workshop this month&lt;/div&gt;\n</description>""")
        self.assertEqual(item.guid.get("isPermaLink"), "true")
        self.assertEqual(item.guid.string, "http://joy.test/events/workshop/2017-05-02-cancellation/")
        self.assertEqual(item.pubDate.string, "Sun, 27 Mar 2016 00:00:00 +0000")
Пример #16
0
class TestUpdate(TestCase):
    @freeze_timetz("2018-02-01 13:00")
    def setUp(self):
        site = Site.objects.get(is_default_site=True)
        site.hostname = "joy.test"
        site.save()
        self.home = getPage("/home/")
        self.user = User.objects.create_user('i', '*****@*****.**', 's3cr3t')
        self.requestFactory = RequestFactory()
        self.calendar = CalendarPage(owner=self.user,
                                     slug="events",
                                     title="Events")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()
        event = SimpleEventPage(
            owner=self.user,
            slug="mini-fair",
            title="Mini-Fair",
            date=dt.date(2018, 4, 7),
            uid="*****@*****.**")
        self.calendar.add_child(instance=event)
        event.save_revision().publish()
        event = RecurringEventPage(
            owner=self.user,
            slug="tango-thursdays",
            title="Tango Thursdays",
            details="Weekly tango lessons at the Dance Spot",
            repeat=Recurrence(dtstart=dt.date(2018, 3, 29),
                              freq=WEEKLY,
                              byweekday=[TH]),
            time_from=dt.time(19, 30),
            time_to=dt.time(22, 0),
            tz=pytz.timezone("US/Eastern"),
            website="http://torontodancespot.com/",
            location="622 Bloor St. W., Toronto ON, M6G 1K7",
            uid="*****@*****.**")
        self.calendar.add_child(instance=event)
        event.save_revision().publish()
        cancellation = CancellationPage(
            owner=self.user,
            slug="2019-02-14-cancellation",
            title="Cancellation for Thursday 14th of April",
            overrides=event,
            except_date=dt.date(2019, 2, 14))
        event.add_child(instance=cancellation)
        cancellation.save_revision().publish()
        info = ExtraInfoPage(owner=self.user,
                             slug="2018-04-05-extra-info",
                             title="Extra-Info for Thursday 5th of April",
                             overrides=event,
                             except_date=dt.date(2018, 4, 5),
                             extra_title="Performance",
                             extra_information="Performance for the public")
        event.add_child(instance=info)
        info.save_revision().publish()

        GROUPS = PageViewRestriction.GROUPS
        self.friends = Group.objects.create(name="Friends")
        self.rendezvous = SimpleEventPage(
            owner=self.user,
            slug="rendezvous",
            title="Private Rendezvous",
            date=dt.date(2013, 1, 10),
            uid="80af64e7-84e6-40d9-8b4f-7edf92aab9f7")
        self.calendar.add_child(instance=self.rendezvous)
        self.rendezvous.save_revision().publish()
        restriction = PageViewRestriction.objects.create(
            restriction_type=GROUPS, page=self.rendezvous)
        restriction.groups.set([self.friends])
        restriction.save()

    def _getRequest(self, path="/"):
        request = self.requestFactory.get(path)
        request.user = self.user
        request.site = self.home.get_site()
        request.session = {}
        request._messages = FallbackStorage(request)
        request.POST = request.POST.copy()
        request.POST['action-publish'] = "action-publish"
        return request

    @freeze_timetz("2018-03-06 9:00")
    def testLoadSimple(self):
        data = b"\r\n".join([
            b"BEGIN:VCALENDAR",
            b"VERSION:2.0",
            b"PRODID:-//Bloor &amp; Spadina - ECPv4.6.13//NONSGML v1.0//EN",
            b"CALSCALE:GREGORIAN",
            b"METHOD:PUBLISH",
            b"X-WR-CALNAME:Bloor &amp; Spadina",
            b"X-ORIGINAL-URL:http://bloorneighbours.ca",
            b"X-WR-CALDESC:Events for Bloor &amp; Spadina",
            b"BEGIN:VEVENT",
            b"DTSTART;TZID=UTC+0:20180407T093000",
            b"DTEND;TZID=UTC+0:20180407T113000",
            b"DTSTAMP:20180402T054745",
            b"CREATED:20180304T225154Z",
            b"LAST-MODIFIED:20180304T225154Z",
            b"UID:[email protected]",
            b"SUMMARY:Mini-Fair & Garage Sale",
            b"DESCRIPTION:",
            b"URL:http://bloorneighbours.ca/event/mini-fair-garage-sale/",
            b"END:VEVENT",
            b"END:VCALENDAR",
        ])
        vcal = VCalendar(self.calendar)
        vcal.load(self._getRequest(), data)
        events = SimpleEventPage.events.child_of(self.calendar)            \
                                       .filter(date=dt.date(2018,4,7)).all()
        self.assertEqual(len(events), 1)
        event = events[0]
        self.assertEqual(event.owner, self.user)
        self.assertEqual(event.slug, "mini-fair")
        self.assertEqual(event.title, "Mini-Fair & Garage Sale")
        self.assertEqual(event.date, dt.date(2018, 4, 7))
        self.assertEqual(event.time_from, dt.time(9, 30))
        self.assertEqual(event.time_to, dt.time(11, 30))
        revisions = event.revisions.all()
        self.assertEqual(len(revisions), 2)
        rev1, rev2 = revisions
        self.assertEqual(rev1.created_at, datetimetz(2018, 2, 1, 13, 0))
        self.assertEqual(rev2.created_at, datetimetz(2018, 3, 6, 9, 0))

    @freeze_timetz("2018-04-08 10:00")
    @timezone.override("America/Toronto")
    def testLoadRecurring(self):
        data = b"\r\n".join([
            b"BEGIN:VCALENDAR",
            b"VERSION:2.0",
            b"PRODID:-//Bloor &amp; Spadina - ECPv4.6.13//NONSGML v1.0//EN",
            b"BEGIN:VEVENT",
            b"SUMMARY:Fierce Tango",
            b"DESCRIPTION:Argentine Show Tango Performance",
            b"DTSTART:20180405T193000",
            b"DTEND:20180405T220000",
            b"RECURRENCE-ID:20180405T193000",
            b"DTSTAMP:20180408T094745Z",
            b"LAST-MODIFIED:20180314T010000Z",
            b"UID:[email protected]",
            b"END:VEVENT",
            b"BEGIN:VEVENT",
            b"SUMMARY:Tango Thursdays",
            b"DESCRIPTION:Weekly tango lessons at the Dance Spot",
            b"DTSTART:20180329T193000",
            b"DTEND:20180329T220000",
            b"RRULE:FREQ=WEEKLY;BYDAY=TH",
            b"DTSTAMP:20180408T094745Z",
            b"LAST-MODIFIED:20180131T010000Z",
            b"EXDATE:20181025T193000",
            b"LOCATION:622 Bloor St. W., Toronto ON, M6G 1K7",
            b"SUMMARY:Tango Thursdays",
            b"UID:[email protected]",
            b"URL:http://torontodancespot.com/",
            b"END:VEVENT",
            b"END:VCALENDAR",
        ])
        vcal = VCalendar(self.calendar)
        vcal.load(self._getRequest(), data)
        events = RecurringEventPage.events.child_of(self.calendar).all()
        self.assertEqual(len(events), 1)
        event = events[0]
        self.assertEqual(event.slug, "tango-thursdays")
        self.assertEqual(event.title, "Tango Thursdays")
        self.assertEqual(repr(event.repeat),
                        "DTSTART:20180329\n" \
                        "RRULE:FREQ=WEEKLY;WKST=SU;BYDAY=TH")
        self.assertEqual(event.time_from, dt.time(19, 30))
        self.assertEqual(event.time_to, dt.time(22, 0))
        revisions = event.revisions.all()
        self.assertEqual(len(revisions), 1)
        info = ExtraInfoPage.events.child_of(event).get()
        self.assertEqual(info.slug, "2018-04-05-extra-info")
        self.assertEqual(info.title, "Extra-Info for Thursday 5th of April")
        self.assertEqual(info.extra_title, "Fierce Tango")
        self.assertEqual(info.extra_information,
                         "Argentine Show Tango Performance")
        self.assertEqual(info.except_date, dt.date(2018, 4, 5))
        revisions = info.revisions.all()
        self.assertEqual(len(revisions), 2)
        cancellations = CancellationPage.events.child_of(event).all()
        self.assertEqual(len(cancellations), 2)
        cancellation = cancellations[0]
        self.assertEqual(cancellation.except_date, dt.date(2019, 2, 14))
        cancellation = cancellations[1]
        self.assertEqual(cancellation.except_date, dt.date(2018, 10, 25))

    @freeze_timetz("2014-05-09 11:00")
    def testLoadRestricted(self):
        data = b"\r\n".join([
            b"BEGIN:VCALENDAR",
            b"VERSION:2.0",
            b"PRODID:-//Bloor &amp; Spadina - ECPv4.6.13//NONSGML v1.0//EN",
            b"CALSCALE:GREGORIAN",
            b"METHOD:PUBLISH",
            b"X-WR-CALNAME:Bloor &amp; Spadina",
            b"X-ORIGINAL-URL:http://bloorneighbours.ca",
            b"X-WR-CALDESC:Events for Bloor &amp; Spadina",
            b"BEGIN:VEVENT",
            b"DTSTART;TZID=UTC+0:20130110T000000",
            b"DTEND;TZID=UTC+0:20130110T100000",
            b"DTSTAMP:20140509T110000",
            b"CREATED:20130304T225154Z",
            b"LAST-MODIFIED:20120304T225154Z",
            b"UID:80af64e7-84e6-40d9-8b4f-7edf92aab9f7",
            b"LOCATION:4 William James Lane, Toronto ON, M5S 1X9",
            b"SUMMARY:Private Rendezvous",
            b"DESCRIPTION:",
            b"END:VEVENT",
            b"END:VCALENDAR",
        ])
        vcal = VCalendar(self.calendar)
        request = self._getRequest()
        vcal.load(request, data)
        events = SimpleEventPage.events.child_of(self.calendar)            \
                                       .filter(date=dt.date(2013,1,10)).all()
        self.assertEqual(len(events), 1)
        event = events[0]
        self.assertEqual(event.title, "Private Rendezvous")
        self.assertEqual(event.location, "")
        revisions = event.revisions.all()
        self.assertEqual(len(revisions), 1)
        msgs = list(messages.get_messages(request))
        self.assertEqual(len(msgs), 1)
        msg = msgs[0]
        self.assertEqual(msg.level, messages.ERROR)
        self.assertEqual(msg.message, "Could not load 1 iCal events")
Пример #17
0
class TestEntry(TestCase):
    def setUp(self):
        imgFile = get_test_image_file()
        imgFile.name = "people.png"
        self.img = Image.objects.create(title="People", file=imgFile)
        imgName = os.path.splitext(os.path.basename(self.img.file.name))[0]
        self.rendName = "{}.width-350.format-png.png".format(imgName)
        Site.objects.update(hostname="joy.test")
        self.home = Page.objects.get(slug='home')
        self.user = User.objects.create_user('i', '*****@*****.**', 's3(R3t')
        self.requestFactory = RequestFactory()
        self.calendar = CalendarPage(owner = self.user,
                                     slug  = "events",
                                     title = "Events")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()

    def tearDown(self):
        self.img.file.delete(False)
        for rend in self.img.renditions.all():
            rend.file.delete(False)

    def _getRequest(self, path="/"):
        request = self.requestFactory.get(path)
        request.user = self.user
        request.site = self.home.get_site()
        request.session = {}
        request._messages = FallbackStorage(request)
        request.POST = request.POST.copy()
        request.POST['action-publish'] = "action-publish"
        return request

    def testSetCategory(self):
        cat = EventCategory.objects.create(code="A1", name="AlphaOne")
        page = MultidayEventPage(owner = self.user,
                                 slug  = "road-trip",
                                 title = "Road Trip",
                                 date_from = dt.date(2016,11,1),
                                 date_to   = dt.date(2016,11,10),
                                 time_from = dt.time(10),
                                 category  = cat)
        self.calendar.add_child(instance=page)
        page.save_revision().publish()
        request = self._getRequest()
        thisEvent = ThisEvent(page.title, page, page.get_url(request))
        entry = EventEntry.fromEvent(thisEvent, request)
        self.assertEqual(entry.category(), [{'term': 'AlphaOne'}])
        rss = entry.rss_entry()
        self.assertEqual(etree.tostring(rss),
b"""<item><title>Road Trip</title><link>http://joy.test/events/road-trip/</link><description>\n\n\n
  &lt;div class="joy-ev-when joy-field"&gt;
    Tuesday 1st of November 2016 at 10am to Thursday 10th of November 2016\n  &lt;/div&gt;\n\n\n\n
&lt;div class="rich-text"&gt;&lt;/div&gt;
</description><guid isPermaLink="true">http://joy.test/events/road-trip/</guid><category>AlphaOne</category></item>""")

    def testSetImage(self):
        page = SimpleEventPage(owner = self.user,
                               slug  = "meetup",
                               title = "Meet Up",
                               image = self.img,
                               date  = dt.date(2016,10,21),
                               time_from = dt.time(16))
        self.calendar.add_child(instance=page)
        page.save_revision().publish()
        request = self._getRequest()
        thisEvent = ThisEvent(page.title, page, page.get_url(request))
        entry = EventEntry.fromEvent(thisEvent, request)
        self.assertEqual(entry.enclosure(), {
            'length': '773',
            'url': 'http://joy.test/media/images/{}'.format(self.rendName),
            'type': 'image/png'})

    def testSetDescription(self):
        group = GroupPage(slug = "sandmen", title = "Sandmen")
        self.home.add_child(instance=group)
        group.save_revision().publish()
        page = MultidayEventPage(owner = self.user,
                                 slug  = "road-trip",
                                 title = "Road Trip",
                                 date_from = dt.date(2016,11,1),
                                 date_to   = dt.date(2016,11,10),
                                 group_page = group)
        self.calendar.add_child(instance=page)
        page.save_revision().publish()
        request = self._getRequest()
        thisEvent = ThisEvent(page.title, page, page.get_url(request))
        entry = EventEntry.fromEvent(thisEvent, request)
        rss = entry.rss_entry()
        self.assertEqual(etree.tostring(rss),
b"""<item><title>Road Trip</title><link>http://joy.test/events/road-trip/</link><description>\n
  &lt;div class="joy-ev-who joy-field"&gt;
    &lt;a class="joy-ev-who__link" href="http://joy.test/sandmen/"&gt;Sandmen&lt;/a&gt;
  &lt;/div&gt;\n\n\n
  &lt;div class="joy-ev-when joy-field"&gt;
    Tuesday 1st of November 2016 to Thursday 10th of November 2016\n  &lt;/div&gt;\n\n\n\n
&lt;div class="rich-text"&gt;&lt;/div&gt;
</description><guid isPermaLink="true">http://joy.test/events/road-trip/</guid></item>""")
Пример #18
0
class Test(TestCase):
    def setUp(self):
        Site.objects.update(hostname="joy.test")
        self.user = User.objects.create_user('i', '*****@*****.**', 's3cr3t')
        self.calendar = CalendarPage(owner = self.user,
                                     slug  = "events",
                                     title = "Events")
        Page.objects.get(slug='home').add_child(instance=self.calendar)
        self.calendar.save()
        self.calendar.save_revision().publish()
        self.event = RecurringEventPage(owner = self.user,
                                        slug  = "lug-meetup",
                                        title = "Linux Users Group Meetup",
                                        repeat = Recurrence(dtstart=dt.date(2017,8,5),
                                                            freq=MONTHLY,
                                                            byweekday=[TU(1)]),
                                        time_from = dt.time(18,30),
                                        time_to   = dt.time(20),
                                        location  = "6 Mackay St, Greymouth (upstairs)")
        self.calendar.add_child(instance=self.event)
        self.event.save_revision().publish()

    def testGetEventsByDay(self):
        events = RecurringEventPage.events.byDay(dt.date(2017,8,1),
                                                 dt.date(2017,10,31))
        self.assertEqual(len(events), 92)
        evod = events[35]
        self.assertEqual(evod.date, dt.date(2017,9,5))
        self.assertEqual(len(evod.all_events), 1)
        self.assertEqual(len(evod.days_events), 1)
        self.assertEqual(len(evod.continuing_events), 0)

    def testStatus(self):
        pastEvent = RecurringEventPage(owner = self.user,
                                       slug  = "past",
                                       title = "Past Event",
                                       repeat = Recurrence(dtstart=dt.date(2008,2,1),
                                                           until=dt.date(2008,5,4),
                                                           freq=WEEKLY,
                                                           byweekday=[SA,SU]))
        self.calendar.add_child(instance=pastEvent)
        self.assertEqual(pastEvent.status, "finished")
        self.assertEqual(pastEvent.status_text, "These events have finished.")
        now = timezone.localtime()
        earlier = now - dt.timedelta(hours=1)
        if earlier.date() != now.date():
            earlier = datetimetz(now.date(), dt.time.min)
        nowEvent = RecurringEventPage(owner = self.user,
                                      slug  = "now",
                                      title = "Now Event",
                                      repeat = Recurrence(dtstart=dt.date(2010,1,1),
                                                          freq=DAILY),
                                      time_from = earlier.time(),
                                      time_to   = dt.time.max)
        self.calendar.add_child(instance=nowEvent)
        self.assertEqual(nowEvent.status, "started")
        self.assertEqual(nowEvent.status_text, "This event has started.")
        today = timezone.localdate()
        notToday = [weekday for weekday in EVERYWEEKDAY if weekday.weekday != today.weekday()]
        pastAndFutureEvent = RecurringEventPage(owner = self.user,
                                                slug  = "not-today",
                                                title = "Any day but today",
                                                repeat = Recurrence(dtstart=dt.date(2009,8,7),
                                                                    freq=WEEKLY,
                                                                    byweekday=notToday))
        self.calendar.add_child(instance=pastAndFutureEvent)
        self.assertIsNone(pastAndFutureEvent.status)
        self.assertEqual(pastAndFutureEvent.status_text, "")

    @freeze_timetz("2008-05-04 09:01")
    def testJustFinishedStatus(self):
        event = RecurringEventPage(owner = self.user,
                                   slug  = "breakfast1",
                                   title = "Breakfast-in-bed",
                                   repeat = Recurrence(dtstart=dt.date(2008,2,1),
                                                       until=dt.date(2008,5,9),
                                                       freq=WEEKLY,
                                                       byweekday=[SA,SU]),
                                      time_from = dt.time(8),
                                      time_to   = dt.time(9))
        self.calendar.add_child(instance=event)
        self.assertEqual(event.status, "finished")

    @freeze_timetz("2008-05-04 07:00")
    def testLastOccurenceCancelledStatus(self):
        event = RecurringEventPage(owner = self.user,
                                   slug  = "breakfast2",
                                   title = "Breakfast-in-bed",
                                   repeat = Recurrence(dtstart=dt.date(2008,2,1),
                                                       until=dt.date(2008,5,9),
                                                       freq=WEEKLY,
                                                       byweekday=[SA,SU]),
                                   time_from = dt.time(8),
                                   time_to   = dt.time(9))
        self.calendar.add_child(instance=event)
        cancellation = CancellationPage(owner = self.user,
                                        overrides = event,
                                        except_date = dt.date(2008, 5, 4),
                                        cancellation_title   = "Fire in the kitchen",
                                        cancellation_details = "The bacon fat is burning")
        event.add_child(instance=cancellation)
        self.assertEqual(event.status, "finished")

    @freeze_timetz("2008-05-04 12:00")
    def testPostponementOccurenceLast(self):
        request = RequestFactory().get("/test")
        request.user = self.user
        request.session = {}
        event = RecurringEventPage(owner = self.user,
                                   slug  = "breakfast3",
                                   title = "Breakfast-in-bed",
                                   repeat = Recurrence(dtstart=dt.date(2008,2,1),
                                                       until=dt.date(2008,5,9),
                                                       freq=WEEKLY,
                                                       byweekday=[SA,SU]),
                                   time_from = dt.time(8),
                                   time_to   = dt.time(9))
        self.calendar.add_child(instance=event)
        postponement = PostponementPage(owner = self.user,
                                        overrides = event,
                                        except_date = dt.date(2008, 5, 3),
                                        postponement_title = "Breakfast in Bed owed from May",
                                        date      = dt.date(2008, 5, 24),
                                        time_from = dt.time(8),
                                        time_to   = dt.time(9))
        event.add_child(instance=postponement)
        self.assertIsNone(event.status)
        self.assertEqual(event._nextOn(request),
                         '<a class="inline-link" href="/events/breakfast3/2008-05-03-postponement/">Saturday 24th of May at 8am</a>')

    def testWhen(self):
        self.assertEqual(self.event.when, "The first Tuesday of the month at 6:30pm to 8pm")

    def testAt(self):
        self.assertEqual(self.event.at.strip(), "6:30pm")

    def testCurrentDt(self):
        lugDt = self.event._current_datetime_from
        self.assertEqual(lugDt.time(), dt.time(18,30))
        self.assertEqual(lugDt.date().weekday(), 1)
        self.assertLess(lugDt.date().day, 8)
        movieNight = RecurringEventPage(owner = self.user,
                                        slug  = "movies",
                                        title = "Movies",
                                        repeat = Recurrence(dtstart=dt.date(2005,2,1),
                                                            freq=WEEKLY,
                                                            byweekday=[TH,]),
                                        time_from = dt.time(20,15),
                                        time_to   = dt.time(21,30))
        self.calendar.add_child(instance=movieNight)
        now = timezone.localtime()
        myday = now.date()
        startTime = dt.time(20,15)
        if now.time() > startTime:
            myday += dt.timedelta(days=1)
        thursday = myday + dt.timedelta(days=(3-myday.weekday())%7)
        self.assertEqual(movieNight._current_datetime_from,
                         datetimetz(thursday, startTime))

    def testFutureDt(self):
        lugDt = self.event._future_datetime_from
        self.assertEqual(lugDt.time(), dt.time(18,30))
        self.assertEqual(lugDt.date().weekday(), 1)
        self.assertLess(lugDt.date().day, 8)
        movieNight = RecurringEventPage(owner = self.user,
                                        slug  = "movies",
                                        title = "Movies",
                                        repeat = Recurrence(dtstart=dt.date(2005,2,1),
                                                            freq=WEEKLY,
                                                            byweekday=[TH,]),
                                        time_from = dt.time(20,15),
                                        time_to   = dt.time(21,30))
        self.calendar.add_child(instance=movieNight)
        now = timezone.localtime()
        myday = now.date()
        startTime = dt.time(20,15)
        if now.time() > startTime:
            myday += dt.timedelta(days=1)
        thursday = myday + dt.timedelta(days=(3-myday.weekday())%7)
        self.assertEqual(movieNight._future_datetime_from,
                         datetimetz(thursday, startTime))

    def testPastDt(self):
        lugDt = self.event._past_datetime_from
        self.assertEqual(lugDt.time(), dt.time(18,30))
        self.assertEqual(lugDt.date().weekday(), 1)
        self.assertLess(lugDt.date().day, 8)
        movieNight = RecurringEventPage(owner = self.user,
                                        slug  = "movies",
                                        title = "Movies",
                                        repeat = Recurrence(dtstart=dt.date(2005,2,1),
                                                            freq=WEEKLY,
                                                            byweekday=[TH,]),
                                        time_from = dt.time(20,15),
                                        time_to   = dt.time(21,30))
        self.calendar.add_child(instance=movieNight)
        now = timezone.localtime()
        myday = now.date()
        startTime = dt.time(20,15)
        if now.time() < startTime:
            myday -= dt.timedelta(days=1)
        thursday = myday - dt.timedelta(days=(myday.weekday()-3)%7)
        self.assertEqual(movieNight._past_datetime_from,
                         datetimetz(thursday, startTime))

    def testGroup(self):
        self.assertIsNone(self.event.group)

    def testOccursOn(self):
        self.assertIs(self.event._occursOn(dt.date(2018,3,6)), True)
        self.assertIs(self.event._occursOn(dt.date(2018,3,13)), False)
Пример #19
0
class Test(TestCase):
    def setUp(self):
        site = Site.objects.get(is_default_site=True)
        site.hostname = "joy.test"
        site.save()
        self.home = getPage("/home/")
        self.user = User.objects.create_user('i', '*****@*****.**', 's3cr3t')
        self.requestFactory = RequestFactory()
        self.calendar = CalendarPage(owner=self.user,
                                     slug="events",
                                     title="Events")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()

    def _getRequest(self, path="/"):
        request = self.requestFactory.get(path)
        request.user = self.user
        request.site = self.home.get_site()
        request.session = {}
        request._messages = FallbackStorage(request)
        request.POST = request.POST.copy()
        request.POST['action-publish'] = "action-publish"
        return request

    @freeze_timetz("2018-05-12 13:00")
    def testFromSimpleCalendarPage(self):
        page = SimpleEventPage(owner=self.user,
                               slug="bbq",
                               title="BBQ",
                               date=dt.date(2008, 7, 15),
                               time_from=dt.time(17, 30),
                               time_to=dt.time(19),
                               tz=pytz.timezone("Pacific/Auckland"))
        self.calendar.add_child(instance=page)
        page.save_revision().publish()
        vcal = VCalendar.fromPage(self.calendar, self._getRequest("/events/"))
        export = vcal.to_ical()
        props = [
            b"SUMMARY:BBQ",
            b"DTSTART;TZID=Pacific/Auckland:20080715T173000",
            b"DTEND;TZID=Pacific/Auckland:20080715T190000",
            b"DTSTAMP:20180512T040000Z",
            b"UID:",
            b"SEQUENCE:1",
            b"CREATED:20180512T040000Z",
            b"DESCRIPTION:",
            b"LAST-MODIFIED:20180512T040000Z",
            b"LOCATION:",
            b"URL:http://joy.test/events/bbq/",
        ]
        for prop in props:
            with self.subTest(prop=prop.split(b'\r\n', 1)[0]):
                self.assertIn(prop, export)

    @freeze_timetz("2019-01-21 15:00")
    def testFromCalendarPage(self):
        page = RecurringEventPage(owner=self.user,
                                  slug="chess",
                                  title="Chess",
                                  repeat=Recurrence(dtstart=dt.date(
                                      2000, 1, 1),
                                                    freq=WEEKLY,
                                                    byweekday=[MO, WE, FR]),
                                  time_from=dt.time(12),
                                  time_to=dt.time(13))
        self.calendar.add_child(instance=page)
        page.save_revision().publish()
        cancellation = CancellationPage(
            owner=self.user,
            slug="2019-02-04-cancellation",
            title="Cancellation for Monday 4th of February",
            overrides=page,
            except_date=dt.date(2019, 2, 4),
            cancellation_title="No Chess Club Today")
        page.add_child(instance=cancellation)
        cancellation.save_revision().publish()
        postponement = PostponementPage(
            owner=self.user,
            slug="2019-10-02-postponement",
            title="Postponement for Wednesday 2nd of October",
            overrides=page,
            except_date=dt.date(2019, 10, 2),
            cancellation_title="",
            postponement_title="Early Morning Matches",
            date=dt.date(2019, 10, 3),
            time_from=dt.time(7, 30),
            time_to=dt.time(8, 30))
        page.add_child(instance=postponement)
        postponement.save_revision().publish()
        vcal = VCalendar.fromPage(self.calendar, self._getRequest("/events/"))
        export = vcal.to_ical()
        props = [
            b"SUMMARY:Chess",
            b"DTSTART;TZID=Asia/Tokyo:20000103T120000",
            b"DTEND;TZID=Asia/Tokyo:20000103T130000",
            b"DTSTAMP:20190121T060000Z",
            b"UID:",
            b"SEQUENCE:1",
            b"RRULE:FREQ=WEEKLY;BYDAY=MO,WE,FR;WKST=SU",
            b"EXDATE;TZID=Asia/Tokyo:20190204T120000",
            b"CREATED:20190121T060000Z",
            b"DESCRIPTION:",
            b"LAST-MODIFIED:20190121T060000Z",
            b"LOCATION:",
            b"URL:http://joy.test/events/chess/",
            b"SUMMARY:Early Morning Matches",
            b"DTSTART;TZID=Asia/Tokyo:20191003T073000",
            b"DTEND;TZID=Asia/Tokyo:20191003T083000",
            b"RECURRENCE-ID;TZID=Asia/Tokyo:20191002T120000",
        ]
        for prop in props:
            with self.subTest(prop=prop):
                self.assertIn(prop, export)

    @freeze_timetz("2018-05-12 13:00")
    def testFromSimpleEventPage(self):
        page = SimpleEventPage(owner=self.user,
                               slug="pet-show",
                               title="Pet Show",
                               date=dt.date(1987, 6, 5),
                               time_from=dt.time(11),
                               time_to=dt.time(17, 30),
                               tz=pytz.timezone("Australia/Sydney"))
        self.calendar.add_child(instance=page)
        page.save_revision().publish()
        vcal = VCalendar.fromPage(page, self._getRequest("/events/pet-show/"))
        export = vcal.to_ical()
        aest = b"\r\n".join([
            b"BEGIN:STANDARD",
            b"DTSTART;VALUE=DATE-TIME:19870315T020000",
            b"TZNAME:AEST",
            b"TZOFFSETFROM:+1100",
            b"TZOFFSETTO:+1000",
            b"END:STANDARD",
        ])
        aedt = b"\r\n".join([
            b"BEGIN:DAYLIGHT",
            b"DTSTART;VALUE=DATE-TIME:19871025T030000",
            b"TZNAME:AEDT",
            b"TZOFFSETFROM:+1000",
            b"TZOFFSETTO:+1100",
            b"END:DAYLIGHT",
        ])
        props = [
            b"SUMMARY:Pet Show",
            b"DTSTART;TZID=Australia/Sydney:19870605T110000",
            b"DTEND;TZID=Australia/Sydney:19870605T173000",
            b"DTSTAMP:20180512T040000Z", b"UID:", b"SEQUENCE:1",
            b"CREATED:20180512T040000Z", b"DESCRIPTION:",
            b"LAST-MODIFIED:20180512T040000Z", b"LOCATION:",
            b"URL:http://joy.test/events/pet-show/", aest, aedt
        ]
        for prop in props:
            with self.subTest(prop=prop.split(b'\r\n', 1)[0]):
                self.assertIn(prop, export)

    @freeze_timetz("2019-01-21 13:00")
    def testFromEventPage(self):
        chess = GroupPage(slug="chess-club", title="Chess Club")
        self.home.add_child(instance=chess)
        page = RecurringEventPage(owner=self.user,
                                  slug="chess",
                                  title="Chess",
                                  repeat=Recurrence(dtstart=dt.date(
                                      2000, 1, 1),
                                                    freq=WEEKLY,
                                                    byweekday=[MO, WE, FR]),
                                  time_from=dt.time(12),
                                  time_to=dt.time(13))
        chess.add_child(instance=page)
        page.save_revision().publish()
        postponement = PostponementPage(
            owner=self.user,
            slug="2019-10-02-postponement",
            title="Postponement for Wednesday 2nd of October",
            overrides=page,
            except_date=dt.date(2019, 10, 2),
            cancellation_title="",
            postponement_title="Early Morning Matches",
            date=dt.date(2019, 10, 3),
            time_from=dt.time(7, 30),
            time_to=dt.time(8, 30))
        page.add_child(instance=postponement)
        postponement.save_revision().publish()
        vcal = VCalendar.fromPage(page, self._getRequest("/events/chess/"))
        export = vcal.to_ical()
        props = [
            b"SUMMARY:Chess",
            b"DTSTART;TZID=Asia/Tokyo:20000103T120000",
            b"DTEND;TZID=Asia/Tokyo:20000103T130000",
            b"DTSTAMP:20190121T040000Z",
            b"UID:",
            b"SEQUENCE:1",
            b"RRULE:FREQ=WEEKLY;BYDAY=MO,WE,FR;WKST=SU",
            b"CREATED:20190121T040000Z",
            b"DESCRIPTION:",
            b"LAST-MODIFIED:20190121T040000Z",
            b"LOCATION:",
            b"URL:http://joy.test/chess-club/chess/",
            b"SUMMARY:Early Morning Matches",
            b"DTSTART;TZID=Asia/Tokyo:20191003T073000",
            b"DTEND;TZID=Asia/Tokyo:20191003T083000",
            b"RECURRENCE-ID;TZID=Asia/Tokyo:20191002T120000",
        ]
        for prop in props:
            with self.subTest(prop=prop):
                self.assertIn(prop, export)

    def testFromUnsupported(self):
        page = Page(owner=self.user,
                    slug="thoughts",
                    title="My thoughts for today")
        self.home.add_child(instance=page)
        page.save_revision().publish()
        with self.assertRaises(CalendarTypeError):
            VCalendar.fromPage(page, self._getRequest("/thoughts/"))

    def testEmptyCalendar(self):
        vcal = VCalendar(self.calendar)
        idParts = vcal['PRODID'].split("//")
        self.assertEqual(len(idParts), 4)
        self.assertEqual(idParts[0], "-")
        self.assertEqual(idParts[1], "linuxsoftware.nz")
        self.assertEqual(idParts[2][:14], "NONSGML Joyous")
        self.assertEqual(idParts[3], "EN")
        self.assertEqual(vcal['VERSION'], "2.0")

    def testLoad(self):
        data = b"\r\n".join([
            b"BEGIN:VCALENDAR",
            b"VERSION:2.0",
            b"PRODID:-//Bloor &amp; Spadina - ECPv4.6.13//NONSGML v1.0//EN",
            b"CALSCALE:GREGORIAN",
            b"METHOD:PUBLISH",
            b"X-WR-CALNAME:Bloor &amp; Spadina",
            b"X-ORIGINAL-URL:http://bloorneighbours.ca",
            b"X-WR-CALDESC:Events for Bloor &amp; Spadina",
            b"BEGIN:VEVENT",
            b"DTSTART;TZID=UTC+0:20180407T093000",
            b"DTEND;TZID=UTC+0:20180407T113000",
            b"DTSTAMP:20180402T054745",
            b"CREATED:20180304T225154Z",
            b"LAST-MODIFIED:20180304T225154Z",
            b"UID:[email protected]",
            b"SUMMARY:Mini-Fair & Garage Sale",
            b"DESCRIPTION:",
            b"URL:http://bloorneighbours.ca/event/mini-fair-garage-sale/",
            b"END:VEVENT",
            b"END:VCALENDAR",
        ])
        vcal = VCalendar(self.calendar)
        vcal.load(self._getRequest(), data)
        events = SimpleEventPage.events.child_of(self.calendar)            \
                                       .filter(date=dt.date(2018,4,7)).all()
        self.assertEqual(len(events), 1)
        event = events[0]
        self.assertEqual(event.owner, self.user)
        self.assertEqual(event.slug, "mini-fair-garage-sale")
        self.assertEqual(event.title, "Mini-Fair & Garage Sale")
        self.assertEqual(event.details, "")
        self.assertEqual(event.date, dt.date(2018, 4, 7))
        self.assertEqual(event.time_from, dt.time(9, 30))
        self.assertEqual(event.time_to, dt.time(11, 30))

    def testLoadInvalidFile(self):
        data = b"FOO:BAR:SNAFU"
        vcal = VCalendar(self.calendar)
        request = self._getRequest()
        vcal.load(request, data)
        msgs = list(messages.get_messages(request))
        self.assertEqual(len(msgs), 1)
        msg = msgs[0]
        self.assertEqual(msg.level, messages.ERROR)
        self.assertEqual(msg.message, "Could not parse iCalendar file ")

    def testLoadEventMissingUID(self):
        data = b"\r\n".join([
            b"BEGIN:VCALENDAR",
            b"VERSION:2.0",
            b"PRODID:-//Bloor &amp; Spadina - ECPv4.6.13//NONSGML v1.0//EN",
            b"CALSCALE:GREGORIAN",
            b"METHOD:PUBLISH",
            b"X-WR-CALNAME:Bloor &amp; Spadina",
            b"X-ORIGINAL-URL:http://bloorneighbours.ca",
            b"X-WR-CALDESC:Events for Bloor &amp; Spadina",
            b"BEGIN:VEVENT",
            b"DTSTART;TZID=UTC+0:20180407T093000",
            b"DTEND;TZID=UTC+0:20180407T113000",
            b"DTSTAMP:20180402T054745",
            b"CREATED:20180304T225154Z",
            b"LAST-MODIFIED:20180304T225154Z",
            b"SUMMARY:Mini-Fair & Garage Sale",
            b"DESCRIPTION:",
            b"URL:http://bloorneighbours.ca/event/mini-fair-garage-sale/",
            b"END:VEVENT",
            b"END:VCALENDAR",
        ])
        vcal = VCalendar(self.calendar)
        request = self._getRequest()
        vcal.load(request, data)
        events = SimpleEventPage.events.child_of(self.calendar)            \
                                       .filter(date=dt.date(2018,4,7)).all()
        self.assertEqual(len(events), 0)
        msgs = list(messages.get_messages(request))
        self.assertEqual(len(msgs), 1)
        msg = msgs[0]
        self.assertEqual(msg.level, messages.ERROR)
        self.assertEqual(msg.message, "Could not load 1 iCal events")

    def testLoadUnknownTZ(self):
        data = b"\r\n".join([
            b"BEGIN:VCALENDAR",
            b"VERSION:2.0",
            b"PRODID:-//Bloor &amp; Spadina - ECPv4.6.13//NONSGML v1.0//EN",
            b"CALSCALE:GREGORIAN",
            b"METHOD:PUBLISH",
            b"X-WR-CALNAME:Bloor &amp; Spadina",
            b"X-ORIGINAL-URL:http://bloorneighbours.ca",
            b"X-WR-CALDESC:Events for Bloor &amp; Spadina",
            b"X-WR-TIMEZONE:Canada/Toronto",
            b"BEGIN:VEVENT",
            b"UID:[email protected]",
            b"DTSTART:20180407T093000",
            b"DTEND:20180407T113000",
            b"DTSTAMP:20180402T054745",
            b"CREATED:20180304T225154Z",
            b"LAST-MODIFIED:20180304T225154Z",
            b"SUMMARY:Mini-Fair & Garage Sale",
            b"DESCRIPTION:",
            b"END:VEVENT",
            b"END:VCALENDAR",
        ])
        vcal = VCalendar(self.calendar)
        request = self._getRequest()
        vcal.load(request, data)
        events = SimpleEventPage.events.child_of(self.calendar)            \
                                       .filter(date=dt.date(2018,4,7)).all()
        self.assertEqual(len(events), 1)
        self.assertEqual(events[0].tz.zone, "Asia/Tokyo")
        msgs = list(messages.get_messages(request))
        self.assertEqual(len(msgs), 2)
        self.assertEqual(msgs[0].level, messages.WARNING)
        self.assertEqual(msgs[0].message, "Unknown time zone Canada/Toronto")
        self.assertEqual(msgs[1].level, messages.SUCCESS)
        self.assertEqual(msgs[1].message, "1 iCal events loaded")
class Test(TestCase):
    @freeze_timetz("2020-03-18")
    def setUp(self):
        self.home = Page.objects.get(slug='home')
        self.user = User.objects.create_user('i', '*****@*****.**', 's3(r3t')
        self.calendar = CalendarPage(owner=self.user,
                                     slug="events",
                                     title="Events")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()
        self.event = RecurringEventPage(slug="test-meeting",
                                        title="Test Meeting",
                                        repeat=Recurrence(
                                            dtstart=dt.date(2010, 1, 1),
                                            freq=WEEKLY,
                                            byweekday=[MO, WE, FR]),
                                        time_from=dt.time(13),
                                        time_to=dt.time(14, 30))
        self.calendar.add_child(instance=self.event)
        self.shutdown = ExtCancellationPage(
            owner=self.user,
            overrides=self.event,
            cancelled_from_date=dt.date(2020, 3, 20),
            cancelled_to_date=dt.date(2020, 6, 1),
            cancellation_title="No Meeting during Shutdown")
        self.event.add_child(instance=self.shutdown)
        self.shutdown.save_revision().publish()

    @freeze_timetz("2021-01-04")
    def testInit(self):
        self.assertEqual(
            self.shutdown.title,
            "Cancellation from Friday 20th of March to Monday 1st of June")
        self.assertEqual(
            self.shutdown.local_title,
            "Cancellation from Friday 20th of March 2020 to Monday 1st of June 2020"
        )
        self.assertEqual(self.shutdown.slug,
                         "2020-03-20-2020-06-01-cancellation")

    def testGetEventsByDay(self):
        shutdown0 = ExtCancellationPage(owner=self.user,
                                        overrides=self.event,
                                        cancelled_from_date=dt.date(
                                            2020, 3, 2),
                                        cancelled_to_date=dt.date(2020, 3, 6))
        self.event.add_child(instance=shutdown0)
        shutdown0.save_revision().publish()
        events = RecurringEventPage.events.byDay(dt.date(2020, 3, 1),
                                                 dt.date(2020, 3, 31))
        self.assertEqual(len(events), 31)
        evod = events[1]
        self.assertEqual(evod.date, dt.date(2020, 3, 2))
        self.assertEqual(len(evod.days_events), 0)
        self.assertEqual(len(evod.continuing_events), 0)
        evod = events[8]
        self.assertEqual(evod.date, dt.date(2020, 3, 9))
        self.assertEqual(len(evod.days_events), 1)
        self.assertEqual(len(evod.continuing_events), 0)
        title, page, url = evod.days_events[0]
        self.assertEqual(title, "Test Meeting")
        evod = events[19]
        self.assertEqual(evod.date, dt.date(2020, 3, 20))
        self.assertEqual(len(evod.days_events), 1)
        self.assertEqual(len(evod.continuing_events), 0)
        title, page, url = evod.days_events[0]
        self.assertEqual(title, "No Meeting during Shutdown")
        self.assertIs(type(page), ExtCancellationPage)

    @freeze_timetz("2020-04-04")
    def testEventFutureExceptions(self):
        request = RequestFactory().get("/test")
        request.user = self.user
        request.session = {}
        exceptions = self.event._futureExceptions(request)
        self.assertEqual(len(exceptions), 1)
        shutdown = exceptions[0]
        self.assertEqual(
            shutdown.title,
            "Cancellation from Friday 20th of March to Monday 1st of June")
        self.assertEqual(shutdown.cancellation_title,
                         "No Meeting during Shutdown")
        self.assertEqual(shutdown._future_datetime_from,
                         datetimetz(2020, 4, 6, 13))

    @freeze_timetz("2020-08-31")
    def testPast(self):
        self.assertEqual(list(ExtCancellationPage.events.past()),
                         [self.shutdown])
        self.assertEqual(ExtCancellationPage.events.past().count(), 1)
        self.assertEqual(ExtCancellationPage.events.future().count(), 0)

    @freeze_timetz("2020-05-04")
    def testFuture(self):
        self.assertEqual(list(ExtCancellationPage.events.future()),
                         [self.shutdown])
        self.assertEqual(ExtCancellationPage.events.past().count(), 1)
        self.assertEqual(ExtCancellationPage.events.future().count(), 1)

    @freeze_timetz("2020-06-01 14:00:00")
    def testCurrent(self):
        self.assertEqual(list(ExtCancellationPage.events.current()),
                         [self.shutdown])
        self.assertEqual(ExtCancellationPage.events.past().count(), 1)
        self.assertEqual(ExtCancellationPage.events.current().count(), 1)
        self.assertEqual(ExtCancellationPage.events.future().count(), 0)

    def testEventOccursOn(self):
        self.assertIs(self.event._occursOn(dt.date(2020, 5, 11)), False)

    @freeze_timetz("2020-05-31")
    def testEventNextDate(self):
        self.assertEqual(self.event.next_date, dt.date(2020, 6, 3))

    @freeze_timetz("2020-06-01")
    def testEventPastDatetime(self):
        self.assertEqual(self.event._past_datetime_from,
                         datetimetz(2020, 3, 18, 13, 0))

    @freeze_timetz("2020-06-01")
    def testEventFutureDatetime(self):
        shutdown = ExtCancellationPage(owner=self.user,
                                       overrides=self.event,
                                       cancelled_from_date=dt.date(
                                           2020, 5, 13))
        self.event.add_child(instance=shutdown)
        shutdown.save_revision().publish()
        self.assertIsNone(self.event._future_datetime_from)

    @freeze_timetz("2020-06-16")
    def testGetUpcomingEvents(self):
        event = RecurringEventPage(slug="lemon",
                                   title="Lemonade Stand",
                                   repeat=Recurrence(dtstart=dt.date(
                                       2021, 1, 1),
                                                     freq=WEEKLY,
                                                     byweekday=[FR]),
                                   time_from=dt.time(11),
                                   time_to=dt.time(13))
        self.calendar.add_child(instance=event)
        shutdown = ExtCancellationPage(owner=self.user,
                                       overrides=event,
                                       cancelled_from_date=dt.date(
                                           2021, 2, 13),
                                       cancellation_title="Gone fishing")
        event.add_child(instance=shutdown)
        shutdown.save_revision().publish()
        events = ExtCancellationPage.events.exclude(cancellation_title="")   \
                                      .upcoming().this()                     \
                                      .descendant_of(event)
        self.assertEqual(len(events), 1)
        title, page, url = events[0]
        self.assertEqual(title, "Gone fishing")
        self.assertEqual(page._future_datetime_from,
                         datetimetz(2021, 2, 19, 11, 0))
        self.assertEqual(url, "/events/lemon/2021-02-13--cancellation/")

    @freeze_timetz("2020-06-16")
    def testGetPastEvents(self):
        events = ExtCancellationPage.events.past().this()
        self.assertEqual(len(events), 1)
        title, page, url = events[0]
        self.assertEqual(title, "No Meeting during Shutdown")
        self.assertEqual(page._past_datetime_from,
                         datetimetz(2020, 6, 1, 13, 0))
        self.assertEqual(
            url, "/events/test-meeting/2020-03-20-2020-06-01-cancellation/")

    def testGetMyDates(self):
        dates = list(self.shutdown._getMyDates())
        self.assertEqual(dates, [
            dt.date(2020, 3, 20),
            dt.date(2020, 3, 23),
            dt.date(2020, 3, 25),
            dt.date(2020, 3, 27),
            dt.date(2020, 3, 30),
            dt.date(2020, 4, 1),
            dt.date(2020, 4, 3),
            dt.date(2020, 4, 6),
            dt.date(2020, 4, 8),
            dt.date(2020, 4, 10),
            dt.date(2020, 4, 13),
            dt.date(2020, 4, 15),
            dt.date(2020, 4, 17),
            dt.date(2020, 4, 20),
            dt.date(2020, 4, 22),
            dt.date(2020, 4, 24),
            dt.date(2020, 4, 27),
            dt.date(2020, 4, 29),
            dt.date(2020, 5, 1),
            dt.date(2020, 5, 4),
            dt.date(2020, 5, 6),
            dt.date(2020, 5, 8),
            dt.date(2020, 5, 11),
            dt.date(2020, 5, 13),
            dt.date(2020, 5, 15),
            dt.date(2020, 5, 18),
            dt.date(2020, 5, 20),
            dt.date(2020, 5, 22),
            dt.date(2020, 5, 25),
            dt.date(2020, 5, 27),
            dt.date(2020, 5, 29),
            dt.date(2020, 6, 1)
        ])

    def testGetMyRawDates(self):
        dates = list(
            self.shutdown._getMyRawDates(dt.date(2020, 5, 30),
                                         dt.date(2020, 6, 10)))
        self.assertEqual(
            dates,
            [dt.date(2020, 5, 30),
             dt.date(2020, 5, 31),
             dt.date(2020, 6, 1)])

    def testClosedOn(self):
        shutdown2 = ExtCancellationPage(owner=self.user,
                                        overrides=self.event,
                                        cancelled_from_date=dt.date(
                                            2020, 9, 2))
        self.event.add_child(instance=shutdown2)
        shutdown2.save_revision().publish()
        self.assertIs(shutdown2._closedOn(dt.date(2020, 9, 21)), True)
        self.assertIs(self.shutdown._closedOn(dt.date(2020, 3, 24)), True)
        self.assertIs(self.shutdown._closedOn(dt.date(2020, 6, 22)), False)

    def testStatus(self):
        self.assertEqual(self.shutdown.status, "cancelled")
        self.assertEqual(self.shutdown.status_text,
                         "This event has been cancelled.")

    @freeze_timetz("2020-03-25 14:00")
    def testWhen(self):
        self.assertEqual(
            self.shutdown.when,
            "Cancelled from Friday 20th of March to Monday 1st of June")

    @freeze_timetz("2020-03-25 14:00")
    def testWhenEver(self):
        event = RecurringEventPage(slug="OpQ",
                                   title="Orangepurple Quagga",
                                   repeat=Recurrence(dtstart=dt.date(
                                       2020, 1, 1),
                                                     freq=MONTHLY,
                                                     byweekday=[FR(-1)]),
                                   time_from=dt.time(19))
        self.calendar.add_child(instance=event)
        shutdown = ExtCancellationPage(owner=self.user,
                                       overrides=event,
                                       cancelled_from_date=dt.date(2020, 4, 1))
        event.add_child(instance=shutdown)
        shutdown.save_revision().publish()
        self.assertEqual(
            shutdown.when,
            "Cancelled from Wednesday 1st of April until further notice")

    def testAt(self):
        self.assertEqual(self.shutdown.at.strip(), "1pm")

    @freeze_timetz("2020-03-25 14:00")
    def testCurrentDt(self):
        self.assertEqual(self.shutdown._current_datetime_from,
                         datetimetz(2020, 3, 25, 13, 0))

    @freeze_timetz("2020-03-25 14:00")
    def testFutureDt(self):
        self.assertEqual(self.shutdown._future_datetime_from,
                         datetimetz(2020, 3, 27, 13, 0))

    @freeze_timetz("2020-03-25 14:00")
    def testPastDt(self):
        self.assertEqual(self.shutdown._past_datetime_from,
                         datetimetz(2020, 3, 25, 13, 0))

    def testUnexplainedCancellation(self):
        shutdown = ExtCancellationPage(
            owner=self.user,
            overrides=self.event,
            cancelled_from_date=dt.date(2019, 2, 8),
            cancellation_title="Restructure Pending",
            cancellation_details="Keep it quiet")
        self.event.add_child(instance=shutdown)
        PASSWORD = PageViewRestriction.PASSWORD
        restriction = PageViewRestriction.objects.create(
            restriction_type=PASSWORD, password="******", page=shutdown)
        restriction.save()
        events = RecurringEventPage.events.byDay(dt.date(2019, 2, 1),
                                                 dt.date(2019, 2, 28))
        self.assertEqual(len(events), 28)
        evod = events[7]
        self.assertEqual(evod.date, dt.date(2019, 2, 8))
        self.assertEqual(len(evod.days_events), 0)
        self.assertEqual(len(evod.continuing_events), 0)

    def testGroup(self):
        self.assertIsNone(self.shutdown.group)

    def testOverridesRepeat(self):
        self.assertEqual(self.shutdown.overrides_repeat, self.event.repeat)

    def testGetContext(self):
        request = RequestFactory().get("/test")
        context = self.shutdown.get_context(request)
        self.assertIn('overrides', context)
Пример #21
0
class TestExceptionDatePanel(TestCase):
    def setUp(self):
        self.home = getPage("/home/")
        self.user = User.objects.create_superuser('i', '*****@*****.**', 's3(r3t')
        self.calendar = CalendarPage(owner=self.user,
                                     slug="events",
                                     title="Events")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()
        self.event = RecurringEventPage(slug="leaders-meeting",
                                        title="Leaders' Meeting",
                                        repeat=Recurrence(dtstart=dt.date(
                                            2016, 2, 16),
                                                          freq=MONTHLY,
                                                          byweekday=[TU(3)]),
                                        time_from=dt.time(19),
                                        tz="Asia/Tokyo")
        self.calendar.add_child(instance=self.event)
        self.event.save_revision().publish()

    def _getRequest(self):
        request = RequestFactory().get("/test")
        request.user = self.user
        request.session = {}
        request.site = Site.objects.get(is_default_site=True)
        return request

    def testWidget(self):
        self.assertIs(ExceptionDatePanel.widget, ExceptionDateInput)

    @skipUnless(WagtailVersion >= (2, 5, 0), "Wagtail <2.5")
    def testBindWithoutForm25(self):
        cancellation = CancellationPage(owner=self.user,
                                        except_date=dt.date(2019, 1, 21))
        panel = ExceptionDatePanel('except_date', classname='full-width')
        panel = panel.bind_to(instance=cancellation)
        self.assertIsNone(panel.form)

    @skipUnless(WagtailVersion >= (2, 5, 0), "Wagtail <2.5")
    def testBindWithoutOverrides25(self):
        cancellation = CancellationPage(owner=self.user,
                                        except_date=dt.date(2019, 1, 21))
        Form = get_form_for_model(CancellationPage,
                                  form_class=CancellationPageForm)
        form = Form(instance=cancellation, parent_page=self.event)
        panel = ExceptionDatePanel('except_date', classname='full-width')
        panel = panel.bind_to(instance=cancellation)
        panel = panel.bind_to(request=self._getRequest())
        panel = panel.bind_to(form=form)
        self.assertIsNotNone(panel.form)
        self.assertIsNone(panel.instance.overrides)

    @skipUnless(WagtailVersion >= (2, 5, 0), "Wagtail <2.5")
    def testBindOverridesRepeat25(self):
        cancellation = CancellationPage(owner=self.user,
                                        overrides=self.event,
                                        except_date=dt.date(2019, 1, 21))
        Form = get_form_for_model(CancellationPage,
                                  form_class=CancellationPageForm)
        form = Form(instance=cancellation, parent_page=self.event)
        widget = form['except_date'].field.widget
        panel = ExceptionDatePanel('except_date', classname='full-width')
        panel = panel.bind_to(instance=cancellation)
        panel = panel.bind_to(request=self._getRequest())
        panel = panel.bind_to(form=form)
        self.assertIs(widget.overrides_repeat, self.event.repeat)
        self.assertIsNone(panel.exceptionTZ)

    @skipUnless(WagtailVersion >= (2, 5, 0), "Wagtail <2.5")
    @timezone.override("America/Los_Angeles")
    def testBindExceptionTZ25(self):
        cancellation = CancellationPage(owner=self.user,
                                        overrides=self.event,
                                        except_date=dt.date(2019, 1, 21))
        Form = get_form_for_model(CancellationPage,
                                  form_class=CancellationPageForm)
        form = Form(instance=cancellation, parent_page=self.event)
        panel = ExceptionDatePanel('except_date', classname='full-width')
        panel = panel.bind_to(instance=cancellation)
        panel = panel.bind_to(request=self._getRequest())
        panel = panel.bind_to(form=form)
        self.assertEqual(panel.exceptionTZ, "Asia/Tokyo")
Пример #22
0
class TestHiddenNumDaysPanel(TestCase):
    FIELD_CONTENT = """
<fieldset>
  <legend>Number of days</legend>
  <ul class="fields">
    <li>
      <div class="field integer_field number_input ">
        <div class="field-content">
          <div class="input  ">
            <input type="number" name="num_days" value="1" required id="id_num_days">
            <span></span>
          </div>
        </div>
      </div>
    </li>
  </ul>
</fieldset>
"""

    def setUp(self):
        self.home = getPage("/home/")
        self.user = User.objects.create_superuser('i', '*****@*****.**', 's3(r3t')
        self.calendar = CalendarPage(owner=self.user,
                                     slug="events",
                                     title="Events")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()
        self.event = RecurringEventPage(slug="leaders-meeting",
                                        title="Leaders' Meeting",
                                        repeat=Recurrence(dtstart=dt.date(
                                            2016, 2, 16),
                                                          freq=MONTHLY,
                                                          byweekday=[TU(3)]),
                                        time_from=dt.time(19),
                                        tz="Asia/Tokyo")
        self.calendar.add_child(instance=self.event)
        self.event.save_revision().publish()
        Form = get_form_for_model(RecurringEventPage,
                                  form_class=RecurringEventPageForm)
        self.form = Form(instance=self.event, parent_page=self.calendar)

    def _getRequest(self):
        request = RequestFactory().get("/test")
        request.user = self.user
        request.session = {}
        request.site = Site.objects.get(is_default_site=True)
        return request

    @skipUnless(WagtailVersion >= (2, 5, 0), "Wagtail <2.5")
    def testHidden25(self):
        panel = HiddenNumDaysPanel()
        panel = panel.bind_to(instance=self.event,
                              request=self._getRequest(),
                              form=self.form)
        content = panel.render_as_object()
        self.assertEqual(content, "")
        content = panel.render_as_field()
        self.assertEqual(content, "")

    @skipUnless(WagtailVersion >= (2, 5, 0), "Wagtail <2.5")
    def testShowWith2Days25(self):
        self.event.num_days = 2
        panel = HiddenNumDaysPanel()
        panel = panel.bind_to(instance=self.event,
                              request=self._getRequest(),
                              form=self.form)
        content = panel.render_as_object()
        self.assertHTMLEqual(content, self.FIELD_CONTENT)

    @skipUnless(WagtailVersion >= (2, 5, 0), "Wagtail <2.5")
    def testShowMulidayRecurringEvent25(self):
        event = MultidayRecurringEventPage(slug="leaders-retreat",
                                           title="Leaders' Retreet",
                                           repeat=Recurrence(
                                               dtstart=dt.date(2016, 2, 16),
                                               freq=YEARLY,
                                               bymonth=3,
                                               byweekday=[FR(1)]),
                                           time_from=dt.time(19),
                                           num_days=3,
                                           tz="Asia/Tokyo")
        self.calendar.add_child(instance=event)
        event.save_revision().publish()
        panel = HiddenNumDaysPanel()
        panel = panel.bind_to(instance=event,
                              request=self._getRequest(),
                              form=self.form)
        content = panel.render_as_object()
        self.assertHTMLEqual(content, self.FIELD_CONTENT)
Пример #23
0
class TestTZ(TestCase):
    def setUp(self):
        self.home = Page.objects.get(slug='home')
        self.user = User.objects.create_user('i', '*****@*****.**', 's3cr3t')
        self.calendar = CalendarPage(owner = self.user,
                                     slug  = "events",
                                     title = "Events")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()
        self.event = RecurringEventPage(owner = self.user,
                                        slug  = "code-for-boston",
                                        title = "Code for Boston",
                                        repeat    = Recurrence(dtstart=dt.date(2017,1,1),
                                                               freq=WEEKLY,
                                                               byweekday=[TU]),
                                        time_from = dt.time(19),
                                        time_to   = dt.time(21,30),
                                        tz = pytz.timezone("US/Eastern"),
                                        location  = "4th Floor, 1 Broadway, Cambridge, MA")
        self.calendar.add_child(instance=self.event)
        self.event.save_revision().publish()

    def testGetEventsByLocalDay(self):
        events = RecurringEventPage.events.byDay(dt.date(2018,4,1),
                                                 dt.date(2018,4,30))
        self.assertEqual(len(events), 30)
        evod1 = events[3]
        self.assertEqual(evod1.date, dt.date(2018,4,4))
        self.assertEqual(len(evod1.days_events), 1)
        self.assertEqual(len(evod1.continuing_events), 0)

    @freeze_timetz("2017-05-31")
    def testLocalWhen(self):
        with timezone.override("America/Los_Angeles"):
            self.assertEqual(self.event.when,
                             "Tuesdays at 4pm to 6:30pm")
        with timezone.override("Australia/Perth"):
            self.assertEqual(self.event.when,
                             "Wednesdays at 7am to 9:30am")

    @timezone.override("America/Los_Angeles")
    def testLocalAt(self):
        self.assertEqual(self.event.at, "4pm")

    @timezone.override("America/Los_Angeles")
    def testCurrentLocalDt(self):
        when = self.event._current_datetime_from
        self.assertEqual(when.tzinfo.zone, "America/Los_Angeles")
        self.assertEqual(when.weekday(), calendar.TUESDAY)

    @timezone.override("America/Los_Angeles")
    def testFutureLocalDt(self):
        when = self.event._future_datetime_from
        self.assertEqual(when.tzinfo.zone, "America/Los_Angeles")
        self.assertEqual(when.weekday(), calendar.TUESDAY)

    @timezone.override("Pacific/Auckland")
    def testPastLocalDt(self):
        when = self.event._past_datetime_from
        self.assertEqual(when.tzinfo.zone, "Pacific/Auckland")
        self.assertEqual(when.weekday(), calendar.WEDNESDAY)

    @timezone.override("Pacific/Kiritimati")
    def testExtremeTimeZones(self):
        lions = RecurringEventPage(owner = self.user,
                                   slug  = "pago-pago-lions",
                                   title = "Pago Pago Lions Club",
                                   repeat = Recurrence(dtstart=dt.date(2015,2,1),
                                                       freq=MONTHLY,
                                                       byweekday=[TH(1),TH(3)]),
                                   time_from = dt.time(23,0),
                                   tz = pytz.timezone("Pacific/Pago_Pago"),
                                   location = "Lions Den, Tafuna, PagoPago",
                                   website = "http://www.lionsclubs.org.nz")
        self.calendar.add_child(instance=lions)
        self.assertEqual(lions.when,
                         "The Saturday after the first Thursday and "
                         "Saturday after the third Thursday of the month at 12am")
class Test(TestCase):
    def setUp(self):
        self.home = Page.objects.get(slug='home')
        self.user = User.objects.create_user('i', '*****@*****.**', 's3(r3t')
        self.calendar = CalendarPage(owner=self.user,
                                     slug="events",
                                     title="Events")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()
        self.event = RecurringEventPage(slug="test-meeting",
                                        title="Test Meeting",
                                        repeat=Recurrence(
                                            dtstart=dt.date(1989, 1, 1),
                                            freq=WEEKLY,
                                            byweekday=[MO, WE, FR]),
                                        time_from=dt.time(13),
                                        time_to=dt.time(15, 30),
                                        holidays=self.calendar.holidays)
        self.calendar.add_child(instance=self.event)
        self.closedHols = ClosedForHolidaysPage(
            owner=self.user,
            overrides=self.event,
            all_holidays=True,
            holidays=self.calendar.holidays)
        self.event.add_child(instance=self.closedHols)
        self.closedHols.save_revision().publish()

    def testCanCreateOnlyOne(self):
        self.assertFalse(ClosedForHolidaysPage.can_create_at(self.event))

    def testInit(self):
        self.assertEqual(self.closedHols.all_holidays, True)
        self.assertEqual(self.closedHols.title, "Closed for holidays")
        self.assertEqual(self.closedHols.local_title, "Closed for holidays")
        self.assertEqual(self.closedHols.slug, "closed-for-holidays")

    def testGetEventsByDay(self):
        events = RecurringEventPage.events.hols(self.calendar.holidays)      \
                                   .byDay(dt.date(1989,1,1), dt.date(1989,1,31))
        self.assertEqual(len(events), 31)
        evod = events[0]
        self.assertEqual(evod.date, dt.date(1989, 1, 1))
        self.assertEqual(evod.holiday, "New Year's Day")
        self.assertEqual(len(evod.days_events), 0)
        self.assertEqual(len(evod.continuing_events), 0)

    @freeze_timetz("1990-11-11 16:29:00")
    def testEventFutureExceptions(self):
        request = RequestFactory().get("/test")
        request.user = self.user
        request.session = {}
        exceptions = self.event._futureExceptions(request)
        self.assertEqual(len(exceptions), 1)
        c4h = exceptions[0]
        self.assertEqual(c4h.title, "Closed for holidays")
        self.assertEqual(c4h._future_datetime_from,
                         datetimetz(1990, 11, 16, 13, 0))

    def testEventOccursOn(self):
        self.assertIs(self.event._occursOn(dt.date(1989, 1, 1)), False)
        self.assertIs(self.event._occursOn(dt.date(1989, 1, 2)), False)
        self.assertIs(self.event._occursOn(dt.date(1989, 1, 6)), True)
        self.assertIs(self.event._occursOn(dt.date(1989, 1, 16)), False)

    @freeze_timetz("2022-12-24")
    def testEventNextDate(self):
        self.assertEqual(self.event.next_date, dt.date(2022, 12, 28))

    @freeze_timetz("2023-01-31")
    def testEventPastDatetime(self):
        self.assertEqual(self.event._past_datetime_from,
                         datetimetz(2023, 1, 27, 13, 0))

    @freeze_timetz("1990-10-11 16:29:00")
    def testGetUpcomingEvents(self):
        event = RecurringEventPage(slug="RST",
                                   title="Ruritania secret taxidermy",
                                   repeat=Recurrence(dtstart=dt.date(
                                       1980, 1, 1),
                                                     freq=MONTHLY,
                                                     byweekday=[MO(1)]),
                                   time_from=dt.time(20))
        self.calendar.add_child(instance=event)
        closedHols = ClosedForHolidaysPage(
            owner=self.user,
            overrides=event,
            all_holidays=False,
            cancellation_title="Closed for the holiday")
        closedHols.closed_for = [
            ClosedFor(name="Wellington Anniversary Day"),
            ClosedFor(name="Auckland Anniversary Day"),
            ClosedFor(name="Nelson Anniversary Day"),
            ClosedFor(name="Taranaki Anniversary Day"),
            ClosedFor(name="Otago Anniversary Day"),
            ClosedFor(name="Southland Anniversary Day"),
            ClosedFor(name="South Canterbury Anniversary Day"),
            ClosedFor(name="Hawke's Bay Anniversary Day"),
            ClosedFor(name="Marlborough Anniversary Day"),
            ClosedFor(name="Canterbury Anniversary Day"),
            ClosedFor(name="Chatham Islands Anniversary Day"),
            ClosedFor(name="Westland Anniversary Day")
        ]
        event.add_child(instance=closedHols)
        closedHols.save_revision().publish()
        events = ClosedForHolidaysPage.events.hols(self.calendar.holidays)   \
                                      .exclude(cancellation_title="")        \
                                      .upcoming().this().descendant_of(event)
        self.assertEqual(len(events), 1)
        title, page, url = events[0]
        self.assertEqual(title, "Closed for the holiday")
        self.assertEqual(page._future_datetime_from,
                         datetimetz(1990, 12, 3, 20, 0))
        self.assertEqual(url, "/events/RST/closed-for-holidays/")

    @freeze_timetz("1990-10-11 16:29:00")
    def testGetPastEvents(self):
        events = ClosedForHolidaysPage.events.hols(self.calendar.holidays)   \
                                      .past().this()
        self.assertEqual(len(events), 1)
        title, page, url = events[0]
        self.assertEqual(title, "")
        self.assertEqual(page._past_datetime_from,
                         datetimetz(1990, 9, 24, 13, 0))
        self.assertEqual(url, "/events/test-meeting/closed-for-holidays/")

    @freeze_timetz("1990-10-11 16:29:00")
    def testWombatGetEventsByDay(self):
        event = RecurringEventPage(slug="UVW",
                                   title="Underwater viking wombats",
                                   repeat=Recurrence(dtstart=dt.date(
                                       1989, 1, 1),
                                                     freq=MONTHLY,
                                                     byweekday=[MO(1)]),
                                   time_from=dt.time(19))
        self.calendar.add_child(instance=event)
        closedHols = ClosedForHolidaysPage(owner=self.user,
                                           overrides=event,
                                           all_holidays=False,
                                           cancellation_title="UVW Cancelled")
        closedHols.closed_for = [
            ClosedFor(name="New Year's Day"),
            ClosedFor(name="Day after New Year's Day"),
            ClosedFor(name="Good Friday"),
            ClosedFor(name="Easter Monday"),
            ClosedFor(name="Christmas Day"),
            ClosedFor(name="Boxing Day")
        ]
        event.add_child(instance=closedHols)
        closedHols.save_revision().publish()
        events = RecurringEventPage.events.hols(self.calendar.holidays)      \
                                   .byDay(dt.date(1989,1,1), dt.date(1989,1,31))
        self.assertEqual(len(events), 31)
        evod = events[1]
        self.assertEqual(evod.date, dt.date(1989, 1, 2))
        self.assertEqual(evod.holiday, "Day after New Year's Day")
        self.assertEqual(len(evod.days_events), 1)
        self.assertEqual(len(evod.continuing_events), 0)
        title, page, url = evod.all_events[0]
        self.assertEqual(title, "UVW Cancelled")
        self.assertEqual(page.title, "Closed for holidays")
        self.assertEqual(page.at, "7pm")
        self.assertEqual(url, "/events/UVW/closed-for-holidays/")

    def testClosedForDates(self):
        dates = list(islice(self.closedHols._closed_for_dates, 10))
        self.assertEqual(dates, [
            dt.date(1989, 1, 2),
            dt.date(1989, 1, 16),
            dt.date(1989, 1, 23),
            dt.date(1989, 1, 30),
            dt.date(1989, 2, 6),
            dt.date(1989, 3, 13),
            dt.date(1989, 3, 20),
            dt.date(1989, 3, 24),
            dt.date(1989, 3, 27),
            dt.date(1989, 6, 5)
        ])

    def testGetMyDates(self):
        event = RecurringEventPage(slug="UVW",
                                   title="Underwater viking wombats",
                                   repeat=Recurrence(dtstart=dt.date(
                                       1989, 1, 1),
                                                     freq=MONTHLY,
                                                     byweekday=[MO(1)]),
                                   time_from=dt.time(19))
        self.calendar.add_child(instance=event)
        closedHols = ClosedForHolidaysPage(owner=self.user,
                                           overrides=event,
                                           all_holidays=False)
        event.add_child(instance=closedHols)
        closedHols.save_revision().publish()
        dates = list(islice(closedHols._getMyDates(), 10))
        self.assertEqual(dates, [])
        closedHols.holidays = self.calendar.holidays
        dates = list(islice(closedHols._getMyDates(), 10))
        self.assertEqual(dates, [])
        closedHols.closed_for = [ClosedFor(name="Good Friday")]
        # Good Friday is never going to fall on a Monday
        dates = list(islice(closedHols._getMyDates(), 10))
        self.assertEqual(dates, [])

    def testClosedOn(self):
        event = RecurringEventPage(slug="XYZ",
                                   title="Xylophone yacht zombies",
                                   repeat=Recurrence(dtstart=dt.date(
                                       1989, 1, 1),
                                                     freq=WEEKLY,
                                                     byweekday=[FR]),
                                   time_from=dt.time(19),
                                   holidays=self.calendar.holidays)
        self.calendar.add_child(instance=event)
        closedHols = ClosedForHolidaysPage(owner=self.user,
                                           overrides=event,
                                           all_holidays=False,
                                           cancellation_title="XYZ Cancelled")
        event.add_child(instance=closedHols)
        closedHols.save_revision().publish()
        self.assertEqual(closedHols._closedOn(dt.date(1989, 3, 24)), False)
        closedHols.holidays = self.calendar.holidays
        self.assertEqual(closedHols._closedOn(dt.date(1989, 3, 24)), False)

    def testStatus(self):
        self.assertEqual(self.closedHols.status, "cancelled")
        self.assertEqual(self.closedHols.status_text, "Closed for holidays.")

    def testWhen(self):
        self.assertEqual(self.closedHols.when, "Closed on all holidays")

    def testWhenEver(self):
        event = RecurringEventPage(slug="XYZ",
                                   title="Xylophone yacht zombies",
                                   repeat=Recurrence(dtstart=dt.date(
                                       1989, 1, 1),
                                                     freq=WEEKLY,
                                                     byweekday=[FR]),
                                   time_from=dt.time(19),
                                   holidays=self.calendar.holidays)
        self.calendar.add_child(instance=event)
        closedHols = ClosedForHolidaysPage(owner=self.user,
                                           overrides=event,
                                           all_holidays=False,
                                           cancellation_title="XYZ Cancelled",
                                           holidays=self.calendar.holidays)
        closedHols.closed_for = [
            ClosedFor(name="Good Friday"),
            ClosedFor(name="Easter Monday")
        ]
        event.add_child(instance=closedHols)
        closedHols.save_revision().publish()
        self.assertEqual(closedHols.when,
                         "Closed on Good Friday and Easter Monday")
        self.assertIs(event._occursOn(dt.date(1989, 3, 24)), False)

    # def testActualHolidaysClosed(self):
    #     event = RecurringEventPage(slug      = "Z1",
    #                                title     = "ZetaOne",
    #                                repeat    = Recurrence(dtstart=dt.date(2020,1,1),
    #                                                       freq=DAILY),
    #                                time_from = dt.time(19),
    #                                holidays = self.calendar.holidays)
    #     self.calendar.add_child(instance=event)
    #     closedHols = ClosedForHolidaysPage(owner = self.user,
    #                                        overrides = event,
    #                                        all_holidays = False,
    #                                        cancellation_title = "Z1 Cancelled",
    #                                        holidays = self.calendar.holidays)
    #     closedHols.closed_for = [ ClosedFor(name="New Year's Day"),
    #                               ClosedFor(name="New Year's Day (Observed)"),
    #                               ClosedFor(name="Labour Day"),
    #                               ClosedFor(name="Christmas Day"),
    #                               ClosedFor(name="Christmas Day (Observed)") ]
    #     event.add_child(instance=closedHols)
    #     closedHols.save_revision().publish()
    #     self.assertCountEqual(closedHols._actual_closed_for_names,
    #                           ["New Year's Day",
    #                            "New Year's Day (Observed)",
    #                            "Labour Day",
    #                            "Christmas Day",
    #                            "Christmas Day (Observed)"])

    def testAt(self):
        self.assertEqual(self.closedHols.at.strip(), "1pm")

    @freeze_timetz("1989-02-15")
    def testCurrentDt(self):
        # Taranaki Anniversary Day
        self.assertEqual(self.closedHols._current_datetime_from,
                         datetimetz(1989, 3, 13, 13, 0))

    @freeze_timetz("1989-02-15")
    def testFutureDt(self):
        # Taranaki Anniversary Day
        self.assertEqual(self.closedHols._future_datetime_from,
                         datetimetz(1989, 3, 13, 13, 0))

    @freeze_timetz("1989-02-15")
    def testPastDt(self):
        # Waitangi Day
        self.assertEqual(self.closedHols._past_datetime_from,
                         datetimetz(1989, 2, 6, 13, 0))

    @freeze_timetz("1989-02-15")
    def testFutureDtNoHolidays(self):
        self.closedHols.holidays = None
        self.assertEqual(self.closedHols._future_datetime_from,
                         ClosedForHolidaysPage.MAX_DATETIME)

    @freeze_timetz("1989-02-15")
    def testPastDtNoHolidays(self):
        self.closedHols.holidays = None
        self.assertEqual(self.closedHols._past_datetime_from,
                         ClosedForHolidaysPage.MIN_DATETIME)

    @freeze_timetz("1989-02-15")
    def testFutureDtCancelled(self):
        # a cancellation page trumps the holiday
        cancellation = CancellationPage(owner=self.user,
                                        overrides=self.event,
                                        except_date=dt.date(1989, 3, 13))
        self.event.add_child(instance=cancellation)
        self.assertEqual(self.closedHols._future_datetime_from,
                         datetimetz(1989, 3, 20, 13, 0))

    @freeze_timetz("1989-02-15")
    def testPastDtCancelled(self):
        # a cancellation page trumps the holiday
        cancellation = CancellationPage(owner=self.user,
                                        overrides=self.event,
                                        except_date=dt.date(1989, 2, 6))
        self.event.add_child(instance=cancellation)
        self.assertEqual(self.closedHols._past_datetime_from,
                         datetimetz(1989, 1, 30, 13, 0))

    @freeze_timetz("1989-02-15")
    def testPastDtShut(self):
        # a shutdown page trumps the holiday
        shutdown = ExtCancellationPage(owner=self.user,
                                       overrides=self.event,
                                       cancelled_from_date=dt.date(
                                           1989, 1, 29),
                                       cancelled_to_date=dt.date(1989, 2, 10))
        self.event.add_child(instance=shutdown)
        self.assertEqual(self.closedHols._past_datetime_from,
                         datetimetz(1989, 1, 23, 13, 0))

    @freeze_timetz("1989-02-15")
    def testFutureDtShut(self):
        # a shutdown page trumps the holiday
        shutdown = ExtCancellationPage(owner=self.user,
                                       overrides=self.event,
                                       cancelled_from_date=dt.date(
                                           1989, 3, 12),
                                       cancelled_to_date=dt.date(1989, 3, 20))
        self.event.add_child(instance=shutdown)
        self.assertEqual(self.closedHols._future_datetime_from,
                         datetimetz(1989, 3, 24, 13, 0))

    @freeze_timetz("1989-02-15")
    def testFutureDtShutUntilFurtherNotice(self):
        # a shutdown page trumps the holiday
        shutdown = ExtCancellationPage(owner=self.user,
                                       overrides=self.event,
                                       cancelled_from_date=dt.date(
                                           1989, 3, 12))
        self.event.add_child(instance=shutdown)
        self.assertIsNone(self.closedHols._future_datetime_from)

    @freeze_timetz("1989-02-15")
    def testFarFutureDt(self):
        event = RecurringEventPage(slug="UVW",
                                   title="Underwater viking wombats",
                                   repeat=Recurrence(dtstart=dt.date(
                                       1989, 1, 1),
                                                     freq=MONTHLY,
                                                     bymonthday=23),
                                   time_from=dt.time(19))
        self.calendar.add_child(instance=event)
        closedHols = ClosedForHolidaysPage(owner=self.user,
                                           overrides=event,
                                           all_holidays=False)
        event.add_child(instance=closedHols)
        closedHols.save_revision().publish()
        dates = list(islice(closedHols._getMyDates(), 10))
        self.assertEqual(dates, [])
        closedHols.holidays = self.calendar.holidays
        dates = list(islice(closedHols._getMyDates(), 10))
        self.assertEqual(dates, [])
        closedHols.closed_for = [ClosedFor(name="Good Friday")]
        # Good Friday falls on 2038-04-23 but that is too far to calculate
        self.assertEqual(closedHols._future_datetime_from,
                         datetimetz(9999, 12, 29, 19, 0))

    def testGroup(self):
        self.assertIsNone(self.closedHols.group)

    def testOverridesRepeat(self):
        self.assertEqual(self.closedHols.overrides_repeat, self.event.repeat)

    def testGetContext(self):
        request = RequestFactory().get("/test")
        context = self.closedHols.get_context(request)
        self.assertIn('overrides', context)

    def testClosedForStr(self):
        xmas = ClosedFor(name="☧mas")
        self.assertEqual(str(xmas), "☧mas")
class TestPageForm(TestCase):
    Form = ClosedForHolidaysPage.get_edit_handler().get_form_class()

    def setUp(self):
        holidays = Holidays(holidaySetting=None)
        holidays.register(WeatherDays())
        self.home = Page.objects.get(slug='home')
        self.user = User.objects.create_user('i', '*****@*****.**', 's3(r3t')
        self.calendar = CalendarPage(owner=self.user,
                                     slug="events",
                                     title="Events")
        self.calendar.holidays = holidays
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()
        self.event = RecurringEventPage(slug="committee-meeting",
                                        title="Committee Meeting",
                                        repeat=Recurrence(
                                            dtstart=dt.date(2017, 1, 1),
                                            freq=MONTHLY,
                                            byweekday=[MO(1), MO(3)]),
                                        time_from=dt.time(13),
                                        time_to=dt.time(15, 30),
                                        holidays=holidays)
        self.calendar.add_child(instance=self.event)

    def testValid(self):
        page = ClosedForHolidaysPage(owner=self.user,
                                     holidays=self.event.holidays)
        form = self.Form(
            {
                'overrides': self.event,
                'all_holidays': False,
                'closed_for': ["St Swithin's Day", "Sleepy Head Day"],
                'cancellation_title': "Holiday",
                'cancellation_details': rich_text("No meeting today!"),
            },
            instance=page,
            parent_page=self.event)
        self.assertCountEqual(form.fields['closed_for'].choices,
                              [("Groundhog Day", "Groundhog Day"),
                               ("St Swithin's Day", "St Swithin's Day"),
                               ("Sleepy Head Day", "Sleepy Head Day")])
        self.assertEqual(form.initial['closed_for'], [])
        self.assertTrue(form.is_valid())  # is_valid() calls full_clean()
        self.assertDictEqual(form.errors, {})
        saved = form.save(commit=False)
        self.assertCountEqual(saved.closed,
                              ["St Swithin's Day", "Sleepy Head Day"])

    def testDefaultHolidayChoices(self):
        page = ClosedForHolidaysPage(owner=self.user)
        form = self.Form({'overrides': self.event},
                         instance=page,
                         parent_page=self.event)
        self.assertCountEqual(
            form.fields['closed_for'].choices,
            [(name, name) for name in
             ("New Year's Day", "Day after New Year's Day",
              "New Year's Day (Observed)",
              "Day after New Year's Day (Observed)",
              'Wellington Anniversary Day', 'Auckland Anniversary Day',
              'Nelson Anniversary Day', 'Waitangi Day',
              'Waitangi Day (Observed)', 'Taranaki Anniversary Day',
              'Otago Anniversary Day', 'Good Friday', 'Easter Monday',
              'Southland Anniversary Day', 'Anzac Day', 'Anzac Day (Observed)',
              "Queen's Birthday", 'South Canterbury Anniversary Day',
              "Hawke's Bay Anniversary Day", 'Labour Day',
              'Marlborough Anniversary Day', 'Canterbury Anniversary Day',
              'Chatham Islands Anniversary Day', 'Westland Anniversary Day',
              'Christmas Day', 'Boxing Day', 'Christmas Day (Observed)',
              'Boxing Day (Observed)')])
Пример #26
0
class TestAuth(TestCase):
    @freeze_timetz("2018-02-01 13:00")
    def setUp(self):
        site = Site.objects.get(is_default_site=True)
        site.hostname = "joy.test"
        site.save()
        self.home = getPage("/home/")
        self.user = User.objects.create_user('i', '*****@*****.**', 's3cr3t')
        self.requestFactory = RequestFactory()
        self.calendar = CalendarPage(owner=self.user,
                                     slug="events",
                                     title="Events")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()
        event = RecurringEventPage(
            owner=self.user,
            slug="fierce-tango-fridays",
            title="Fierce Tango Fridays",
            details="Weekly fierce tango lessons at the Dance Spot",
            repeat=Recurrence(dtstart=dt.date(2018, 3, 30),
                              until=dt.date(2018, 8, 31),
                              freq=WEEKLY,
                              byweekday=[FR]),
            time_from=dt.time(19, 30),
            time_to=dt.time(22, 0),
            tz=pytz.timezone("US/Eastern"),
            website="http://torontodancespot.com/",
            location="622 Bloor St. W., Toronto ON, M6G 1K7",
            uid="*****@*****.**")
        self.calendar.add_child(instance=event)
        event.save_revision().publish()
        GROUPS = PageViewRestriction.GROUPS
        self.group = Group.objects.create(name="Friday Class")
        info = ExtraInfoPage(owner=self.user,
                             slug="2018-08-31-extra-info",
                             title="Extra-Info for Friday 31st of August",
                             overrides=event,
                             except_date=dt.date(2018, 8, 31),
                             extra_title="Surprise",
                             extra_information="Surprise party")
        event.add_child(instance=info)
        info.save_revision().publish()
        restriction = PageViewRestriction.objects.create(
            restriction_type=GROUPS, page=info)
        restriction.groups.set([self.group])
        restriction.save()

    def _getRequest(self, path="/"):
        request = self.requestFactory.get(path)
        request.user = self.user
        request.site = self.home.get_site()
        request.session = {}
        request._messages = FallbackStorage(request)
        request.POST = request.POST.copy()
        request.POST['action-publish'] = "action-publish"
        return request

    @freeze_timetz("2018-04-08 10:00")
    @timezone.override("America/Toronto")
    def testLoadRestrictedExtraInfo(self):
        data = b"\r\n".join([
            b"BEGIN:VCALENDAR",
            b"VERSION:2.0",
            b"PRODID:-//Bloor &amp; Spadina - ECPv4.6.13//NONSGML v1.0//EN",
            b"BEGIN:VEVENT",
            b"SUMMARY:Surprise party",
            b"DESCRIPTION:Fierce Tango Final Friday",
            b"DTSTART:20180831T193000",
            b"DTEND:20180831T220000",
            b"RECURRENCE-ID:20180831T193000",
            b"DTSTAMP:20180408T094745Z",
            b"LAST-MODIFIED:20180314T010000Z",
            b"UID:[email protected]",
            b"END:VEVENT",
            b"BEGIN:VEVENT",
            b"SUMMARY:Fierce Tango Fridays",
            b"DESCRIPTION:Weekly fierce tango lessons at the Dance Spot",
            b"DTSTART:20180330T193000",
            b"DTEND:20180330T220000",
            b"RRULE:FREQ=WEEKLY;BYDAY=FR;UNTIL:20180831",
            b"DTSTAMP:20180408T094745Z",
            b"LAST-MODIFIED:20180131T010000Z",
            b"LOCATION:622 Bloor St. W., Toronto ON, M6G 1K7",
            b"SUMMARY:Fierce Tango Fridays",
            b"UID:[email protected]",
            b"URL:http://torontodancespot.com/",
            b"END:VEVENT",
            b"END:VCALENDAR",
        ])
        vcal = VCalendar(self.calendar)
        results = vcal.load(self._getRequest(), data)
        self.assertEqual(results.success, 0)
        self.assertEqual(results.fail, 1)
        self.assertEqual(results.error, 0)
        events = RecurringEventPage.events.child_of(self.calendar).all()
        self.assertEqual(len(events), 1)
        event = events[0]
        self.assertEqual(event.slug, "fierce-tango-fridays")
        self.assertEqual(event.title, "Fierce Tango Fridays")
        self.assertEqual(repr(event.repeat),
                        "DTSTART:20180330\n" \
                        "RRULE:FREQ=WEEKLY;WKST=SU;UNTIL=20180831;BYDAY=FR")
        self.assertEqual(event.time_from, dt.time(19, 30))
        self.assertEqual(event.time_to, dt.time(22, 0))
        self.assertEqual(event.revisions.count(), 1)
        info = ExtraInfoPage.events.child_of(event).get()
        self.assertEqual(info.slug, "2018-08-31-extra-info")
        self.assertEqual(info.title, "Extra-Info for Friday 31st of August")
        self.assertEqual(info.extra_title, "Surprise")
        self.assertEqual(info.extra_information, "Surprise party")
        self.assertEqual(info.except_date, dt.date(2018, 8, 31))
        self.assertEqual(info.revisions.count(), 1)
Пример #27
0
class Test(TestCase):
    def setUp(self):
        self.user = User.objects.create_user('i', '*****@*****.**', 's3cr3t')
        self.calendar = CalendarPage(owner=self.user,
                                     slug="events",
                                     title="Events")
        Page.objects.get(slug='home').add_child(instance=self.calendar)
        self.calendar.save()
        self.calendar.save_revision().publish()
        self.event = MultidayRecurringEventPage(
            owner=self.user,
            slug="team-retreat",
            title="Team Retreat",
            repeat=Recurrence(dtstart=dt.date(2000, 1, 1),
                              freq=YEARLY,
                              bymonth=8,
                              byweekday=FR(1)),
            num_days=3,
            time_from=dt.time(18),
            time_to=dt.time(16, 30))
        self.calendar.add_child(instance=self.event)
        self.event.save_revision().publish()

    def testGetEventsByDay(self):
        events = MultidayRecurringEventPage.events.byDay(
            dt.date(2017, 8, 1), dt.date(2017, 8, 31))
        self.assertEqual(len(events), 31)
        evod = events[3]
        self.assertEqual(evod.date, dt.date(2017, 8, 4))
        self.assertEqual(len(evod.days_events), 1)
        self.assertEqual(len(evod.continuing_events), 0)
        evod = events[4]
        self.assertEqual(evod.date, dt.date(2017, 8, 5))
        self.assertEqual(len(evod.days_events), 0)
        self.assertEqual(len(evod.continuing_events), 1)
        evod = events[5]
        self.assertEqual(evod.date, dt.date(2017, 8, 6))
        self.assertEqual(len(evod.days_events), 0)
        self.assertEqual(len(evod.continuing_events), 1)

    def testStatus(self):
        with freeze_timetz("2014-08-01 17:00:00"):
            self.assertEqual(self.event.status_text, "")
        with freeze_timetz("2014-08-02 13:00:00"):
            self.assertEqual(self.event.status_text, "This event has started.")
        with freeze_timetz("2014-08-03 15:00:00"):
            self.assertEqual(self.event.status_text, "This event has started.")
        with freeze_timetz("2014-08-03 17:00:00"):
            self.assertEqual(self.event.status_text, "")

    def testNextOn(self):
        request = RequestFactory().get("/test")
        request.user = self.user
        request.session = {}
        oldEvent = MultidayRecurringEventPage(owner=self.user,
                                              slug="same-old-thing",
                                              title="Same Ol'",
                                              repeat=Recurrence(
                                                  dtstart=dt.date(1971, 1, 1),
                                                  until=dt.date(1982, 1, 1),
                                                  freq=WEEKLY,
                                                  byweekday=SA(1)),
                                              num_days=2)
        self.calendar.add_child(instance=oldEvent)
        oldEvent.save_revision().publish()
        with freeze_timetz("1974-08-01 17:00:00"):
            self.assertEqual(oldEvent.next_date, dt.date(1974, 8, 3))
            self.assertEqual(oldEvent._nextOn(request),
                             "Saturday 3rd of August ")
        with freeze_timetz("1982-01-01 17:00:00"):
            self.assertIsNone(oldEvent.next_date)
            self.assertEqual(oldEvent._nextOn(request), None)

    def testWhen(self):
        self.assertEqual(
            self.event.when, "The first Friday of August for 3 days "
            "starting at 6pm finishing at 4:30pm")

    def testAt(self):
        self.assertEqual(self.event.at.strip(), "6pm")

    @freeze_timetz("2035-04-03 10:00:00")
    def testPrevDate(self):
        self.assertEqual(self.event.prev_date, dt.date(2034, 8, 4))

    @freeze_timetz("2018-04-03 10:00:00")
    def testFutureExceptions(self):
        request = RequestFactory().get("/test")
        request.user = self.user
        request.session = {}
        info2018 = ExtraInfoPage(owner=self.user,
                                 overrides=self.event,
                                 except_date=dt.date(2018, 8, 3),
                                 extra_title="Team Retreat 2018",
                                 extra_information="Weekend at Bernie's")
        self.event.add_child(instance=info2018)
        exceptions = self.event._futureExceptions(request)
        self.assertEqual(len(exceptions), 1)
        info = exceptions[0]
        self.assertEqual(info.slug, "2018-08-03-extra-info")
        self.assertEqual(info.extra_title, "Team Retreat 2018")

    @freeze_timetz("2018-08-04 02:00:00")
    def testPastExcludeExtraInfo(self):
        info2018 = ExtraInfoPage(owner=self.user,
                                 overrides=self.event,
                                 except_date=dt.date(2018, 8, 3),
                                 extra_title="Team Retreat 2018",
                                 extra_information="Weekend at Bernie's")
        self.event.add_child(instance=info2018)
        before = self.event._past_datetime_from
        self.assertEqual(before, datetimetz(2017, 8, 4, 18))
Пример #28
0
class TestHiddenNumDaysPanel(TestCase):
    FIELDSET_CONTENT = """
<fieldset>
  <legend>Number of days</legend>
  <ul class="fields">
    <li>
      <div class="field integer_field number_input ">
        <div class="field-content">
          <div class="input  ">
            <input type="number" name="num_days" value="1" required id="id_num_days">
            <span></span>
          </div>
        </div>
      </div>
    </li>
  </ul>
</fieldset>
"""
    COMMENT_CONTROL_CONTENT = """
<div class="field-comment-control field-comment-control--object">
  <button aria-label="Add comment" class="u-hidden" data-comment-add data-component="add-comment-button" type="button">
    <svg aria-hidden="true" class="icon icon-comment-add icon-default initial" focusable="false">
      <use href="#icon-comment-add">
    </svg>
    <svg aria-hidden="true" class="icon icon-comment-add icon-reversed initial" focusable="false">
      <use href="#icon-comment-add-reversed">
    </svg>
  </button>
</div>
"""

    def setUp(self):
        if WagtailVersion > (2, 13, 0):
            self.FIELD_CONTENT = """
<div data-contentpath="num_days">
    {}
    {}
</div>
""".format(self.FIELDSET_CONTENT, self.COMMENT_CONTROL_CONTENT)
        else:
            self.FIELD_CONTENT = self.FIELDSET_CONTENT
        self.maxDiff = None
        self.home = getPage("/home/")
        self.user = User.objects.create_superuser('i', '*****@*****.**', 's3(r3t')
        self.calendar = CalendarPage(owner=self.user,
                                     slug="events",
                                     title="Events")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()
        self.event = RecurringEventPage(slug="leaders-meeting",
                                        title="Leaders' Meeting",
                                        repeat=Recurrence(dtstart=dt.date(
                                            2016, 2, 16),
                                                          freq=MONTHLY,
                                                          byweekday=[TU(3)]),
                                        time_from=dt.time(19),
                                        tz="Asia/Tokyo")
        self.calendar.add_child(instance=self.event)
        self.event.save_revision().publish()
        Form = get_form_for_model(RecurringEventPage,
                                  form_class=RecurringEventPageForm)
        self.form = Form(instance=self.event, parent_page=self.calendar)

    def _getRequest(self):
        request = RequestFactory().get("/test")
        request.user = self.user
        request.session = {}
        request.site = Site.objects.get(is_default_site=True)
        return request

    def testHidden(self):
        panel = HiddenNumDaysPanel()
        panel = panel.bind_to(instance=self.event,
                              request=self._getRequest(),
                              form=self.form)
        content = panel.render_as_object()
        self.assertEqual(content, "")
        content = panel.render_as_field()
        self.assertEqual(content, "")

    def testShowWith2Days(self):
        self.event.num_days = 2
        panel = HiddenNumDaysPanel()
        panel = panel.bind_to(instance=self.event,
                              request=self._getRequest(),
                              form=self.form)
        content = panel.render_as_object()
        self.assertHTMLEqual(content, self.FIELD_CONTENT)

    def testShowMulidayRecurringEvent(self):
        event = MultidayRecurringEventPage(slug="leaders-retreat",
                                           title="Leaders' Retreet",
                                           repeat=Recurrence(
                                               dtstart=dt.date(2016, 2, 16),
                                               freq=YEARLY,
                                               bymonth=3,
                                               byweekday=[FR(1)]),
                                           time_from=dt.time(19),
                                           num_days=3,
                                           tz="Asia/Tokyo")
        self.calendar.add_child(instance=event)
        event.save_revision().publish()
        panel = HiddenNumDaysPanel()
        panel = panel.bind_to(instance=event,
                              request=self._getRequest(),
                              form=self.form)
        content = panel.render_as_object()
        self.assertHTMLEqual(content, self.FIELD_CONTENT)
Пример #29
0
 def _setUpMainSite(self):
     Site.objects.filter(is_default_site=True).update(hostname="joy.test")
     home = getPage("/home/")
     events = CalendarPage(owner=self.user, slug="events", title="Events")
     home.add_child(instance=events)
     events.save_revision().publish()
     chess = GroupPage(slug="chess-club", title="Chess Club")
     home.add_child(instance=chess)
     chess.save_revision().publish()
     event = RecurringEventPage(owner=self.user,
                                slug="lunchtime-matches",
                                title="Lunchtime Chess Matches",
                                repeat=Recurrence(dtstart=dt.date(
                                    1984, 8, 5),
                                                  freq=WEEKLY,
                                                  byweekday=[MO, WE, FR]),
                                time_from=dt.time(12),
                                time_to=dt.time(13))
     chess.add_child(instance=event)
     event.save_revision().publish()
     cancellation = CancellationPage(
         owner=self.user,
         slug="1984-10-01-cancellation",
         title="Cancellation for Monday 1st of October",
         overrides=event,
         except_date=dt.date(1984, 10, 1),
         cancellation_title="No Chess Club Today")
     event.add_child(instance=cancellation)
     cancellation.save_revision().publish()
     postponement = PostponementPage(
         owner=self.user,
         slug="1984-10-03-postponement",
         title="Postponement for Wednesday 3rd of October",
         overrides=event,
         except_date=dt.date(1984, 10, 3),
         cancellation_title="",
         postponement_title="Early Morning Matches",
         date=dt.date(1984, 10, 4),
         time_from=dt.time(7, 30),
         time_to=dt.time(8, 30))
     event.add_child(instance=postponement)
     postponement.save_revision().publish()
     event = RecurringEventPage(owner=self.user,
                                slug="flea-market",
                                title="Flea Market",
                                repeat=Recurrence(dtstart=dt.date(
                                    1984, 7, 1),
                                                  freq=YEARLY,
                                                  byweekday=[SA(1),
                                                             SA(3)],
                                                  bymonth=range(2, 12)),
                                time_from=dt.time(8),
                                time_to=dt.time(13))
     events.add_child(instance=event)
     event.save_revision().publish()
     event = RecurringEventPage(owner=self.user,
                                slug="drama-practice",
                                title="Drama Group",
                                repeat=Recurrence(dtstart=dt.date(
                                    1984, 8, 14),
                                                  freq=WEEKLY,
                                                  byweekday=[TH],
                                                  interval=2),
                                time_from=dt.time(17))
     events.add_child(instance=event)
     event.save_revision().publish()
     event = SimpleEventPage(owner=self.user,
                             slug="public-lecture3",
                             title="The Human Environment",
                             date=dt.date(1984, 9, 14),
                             time_from=dt.time(19),
                             location="Lecture Hall C")
     events.add_child(instance=event)
     event.save_revision().publish()
Пример #30
0
class TestConcealedPanel(TestCase):
    def setUp(self):
        self.home = getPage("/home/")
        self.user = User.objects.create_superuser('i', '*****@*****.**', 's3(r3t')
        self.calendar = CalendarPage(owner=self.user,
                                     slug="events",
                                     title="Events")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()
        self.event = RecurringEventPage(slug="leaders-meeting",
                                        title="Leaders' Meeting",
                                        repeat=Recurrence(dtstart=dt.date(
                                            2016, 2, 16),
                                                          freq=MONTHLY,
                                                          byweekday=[TU(3)]),
                                        time_from=dt.time(19),
                                        tz="Asia/Tokyo")
        self.calendar.add_child(instance=self.event)
        self.event.save_revision().publish()

    def _getRequest(self):
        request = RequestFactory().get("/test")
        request.user = self.user
        request.session = {}
        request.site = Site.objects.get(is_default_site=True)
        return request

    def testInit(self):
        panel = ConcealedPanel([], "Test", help_text="Nothing")
        self.assertEqual(panel._heading, "Test")
        self.assertEqual(panel._help_text, "Nothing")
        self.assertEqual(panel.heading, "")
        self.assertEqual(panel.help_text, "")

    @skipUnless(WagtailVersion >= (2, 5, 0), "Wagtail <2.5")
    def testConcealed25(self):
        panel = ConcealedPanel([], "Test")
        panel = panel.bind_to(instance=self.event)
        panel = panel.bind_to(request=self._getRequest())
        content = panel.render()
        self.assertEqual(content, "")
        self.assertEqual(panel.heading, "")
        self.assertEqual(panel.help_text, "")

    @skipUnless(WagtailVersion >= (2, 5, 0), "Wagtail <2.5")
    def testShown25(self):
        class ShownPanel(ConcealedPanel):
            def _show(self):
                return True

        panel = ShownPanel([], "Test", help_text="Nothing")
        panel = panel.bind_to(instance=self.event)
        self.assertEqual(panel.heading, "")
        self.assertEqual(panel.help_text, "")
        panel = panel.bind_to(request=self._getRequest())
        content = panel.render()
        self.assertHTMLEqual(
            content, """
<fieldset>
    <legend>Test</legend>
    <ul class="fields">
    </ul>
</fieldset>
""")
        self.assertEqual(panel.heading, "Test")
        self.assertEqual(panel.help_text, "Nothing")