示例#1
0
    def ItemsToVobject(self):
        """Tests itemsToVObject, which converts Chandler items to vobject."""
        event = Calendar.CalendarEvent(view = self.repo.view)
        event.displayName = "test"
        event.startTime = datetime.datetime(2010, 1, 1, 10)
        event.endTime = datetime.datetime(2010, 1, 1, 11)        

        cal = ICalendar.itemsToVObject(self.repo.view, [event])

        self.assert_(cal.vevent[0].summary[0].value == "test",
         "summary not set properly, summary is %s"
         % cal.vevent[0].summary[0].value)

        start = event.startTime.replace(tzinfo=ICalendar.localtime)

        self.assert_(cal.vevent[0].dtstart[0].value == start,
         "dtstart not set properly, dtstart is %s"
         % cal.vevent[0].summary[0].value)

        event = Calendar.CalendarEvent(view = self.repo.view)
        event.displayName = "test2"
        event.startTime = datetime.datetime(2010, 1, 1)
        event.allDay = True        

        cal = ICalendar.itemsToVObject(self.repo.view, [event])

        self.assert_(cal.vevent[0].dtstart[0].value == datetime.date(2010,1,1),
         "dtstart for allDay event not set properly, dtstart is %s"
         % cal.vevent[0].summary[0].value)
示例#2
0
    def testICSSerializer(self):
        """Tests serialization of items to icalendar streams."""
        event = Calendar.CalendarEvent(itsView=self.view)
        event.anyTime = False
        event.summary = uw("test")
        event.startTime = datetime.datetime(2010,
                                            1,
                                            1,
                                            10,
                                            tzinfo=self.view.tzinfo.default)
        event.endTime = datetime.datetime(2010,
                                          1,
                                          1,
                                          11,
                                          tzinfo=self.view.tzinfo.default)

        cal = getVObjectData(self.view, [event.itsItem])

        self.failUnlessEqual(
            cal.vevent.summary.value, uw("test"),
            u"summary not set properly, summary is %s" %
            cal.vevent.summary.value)

        start = event.startTime
        self.assert_(
            cal.vevent.dtstart.value == start,
            "dtstart not set properly, dtstart is %s" %
            cal.vevent.summary.value)

        event = Calendar.CalendarEvent(itsView=self.view)
        event.summary = uw("test2")
        event.startTime = datetime.datetime(2010,
                                            1,
                                            1,
                                            tzinfo=self.view.tzinfo.floating)
        event.allDay = True
        event.duration = datetime.timedelta(1)
        self.assertEqual(event.effectiveEndTime - event.effectiveStartTime,
                         datetime.timedelta(2))
        cal = getVObjectData(self.view, [event.itsItem])

        self.assert_(
            cal.vevent.dtstart.value == datetime.date(2010, 1, 1),
            u"dtstart for allDay event not set properly, dtstart is %s" %
            cal.vevent.summary.value)

        # test bug 9137, multi-day all-day events with
        # duration modulo 1 day == 0 are serialized as 1 day instead of 2
        self.assertEqual(cal.vevent.duration.value, datetime.timedelta(2))
示例#3
0
 def _createEvent(self, startTime):
     event = Calendar.CalendarEvent(None, itsView=self.view)
     event.startTime = startTime
     event.endTime = event.startTime + timedelta(hours=1)
     event.anyTime = False
     event.summary = uw("Sample event")
     return event    
    def testAllDay(self):
        event = Calendar.CalendarEvent(itsParent=self.sandbox,
                                       anyTime=False,
                                       allDay=True)
        self.failUnlessEqual(event.effectiveStartTime.timetz(),
                             self.floatingMidnight)
        self.failUnlessEqual(event.effectiveStartTime.date(),
                             event.startTime.date())
        self.failUnlessEqual(event.effectiveEndTime,
                             event.effectiveStartTime + timedelta(days=1))

        event.anyTime = True
        self.failUnlessEqual(event.effectiveStartTime.timetz(),
                             self.floatingMidnight)
        self.failUnlessEqual(event.effectiveStartTime.date(),
                             event.startTime.date())
        self.failUnlessEqual(event.effectiveEndTime,
                             event.effectiveStartTime + timedelta(days=1))

        event.anyTime = event.allDay = False
        self.failUnlessEqual(event.startTime, event.effectiveStartTime)
        self.failUnlessEqual(event.effectiveStartTime.date(),
                             event.startTime.date())
        self.failUnlessEqual(event.effectiveEndTime,
                             event.effectiveStartTime + event.duration)
    def testDefaultSettings(self):
        defaultTz = TimeZoneInfo.get(self.sandbox.itsView).default
        ROUND = 30

        # A new event, by default, has its startTime set to the current time
        # rounded to a 30-minute boundary
        start = datetime.now(defaultTz)
        event = Calendar.CalendarEvent(itsParent=self.sandbox,
                                       anyTime=False,
                                       allDay=False)
        end = datetime.now(defaultTz)

        # Check that it falls within 30 minutes of now
        self.failUnless(start - timedelta(minutes=ROUND) <= event.startTime
                        and event.startTime <= end + timedelta(minutes=ROUND))

        # Check that the correct rounding occurred
        self.failUnlessEqual(event.startTime.second, 0)
        self.failUnlessEqual(event.startTime.microsecond, 0)
        self.failUnlessEqual(event.startTime.minute % ROUND, 0)

        # Make sure it's in the right timezone
        self.failUnlessEqual(event.startTime.tzinfo, defaultTz)

        # Lastly, check the dates if possible
        if start.date() == end.date():
            self.failUnlessEqual(start.date(), event.startTime.date())

        self.failUnlessEqual(event.effectiveStartTime, event.startTime)
        self.failUnlessEqual(event.effectiveEndTime, event.endTime)
    def testMultidayEdgeCase(self):
        tzinfo = self.sandbox.itsView.tzinfo

        event = Calendar.CalendarEvent(
            itsParent=self.sandbox,
            allDay=True,
            anyTime=False,
            startTime=datetime(2007, 7, 20, tzinfo=tzinfo.floating),
            duration=timedelta(days=0),
        )
        self.failUnlessEqual(event.effectiveStartTime,
                             datetime(2007, 7, 20, tzinfo=tzinfo.floating))
        self.failUnlessEqual(event.effectiveEndTime,
                             datetime(2007, 7, 21, tzinfo=tzinfo.floating))

        event.duration = timedelta(days=1)
        # Really, the following should be 2007/07/21. However, for a while
        # Chandler has treated an all-day event with duration of exactly
        # one day as lasting two days. Jeffrey pointed out that there is
        # import/export code we would need to change in addition to the
        # domain model here. [grant 2007/10/17]
        self.failUnlessEqual(event.effectiveEndTime,
                             datetime(2007, 7, 22, tzinfo=tzinfo.floating))

        event.duration = timedelta(days=2, hours=3)
        self.failUnlessEqual(event.effectiveEndTime,
                             datetime(2007, 7, 23, tzinfo=tzinfo.floating))
    def setUp(self):

        if not hasattr(RecurrenceConflictTestCase, 'view'):
            super(RecurrenceConflictTestCase, self).setUp()
            RecurrenceConflictTestCase.view = self.view
            del self.view

        view = RecurrenceConflictTestCase.view
        self.sandbox = Item("sandbox", view, None)

        self.pacific = self.view.tzinfo.getInstance("America/Los_Angeles")
        self.floating = self.view.tzinfo.floating
        self.utc = self.view.tzinfo.UTC

        self.start = datetime.datetime(2007, 4, 10, 9, tzinfo=self.floating)

        self.master = Calendar.CalendarEvent(None, itsParent=self.sandbox)
        self.uuid = self.master.itsItem.itsUUID.str16()
        self.master.startTime = self.start
        self.master.anyTime = self.master.allDay = False

        # create a baseline dictionary with keywords for creating an EventRecord
        names = (i.name for i in EventRecord.__fields__ if i.name != 'uuid')
        # default values to NoChange
        self.kwds = dict.fromkeys(names, sharing.NoChange)
 def testAtTime(self):
     event = Calendar.CalendarEvent(itsParent=self.sandbox,
                                    anyTime=False,
                                    allDay=False,
                                    duration=timedelta(0))
     self.failUnlessEqual(event.effectiveStartTime, event.startTime)
     self.failUnlessEqual(event.endTime, event.startTime)
     self.failUnlessEqual(event.effectiveEndTime, event.startTime)
示例#9
0
    def testExportRecurrence(self):
        eastern = self.view.tzinfo.getInstance("America/New_York")
        start = datetime.datetime(2005, 2, 1, tzinfo=eastern)
        vevent = vobject.icalendar.RecurringComponent(name='VEVENT')
        vevent.behavior = vobject.icalendar.VEvent

        vevent.add('dtstart').value = start

        ruleSetItem = self._makeRecurrenceRuleSet()
        vevent.rruleset = ruleSetItem.createDateUtilFromRule(start)

        self.assertEqual(vevent.rrule.value, 'FREQ=DAILY')

        event = Calendar.CalendarEvent(itsView=self.view)
        event.anyTime = False
        event.summary = uw("blah")
        event.startTime = start
        event.endTime = datetime.datetime(2005, 2, 1, 1, tzinfo=eastern)

        event.rruleset = self._makeRecurrenceRuleSet(
            datetime.datetime(2005, 3, 1, tzinfo=eastern),
            freq='weekly',
            byweekday=[
                WeekdayAndPositionStruct(i, 0) for i in "tuesday", "thursday"
            ])

        vcalendar = getVObjectData(self.view, [event.itsItem])

        self.assertEqual(vcalendar.vevent.dtstart.serialize(),
                         'DTSTART;TZID=America/New_York:20050201T000000\r\n')
        vcalendar.vevent = vcalendar.vevent.transformFromNative()
        self.assertEqual(
            vcalendar.vevent.rrule.serialize(),
            'RRULE:FREQ=WEEKLY;BYDAY=TU,TH;UNTIL=20050302T045900Z\r\n')

        # move the second occurrence one day later
        nextEvent = event.getFirstOccurrence().getNextOccurrence()
        nextEvent.changeThis(
            pim.EventStamp.startTime.name,
            datetime.datetime(2005, 2, 9, tzinfo=self.view.tzinfo.floating))

        nextEvent.getNextOccurrence().deleteThis()

        vcalendar = getVObjectData(self.view, [event.itsItem, nextEvent])
        for ev in vcalendar.vevent_list:
            if hasattr(ev, 'recurrence_id'):
                modified = ev
            else:
                master = ev
        self.assertEqual(modified.dtstart.serialize(),
                         'DTSTART:20050209T000000\r\n')
        self.assertEqual(
            modified.recurrence_id.serialize(),
            'RECURRENCE-ID;TZID=America/New_York:20050203T000000\r\n')
        self.assertEqual(master.exdate.serialize(),
                         'EXDATE;TZID=America/New_York:20050210T000000\r\n')
        vcalendar.behavior.generateImplicitParameters(vcalendar)
        self.assertEqual(vcalendar.vtimezone.tzid.value, "America/New_York")
示例#10
0
    def testTimeFields(self):
        """ Test time related fields and methods """

        self.loadParcel("parcel:osaf.pim.calendar")

        # Test getDuration
        view = self.rep.view
        firstItem = Calendar.CalendarEvent(view=view)
        firstItem.anyTime = False
        firstItem.startTime = datetime(2003, 2, 1, 10)
        firstItem.endTime = datetime(2003, 2, 1, 11, 30)
        self.assertEqual(firstItem.duration, timedelta(hours=1.5))

        # Test setDuration
        secondItem = Calendar.CalendarEvent(view=view)
        secondItem.anyTime = False
        secondItem.startTime = datetime(2003, 3, 5, 9)
        secondItem.duration = timedelta(hours=1.5)
        self.assertEqual(secondItem.endTime,
                         datetime(2003, 3, 5, 10, 30))

        # Test changeStartTime
        firstItem.ChangeStart(datetime(2003, 3, 4, 12, 45))
        self.assertEqual(firstItem.duration, timedelta(hours=1.5))
        self.assertEqual(firstItem.startTime, datetime(2003, 3, 4, 12, 45))

        # Test reminderTime
        firstItem.SetReminderDelta(timedelta(minutes=-30))
        self.assertEqual(firstItem.reminderTime, datetime(2003, 3, 4, 12, 15))
        firstItem.SetReminderDelta(None)
        self.failIf(firstItem.hasLocalAttributeValue('reminderTime'))

        # Test allDay
        firstItem.allDay = True
        self.assertEqual(firstItem.allDay, True)
        firstItem.allDay = False
        self.assertEqual(firstItem.allDay, False)

        # Test anyTime
        firstItem.anyTime = True
        self.assertEqual(firstItem.anyTime, True)
        firstItem.anyTime = False
        self.assertEqual(firstItem.anyTime, False)
示例#11
0
    def testCreate(self):
        eventCreateDict = {
            'itsView': self.view,
            'summary': u'event creation test',
            Note.icalUID.name: u'abcdef',
            'startTime': datetime.datetime(1996, 11, 11)
        }
        event = Calendar.CalendarEvent(**eventCreateDict)

        self.failUnlessEqual(u'abcdef', event.itsItem.icalUID)
示例#12
0
    def __init__(self, view, type, logger):
        if not type in ["Event", "Note", "Task", "MailMessage", "Collection"]:
            return
        else:
            self.isNote = self.isEvent = self.isTask = self.isMessage = self.allDay = False
            self.logger = logger
            now = datetime.now()
            if type == "Event": # New Calendar Event
                # set up the expected data dictionary with the default values
                self.expected_field_dict = {"displayName" : "New Event", "startTime" : now, "endTime" : now, "duration" : timedelta(minutes=60)}
                # create a default Calendar Event
                item = Calendar.CalendarEvent(view=view)
                item.startTime = self.expected_field_dict["startTime"] # because startTime is needed befor duration
                self.isEvent = True
            elif type == "Note": # New Note
                # set up the expected data dictionary with the default values
                self.expected_field_dict = {"displayName" : "New Note", "createdOn" : now}
                # create a default Note
                item = pim.Note(view=view)
                self.isNote = True
            elif type == "Task": # New Task
                # set up the expected data dictionary with the default values
                self.expected_field_dict = {"displayName" : "New Task", "createdOn" : now}
                # create a default Task
                item = pim.Task(view=view)
                self.isTask = True
            elif type == "MailMessage": # New Mail Message
                # set up the expected data dictionary with the default values
                email = Mail.EmailAddress(view=view)
                email.emailAddress = 'me'
                self.expected_field_dict = {"subject" : "untitled", "dateSent" : now, "fromAddress" : email}
                # create a default Message
                item = Mail.MailMessage(view=view)
                self.isMessage = True
            elif type == "Collection": # New Collection
                # set up the expected data dictionary with the default values
                self.expected_field_dict = {"displayName" : "Untitled"}
                # create a default Collection
                item = pim.ItemCollection(view=view)
                
                
            # fields affectation
            for field in self.expected_field_dict.keys():
                setattr(item, field, self.expected_field_dict[field])

            self.item = item

            if type =="Collection":
                Sgf.SidebarAdd(self.item)
                Sgf.SidebarSelect(self.item)
            else:
                Sgf.SummaryViewSelect(self.item)
示例#13
0
    def testUpdate(self):
        uid = u'on-a-limo-to-milano-solo-gigolos-dont-nod'

        task = pim.Task(itsView=self.view)
        task.itsItem.icalUID = uid

        event = Calendar.CalendarEvent(itsView=self.view,
                                       startTime=datetime.datetime(2000, 1, 1))

        event.itsItem.icalUID = uid
        del task.itsItem.icalUID  # Necessary?

        self.failUnless(event.itsItem is sharing.findUID(self.view, uid))
    def testDeleteItem(self):
        """ Test calendar event deletion """

        view = self.sandbox.itsView
        event = Calendar.CalendarEvent(itsParent=self.sandbox)
        item = event.itsItem
        path = item.itsPath
        item.delete()
        del item
        self.sandbox.itsView.commit()

        itemShouldBeGone = view.find(path)
        self.assertEqual(itemShouldBeGone, None)
    def testDayBoundary(self):
        tzinfo = self.sandbox.itsView.tzinfo

        event = Calendar.CalendarEvent(
            itsParent=self.sandbox,
            allDay=True,
            anyTime=False,
            startTime=datetime(2007, 10, 16, 23, 30, tzinfo=tzinfo.default),
            duration=timedelta(hours=1),
        )
        self.failUnlessEqual(event.effectiveStartTime,
                             datetime(2007, 10, 16, tzinfo=tzinfo.floating))
        self.failUnlessEqual(event.effectiveEndTime,
                             datetime(2007, 10, 17, tzinfo=tzinfo.floating))
示例#16
0
    def testDeleteItem(self):

        """ Test calendar event deletion """

        self.loadParcel("parcel:osaf.pim.calendar")

        view = self.rep.view
        item = Calendar.CalendarEvent(view=view)
        path = item.itsPath
        item.delete()
        del item
        itemShouldBeGone = view.find(path)
        self.assertEqual(itemShouldBeGone, None)
        view.commit()
示例#17
0
def GenerateCalendarEvent(view, days=30, tzinfo=None):
    if tzinfo is None:
        tzinfo = view.tzinfo.floating
    event = Calendar.CalendarEvent(itsView=view)
    event.summary = random.choice(HEADLINES)

    if TEST_I18N:
        event.summary = uw(event.summary)

    # Choose random days, hours
    startDelta = timedelta(days=random.randint(0, days),
                           hours=random.randint(0, 24))

    now = datetime.now(tzinfo)
    closeToNow = datetime(now.year,
                          now.month,
                          now.day,
                          now.hour,
                          int(now.minute / 30) * 30,
                          tzinfo=now.tzinfo)
    event.startTime = closeToNow + startDelta

    # Events are anyTime by default. Give a 5% chance of allDay instead,
    # or 90% of a normal event.
    r = random.randint(0, 100)
    if r < 95:  # 5% chance that we'll leave anyTime on
        event.anyTime = False
    if r < 5:  # 5% chance of allDay
        event.allDay = True

    # Choose random minutes
    event.duration = timedelta(minutes=random.choice(DURATIONS))

    # Maybe a nice reminder?
    reminderInterval = random.choice(REMINDERS)
    if reminderInterval is not None:
        event.userReminderInterval = timedelta(minutes=-reminderInterval)

    # Add a location to 2/3 of the events
    if random.randrange(3) > 0:
        if TEST_I18N:
            event.location = Calendar.Location.getLocation(
                view, uw(random.choice(LOCATIONS)))
        else:
            event.location = Calendar.Location.getLocation(
                view, random.choice(LOCATIONS))

    event.itsItem.importance = random.choice(pim.ImportanceEnum.values)
    event.itsItem.setTriageStatus(randomEnum(pim.TriageEnum))
    return event.itsItem
    def testTimeFields(self):
        """ Test time related fields and methods """

        # Test getting duration, setting endTime
        defaultTz = self.sandbox.itsView.tzinfo.default
        firstEvent = Calendar.CalendarEvent(itsParent=self.sandbox)
        firstEvent.anyTime = False
        firstEvent.startTime = datetime(2003, 2, 1, 10, tzinfo=defaultTz)
        firstEvent.endTime = datetime(2003, 2, 1, 11, 30, tzinfo=defaultTz)
        self.assertEqual(firstEvent.duration, timedelta(hours=1.5))

        # Test setting duration and getting endTime
        secondEvent = Calendar.CalendarEvent(itsParent=self.sandbox)
        secondEvent.anyTime = False
        secondEvent.startTime = datetime(2003, 3, 5, 9, tzinfo=defaultTz)
        secondEvent.duration = timedelta(hours=1.5)
        self.assertEqual(secondEvent.endTime,
                         datetime(2003, 3, 5, 10, 30, tzinfo=defaultTz))

        # Test changing startTime (shouldn't change duration)
        firstEvent.startTime = datetime(2003, 3, 4, 12, 45, tzinfo=defaultTz)
        self.assertEqual(firstEvent.duration, timedelta(hours=1.5))
        self.assertEqual(firstEvent.startTime,
                         datetime(2003, 3, 4, 12, 45, tzinfo=defaultTz))

        # Test allDay
        firstEvent.allDay = True
        self.assertEqual(firstEvent.allDay, True)
        firstEvent.allDay = False
        self.assertEqual(firstEvent.allDay, False)

        # Test anyTime
        firstEvent.anyTime = True
        self.assertEqual(firstEvent.anyTime, True)
        firstEvent.anyTime = False
        self.assertEqual(firstEvent.anyTime, False)
 def testTimed(self):
     event = Calendar.CalendarEvent(
         itsParent=self.sandbox,
         anyTime=False,
         allDay=False,
         startTime=datetime(2006,
                            11,
                            4,
                            13,
                            25,
                            tzinfo=self.sandbox.itsView.tzinfo.default),
         duration=timedelta(hours=1))
     self.failUnlessEqual(event.effectiveStartTime, event.startTime)
     self.failUnlessEqual(event.endTime - timedelta(hours=1),
                          event.startTime)
     self.failUnlessEqual(event.effectiveEndTime, event.endTime)
示例#20
0
    def testFindEventUID(self):
        uid = u'123'

        self.failUnless(sharing.findUID(self.view, uid) is None)

        event = Calendar.CalendarEvent(itsView=self.view,
                                       displayName=u"event test",
                                       startTime=datetime.datetime(
                                           2010, 1, 1, 10),
                                       duration=datetime.timedelta(hours=2))

        self.failUnless(sharing.findUID(self.view, uid) is None)

        item = event.itsItem
        setattr(item, Note.icalUID.name, uid)

        self.failUnless(sharing.findUID(self.view, uid) is item)
示例#21
0
    def setUp(self):
        super(RecurringEventTest, self).setUp()
        self.start = datetime(2005, 7, 4, 13)  #1PM, July 4, 2005

        self.weekly = {
            'end': datetime(2005, 11, 14, 13),
            'start': self.start,
            'count': 20
        }

        self.monthly = {
            'end': datetime(2005, 11, 4, 13),
            'start': self.start,
            'count': 5
        }
        self.event = Calendar.CalendarEvent(None, view=self.rep.view)
        self.event.startTime = self.start
        self.event.endTime = self.event.startTime + timedelta(hours=1)
        self.event.anyTime = False
        self.event.displayName = "Sample event"
    def testCalendarEvent(self):
        from i18n import ChandlerMessageFactory

        event = Calendar.CalendarEvent(itsParent=self.sandbox, )

        # Call InitOutgoingAttributes() on the created event, the
        # hook for item/stamp creation in the Chandler UI.
        item = event.itsItem
        event.InitOutgoingAttributes()

        newEventTitle = ChandlerMessageFactory(u"New Event")

        self.failUnless(stamping.has_stamp(event, Calendar.EventStamp))
        self.failUnlessEqual(item.displayName, newEventTitle)

        newNote = type(item)(itsParent=self.sandbox)
        newNote.InitOutgoingAttributes()  # Should be _(u"Untitled")

        # Make sure the new event title gets reset on unstamp
        event.remove()

        self.failUnlessEqual(item.displayName, newNote.displayName)
示例#23
0
    def _populateCollection(self, repo):
        sandbox = repo.findPath("//sandbox")

        coll = sandbox.findPath("testcollection")

        names = [
            ("Morgen", "Sagen", "*****@*****.**"),
            ("Ted", "Leung", "*****@*****.**"),
            ("Andi", "Vajda", "*****@*****.**"),
        ]

        contacts = []

        for name in names:
            c = Contact(parent=sandbox)
            c.contactName = ContactName(parent=sandbox)
            c.contactName.firstName = name[0]
            c.contactName.lastName = name[1]
            c.emailAddress = name[2]
            c.displayName = "%s %s" % (name[0], name[1])
            contacts.append(c)

        coll.displayName = "test collection"

        events = [
            "breakfast",
            "lunch",
            "dinner",
            "meeting",
            "movie",
            "game",
        ]
        for i in xrange(6):
            c = Calendar.CalendarEvent(parent=sandbox)
            c.displayName = events[i % 6]
            c.organizer = contacts[0]
            c.participants = [contacts[1], contacts[2]]
            c.issues = ["123", "abc", "xyz"]
            coll.add(c)
示例#24
0
def process_create(view, subcommand, text):
    if subcommand == 'note':
        note = pim.Note(itsView=view, displayName=text)
        view.commit()
    elif subcommand == 'event':
        first_space = text.find(' ')
        s = text[:first_space]
        second_space = text.find(' ', first_space + 1)
        l = text[first_space + 1:second_space]
        data = text[second_space + 1:]

        start = parse_datetime(s)
        length = parse_timedelta(l)
        task = Calendar.CalendarEvent(itsView=view,
                                      startTime=start,
                                      duration=length)
        view.commit()
    elif subcommand == 'task':
        task = pim.Task(itsView=view, displayName=text)
        view.commit()
    else:
        print "illegal create subcomand"
示例#25
0
    def writeICalendarUnicodeBug3338(self):
        event = Calendar.CalendarEvent(view = self.repo.view)
        event.displayName = u"unicode \u0633\u0644\u0627\u0645"
        event.startTime = datetime.datetime(2010, 1, 1, 10)
        event.endTime = datetime.datetime(2010, 1, 1, 11)

        coll = ItemCollection(name="testcollection", 
                                             parent=self.sandbox)
        coll.add(event)
        filename = "unicode_export.ics"

        conduit = Sharing.FileSystemConduit(name="conduit", sharePath=".",
                            shareName=filename, view=self.repo.view)
        format = ICalendar.ICalendarFormat(name="format", view=self.repo.view)
        self.share = Sharing.Share(name="share",contents=coll, conduit=conduit,
                                    format=format, view=self.repo.view)
        if self.share.exists():
            self.share.destroy()
        self.share.create()
        self.share.put()
        cal=vobject.readComponents(file(filename, 'rb')).next()
        self.assertEqual(cal.vevent[0].summary[0].value, event.displayName)
        self.share.destroy()
示例#26
0
def GenerateCalendarEvent(view, days=30):
    event = Calendar.CalendarEvent(view=view)
    event.displayName = random.choice(HEADLINES)

    # Choose random days, hours
    startDelta = timedelta(days=random.randint(0, days),
                           hours=random.randint(0, 24))

    now = datetime.now()
    closeToNow = datetime(now.year, now.month, now.day, now.hour,
                          int(now.minute / 30) * 30)
    event.startTime = closeToNow + startDelta

    # Events are anyTime by default. Give a 5% chance of allDay instead,
    # or 90% of a normal event.
    r = random.randint(0, 100)
    if r < 95:  # 5% chance that we'll turn anyTime off
        event.anyTime = False
    if r < 5:  # 5% chance of allDay
        event.allDay = True

    # Choose random minutes
    event.duration = timedelta(minutes=random.choice(DURATIONS))

    # Maybe a nice reminder?
    reminderInterval = random.choice(REMINDERS)
    if reminderInterval is not None:
        event.reminderTime = event.startTime - timedelta(
            minutes=reminderInterval)

    # Add a location to 2/3 of the events
    if random.randrange(3) > 0:
        event.location = Calendar.Location.getLocation(
            view, random.choice(LOCATIONS))

    event.importance = random.choice(IMPORTANCE)
    return event
示例#27
0
    def testWriteICalendarUnicodeBug3338(self):
        event = Calendar.CalendarEvent(itsView=self.view)
        event.summary = u"unicode \u0633\u0644\u0627\u0645"
        event.startTime = datetime.datetime(2010,
                                            1,
                                            1,
                                            10,
                                            tzinfo=self.view.tzinfo.default)
        event.endTime = datetime.datetime(2010,
                                          1,
                                          1,
                                          11,
                                          tzinfo=self.view.tzinfo.default)
        event.rruleset = self._makeRecurrenceRuleSet()

        coll = ListCollection("testcollection", itsParent=self.sandbox)
        coll.displayName = "test"
        coll.add(event.itsItem)
        # the view needs to be committed for event to be seen by sync
        self.view.commit()

        filename = u"unicode_export.ics"

        def delFile():
            try:
                os.remove(filename)
            except OSError:
                pass

        delFile()
        sharing.exportFile(self.view, os.path.join(".", filename), coll)

        cal = vobject.readComponents(file(filename, 'rb')).next()
        self.assertEqual(cal.vevent.summary.value, event.summary)
        # no modifications should be serialized
        self.assertEqual(len(cal.vevent_list), 1)
        delFile()
    def testCalendar(self):
        """ Simple test for creating instances of calendar related kinds """
        def getEventValue(event, attrName):
            try:
                attrName = getattr(type(event), attrName).name
            except AttributeError:
                pass
            return getattr(event.itsItem, attrName)

        def _verifyCalendarEvent(event):
            self.failUnless(stamping.has_stamp(event, Calendar.EventStamp))

            self.assertEqual(event.summary, uw("simple headline"))

            self.assertEqual(event.itsItem.importance, 'fyi')
            self.assertEqual(getEventValue(event, 'importance'), 'fyi')

            self.assertEqual(event.transparency, "confirmed")
            self.assertEqual(getEventValue(event, 'transparency'), "confirmed")

            self.assertEqual(event.allDay, False)
            self.assertEqual(getEventValue(event, 'allDay'), False)

            self.assertEqual(event.anyTime, True)
            self.assertEqual(getEventValue(event, 'anyTime'), True)

        def _verifyCalendarItems(location, recurrence):
            self.assertEqual(location.displayName, uw("simple location"))

        # Check that the globals got created by the parcel
        calendarPath = Path('//parcels/osaf/pim/calendar')
        view = self.sandbox.itsView

        self.assertEqual(schema.itemFor(Calendar.EventStamp, view),
                         view.find(Path(calendarPath, 'EventStamp')))
        self.assertEqual(Calendar.Location.getKind(view),
                         view.find(Path(calendarPath, 'Location')))
        self.assertEqual(Calendar.RecurrencePattern.getKind(view),
                         view.find(Path(calendarPath, 'RecurrencePattern')))

        # Construct a sample item
        calendarEventItem = Calendar.CalendarEvent("calendarEventItem",
                                                   itsParent=self.sandbox)
        locationItem = Calendar.Location("locationItem",
                                         itsParent=self.sandbox)
        recurrenceItem = Calendar.RecurrencePattern("recurrenceItem",
                                                    itsParent=self.sandbox)

        # CalendarEvent properties
        calendarEventItem.summary = uw("simple headline")
        calendarEventItem.itsItem.importance = "fyi"
        _verifyCalendarEvent(calendarEventItem)
        calendarEventItem.location = locationItem

        # Calendar properties
        locationItem.displayName = uw("simple location")
        _verifyCalendarItems(locationItem, recurrenceItem)

        # Check cloud membership - event + location
        items = calendarEventItem.itsItem.getItemCloud('copying')
        self.assertEqual(len(items), 2)

        # Re-examine items
        self.reopenRepository()
        view = self.sandbox.itsView

        calendarEventItem = Calendar.EventStamp(
            self.sandbox.getItemChild("calendarEventItem"))
        locationItem = self.sandbox.getItemChild("locationItem")
        recurrenceItem = self.sandbox.getItemChild("recurrenceItem")

        _verifyCalendarEvent(calendarEventItem)
        _verifyCalendarItems(locationItem, recurrenceItem)
示例#29
0
    def testCalendar(self):

        """ Simple test for creating instances of calendar related kinds """

        self.loadParcel("parcel:osaf.pim.calendar")

        def _verifyCalendarEvent(event):
            self.assertEqual(event.displayName, "simple headline")
            self.assertEqual(event.getItemDisplayName(), "simple headline")

            self.assertEqual(event.importance, 'fyi')
            self.assertEqual(event.getAttributeValue('importance'), 'fyi')

            self.assertEqual(event.transparency, "confirmed")
            self.assertEqual(event.getAttributeValue('transparency'), "confirmed")
            
            self.assertEqual(event.allDay, False)
            self.assertEqual(event.getAttributeValue('allDay'), False)
            
            self.assertEqual(event.anyTime, True)
            self.assertEqual(event.getAttributeValue('anyTime'), True)

        def _verifyCalendarItems(calendar, location, recurrence):
            self.assertEqual(calendar.displayName, "simple calendar")
            self.assertEqual(calendar.getAttributeValue('displayName'),
                              "simple calendar")

            self.assertEqual(location.displayName, "simple location")
            self.assertEqual(location.getAttributeValue('displayName'),
                              "simple location")

        # Check that the globals got created by the parcel
        calendarPath = Path('//parcels/osaf/pim/calendar')
        view = self.rep.view
        
        self.assertEqual(Calendar.CalendarEvent.getKind(view),
                         view.find(Path(calendarPath, 'CalendarEvent')))
        self.assertEqual(Calendar.Calendar.getKind(view),
                         view.find(Path(calendarPath, 'Calendar')))
        self.assertEqual(Calendar.Location.getKind(view),
                         view.find(Path(calendarPath, 'Location')))
        self.assertEqual(Calendar.RecurrencePattern.getKind(view),
                         view.find(Path(calendarPath, 'RecurrencePattern')))

        # Construct a sample item
        calendarEventItem = Calendar.CalendarEvent("calendarEventItem",
                                                   view=view)
        calendarItem = Calendar.Calendar("calendarItem", view=view)
        locationItem = Calendar.Location("locationItem", view=view)
        recurrenceItem = Calendar.RecurrencePattern("recurrenceItem", view=view)

        # CalendarEvent properties
        calendarEventItem.displayName = "simple headline"
        calendarEventItem.importance = "fyi"
        _verifyCalendarEvent(calendarEventItem)
        calendarEventItem.location = locationItem

        # Calendar properties
        calendarItem.displayName = "simple calendar"
        locationItem.displayName = "simple location"
        _verifyCalendarItems(calendarItem, locationItem,
                             recurrenceItem)

        # Check cloud membership - event + location

        items = calendarEventItem.getItemCloud('copying')
        self.assertEqual(len(items), 2)

        # Re-examine items
        self._reopenRepository()

        contentItemParent = self.rep.findPath("//userdata")

        calendarEventItem = contentItemParent.getItemChild("calendarEventItem")
        calendarItem = contentItemParent.getItemChild("calendarItem")
        locationItem = contentItemParent.getItemChild("locationItem")
        recurrenceItem = contentItemParent.getItemChild("recurrenceItem")

        _verifyCalendarEvent(calendarEventItem)
        _verifyCalendarItems(calendarItem, locationItem,
                             recurrenceItem)
    def testStamping(self):
        view = self.sandbox.itsView

        # Get the stamp kinds
        mailStamp = Mail.MailStamp
        taskStamp = pim.TaskStamp
        eventStamp = Calendar.EventStamp
        noteKind = pim.Note.getKind(view)

        # start out with a Note
        aNote = pim.Note("noteItem1", itsParent=self.sandbox)
        self.setAttributes(aNote, doWho=False)
        self.assertAttributes(aNote)
        add = 'add'
        remove = 'remove'

        # stamp everything on and off the note
        self.traverseStampSquence(aNote,
                                  ((add, mailStamp), (add, taskStamp),
                                   (add, eventStamp), (remove, eventStamp),
                                   (remove, taskStamp), (remove, mailStamp)))

        # stamp everything on again, remove in a different order
        self.traverseStampSquence(aNote,
                                  ((add, mailStamp), (add, taskStamp),
                                   (add, eventStamp), (remove, mailStamp),
                                   (remove, taskStamp), (remove, eventStamp)))
        self.assertAttributes(aNote)

        # Create a Task, and do all kinds of stamping on it
        aTask = pim.Task("aTask", itsParent=self.sandbox).itsItem
        self.setAttributes(aTask)

        self.traverseStampSquence(aTask,
                                  ((add, eventStamp), (remove, taskStamp)))
        # now it's an Event

        self.traverseStampSquence(aTask,
                                  ((add, mailStamp), (remove, mailStamp)))

        self.traverseStampSquence(aTask,
                                  ((add, mailStamp), (add, taskStamp),
                                   (remove, mailStamp), (remove, taskStamp)))

        self.traverseStampSquence(aTask,
                                  ((add, taskStamp), (add, mailStamp),
                                   (remove, mailStamp), (remove, taskStamp)))

        self.traverseStampSquence(aTask,
                                  ((add, mailStamp), (remove, eventStamp)))
        # now it's a Mail

        self.traverseStampSquence(aTask,
                                  ((add, taskStamp), (remove, mailStamp)))
        # it's a Task again

        self.traverseStampSquence(aTask,
                                  ((add, mailStamp), (remove, taskStamp)))

        self.traverseStampSquence(aTask,
                                  ((add, taskStamp), (remove, mailStamp)))
        # it's a Task again

        self.traverseStampSquence(aTask,
                                  ((add, eventStamp), (remove, taskStamp),
                                   (add, mailStamp), (remove, eventStamp),
                                   (add, taskStamp), (remove, mailStamp)))
        self.failUnless(has_stamp(aTask, taskStamp))

        # check stamping on an Event
        anEvent = Calendar.CalendarEvent("anEvent",
                                         itsParent=self.sandbox).itsItem
        self.setAttributes(anEvent)

        # round-robin its Kind back to event
        self.traverseStampSquence(anEvent,
                                  ((add, mailStamp), (remove, eventStamp),
                                   (add, taskStamp), (remove, mailStamp),
                                   (add, eventStamp), (remove, taskStamp)))
        self.failUnless(has_stamp(anEvent, eventStamp))

        # check stamping on a Mail Message
        aMessage = Mail.MailMessage("aMessage", itsParent=self.sandbox).itsItem
        self.setAttributes(aMessage)
        self.traverseStampSquence(aMessage,
                                  ((add, eventStamp), (add, taskStamp),
                                   (remove, eventStamp), (remove, taskStamp)))
        self.failUnless(has_stamp(aMessage, mailStamp))

        # now mixin some arbitrary Kind
        #anotherKind = view.findPath('//parcels/osaf/framework/blocks/Block')

        # stamp an event, mail, task with another kind
        #aNote.StampKind(add, anotherKind)
        #aTask.StampKind(add, anotherKind)
        #anEvent.StampKind(add, anotherKind)
        #aMessage.StampKind(add, anotherKind)

        #self.assertKinds(aNote, (noteKind, anotherKind))
        #self.assertKinds(aTask, (taskKind, anotherKind))
        #self.assertKinds(anEvent, (eventKind, anotherKind))
        #self.assertKinds(aMessage, (mailKind, anotherKind))

        # unstamp with another kind
        #aNote.StampKind(remove, anotherKind)
        #aTask.StampKind(remove, anotherKind)
        #anEvent.StampKind(remove, anotherKind)
        #aMessage.StampKind(remove, anotherKind)

        # see that they still have their attributes
        #self.assertKinds(aNote, (noteKind, ))
        #self.assertKinds(aTask, (taskKind, ))
        #self.assertKinds(anEvent, (eventKind, ))
        #self.assertKinds(aMessage, (mailKind, ))

        # Test some failure cases
        # These cases should produce suitable warning messages in Chandler.log
        if testFailureCases:
            anotherEvent = Calendar.CalendarEvent(
                "anotherEvent", itsParent=self.sandbox).itsItem
            self.setAttributes(anotherEvent)
            self.failUnless(has_stamp(anotherEvent, eventStamp))
            # Could use assertRaises here, but it's syntax with respect to parameters is
            #   not clear with my complex arguments, so try/except/else is more readable.
            try:
                # double stamping
                self.traverseStampSquence(anotherEvent,
                                          ((add, mailStamp), (add, mailStamp)))
            except StampAlreadyPresentError:
                pass
            else:
                self.failUnless(False,
                                "Double stamping should raise an exception!")

            try:
                # unstamping something not present
                self.traverseStampSquence(anotherEvent,
                                          ((remove, taskStamp), ))
            except StampNotPresentError:
                pass
            else:
                self.failUnless(
                    False,
                    "Unstamping a stamp not present should raise an exception!"
                )
            # Test for Bug:6151: Make sure items don't disappear
            # from the all collection if they're unstamped
            #
            # Make an email ...
            aMessage = Mail.MailMessage("aNewMessage", itsParent=self.sandbox)
            self.setAttributes(aMessage.itsItem)

            # Make sure it's in "Out"
            aMessage.fromMe = True
            outCollection = schema.ns("osaf.pim", view).outCollection

            self.failUnless(aMessage.itsItem in outCollection)

            # unstamp its emailness
            self.traverseStampSquence(aMessage.itsItem,
                                      (('add', taskStamp),
                                       ('remove', mailStamp)))

            allCollection = schema.ns("osaf.pim", view).allCollection
            self.failUnless(aMessage.itsItem in allCollection)