コード例 #1
0
    def post(self, childTitle, childBody, childAuthor, roleToPerms=None):
        """
        Create a new child of this Blurb, with a flavor derived from the
        mapping into FLAVOR.commentFlavors of self.flavor, shared to every role
        specified by FlavorPermission items that refer to the new flavor of
        blurb that will be created, and this blurb or any of my parents.

        For example, if I am a FLAVOR.BLOG, the child will be a
        FLAVOR.BLOG_POST.  If the FlavorPermissions are set up correctly for
        me, one role will be able to view that post, another to comment on it.

        By using FlavorPermissions appropriately, you can have a blog that
        allows public posting, and a blog that allows private posting and no
        public viewing, and a blog that allows public viewing but only
        permissioned posting and commenting, all in the same store.

        @return: A share ID.
        """
        newFlavor = FLAVOR.commentFlavors[self.flavor]
        newBlurb = Blurb(store=self.store,
                         flavor=newFlavor,
                         parent=self,
                         body=childBody,
                         title=childTitle,
                         author=childAuthor,
                         dateCreated=Time(),
                         dateLastEdited=Time(),
                         hits=0)

        if roleToPerms is None:
            roleToPerms = self._getChildPerms(childAuthor)

        return self._setBlurbPermissions(newBlurb, roleToPerms)
コード例 #2
0
ファイル: mimestorage.py プロジェクト: pombredanne/quotient
    def guessSentTime(self, default=None):
        """
        Try to determine the time this message claims to have been sent by
        analyzing various headers.

        @return: a L{Time} instance, or C{None}, if we don't have a guess.
        """

        try:
            sentHeader = self.getHeader(u'date')
        except equotient.NoSuchHeader:
            sentHeader = None
        else:
            try:
                return Time.fromRFC2822(sentHeader)
            except ValueError:
                pass

        for received in list(self.getHeaders(u'received'))[::-1]:
            lines = received.value.splitlines()
            if lines:
                lastLine = lines[-1]
                parts = lastLine.split('; ')
                if parts:
                    date = parts[-1]
                    try:
                        when = rfc822.parsedate(date)
                        if when is None:
                            continue
                    except ValueError:
                        pass
                    else:
                        return Time.fromStructTime(when)

        return default
コード例 #3
0
ファイル: test_scheduler.py プロジェクト: calston/tums
    def testScheduleWithLaterTimedEvents(self):
        """
        Like L{testSchedule}, but use a SubScheduler which has pre-existing
        TimedEvents which are beyond the new runnable's scheduled time (to
        trigger the reschedule-using code-path in
        _SubSchedulerParentHook._schedule).
        """
        now = self.clock.seconds()
        when = Time.fromPOSIXTimestamp(now + 30)
        null = NullRunnable(store=self.substore)
        self.subscheduler.schedule(null, when)
        runnable = self._scheduleRunner(now, 10)

        self.clock.advance(11)

        self.assertEqual(list(self.subscheduler.scheduledTimes(runnable)),
                         [Time.fromPOSIXTimestamp(now + 20)])

        self.assertEqual(list(self.subscheduler.scheduledTimes(null)),
                         [Time.fromPOSIXTimestamp(now + 30)])

        hook = self.store.findUnique(
            _SubSchedulerParentHook,
            _SubSchedulerParentHook.loginAccount == self.substoreItem)

        self.assertEqual(list(self.scheduler.scheduledTimes(hook)),
                         [Time.fromPOSIXTimestamp(20)])
コード例 #4
0
ファイル: test_scheduler.py プロジェクト: calston/tums
 def _scheduleRunner(self, now, offset):
     scheduledAt = Time.fromPOSIXTimestamp(now + offset)
     rescheduleFor = Time.fromPOSIXTimestamp(now + offset + 10)
     runnable = ScheduleCallingItem(store=self.substore,
                                    rescheduleFor=rescheduleFor)
     self.subscheduler.schedule(runnable, scheduledAt)
     return runnable
コード例 #5
0
def main(cursor, forAuthor, start=None, end=None):
    if start is not None:
        start = Time.fromISO8601TimeAndDate(start).asDatetime()
    else:
        start = datetime.now() - timedelta(days=365)
    if end is not None:
        end = Time.fromISO8601TimeAndDate(end).asDatetime()
    else:
        end = datetime.now()

    statement = (
        "select time, ticket, field, oldvalue, newvalue, author "
        "from ticket_change "
        "where field = 'keywords' and (time > %(start)d and time < %(end)d) "
        "order by time asc") % {
            'start': time.mktime(start.utctimetuple()),
            'end': time.mktime(end.utctimetuple())
        }
    cursor.execute(statement)
    for (when, ticket, field, old, new, author) in cursor.fetchall():

        # Check to see if it is by the right author
        if author != forAuthor:
            continue

        if 'review' in old and 'review' not in new:
            print 'Reviewed', ticket, 'on', datetime.fromtimestamp(when)

    raise SystemExit()
コード例 #6
0
def main(cursor, start=None, end=None):
    if start is not None:
        start = Time.fromISO8601TimeAndDate(start).asDatetime()
    else:
        start = datetime.now() - timedelta(days=365)
    if end is not None:
        end = Time.fromISO8601TimeAndDate(end).asDatetime()
    else:
        end = datetime.now()

    reviewers = {}

    statement = (
        "select time, ticket, field, oldvalue, newvalue, author "
        "from ticket_change "
        "where field = 'keywords' and (time > %(start)d and time < %(end)d) "
        "order by time asc") % {
            'start': time.mktime(start.utctimetuple()),
            'end': time.mktime(end.utctimetuple())
        }
    cursor.execute(statement)
    for (when, ticket, field, old, new, author) in cursor.fetchall():
        if 'review' in old and 'review' not in new:
            reviewers[author] = reviewers.get(author, 0) + 1

    return tracstats.Frequencies(
        "Ticket Reviewers", sorted(reviewers.items(), key=lambda (a, b): b))
コード例 #7
0
 def _testSchedule(self, scheduler):
     t1 = TestEvent(store=scheduler.store)
     scheduler.schedule(t1, Time.fromPOSIXTimestamp(0))
     self.failIf(self.calls,
                 "Should not have had any calls: %r" % (self.calls,))
     self.assertIdentical(
         scheduler._getNextEvent(Time.fromPOSIXTimestamp(1)).runnable, t1)
コード例 #8
0
class _ControllerMixin:
    aliceEmail = u'*****@*****.**'
    bobEmail = u'*****@*****.**'
    tzfactor = time.daylight and time.altzone or time.timezone
    sent = Time.fromDatetime(datetime(1999, 12, 13))
    sent2 = Time().oneDay() + timedelta(hours=16, minutes=5, seconds=tzfactor)

    def getInbox(self):
        """
        Return a newly created Inbox, in a newly created Store.
        """
        s = Store()
        LoginMethod(store=s,
                    internal=False,
                    protocol=u'email',
                    localpart=u'default',
                    domain=u'host',
                    verified=True,
                    account=s)

        installOn(Composer(store=s), s)
        installOn(Catalog(store=s), s)
        installOn(MessageLister(store=s), s)
        inbox = Inbox(store=s)
        installOn(inbox, s)
        return inbox

    def widgetFor(self, inbox):
        """
        Create and return an InboxScreen for the given inbox.
        """
        fragment = InboxScreen(inbox)
        fragment.messageDetailFragmentFactory = ActionlessMsgDetailWithStubCompose
        fragment.setFragmentParent(self)
        return fragment
コード例 #9
0
    def testScheduleWithEarlierTimedEvents(self):
        """
        Like L{testSchedule}, but use a SubScheduler which has pre-existing
        TimedEvents which are before the new runnable's scheduled time.
        """
        now = self.clock.seconds()
        when = Time.fromPOSIXTimestamp(now + 15)
        null = NullRunnable(store=self.substore)
        self.subscheduler.schedule(null, when)
        runnable = self._scheduleRunner(now, 10)

        self.clock.advance(11)

        self.assertEqual(
            list(self.subscheduler.scheduledTimes(runnable)),
            [Time.fromPOSIXTimestamp(now + 20)])

        self.assertEqual(
            list(self.subscheduler.scheduledTimes(null)),
            [Time.fromPOSIXTimestamp(now + 15)])

        hook = self.store.findUnique(
            _SubSchedulerParentHook,
            _SubSchedulerParentHook.subStore == self.substoreItem)

        self.assertEqual(
            list(self.scheduler.scheduledTimes(hook)),
            [Time.fromPOSIXTimestamp(now + 15)])
コード例 #10
0
    def guessSentTime(self, default=None):
        """
        Try to determine the time this message claims to have been sent by
        analyzing various headers.

        @return: a L{Time} instance, or C{None}, if we don't have a guess.
        """

        try:
            sentHeader = self.getHeader(u'date')
        except equotient.NoSuchHeader:
            sentHeader = None
        else:
            try:
                return Time.fromRFC2822(sentHeader)
            except ValueError:
                pass

        for received in list(self.getHeaders(u'received'))[::-1]:
            lines = received.value.splitlines()
            if lines:
                lastLine = lines[-1]
                parts = lastLine.split('; ')
                if parts:
                    date = parts[-1]
                    try:
                        when = rfc822.parsedate(date)
                        if when is None:
                            continue
                    except ValueError:
                        pass
                    else:
                        return Time.fromStructTime(when)

        return default
コード例 #11
0
ファイル: test_scheduler.py プロジェクト: calston/tums
    def testScheduledErrorWithHandler(self):
        S = IScheduler(self.store)
        now = Time()
        spec = SpecialErrorHandler(store=self.store)
        S.schedule(spec, now)
        d = Deferred()
        te = TestEvent(store=self.store,
                       testCase=self,
                       name=u't1',
                       maxRunCount=1,
                       runAgain=None,
                       winner=True,
                       deferred=d)
        self.te = te  # don't gc the deferred
        now2 = Time()
        S.schedule(te, now2)
        self.assertEquals(self.store.query(TimedEventFailureLog).count(), 0)

        def later(result):
            errs = log.flushErrors(SpecialError)
            self.assertEquals(len(errs), 1)
            self.assertEquals(
                self.store.query(TimedEventFailureLog).count(), 0)
            self.failUnless(spec.procd)
            self.failIf(spec.broken)

        return d.addCallback(later)
コード例 #12
0
 def test_blurbCreationNoSource(self):
     """
     Test that blurb creation goes OK when there is no
     L{hyperbola.hyperblurb.BlurbSource} installed
     """
     hyperblurb.Blurb(store=self.store,
                      title=u'',
                      body=u'',
                      author=self.me,
                      hits=0,
                      dateCreated=Time(),
                      dateLastEdited=Time(),
                      flavor=hyperblurb.FLAVOR.BLOG)
コード例 #13
0
def makeMessage(receiver, parts, impl):
    """
    Create a new L{exmess.Message}, either by parsing C{parts} or by wrapping
    one around C{impl}.
    """
    if impl is None:
        return receiver.feedStringNow(parts)
    else:
        return testMessageFactory(store=impl.store,
                                  receivedWhen=Time(),
                                  sentWhen=Time(),
                                  spam=False,
                                  subject=u'',
                                  impl=impl)
コード例 #14
0
ファイル: client.py プロジェクト: almet/leastauthority.com
    def _parse_get_bucket(self, xml_bytes):
        root = XML(xml_bytes)
        name = root.findtext("Name")
        prefix = root.findtext("Prefix")
        marker = root.findtext("Marker")
        max_keys = root.findtext("MaxKeys")
        is_truncated = root.findtext("IsTruncated")
        contents = []

        for content_data in root.findall("Contents"):
            key = content_data.findtext("Key")
            date_text = content_data.findtext("LastModified")
            modification_date = Time.fromISO8601TimeAndDate(
                date_text).asDatetime()
            etag = content_data.findtext("ETag")
            size = content_data.findtext("Size")
            storage_class = content_data.findtext("StorageClass")
            owner_id = content_data.findtext("Owner/ID")
            owner_display_name = content_data.findtext("Owner/DisplayName")
            owner = ItemOwner(owner_id, owner_display_name)
            content_item = BucketItem(key, modification_date, etag, size,
                                      storage_class, owner)
            contents.append(content_item)

        common_prefixes = []
        for prefix_data in root.findall("CommonPrefixes"):
            common_prefixes.append(prefix_data.text)

        return BucketListing(name, prefix, marker, max_keys, is_truncated,
                             contents, common_prefixes)
コード例 #15
0
        def _txn():
            svc = s.findOrCreate(
                DataService,
                smtpFrom=unicode(self['smtpFrom']),
                smtpServer=unicode(self['smtpServer']),
            )
            installOn(svc, s)

            ircsvc = s.findOrCreate(ircserver.IRCService,
                                    portNumber=6667,
                                    interface=u'127.0.0.1')
            installOn(ircsvc, s)

            websvc = s.findOrCreate(
                web.WebService,
                portNumber=8080,
            )
            installOn(websvc, s)

            if self['demodata']:
                s.findOrCreate(User,
                               email=u'*****@*****.**',
                               nick=u'MFen',
                               password=u'password')
                s.findOrCreate(Channel,
                               name=u'#vellum',
                               topic=u'Welcome to #vellum',
                               topicAuthor=u'VellumTalk',
                               topicTime=Time())
コード例 #16
0
ファイル: util.py プロジェクト: DalavanCloud/hyperbola
    def _makeBlurb(self, flavor, title=None, body=None):
        """
        Make a minimal nonsense blurb with flavor C{flavor}

        @param flavor: the blurb flavor
        @type flavor: one of the C{unicode} L{hyperbola.hyperblurb.FLAVOR}
        constants

        @param title: the blurb title.  defaults to C{flavor}
        @type title: C{unicode}

        @param body: the blurb body.  defaults to C{flavor}
        @type body: C{unicode}

        @rtype: L{hyperbola.hyperblurb.Blurb}
        """
        if title is None:
            title = flavor
        if body is None:
            body = flavor
        return hyperblurb.Blurb(store=self.userStore,
                                title=title,
                                body=body,
                                flavor=flavor,
                                dateCreated=Time(),
                                author=self.role)
コード例 #17
0
ファイル: paste.py プロジェクト: jonathanj/Codetip
class Paste(Item):
    """
    Paste item.
    """
    created = timestamp(defaultFactory=lambda: Time(),
                        doc=u'Creation timestamp')
    languageHint = text(doc=u'Paste content language hint')
    name = text(allowNone=False, indexed=True, doc=u'Paste name')
    content = text(allowNone=False, doc=u'Paste content')

    def run(self):
        self.deleteFromStore()

    def toJSON(self):
        """
        Describe the L{Paste} item as I{JSON}.
        """
        attrs = dict(self.persistentValues())
        attrs['id'] = attrs['name']
        return json.dumps(attrs, default=jsonSerialize)

    @classmethod
    def findByName(cls, store, name):
        """
        Get a L{Paste} item by name.
        """
        return store.findUnique(Paste, Paste.name == name)
コード例 #18
0
def now(timezoneName):
    """
    Get the current time in the timezone named C{timezoneName}.

    @rtype: C{datetime.datetime}
    """
    return Time().asDatetime(tzinfo=pytz.timezone(timezoneName))
コード例 #19
0
    def createBlog(self, title, description):
        """
        Create a top-level BLOG-flavored Blurb with the given title and
        description, shared for edit with the owner of this store and for
        viewing with everyone, and return it.

        @param title: the blog title
        @type title: C{unicode}

        @param description: the blog description
        @type description: C{unicode}
        """
        store = self.store

        now = Time()
        blog = Blurb(store=self.store,
                     dateCreated=now,
                     dateLastEdited=now,
                     title=title,
                     body=description,
                     flavor=FLAVOR.BLOG,
                     author=sharing.getSelfRole(self.store))

        authorsRole = sharing.getPrimaryRole(store, title + u' blog', True)
        sharing.getSelfRole(store).becomeMemberOf(authorsRole)

        sharing.shareItem(blog, authorsRole, shareID=u'blog')

        everyoneRole = sharing.getEveryoneRole(store)
        sharing.shareItem(blog, everyoneRole, shareID=u'blog',
                          interfaces=[IViewable])

        # this should be configurable
        blog.permitChildren(everyoneRole, FLAVOR.BLOG_POST, IViewable)
コード例 #20
0
ファイル: test_scheduler.py プロジェクト: calston/tums
    def run(self):
        # When this is run from testSubScheduler, we want to make an
        # additional assertion.  There is exactly one SubStore in this
        # configuration, so there should be no more than one
        # TimedEvent with a _SubSchedulerParentHook as its runnable.
        if self.store.parent is not None:
            count = 0
            s = self.store.parent
            for evt in s.query(TimedEvent):
                if isinstance(evt.runnable, _SubSchedulerParentHook):
                    count += 1
            if count > 1:
                return self.fail("Too many TimedEvents for the SubStore",
                                 count)

        self.runCount += 1
        if self.runCount > self.maxRunCount:
            return self.fail("%s ran too many times" % (self.name))
        if self.runAgain is not None:
            result = Time() + timedelta(milliseconds=self.runAgain)
            self.runAgain = None
        else:
            if self.winner and self.deferred is not None:
                self.deferred.callback('done')
            result = None
        return result
コード例 #21
0
    def setUp(self):
        self.clock = Clock()

        self.dbdir = filepath.FilePath(self.mktemp())
        self.store = Store(self.dbdir)
        self.substoreItem = SubStore.createNew(self.store, ['sub'])
        self.substore = self.substoreItem.open()

        self.scheduler = IScheduler(self.store)
        self.subscheduler = IScheduler(self.substore)

        self.scheduler.callLater = self.clock.callLater
        self.scheduler.now = lambda: Time.fromPOSIXTimestamp(self.clock.seconds())
        self.subscheduler.now = lambda: Time.fromPOSIXTimestamp(self.clock.seconds())

        IService(self.store).startService()
コード例 #22
0
ファイル: test_scheduler.py プロジェクト: calston/tums
    def testUnscheduling(self):
        """
        Test the unscheduleFirst method of the scheduler.
        """
        now = Time()
        d = Deferred()
        sch = IScheduler(self.store)
        t1 = TestEvent(testCase=self,
                       name=u't1',
                       store=self.store,
                       maxRunCount=0)
        t2 = TestEvent(testCase=self,
                       name=u't2',
                       store=self.store,
                       maxRunCount=1,
                       runAgain=None,
                       winner=True,
                       deferred=d)

        # Make sure the inmemory attributes hang around
        self.ts = [t1, t2]

        sch.schedule(t1, now + timedelta(milliseconds=100))
        sch.schedule(t2, now + timedelta(milliseconds=200))
        sch.unscheduleFirst(t1)

        return d
コード例 #23
0
ファイル: client.py プロジェクト: zancas/txaws
    def _parse_get_bucket(self, xml_bytes):
        root = XML(xml_bytes)
        name = root.findtext("Name")
        prefix = root.findtext("Prefix")
        marker = root.findtext("Marker")
        max_keys = root.findtext("MaxKeys")
        is_truncated = root.findtext("IsTruncated")
        contents = []

        for content_data in root.findall("Contents"):
            key = content_data.findtext("Key")
            date_text = content_data.findtext("LastModified")
            modification_date = Time.fromISO8601TimeAndDate(
                date_text).asDatetime()
            etag = content_data.findtext("ETag")
            size = content_data.findtext("Size")
            storage_class = content_data.findtext("StorageClass")
            owner_id = content_data.findtext("Owner/ID")
            owner_display_name = content_data.findtext("Owner/DisplayName")
            owner = ItemOwner(owner_id, owner_display_name)
            content_item = BucketItem(key, modification_date, etag, size,
                                      storage_class, owner)
            contents.append(content_item)

        common_prefixes = []
        for prefix_data in root.findall("CommonPrefixes"):
            common_prefixes.append(prefix_data.text)

        return BucketListing(name, prefix, marker, max_keys, is_truncated,
                             contents, common_prefixes)
コード例 #24
0
    def enter_recording(self, currentlyPlaying=None, offset=0):
        """
        User has pressed '1' to start the recording.
        """
        self.app.pingWebSessions()

        start = Time()
        filename = Recording.userRecordingFilename(self.app)
        d = self.agi.recordFile("weareforests-recordings/" + filename, "gsm",
                                chr(self.digit), 45)

        def save(r):
            digit, tpe, duration = r
            duration = duration / 8000
            rec = Recording(store=self.app.store,
                            filename=unicode(filename),
                            created=start,
                            caller_id=self.callerId,
                            duration=duration,
                            user_recording=True)
            print "saved!"
            if tpe == 'hangup':
                print "user hung up during recording."
                self.app.sessionEnded(self.channel)

            # add it to everybody's queue
            self.app.recordingAdded(self, rec)
            # resume play where we stopped
            self.setStateAfterSample("play", "weareforests-audio/listen",
                                     currentlyPlaying, offset)

        d.addCallback(save)
        d.addErrback(self.catchHangup)
コード例 #25
0
    def edit(self, newTitle, newBody, newAuthor, newTags):
        """
        Edit an existing blurb, saving a PastBlurb of its current state for
        rollback purposes.
        """
        # Edit is only called on subsequent edits, not the first time, so we
        # need to save our current contents as history.
        editDate = Time()
        pb = PastBlurb(store=self.store,
                       title=self.title,
                       body=self.body,
                       author=self.author,
                       blurb=self,
                       dateEdited=self.dateLastEdited,
                       hits=self.hits)

        catalog = self.store.findOrCreate(Catalog)
        for tag in self.tags():
            catalog.tag(pb, tag)

        self.title = newTitle
        self.body = newBody
        self.dateLastEdited = editDate
        self.author = newAuthor

        self.store.query(Tag, Tag.object == self).deleteFromStore()
        for tag in newTags:
            catalog.tag(self, tag)
コード例 #26
0
    def _setUpMsg(self):
        """
        Install an innocuous incoming message in a newly-created store

        @rtype: L{xquotient.exmess.Message}
        """
        s = self._setUpStore()

        m = Message.createIncoming(s, _Part(store=s), u'test://test')
        m.subject = u'the subject'
        m.sender = u'sender@host'
        m.senderDisplay = u'Sender'
        m.recipient = u'recipient@host'
        m.sentWhen = Time.fromPOSIXTimestamp(0)
        m.receivedWhen = Time.fromPOSIXTimestamp(1)
        m.classifyClean()
        return m
コード例 #27
0
ファイル: cal.py プロジェクト: rcarmo/divmod.org
 def peerRequestedAppointment(self, whom, when):
     app = Appointment(
         store=self.store, when=Time.fromISO8601TimeAndDate(when),
         withWhomUsername=whom.localpart, withWhomDomain=whom.domain,
         withWhomShareID=whom.shareID, remoteID=whom.shareID)
     role = getPrimaryRole(self.store, u"%s@%s" % (whom.localpart, whom.domain), True)
     appointmentID = role.shareItem(app, interfaces=[IMessageReceiver]).shareID
     return {'appointmentID': appointmentID}
コード例 #28
0
 def makeMessages(self, number, **flags):
     messages = []
     for i in xrange(number):
         m = testMessageFactory(store=self.store,
                                receivedWhen=Time(),
                                **flags)
         messages.append(m)
     return messages
コード例 #29
0
 def makeMessages(n, email):
     return list(reversed(list(
                 testMessageFactory(store=s,
                                    subject=u'Message %d' % (i,),
                                    sender=email,
                                    spam=False,
                                    receivedWhen=Time())
                 for i in xrange(n))))
コード例 #30
0
ファイル: cal.py プロジェクト: jonathanj/mantissa
 def peerRequestedAppointment(self, whom, when):
     app = Appointment(
         store=self.store, when=Time.fromISO8601TimeAndDate(when),
         withWhomUsername=whom.localpart, withWhomDomain=whom.domain,
         withWhomShareID=whom.shareID, remoteID=whom.shareID)
     role = getPrimaryRole(self.store, u"%s@%s" % (whom.localpart, whom.domain), True)
     appointmentID = role.shareItem(app, interfaces=[IMessageReceiver]).shareID
     return {'appointmentID': appointmentID}
コード例 #31
0
ファイル: test_view.py プロジェクト: fusionapp/methanal
    def test_getValue(self):
        """
        L{methanal.view.DateInput.getValue} retrieves an empty string in the
        C{None} case and a string representing the C{Time} specified by
        parameter's value, in the case where a value exists.
        """
        control = self.createControl(dict(timezone=FixedOffset(0, 0)))
        param = control.parent.param

        param.value = None
        self.assertEquals(control.getValue(), u"")

        param.value = Time.fromDatetime(datetime(2007, 1, 1))
        self.assertTrue(isinstance(control.getValue(), unicode))
        self.assertEquals(control.getValue(), u"2007-01-01")

        param.value = Time.fromDatetime(datetime(542, 12, 18))
        self.assertEquals(control.getValue(), u"0542-12-18")
コード例 #32
0
 def cleanRecentlyDisconnected(self):
     now = Time()
     dirty = False
     for callerId, t in self.recentlyDisconnected.items():
         if (now-t).seconds > 300:
             del self.recentlyDisconnected[callerId]
             dirty = True
     if dirty:
         self.pingWebSessions()
コード例 #33
0
    def test_getValue(self):
        """
        L{methanal.view.DateInput.getValue} retrieves an empty string in the
        C{None} case and a string representing the C{Time} specified by
        parameter's value, in the case where a value exists.
        """
        control = self.createControl(dict(timezone=FixedOffset(0, 0)))
        param = control.parent.param

        param.value = None
        self.assertEquals(control.getValue(), u'')

        param.value = Time.fromDatetime(datetime(2007, 1, 1))
        self.assertTrue(isinstance(control.getValue(), unicode))
        self.assertEquals(control.getValue(), u'2007-01-01')

        param.value = Time.fromDatetime(datetime(542, 12, 18))
        self.assertEquals(control.getValue(), u'0542-12-18')
コード例 #34
0
ファイル: agi2.py プロジェクト: weareforests/weareforests
 def lookupNextRecording(self):
     timePoint = Time() - timedelta(minutes=15)
     for r in self.app.store.query(Recording,
                                   Recording.created >= timePoint,
                                   sort=Recording.created.ascending):
         if r.storeID in self.listened:
             continue
         return r
     return random.choice(self.app.getIdleRecordings())
コード例 #35
0
ファイル: test_userbase.py プロジェクト: perkinslr/axiom-py3
 def test_extraction(self):
     """
     Ensure that user store extraction works correctly,
     particularly in the presence of timed events.
     """
     thing = ThingThatMovesAround(store=self.accountStore,
                                  superValue=self.IMPORTANT_VALUE)
     self.ss.schedule(thing, Time() + datetime.timedelta(days=1))
     self.test_noTimedEventsExtraction()
コード例 #36
0
ファイル: test_scheduler.py プロジェクト: ldanielburr/axiom
    def test_now(self):
        """
        The user store's L{IScheduler} powerup's C{now} method returns whatever
        the site store's L{IScheduler} powerup's C{now} method returns.
        """
        # I don't want the stubbed now method.
        del self.scheduler.now

        self.clock.advance(17)
        self.assertEquals(
            self.scheduler.now(),
            Time.fromPOSIXTimestamp(self.clock.seconds()))
コード例 #37
0
ファイル: test_scheduler.py プロジェクト: ldanielburr/axiom
    def testSchedule(self):
        """
        Test the schedule method, as invoked from the run method of an item
        being run by the subscheduler.
        """
        now = self.clock.seconds()
        runnable = self._scheduleRunner(now, 10)

        self.clock.advance(11)

        self.assertEqual(
            list(self.subscheduler.scheduledTimes(runnable)),
            [Time.fromPOSIXTimestamp(now + 20)])

        hook = self.store.findUnique(
            _SubSchedulerParentHook,
            _SubSchedulerParentHook.subStore == self.substoreItem)

        self.assertEqual(
            list(self.scheduler.scheduledTimes(hook)),
            [Time.fromPOSIXTimestamp(now + 20)])
コード例 #38
0
ファイル: client.py プロジェクト: zancas/txaws
 def _parse_list_buckets(self, xml_bytes):
     """
     Parse XML bucket list response.
     """
     root = XML(xml_bytes)
     buckets = []
     for bucket_data in root.find("Buckets"):
         name = bucket_data.findtext("Name")
         date_text = bucket_data.findtext("CreationDate")
         date_time = Time.fromISO8601TimeAndDate(date_text).asDatetime()
         bucket = Bucket(name, date_time)
         buckets.append(bucket)
     return buckets
コード例 #39
0
ファイル: test_view.py プロジェクト: pombredanne/hyperbola
 def test_blurbTimestampColumn(self):
     """
     Verify the L{xmantissa.ixmantissa.IColumn} implementation of
     L{hyperbola_view._BlurbTimestampColumn}.
     """
     col = hyperbola_view._BlurbTimestampColumn()
     self.assertEqual(col.attributeID, 'dateCreated')
     self.assertEqual(col.getType(), 'timestamp')
     self.blogPostItem.dateCreated = Time.fromPOSIXTimestamp(345)
     value = col.extractValue(None, self.blogPostItem)
     self.assertEqual(value, 345)
     self.assertIdentical(col.sortAttribute(), hyperblurb.Blurb.dateCreated)
     comparable = col.toComparableValue(345)
     self.assertEqual(comparable, self.blogPostItem.dateCreated)
コード例 #40
0
    def test_attributes(self):
        """
        Verify all the attributes directly on the Message class are preserved
        by the upgrade function.
        """

        for i, msg in enumerate(self.messageList):
            # The code at the revision which this stub requires randomly
            # mangles the sentWhen of the 3rd and 4th message (because they're
            # drafts), so we can't reasonably test them, except to make sure
            # they're not none.
            if i == 3 or i == 4:
                self.assertNotEqual(msg.sentWhen, None)
            else:
                self.assertEqual(
                    msg.sentWhen,
                    Time.fromRFC2822("Thu, 26 Apr 2001 22:01:%d GMT" % (i,)))

            # Received when is set to the time the stub is generated!  So we
            # can only test for non-Noneness.
            self.assertNotEqual(msg.receivedWhen, None)

            self.assertEqual(msg.sender, u"*****@*****.**")
            self.assertEqual(msg.senderDisplay, u"*****@*****.**")
            self.assertEqual(msg.recipient, u"*****@*****.**")
            self.assertEqual(msg.subject, u"message number %d" % (i,))
            self.assertEqual(msg.attachments, i * 2)
            self.assertEqual(msg.read, i == 2)
            self.assertEqual(msg.everDeferred, i == 1 or i == 2)

            if i == 0 or i == 1 or i == 2 or i == 5:
                _spam = False
            elif i == 3 or i == 4:
                _spam = None
            elif i == 6 or i == 7:
                _spam = True
            self.assertEqual(msg._spam, _spam)

            self.assertEqual(msg.shouldBeClassified, not (i == 3 or i == 4 or i == 7))

            self.assertEqual(msg.impl.getHeader(u"subject"), msg.subject)

            if i == 7:
                frozenWith = SPAM_STATUS
            elif i == 5 or i == 6:
                frozenWith = TRASH_STATUS
            else:
                frozenWith = None

            self.assertEqual(msg._frozenWith, frozenWith)
コード例 #41
0
ファイル: ircserver.py プロジェクト: corydodt/Vellum
 def setMetadata(self, meta):
     """
     Set the topic in the database
     """
     self.channelItem.topic = unicode(meta['topic'])
     self.channelItem.topicAuthor = unicode(meta['topic_author'])
     self.channelItem.topicTime = Time.fromPOSIXTimestamp(meta['topic_date'])
     sets = []
     for p in self.users.itervalues():
         d = defer.maybeDeferred(p.groupMetaUpdate, self, meta)
         d.addErrback(self._ebUserCall, p=p)
         sets.append(d)
     defer.DeferredList(sets).addCallback(self._cbUserCall)
     return defer.succeed(None)
コード例 #42
0
ファイル: test_scheduler.py プロジェクト: ldanielburr/axiom
    def testMultipleEventsPerTick(self):
        """
        Test running several runnables in a single tick of the subscheduler.
        """
        now = self.clock.seconds()
        runnables = [
            self._scheduleRunner(now, 10),
            self._scheduleRunner(now, 11),
            self._scheduleRunner(now, 12)]

        self.clock.advance(13)

        for n, runnable in enumerate(runnables):
            self.assertEqual(
                list(self.subscheduler.scheduledTimes(runnable)),
                [Time.fromPOSIXTimestamp(now + n + 20)])

        hook = self.store.findUnique(
            _SubSchedulerParentHook,
            _SubSchedulerParentHook.subStore == self.substoreItem)

        self.assertEqual(
            list(self.scheduler.scheduledTimes(hook)),
            [Time.fromPOSIXTimestamp(now + 20)])
コード例 #43
0
ファイル: test_inbox.py プロジェクト: pombredanne/quotient
    def _makeMessages(self):
        """
        Make 3 incoming messages

        @rtype: C{list} of L{xquotient.exmess.Message}
        """
        msgs = []
        for (subject, timestamp) in ((u'3', 67), (u'1', 43), (u'2', 55)):
            msgs.append(
                testMessageFactory(
                    store=self.store,
                    read=False,
                    spam=False,
                    subject=subject,
                    receivedWhen=Time.fromPOSIXTimestamp(timestamp)))
        return msgs
コード例 #44
0
ファイル: feedupdates.py プロジェクト: mithrandi/eridanus
    def formatEntry(self, formatting, entry):
        """
        Format an Superfeedr entry element according to the formatting type.
        """
        parts = [
            getattr(entry, elemName, None) or u'<unknown>'
            for elemName in formatting]
        parts = u' -- '.join(map(str, parts))

        try:
            timestamp = Time.fromISO8601TimeAndDate(
                str(entry.published)).asHumanly(tzinfo=const.timezone)
            timestamp = u' (%s)' % (timestamp,)
        except ValueError:
            timestamp = u''

        return u'%s%s' % (parts, timestamp)
コード例 #45
0
ファイル: test_inbox.py プロジェクト: pombredanne/quotient
    def setUp(self):
        """
        Create a handful of messages spread out over a brief time period so
        that tests can assert things about methods which operate on messages.
        """
        self.store = Store()

        inboxItem = Inbox(store=self.store)
        installOn(inboxItem, self.store)
        self.privateApplication = inboxItem.privateApplication
        self.webTranslator = IWebTranslator(self.store)

        baseTime = datetime(year=2001, month=3, day=6)
        self.msgs = []
        for i in xrange(5):
            self.msgs.append(
                testMessageFactory(store=self.store,
                        read=False,
                        spam=False,
                        receivedWhen=Time.fromDatetime(
                            baseTime + timedelta(seconds=i))))

        self.inbox = InboxScreen(inboxItem)
コード例 #46
0
ファイル: scrolltable.py プロジェクト: fusionapp/mantissa
 def fxn():
     for x in xrange(itemCount):
         yield (x * 2,
                u"Number %d" % (x,),
                Time.fromPOSIXTimestamp(now - x),
                colors[x % 2])
コード例 #47
0
ファイル: view.py プロジェクト: jonathanj/methanal
 def invoke(self, data):
     value = data[self.param.name]
     if value is not None:
         value = Time.fromPOSIXTimestamp(value / 1000)
     self.param.value = value
コード例 #48
0
ファイル: test_scheduler.py プロジェクト: ldanielburr/axiom
 def _scheduleRunner(self, now, offset):
     scheduledAt = Time.fromPOSIXTimestamp(now + offset)
     rescheduleFor = Time.fromPOSIXTimestamp(now + offset + 10)
     runnable = ScheduleCallingItem(store=self.substore, rescheduleFor=rescheduleFor)
     self.subscheduler.schedule(runnable, scheduledAt)
     return runnable
コード例 #49
0
ファイル: scrolltable.py プロジェクト: fusionapp/mantissa
 def toComparableValue(self, value):
     """
     Override L{AttributeColumn}'s implementation to return a L{Time} instance.
     """
     return Time.fromPOSIXTimestamp(value)
コード例 #50
0
ファイル: test_scheduler.py プロジェクト: ldanielburr/axiom
 def now(self):
     return Time.fromPOSIXTimestamp(self.clock.seconds())
コード例 #51
0
ファイル: sipserver.py プロジェクト: habnabit/divmod-sine
 def registerAddress(self, physicalURL, expiryTime):
     self.physicalURL = physicalURL.toString()
     self.expiryTime = Time.fromPOSIXTimestamp(time.time() + expiryTime)
     return [(physicalURL, self.expiryTime)]
コード例 #52
0
ファイル: soap.py プロジェクト: mithrandi/eridanus
    @raise ValueError: If no XSI type information could be found

    @rtype: C{unicode}
    @return: The XSI type string
    """
    xsiType = elem.get(XSI + 'type')
    if xsiType is None:
        xsiType = elem.get(XSI2001 + 'type')

    if xsiType is not None:
        return unicode(xsiType, 'ascii')

    raise ValueError(u'"%s" has no XSI type information' % (elem.tag,))


_xsiTypes = {
    u'xsd:string': unicode,
    u'xsd:int': int,
    u'xsd:boolean': lambda t: t.lower() == 'true',
    u'xsd:dateTime': lambda t: Time.fromISO8601TimeAndDate(t),
    }

def getValueFromXSIType(elem, xsiType=None):
    """
    Convert C{elem} to it's Python value based on it's C{xsi:type} attriubte.
    """
    if xsiType is None:
        xsiType = getXSIType(elem)
    return _xsiTypes[xsiType](elem.text)
コード例 #53
0
ファイル: stub_person2to3.py プロジェクト: fusionapp/mantissa
"""
Generate a stub for the tests for the upgrade from schema version 2 to 3 of the
Person item.
"""

from epsilon.extime import Time

from axiom.test.historic.stubloader import saveStub

from xmantissa.people import Organizer, Person

NAME = u"Test User"
CREATED = Time.fromPOSIXTimestamp(1234567890)


def createDatabase(store):
    """
    Make a L{Person} in the given store.
    """
    organizer = Organizer(store=store)
    person = Person(store=store, organizer=organizer, name=NAME)
    person.created = CREATED


if __name__ == "__main__":
    saveStub(createDatabase, 13344)
コード例 #54
0
from epsilon.extime import Time

from xquotient.exmess import Message
from xquotient.mimestorage import Part

attrs = dict(
    sender=u"*****@*****.**",
    subject=u"This is a spam",
    recipient=u"*****@*****.**",
    senderDisplay=u"Spammer",
    spam=True,
    archived=False,
    trash=True,
    outgoing=False,
    draft=False,
    trained=True,
    read=True,
    attachments=23,
    sentWhen=Time.fromPOSIXTimestamp(123),
    receivedWhen=Time.fromPOSIXTimestamp(456),
)


def createDatabase(s):
    Message(store=s, impl=Part(store=s), **attrs)


if __name__ == "__main__":
    saveStub(createDatabase, 7105)
コード例 #55
0
        s = Store()
        err = self.assertRaises(AttributeError,
                                    FunkyItem, store=s, name="foo")
        self.assertEqual(str(err), "'FunkyItem' can't set attribute 'name'")


class WhiteboxComparableTest(TestCase):
    def test_likeRejectsIllegalOperations(self):
        """
        Test that invoking the underlying method which provides the interface
        to the LIKE operator raises a TypeError if it is invoked with too few
        arguments.
        """
        self.assertRaises(TypeError, Comparable()._like, 'XYZ')

someRandomDate = Time.fromISO8601TimeAndDate("1980-05-29")

class DatedThing(Item):
    date = timestamp(default=someRandomDate)

class CreationDatedThing(Item):
    creationDate = timestamp(defaultFactory=lambda : Time())

class StructuredDefaultTestCase(TestCase):
    def testTimestampDefault(self):
        s = Store()
        sid = DatedThing(store=s).storeID
        self.assertEqual(s.getItemByID(sid).date,
                          someRandomDate)

    def testTimestampNow(self):
コード例 #56
0
ファイル: attributes.py プロジェクト: bne/squeal
 def outfilter(self, dbval, oself):
     if dbval is None:
         return None
     return Time.fromPOSIXTimestamp(dbval / MICRO)
コード例 #57
0
ファイル: linkdb.py プロジェクト: mithrandi/eridanus
 def readTimestamp(self):
     return Time.fromPOSIXTimestamp(float(self.readline()))