Exemplo n.º 1
0
    def _getPath(self, path=None):

        if path is None:
            path = Path()
        path.set('//')

        return path
Exemplo n.º 2
0
    def testImportWithCopy(self):

        def mkdir(parent, name, child):
            if child is not None:
                return child
            return Item(name, parent, None)

        cineguidePack = os.path.join(self.testdir, 'data', 'packs',
                                     'cineguide.pack')

        view = self.rep.view

        nv.loadPack(self.chandlerPack)
        nv.loadPack(cineguidePack)
        nv.findPath('//CineGuide/KHepburn').movies.addIndex('n', 'numeric')
        nv.findPath('//CineGuide/KHepburn').movies.addIndex('t', 'attribute',
                                                            attribute='title')
        self._setCopyExport(nv['Schema'])
        self._unsetCopyExport(nv['Schema']['Core']['items'])

        view.walk(Path('//Schema/CineGuide/Kinds'), mkdir)
        view.walk(Path('//Schema/CineGuide/Attributes'), mkdir)
        view.walk(Path('//Schema/CineGuide/Types'), mkdir)
        view.commit()

        view.importItem(nv.findPath('//CineGuide/KHepburn'))

        self.assert_(view.check())
        self.assert_(nv.check())

        view.commit()

        self._reopenRepository()
        self.assert_(self.rep.view.check())
Exemplo n.º 3
0
    def _getPath(self, path=None):

        if path is None:
            path = Path()
        path.set('//')

        return path
Exemplo n.º 4
0
    def testTask(self):
        """ Simple test for creating instances of tasks """
        def _verifyTask(task):
            self.assert_(task != None)
            self.assertEqual(task.displayName, "test headline")
            self.assertEqual(task.getItemDisplayName(), "test headline")

            self.assertEqual(task.importance, 'important')
            self.assertEqual(task.getAttributeValue('importance'), 'important')
            self.assertEqual(task.about, "test headline")

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

        # Check that the globals got created by the parcel
        view = self.rep.view
        taskPath = Path('//parcels/osaf/pim/tasks')
        self.assert_(Task.getKind(view) != None)
        self.assert_(view.find(Path(taskPath, 'Task')) != None)

        self.assertEqual(Task.getKind(view), view.find(Path(taskPath, 'Task')))

        # Construct A Sample Item
        taskItem = Task("TestTask", view=view)
        taskItem.displayName = "test headline"
        taskItem.importance = "important"

        self._reopenRepository()
        view = self.rep.view

        contentItemParent = view.findPath("//userdata")

        taskItem2 = contentItemParent.getItemChild("TestTask")
        _verifyTask(taskItem2)
Exemplo n.º 5
0
    def dir(self, item=None, path=None):
        """
        Print out a listing of each item in the repository or under item.

        This is a debugging feature.

        @param item: the item to list children of, or C{None}
        @type item: an item
        @param path: the path to the item to list children of, or C{None}
        @type path: a L{Path<repository.util.Path.Path>} instance
        """
        
        if item is None:
            path = Path('//')
            for root in self.iterRoots():
                self.dir(root, path)
        else:
            if path is None:
                path = item.itsPath
            else:
                path.append(item._name or item._uuid)
            print path
            for child in item.iterChildren():
                self.dir(child, path)
            path.pop()
Exemplo n.º 6
0
    def getTypeName(self, attribute, attrs, default):

        name = None

        if attrs.has_key('typeid'):
            try:
                name = self.repository[UUID(attrs['typeid'])].handlerName()
            except KeyError:
                raise TypeError, "Type %s not found" % (attrs['typeid'])

        elif attrs.has_key('typepath'):
            typeItem = self.repository.find(Path(attrs['typepath']))
            if typeItem is None:
                raise TypeError, "Type %s not found" % (attrs['typepath'])
            name = typeItem.handlerName()

        elif attrs.has_key('type'):
            name = attrs['type']

        elif attribute is not None:
            attrType = attribute.getAspect('type', None)
            if attrType is not None:
                name = attrType.handlerName()

        return name or default
Exemplo n.º 7
0
    def _makeValidValues(self):
        """ create valid values of appropriate types"""

        class myStruct(object):
            __slots__ = ('name', 'rank')
            
        self.uuid = self.attrKind.itsUUID
        self.uuidString = str(self.uuid)
        self.pathString = '//Schema/Core/Item'
        self.path = Path(self.pathString)
        self.singleRef = SingleRef(self.uuid)
        self.itemClass = eval('repository.item.Item.Item')
        self.dateTimeString = '2004-01-08 12:34:56 US/Mountain'
        self.dateTime = datetime(2004, 1, 8, 12, 34, 56,
                                 tzinfo=ICUtzinfo.getInstance('US/Mountain'))
        self.timeDeltaString= '-8+45.000012'
        self.timeDelta = timedelta(-8, 45, 12)
        
        self.enum = self.types['Enumeration'].newItem('myEnum', self.rep)
        self.enum.values = ['red', 'green', 'blue']

        self.structType = self.types['Struct'].newItem('myStruct', self.rep)
        self.structType.fields=['name','rank']
        self.structType.implementationTypes = {'python': myStruct }
        self.struct = myStruct()

        self.lob = self.types['Lob'].makeValue("aba;dsjfa;jfdl;ajru87z.vncxyt89q47654", encoding='utf-8', mimetype='text/plain')
Exemplo n.º 8
0
    def itemStart(self, attrs):

        parent = None

        if attrs.get('afterLoadHooks', 'False') == 'True':
            self.hooks.append([])

        if attrs.has_key('path'):
            parent = self.view.find(Path(attrs['path']))
        elif attrs.has_key('uuid'):
            parent = self.view.find(UUID(attrs['uuid']))
        elif attrs.has_key('file'):
            parent = self.loadItem(os.path.join(self.cwd[-1], attrs['file']),
                                   self.parent[-1])
        elif attrs.has_key('files'):
            pattern = '^' + attrs['files'] + '$'
            pattern = pattern.replace('.', '\\.').replace('*', '.*')
            exp = re.compile(pattern)

            for file in os.listdir(self.cwd[-1]):
                if exp.match(file):
                    parent = self.loadItem(os.path.join(self.cwd[-1], file),
                                           self.parent[-1])
                    if self.errorOccurred():
                        return

        self.parent.append(parent)

        if attrs.has_key('cwd'):
            self.cwd.append(os.path.join(self.cwd[-1], attrs['cwd']))
Exemplo n.º 9
0
    def testWalk(self):
        def callme(self, path, x):
            print path
            print x.itsName

        self.rep.walk(Path('//Schema/Core/Parcel'), callme)
        #TODO what's a resonable test here?
        pass
Exemplo n.º 10
0
    def kindEnd(self, itemHandler, attrs):

        if attrs['type'] == 'uuid':
            self.kindRef = UUID(self.data)
        else:
            self.kindRef = Path(self.data)

        self.kind = self.repository._findSchema(self.kindRef, self.withSchema)
Exemplo n.º 11
0
    def __getFeeds(self):
        """Return a list of channel items"""
        repository = self.rep
        chanKind = repository.find(Path(BASE_PATH, 'RSSChannel'))

        feeds = []
        parent = repository.find(BASE_PATH)

        for url in _defaultBlogs:
            urlhash = str(hash(url))
            item = repository.find(Path(BASE_PATH, urlhash))
            if not item:
                item = zaobao.RSSChannel(view=repository.view)
                item.url = url
            feeds.append(item.itsUUID)

        return feeds
Exemplo n.º 12
0
    def testNotes(self):
        """ Simple test for creating instances of note related kinds """

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

        def _verifyNote(note):
            self.assertEqual(note.displayName, "sample note")

            reader = note.body.getReader()
            self.assertEqual(reader.read(), "more elaborate sample note body")
            reader.close()

        # Test the globals
        notesPath = Path('//parcels/osaf/pim')
        view = self.rep.view

        self.assertEqual(pim.Note.getKind(view),
                         view.find(Path(notesPath, 'Note')))

        # Construct sample items
        noteItem = pim.Note("noteItem", view=view)

        # Double check kinds
        self.assertEqual(noteItem.itsKind, pim.Note.getKind(view))

        # Literal properties
        noteItem.displayName = "sample note"

        # Lob property
        lobType = noteItem.getAttributeAspect('body', 'type')

        # when data is unicode, encoding defaults to utf-8
        noteItem.body = lobType.makeValue(u"more elaborate sample note body")

        _verifyNote(noteItem)

        self._reopenRepository()

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

        noteItem = contentItemParent.getItemChild("noteItem")

        _verifyNote(noteItem)
Exemplo n.º 13
0
    def setUp(self):

        super(TestIndexes, self).setUp()

        cineguidePack = os.path.join(self.testdir, 'data', 'packs',
                                     'cineguide.pack')
        self.kh = Path('//CineGuide/KHepburn')
        self.rep.loadPack(cineguidePack)
        self.rep.find(self.kh).movies.addIndex('n', 'numeric')
        self.rep.commit()
Exemplo n.º 14
0
    def parentEnd(self, itemHandler, attrs):

        if attrs['type'] == 'uuid':
            self.parentRef = UUID(self.data)
        else:
            self.parentRef = Path(self.data)

        self.isContainer = attrs.get('container', 'False') == 'True'
        self.parent = self.repository.find(self.parentRef)

        if self.parent is None:
            self.afterLoadHooks.append(self._move)
Exemplo n.º 15
0
    def dir(self, item=None, path=None):
        """
        Print out a listing of each item in the repository or under item.

        This is a debugging feature.

        @param item: the item to list children of, or C{None}
        @type item: an item
        @param path: the path to the item to list children of, or C{None}
        @type path: a L{Path<repository.util.Path.Path>} instance
        """

        if item is None:
            path = Path('//')
            for root in self.iterRoots():
                self.dir(root, path)
        else:
            if path is None:
                path = item.itsPath
            else:
                path.append(item._name or item._uuid)
            print path
            for child in item.iterChildren():
                self.dir(child, path)
            path.pop()
Exemplo n.º 16
0
    def testContacts(self):
        """ Simple test for creating instances of contact related kinds """

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

        def _verifyContactName(name):
            self.assertEqual(name.firstName, 'Sylvia')
            self.assertEqual(name.getAttributeValue('firstName'), 'Sylvia')
            self.assertEqual(name.lastName, 'Plath')
            self.assertEqual(name.getAttributeValue('lastName'), 'Plath')

        # Test the globals
        contactsPath = Path('//parcels/osaf/pim/contacts')
        view = self.rep.view

        self.assertEqual(Contact.getKind(view),
                         view.find(Path(contactsPath, 'Contact')))
        self.assertEqual(ContactName.getKind(view),
                         view.find(Path(contactsPath, 'ContactName')))

        # Construct sample items
        contactItem = Contact("contactItem", view=view)
        contactNameItem = ContactName("contactNameItem", view=view)

        # Double check kinds
        self.assertEqual(contactItem.itsKind, Contact.getKind(view))
        self.assertEqual(contactNameItem.itsKind, ContactName.getKind(view))

        # Literal properties
        contactNameItem.firstName = "Sylvia"
        contactNameItem.lastName = "Plath"

        _verifyContactName(contactNameItem)

        self._reopenRepository()

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

        contactNameItem = contentItemParent.getItemChild("contactNameItem")
        _verifyContactName(contactNameItem)
Exemplo n.º 17
0
        def _find(spec):

            typeAttr = attrs.get('type', 'path')
            if typeAttr == 'path':
                item = self.parent.find(Path(spec))
            elif typeAttr == 'uuid':
                item = self.parent.find(UUID(spec))
            else:
                raise TypeError, typeAttr

            if item is None:
                raise NoSuchItemError, (spec, self.version)

            return item
Exemplo n.º 18
0
    def refEnd(self, itemHandler, attrs):

        if self.tags[-1] == 'item':
            attribute = self.attributes.pop()
            cardinality = self.getCardinality(attribute, attrs)
            otherCard = attrs.get('otherCard', None)

        else:
            cardinality = 'single'
            otherCard = self.tagAttrs[-1].get('otherCard', None)

        if cardinality == 'single':  # cardinality of tag
            typeName = attrs.get('type', 'path')

            if typeName == 'path':
                ref = Path(self.data)
            elif typeName == 'none':
                self.references[attrs['name']] = None
                return
            else:
                ref = UUID(self.data)

            if self.collections:
                refList = self.collections[-1]
                self.refs.append(
                    RefArgs(refList._name,
                            None,
                            refList._otherName,
                            ref,
                            otherCard=otherCard,
                            otherAlias=attrs.get('otherAlias'),
                            previous=self.refName(attrs, 'previous'),
                            next=self.refName(attrs, 'next'),
                            alias=attrs.get('alias')))
            else:
                name = attrs['name']
                otherName = self.getOtherName(name, self.getAttribute(name),
                                              attrs)
                self.refs.append(
                    RefArgs(name,
                            None,
                            otherName,
                            ref,
                            otherCard=otherCard,
                            otherAlias=attrs.get('otherAlias')))
        else:
            value = self.collections.pop()
            self.references[attrs['name']] = value
            if value._indexes:
                self.afterLoadHooks.append(value._restoreIndexes)
Exemplo n.º 19
0
    def testLocations(self):
        """ Simple test for the Locations Factory - getLocation """

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

        # Test the globals
        locationsPath = Path('//parcels/osaf/pim/calendar')
        view = self.rep.view

        self.assertEqual(Calendar.Location.getKind(view),
                         view.find(Path(locationsPath, 'Location')))

        locationNames = ["Alderon", "Atlantis", "Arcadia"]

        # Construct sample items
        for loc in locationNames:
            # use the factory to create or lookup an item
            aRoom = Calendar.Location.getLocation(view, loc)
            # test that convert to string yeilds the name of the location
            self.assertEqual(loc, str(aRoom))

        # call the factory on the last name again, to ensure reuse
        sameLocation = Calendar.Location.getLocation(view, locationNames[-1])
        self.assert_(aRoom is sameLocation,
                     "Location factory failed to return the same location!")

        # Double check kinds
        self.assertEqual(aRoom.itsKind, Calendar.Location.getKind(view))

        # Literal properties
        aRoom.displayName = "A Nice Place"  # change the Location name
        # make sure we can get the name, and find it by that name
        sameLocation = Calendar.Location.getLocation(view, aRoom.displayName)
        self.assert_(
            aRoom is sameLocation,
            "Location factory failed to return an identical location!")
Exemplo n.º 20
0
    def findPath(self, path, load=True):
        """
        Find an item by path.

        See L{find} for more information.

        @param path: a path
        @type path: L{Path<repository.util.Path.Path>} or a path string
        @param load: load the item if it not yet loaded, C{True} by default
        @type load: boolean
        @return: an item or C{None} if not found
        """

        if isinstance(path, str) or isinstance(path, unicode):
            path = Path(path)
        elif not isinstance(path, Path):
            raise TypeError, '%s is not Path or string' % (type(path))

        return self._fwalk(path, load)
Exemplo n.º 21
0
    def packStart(self, attrs):

        if attrs.has_key('cwd'):
            self.cwd[-1] = os.path.join(self.cwd[-1], attrs['cwd'])

        if attrs.has_key('file'):
            if not self.view.find(Path('//', 'Packs', attrs['name'])):
                try:
                    self.view.loadPack(
                        os.path.join(self.cwd[-1], attrs['file']),
                        self.parent[-1])
                except:
                    self.saveException()
                    return

        else:
            self.name = attrs['name']
            self.pack = Item(self.name, self.packs, None)
            self.hooks.append([])
Exemplo n.º 22
0
    def testMail(self):
        """ Simple test for creating instances of email related kinds """

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

        # Test the globals
        mailPath = Path('//parcels/osaf/pim/mail')
        view = self.rep.view

        self.assertEqual(Mail.AccountBase.getKind(view),
                         view.find(Path(mailPath, 'AccountBase')))

        self.assertEqual(Mail.IMAPAccount.getKind(view),
                         view.find(Path(mailPath, 'IMAPAccount')))

        self.assertEqual(Mail.SMTPAccount.getKind(view),
                         view.find(Path(mailPath, 'SMTPAccount')))

        self.assertEqual(Mail.MailDeliveryError.getKind(view),
                         view.find(Path(mailPath, 'MailDeliveryError')))

        self.assertEqual(Mail.MailDeliveryBase.getKind(view),
                         view.find(Path(mailPath, 'MailDeliveryBase')))

        self.assertEqual(Mail.SMTPDelivery.getKind(view),
                         view.find(Path(mailPath, 'SMTPDelivery')))

        self.assertEqual(Mail.IMAPDelivery.getKind(view),
                         view.find(Path(mailPath, 'IMAPDelivery')))

        self.assertEqual(Mail.MIMEBase.getKind(view),
                         view.find(Path(mailPath, 'MIMEBase')))

        self.assertEqual(Mail.MIMENote.getKind(view),
                         view.find(Path(mailPath, 'MIMENote')))

        self.assertEqual(Mail.MailMessage.getKind(view),
                         view.find(Path(mailPath, 'MailMessage')))

        self.assertEqual(Mail.MailMessageMixin.getKind(view),
                         view.find(Path(mailPath, 'MailMessageMixin')))

        self.assertEqual(Mail.MIMEBinary.getKind(view),
                         view.find(Path(mailPath, 'MIMEBinary')))

        self.assertEqual(Mail.MIMEText.getKind(view),
                         view.find(Path(mailPath, 'MIMEText')))

        self.assertEqual(Mail.MIMEContainer.getKind(view),
                         view.find(Path(mailPath, 'MIMEContainer')))

        self.assertEqual(Mail.MIMESecurity.getKind(view),
                         view.find(Path(mailPath, 'MIMESecurity')))

        self.assertEqual(Mail.EmailAddress.getKind(view),
                         view.find(Path(mailPath, 'EmailAddress')))

        # Construct sample items
        accountBaseItem = Mail.AccountBase("accountBaseItem", view=view)
        imapAccountItem = Mail.IMAPAccount("imapAccountItem", view=view)
        smtpAccountItem = Mail.SMTPAccount("smtpAccountItem", view=view)
        mailDeliveryErrorItem = Mail.MailDeliveryError("mailDeliveryErrorItem",
                                                       view=view)
        mailDeliveryBaseItem = Mail.MailDeliveryBase("mailDeliveryBaseItem",
                                                     view=view)
        smtpDeliveryItem = Mail.SMTPDelivery("smtpDeliveryItem", view=view)
        imapDeliveryItem = Mail.IMAPDelivery("imapDeliveryItem", view=view)
        mimeBaseItem = Mail.MIMEBase("mimeBaseItem", view=view)
        mimeNoteItem = Mail.MIMENote("mimeNoteItem", view=view)
        mailMessageItem = Mail.MailMessage("mailMessageItem", view=view)
        mailMessageMixinItem = Mail.MailMessageMixin("mailMessageMixinItem",
                                                     view=view)
        mimeBinaryItem = Mail.MIMEBinary("mimeBinaryItem", view=view)
        mimeTextItem = Mail.MIMEText("mimeTextItem", view=view)
        mimeContainerItem = Mail.MIMEContainer("mimeContainerItem", view=view)
        mimeSecurityItem = Mail.MIMESecurity("mimeSecurityItem", view=view)
        emailAddressItem = Mail.EmailAddress("emailAddressItem", view=view)

        # Double check kinds
        self.assertEqual(accountBaseItem.itsKind,
                         Mail.AccountBase.getKind(view))

        self.assertEqual(imapAccountItem.itsKind,
                         Mail.IMAPAccount.getKind(view))

        self.assertEqual(smtpAccountItem.itsKind,
                         Mail.SMTPAccount.getKind(view))

        self.assertEqual(mailDeliveryErrorItem.itsKind,
                         Mail.MailDeliveryError.getKind(view))

        self.assertEqual(mailDeliveryBaseItem.itsKind,
                         Mail.MailDeliveryBase.getKind(view))

        self.assertEqual(smtpDeliveryItem.itsKind,
                         Mail.SMTPDelivery.getKind(view))

        self.assertEqual(imapDeliveryItem.itsKind,
                         Mail.IMAPDelivery.getKind(view))

        self.assertEqual(mimeBaseItem.itsKind, Mail.MIMEBase.getKind(view))

        self.assertEqual(mimeNoteItem.itsKind, Mail.MIMENote.getKind(view))

        self.assertEqual(mailMessageItem.itsKind,
                         Mail.MailMessage.getKind(view))

        self.assertEqual(mailMessageMixinItem.itsKind,
                         Mail.MailMessageMixin.getKind(view))

        self.assertEqual(mimeBinaryItem.itsKind, Mail.MIMEBinary.getKind(view))

        self.assertEqual(mimeTextItem.itsKind, Mail.MIMEText.getKind(view))

        self.assertEqual(mimeContainerItem.itsKind,
                         Mail.MIMEContainer.getKind(view))

        self.assertEqual(mimeSecurityItem.itsKind,
                         Mail.MIMESecurity.getKind(view))

        self.assertEqual(emailAddressItem.itsKind,
                         Mail.EmailAddress.getKind(view))

        accountBaseItem = self.__populateAccount(accountBaseItem)
        smtpAccountItem = self.__populateAccount(smtpAccountItem)
        imapAccountItem = self.__populateAccount(imapAccountItem)

        mailDeliveryErrorItem.errorCode = 25
        mailDeliveryErrorItem.errorString = "Test String"
        mailDeliveryErrorItem.errorDate = datetime.now()

        smtpDeliveryItem.state = "DRAFT"
        smtpDeliveryItem.deliveryError = mailDeliveryErrorItem
        imapDeliveryItem.uid = 0
        mimeBaseItem.mimeType = "SGML"
        mimeBinaryItem.mimeType = "APPLICATION"
        mimeTextItem.mimeType = "PLAIN"
        mimeContainerItem.mimeType = "ALTERNATIVE"
        mimeSecurityItem.mimeType = "SIGNED"

        # Literal properties
        mailMessageItem.dateSent = datetime.now()
        mailMessageItem.dateReceived = datetime.now()
        mailMessageItem.subject = "Hello"
        mailMessageItem.spamScore = 5

        # Item Properties
        emailAddressItem.emailAddress = "*****@*****.**"
        mailMessageItem.replyAddress = emailAddressItem

        self._reopenRepository()
        view = self.rep.view

        contentItemParent = view.findPath("//userdata")
        mailMessageItem = contentItemParent.getItemChild("mailMessageItem")

        #Test cloud membership

        items = mailMessageItem.getItemCloud('copying')
        self.assertEqual(len(items), 1)
Exemplo n.º 23
0
class TestMerge(RepositoryTestCase):
    """ Test item merging """

    itemPath = Path('//Schema/Core/Item')
    kindPath = Path('//Schema/Core/Kind')
    attributePath = Path('//Schema/Core/Attribute')
    cPath = Path('//kinds/c')
    
    def setUp(self):

        super(TestMerge, self).setUp()

        item = self.rep.find(TestMerge.itemPath)
        kind = self.rep.find(TestMerge.kindPath)
        attribute = self.rep.find(TestMerge.attributePath)

        kinds = item.newItem('kinds', self.rep)
        item.newItem('cm', self.rep)
        item.newItem('co', self.rep)

        p = kind.newItem('p', kinds)
        p.addValue('superKinds', item)
        c = kind.newItem('c', kinds)
        c.addValue('superKinds', item)

        ap = attribute.newItem('ap', p)
        ap.otherName = 'ac'
        ap.cardinality = 'list'
        p.addValue('attributes', ap, alias='ap')

        ac = attribute.newItem('ac', c)
        ac.otherName = 'ap'
        ac.cardinality = 'single'
        c.addValue('attributes', ac, alias='ac')

        p.newItem('p', self.rep)

        self.rep.commit()
        
    def merge(self, o, m):

        pm = self.rep['p']
        km = self.rep.find(TestMerge.cPath)
        am = []

        oc = [c.itsName for c in pm.iterChildren()]
        view = self.rep.createView('view')
        main = self.rep.setCurrentView(view)

        po = self.rep['p']
        ko = self.rep.find(TestMerge.cPath)
        ao = []
        for i in xrange(o):
            ao.append(ko.newItem('ao_%02d' %(i), po))
        view.commit()

        view = self.rep.setCurrentView(main)
        for i in xrange(m):
            am.append(km.newItem('am_%02d' %(i), pm))
        main.commit()

        ic = [c.itsName for c in pm.iterChildren()]
        uc = oc[:]
        uc.extend([c.itsName for c in ao])
        uc.extend([c.itsName for c in am])
        self.assert_(ic == uc)

        c = pm._children

        for i in xrange(o - 1):
            self.assert_(c.nextKey(ao[i].itsUUID) == ao[i + 1].itsUUID)
        for i in xrange(1, o):
            self.assert_(c.previousKey(ao[i].itsUUID) == ao[i - 1].itsUUID)

        self.assert_(c.nextKey(ao[o - 1].itsUUID) == am[0].itsUUID)
        self.assert_(c.previousKey(am[0].itsUUID) == ao[o - 1].itsUUID)

        for i in xrange(m - 1):
            self.assert_(c.nextKey(am[i].itsUUID) == am[i + 1].itsUUID)
        for i in xrange(1, m):
            self.assert_(c.previousKey(am[i].itsUUID) == am[i - 1].itsUUID)

        self.assert_(c.lastKey() == am[m - 1].itsUUID)
 
    def mergeRefs(self, o, m):

        pm = self.rep['p']
        cm = self.rep['cm']
        km = self.rep.find(TestMerge.cPath)
        am = []

        oc = [c.itsName for c in pm.ap]
        
        view = self.rep.createView('view')
        main = self.rep.setCurrentView(view)

        po = self.rep['p']
        co = self.rep['co']
        ko = self.rep.find(TestMerge.cPath)
        ao = []
        for i in xrange(o):
            c = ko.newItem('ao_%02d' %(i), co)
            c.ac = po
            #po.ap.dir()
            ao.append(c)
        view.commit()

        view = self.rep.setCurrentView(main)
        for i in xrange(m):
            c = km.newItem('am_%02d' %(i), cm)
            c.ac = pm
            #pm.ap.dir()
            am.append(c)
        main.commit()

        ic = [c.itsName for c in pm.ap]
        uc = oc[:]
        uc.extend([c.itsName for c in ao])
        uc.extend([c.itsName for c in am])
        self.assert_(ic == uc)

        c = pm.ap

        for i in xrange(o - 1):
            self.assert_(c.nextKey(ao[i].itsUUID) == ao[i + 1].itsUUID)
        for i in xrange(1, o):
            self.assert_(c.previousKey(ao[i].itsUUID) == ao[i - 1].itsUUID)

        self.assert_(c.nextKey(ao[o - 1].itsUUID) == am[0].itsUUID)
        self.assert_(c.previousKey(am[0].itsUUID) == ao[o - 1].itsUUID)

        for i in xrange(m - 1):
            self.assert_(c.nextKey(am[i].itsUUID) == am[i + 1].itsUUID)
        for i in xrange(1, m):
            self.assert_(c.previousKey(am[i].itsUUID) == am[i - 1].itsUUID)

        self.assert_(c.lastKey() == am[m - 1].itsUUID)
 
    def rename(self, o_name, m_name):

        pm = self.rep['p']
        km = self.rep.find(TestMerge.cPath)

        cm = km.newItem('child', pm)
        self.rep.commit()
        
        view = self.rep.createView('view')
        main = self.rep.setCurrentView(view)

        po = self.rep['p']
        co = po['child']
        co.rename(o_name)
        view.commit()

        view = self.rep.setCurrentView(main)
        cm.rename(m_name)
        main.commit()

    def move(self, o_name, m_name):

        pm = self.rep['p']
        km = self.rep.find(TestMerge.cPath)

        cm = km.newItem('child', pm)
        km.newItem(m_name, self.rep)
        if o_name != m_name:
            km.newItem(o_name, self.rep)
            
        self.rep.commit()
        
        view = self.rep.createView('view')
        main = self.rep.setCurrentView(view)

        po = self.rep['p']
        co = po['child']
        co.move(self.rep[o_name])
        view.commit()

        view = self.rep.setCurrentView(main)
        cm.move(self.rep[m_name])
        main.commit()

    def test1Merge1(self):
        self.rep.find(TestMerge.cPath).newItem('c0', self.rep['p'])
        self.rep.commit()
        self.merge(1, 1)

    def test1Merge2(self):
        self.rep.find(TestMerge.cPath).newItem('c0', self.rep['p'])
        self.rep.commit()
        self.merge(2, 2)

    def test1MergeN(self):
        self.rep.find(TestMerge.cPath).newItem('c0', self.rep['p'])
        self.rep.commit()
        self.merge(5, 8)
        self.assert_(self.rep.view.check(), 'view did not check out')

    def test0Merge1(self):
        self.merge(1, 1)

    def test0Merge2(self):
        self.merge(2, 2)

    def test0MergeN(self):
        self.merge(6, 9)

    def testRenameSameSame(self):
        self.rename('foo', 'foo')

    def testRenameSameDifferent(self):
        try:
            self.rename('foo', 'bar')
        except MergeError, e:
            #print e
            self.assert_(e.getReasonCode() == MergeError.RENAME)
Exemplo n.º 24
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)
Exemplo n.º 25
0
    os.path.join(_chandlerDir, 'parcels', 'osaf', 'examples', 'zaobao'))
import feedparser

# get all the RSS files in RSS_HOME (repository/tests/data/rssfeeds)
# You can obtain the files from http://aloha.osafoundation.org/~twl/RSSdata/rssfeeds.syndic8.tar.bz2
RSS_HOME = os.path.join(_chandlerDir, 'repository', 'tests', 'data',
                        'rssfeeds/')
if os.path.exists(RSS_HOME):
    _rssfiles = os.listdir(RSS_HOME)
else:
    _rssfiles = []

# make them file URL's
_defaultBlogs = ["%s%s%s" % ("", RSS_HOME, f) for f in _rssfiles]

BASE_PATH = Path('//parcels/osaf/examples/zaobao/schema')


class TestPerfWithRSS(RepositoryTestCase):
    """ Simple performance tests """
    def setUp(self):

        super(TestPerfWithRSS, self).setUp()

        # sys.path.insert(1, parcelDir)
        self.loadParcel("parcel:osaf.examples.zaobao")

        self.rep.commit()
        self.rep.logger.debug("Going to try: ", len(_defaultBlogs), " feeds")

    def _stressTest(self, commitInsideLoop=False):
Exemplo n.º 26
0
class RepositoryTestCase(TestCase):

    logLevel = logging.WARNING  # a nice quiet default

    def _setup(self, ramdb=True):
        schema.reset()
        self.rootdir = os.environ['CHANDLERHOME']
        self.chandlerPack = os.path.join(self.rootdir, 'repository', 'packs',
                                         'chandler.pack')

        handler = \
         logging.FileHandler(os.path.join(self.rootdir,'chandler.log'))
        formatter = \
         logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
        handler.setFormatter(formatter)
        root = logging.getLogger()
        root.addHandler(handler)

        self.ramdb = ramdb

    def _openRepository(self, ramdb=True):
        preloadedRepositoryPath = os.path.join(self.testdir,
                                               '__preloaded_repository__')
        self.rep = DBRepository(os.path.join(self.testdir, '__repository__'))

        if os.path.exists(preloadedRepositoryPath):
            self.ramdb = False
            self.rep.open(ramdb=False,
                          restore=preloadedRepositoryPath,
                          refcounted=True)
            self.rep.logger.setLevel(self.logLevel)
            self.rep.logger.info('Using preloaded repository')
        else:
            self.rep.create(ramdb=self.ramdb, refcounted=True)
            self.rep.logger.setLevel(self.logLevel)
            self.rep.loadPack(self.chandlerPack)
            self.rep.commit()

        self.manager = \
         ParcelManager.get(self.rep.view, \
         path=[os.path.join(self.rootdir, 'parcels')])

    def setUp(self, ramdb=True):
        self._setup(ramdb)

        self.testdir = os.path.join(self.rootdir, 'repository', 'tests')
        self._openRepository(ramdb)

    def tearDown(self):
        self.rep.close()
        self.rep.logger.debug('RAMDB = %s', self.ramdb)
        if not self.ramdb:
            self.rep.delete()

    def _reopenRepository(self):
        self.rep.commit()

        if self.ramdb:
            self.rep.closeView()
            self.rep.openView()
        else:
            self.rep.close()
            self.rep = DBRepository(
                os.path.join(self.testdir, '__repository__'))
            self.rep.open()

        self.manager = \
         ParcelManager.get(self.rep.view, \
         path=[os.path.join(self.rootdir, 'parcels')])

    def _find(self, path):
        return self.rep.findPath(path)

    def loadParcel(self, namespace):
        self.loadParcels([namespace])

    def loadParcels(self, namespaces=None):

        self.manager.loadParcels(namespaces)
        if namespaces:
            for namespace in namespaces:
                parcelItem = self.manager.lookup(namespace)
                self.assert_(parcelItem)
                # print "Loaded namespace %s as item %s" % \
                # (namespace, parcelItem.itsPath)

    _KIND_KIND = Path("//Schema/Core/Kind")
    _ITEM_KIND = Path("//Schema/Core/Item")

    # Repository specific assertions
    def assertIsRoot(self, item):
        self.assert_(item in list(self.rep.iterRoots()))

    def assertItemPathEqual(self, item, string):
        self.assertEqual(str(item.itsPath), string)