def test_twoInterfacesTwoGroupsUnsortedQuery(self): """ Verify that when duplicate shares exist for the same item and an asAccessibleTo query is made with no specified sort, the roles are still deduplicated properly. """ us = sharing.getPrimaryRole(self.store, u'us', True) them = sharing.getPrimaryRole(self.store, u'them', True) self.bob.becomeMemberOf(us) self.bob.becomeMemberOf(them) for x in range(3): it = PrivateThing(store=self.store, publicData=x) sharing.shareItem(it, toRole=us, shareID=u'q', interfaces=[IPrivateThing]) sharing.shareItem(it, toRole=them, shareID=u'q', interfaces=[IReadOnly]) # sanity check self.assertEquals(self.store.query(PrivateThing).count(), 3) aat = list(sharing.asAccessibleTo(self.bob, self.store.query( PrivateThing))) # sanity check x2 for acc in aat: acc.mutateSomeState() expectedData = [x + 5 for x in range(3)] aat.sort(key=lambda i: i.retrieveSomeState()) self.assertEquals([acc.retrieveSomeState() for acc in aat], expectedData)
def test_differentUserSameID(self): """ Verify that if different facets of the same item are shared to different users with the same shareID, each user will receive the correct respective facet with only the correct methods exposed. """ t = PrivateThing(store=self.store, publicData=789) toBob = sharing.shareItem(t, toName=u'*****@*****.**', interfaces=[IReadOnly]) toAlice = sharing.shareItem(t, toName=u'*****@*****.**', shareID=toBob.shareID, interfaces=[IPrivateThing]) # Sanity check. self.assertEquals(toBob.shareID, toAlice.shareID) asBob = sharing.getShare(self.store, sharing.getPrimaryRole( self.store, u'*****@*****.**'), toBob.shareID) asAlice = sharing.getShare(self.store, sharing.getPrimaryRole( self.store, u'*****@*****.**'), toBob.shareID) self.assertEquals(asBob.retrieveSomeState(), 789) self.assertRaises(AttributeError, lambda : asBob.mutateSomeState) self.assertRaises(AttributeError, lambda : asAlice.retrieveSomeState) asAlice.mutateSomeState() # Make sure they're both seeing the same item. self.assertEquals(asBob.retrieveSomeState(), 789+5)
def test_twoInterfacesTwoGroupsQuery(self): """ Verify that when an item is shared to two roles that a user is a member of, and then retrieved by an asAccessibleTo query, both interfaces will be accessible on each object in the query result, and the same number of items will be accessible in the query as were shared. """ us = sharing.getPrimaryRole(self.store, u'us', True) them = sharing.getPrimaryRole(self.store, u'them', True) self.bob.becomeMemberOf(us) self.bob.becomeMemberOf(them) for x in range(3): it = PrivateThing(store=self.store, publicData=x) sharing.shareItem(it, toRole=us, shareID=u'q', interfaces=[IPrivateThing]) sharing.shareItem(it, toRole=them, shareID=u'q', interfaces=[IReadOnly]) # sanity check self.assertEquals(self.store.query(PrivateThing).count(), 3) aat = list(sharing.asAccessibleTo(self.bob, self.store.query( PrivateThing, sort=PrivateThing.publicData.descending))) aat2 = list(sharing.asAccessibleTo(self.bob, self.store.query( PrivateThing, sort=PrivateThing.publicData.ascending))) # sanity check x2 for acc in aat: acc.mutateSomeState() expectedData = [x + 5 for x in reversed(range(3))] self.assertEquals([acc.retrieveSomeState() for acc in aat], expectedData) self.assertEquals([acc.retrieveSomeState() for acc in aat2], list(reversed(expectedData)))
def setUp(self): self.i = 0 self.store = Store() self.things = [] self.bobThings = [] self.aliceThings = [] self.bob = sharing.getPrimaryRole(self.store, u'*****@*****.**', createIfNotFound=True) self.alice = sharing.getPrimaryRole(self.store, u'*****@*****.**', createIfNotFound=True)
def roleIn(self, userStore): """ Get the authenticated role for the user represented by this view in the given user store. """ return getPrimaryRole(userStore, self._privateApplication._getUsername())
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)
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}
def test_twoInterfacesTwoGroups(self): """ Verify that when an item is shared to two roles that a user is a member of, they will have access to both interfaces when it is retrieved with getShare. """ self.addSomeThings() us = sharing.getPrimaryRole(self.store, u'us', True) them = sharing.getPrimaryRole(self.store, u'them', True) self.bob.becomeMemberOf(us) self.bob.becomeMemberOf(them) it = PrivateThing(store=self.store, publicData=1234) sharing.shareItem(it, toRole=us, shareID=u'q', interfaces=[IPrivateThing]) sharing.shareItem(it, toRole=them, shareID=u'q', interfaces=[IReadOnly]) that = sharing.getShare(self.store, self.bob, u'q') self.assertEquals(that.retrieveSomeState(), 1234) that.mutateSomeState() self.assertEquals(that.retrieveSomeState(), 1239)
def test_roleInSomebodyElsesStoreDoesKnowMe(self): """ L{_AuthenticatedWebViewer} should return the authenticated role for users with no specific role to map. """ someStore = self.loginSystem.addAccount( u'someguy', u'localhost', u'asdf').avatars.open() role = getPrimaryRole(someStore, u'admin@localhost', True) self.assertIdentical(self.pageFactory.roleIn(someStore), role)
def getRole(self): """ Retrieve the role currently viewing this blurb viewer. """ store = sharing.itemFromProxy(self.original).store if self.customizedFor is None: # If this hasn't been customized, it's public. return sharing.getEveryoneRole(store) else: # Otherwise, get the primary role of the current observer. return sharing.getPrimaryRole(store, self.customizedFor)
def test_invalidShareID(self): """ Verify that NoSuchShare is raised when getShare is called without sharing anything first. """ self.assertRaises(sharing.NoSuchShare, sharing.getShare, self.store, sharing.getPrimaryRole(self.store, u'*****@*****.**'), u"not a valid shareID")
def requestAppointmentWith(self, whom, when): appointment = Appointment( store=self.store, when=when, withWhomShareID=whom.shareID, withWhomUsername=whom.localpart, withWhomDomain=whom.domain) role = getPrimaryRole(self.store, u"%s@%s" % (whom.localpart, whom.domain), True) appointmentID = role.shareItem(appointment, interfaces=[IMessageReceiver]).shareID messenger = AMPMessenger( self.messageQueue, Identifier(appointmentID, *getAccountNames(self.store).next()), whom) messenger.messageRemote( MakeAppointment, appointment, when=when.asISO8601TimeAndDate())
def test_simpleShareMethods(self): """ Verify that an item which is shared with Role.shareItem can be retrieved and manipulated with Role.getShare. This is the new-style API, which isn't yet widely used, but should be preferred in new code. """ t = PrivateThing(store=self.store, publicData=456) bob = sharing.getPrimaryRole(self.store, u'*****@*****.**', createIfNotFound=True) shareItemResult = bob.shareItem(t) gotShare = bob.getShare(shareItemResult.shareID) gotShare.mutateSomeState() self.assertEquals(t.publicData, 456 + 5)
def test_unauthorizedAccessNoShare(self): """ Verify that NoSuchShare is raised when getShare is called with a user who is not allowed to access a shared item. """ t = PrivateThing(store=self.store, publicData=345) theShare = sharing.shareItem(t, toName=u'*****@*****.**') self.assertRaises(sharing.NoSuchShare, sharing.getShare, self.store, sharing.getPrimaryRole(self.store, u'*****@*****.**'), theShare.shareID)
def test_deletedOriginalNoShare(self): """ NoSuchShare should be raised when getShare is called with an item who is not allowed to access a shared item. """ t = PrivateThing(store=self.store, publicData=234) theShare = sharing.shareItem(t, toName=u'*****@*****.**') t.deleteFromStore() self.assertRaises(sharing.NoSuchShare, sharing.getShare, self.store, sharing.getPrimaryRole(self.store, u'*****@*****.**'), theShare.shareID)
def test_getShareProxyWithAdapter(self): """ When you share an item with an interface that has an adapter for that interface, the object that results from getShare should provide the interface by exposing the adapter rather than the original item. """ privateThing = PrivateThing(store=self.store) shared = sharing.shareItem(privateThing, toName=u'testshare', interfaces=[IExternal]) proxy = sharing.getShare(self.store, sharing.getPrimaryRole(self.store, u'testshare'), shared.shareID) proxy.doExternal() self.assertTrue(privateThing.externalized)
def test_shareAndAdapt(self): """ Verify that when an item is shared to a particular user with a particular interface, retrieving it for that user results in methods on the given interface being callable and other methods being restricted. """ t = PrivateThing(store=self.store, publicData=789) # Sanity check. self.failUnless(IPublicThing(t).isMethodAvailable()) shared = sharing.shareItem(t, toName=u'testshare', interfaces=[IReadOnly]) proxy = sharing.getShare(self.store, sharing.getPrimaryRole(self.store, u'testshare'), shared.shareID) self.assertFalse(IPublicThing(proxy).isMethodAvailable()) self.assertRaises(AttributeError, IPublicThing(proxy).callMethod)
def routeMessage(self, sender, target, value, messageID): """ Implement L{IMessageRouter.routeMessage} by locating a shared item which provides L{IMessageReceiver}, identified by L{target} in this L{MessageQueue}'s L{Store}, as shared to the specified C{sender}, then invoke its L{messageReceived} method. Then, take the results of that L{messageReceived} invocation and deliver them as an answer to the object specified by L{sender}. If any of these steps fail such that no L{IMessageReceiver.messageReceived} method may be invoked, generate a L{DELIVERY_ERROR} response instead. """ avatarName = sender.localpart + u"@" + sender.domain # Look for the sender. answer = self.store.findUnique( _AlreadyAnswered, AND(_AlreadyAnswered.originalSender == sender, _AlreadyAnswered.messageID == messageID), default=None) if answer is None: role = getPrimaryRole(self.store, avatarName) try: receiver = role.getShare(target.shareID) except NoSuchShare: response = Value(DELIVERY_ERROR, ERROR_NO_SHARE) else: try: def txn(): output = receiver.messageReceived( value, sender, target) if not isinstance(output, Value): raise TypeError("%r returned non-Value %r" % (receiver, output)) return output response = self.store.transact(txn) except RevertAndRespond, rar: response = rar.value except: log.err(
def test_coalesceInheritedAdapters(self): """ If multiple interfaces that are part of the same inheritance hierarchy are specified, only the leaf interfaces should be adapted to, and provided for all interfaces it inherits from. """ extraPrivateThing = ExtraPrivateThing(store=self.store) role = sharing.getPrimaryRole(self.store, u'testshare') extraProxy = sharing.getShare( self.store, role, sharing.shareItem( extraPrivateThing, toRole=role, interfaces=[IExternal, IExtraExternal]).shareID) externalTag, externalObj = extraProxy.doExternal() extraExternalTag, extraExternalObj = extraProxy.doExternalExtra() self.assertIdentical(externalObj, extraExternalObj) self.assertEquals(externalTag, 'external') self.assertEquals(extraExternalTag, 'external-extra')
def test_simpleShare(self): """ Verify that an item which is shared with shareItem can be retrieved and manipulated with getShare. This is an older-style API, on its way to deprecation. """ t = PrivateThing(store=self.store, publicData=456) shareItemResult = self.assertWarns( PendingDeprecationWarning, "Use Role.shareItem() instead of sharing.shareItem().", __file__, lambda : sharing.shareItem(t, toName=u'*****@*****.**')) bob = sharing.getPrimaryRole(self.store, u'*****@*****.**') gotShare = self.assertWarns( PendingDeprecationWarning, "Use Role.getShare() instead of sharing.getShare().", __file__, lambda : sharing.getShare(self.store, bob, shareItemResult.shareID)) gotShare.mutateSomeState() self.assertEquals(t.publicData, 456 + 5)
def routeMessage(self, sender, target, value, messageID): """ Implement L{IMessageRouter.routeMessage} by locating a shared item which provides L{IMessageReceiver}, identified by L{target} in this L{MessageQueue}'s L{Store}, as shared to the specified C{sender}, then invoke its L{messageReceived} method. Then, take the results of that L{messageReceived} invocation and deliver them as an answer to the object specified by L{sender}. If any of these steps fail such that no L{IMessageReceiver.messageReceived} method may be invoked, generate a L{DELIVERY_ERROR} response instead. """ avatarName = sender.localpart + u"@" + sender.domain # Look for the sender. answer = self.store.findUnique( _AlreadyAnswered, AND(_AlreadyAnswered.originalSender == sender, _AlreadyAnswered.messageID == messageID), default=None) if answer is None: role = getPrimaryRole(self.store, avatarName) try: receiver = role.getShare(target.shareID) except NoSuchShare: response = Value(DELIVERY_ERROR, ERROR_NO_SHARE) else: try: def txn(): output = receiver.messageReceived(value, sender, target) if not isinstance(output, Value): raise TypeError("%r returned non-Value %r" % (receiver, output)) return output response = self.store.transact(txn) except RevertAndRespond, rar: response = rar.value except: log.err(Failure(),
def roleIn(self, userStore): """ Return the primary role for the username passed to me. """ return sharing.getPrimaryRole(userStore, self.username)