class IntegrationTestsMixin: """ L{TestCase} mixin defining setup and teardown such that requests can be made against a site strongly resembling an actual one. @type store: L{Store} @ivar store: The site store. @type web: L{WebSite} @ivar web: The site store's web site. @type login: L{LoginSystem} @ivar login: The site store's login system. @ivar site: A protocol factory created by the site store's L{WebSite}. This is probably a L{NevowSite}, but that should be an irrelevant detail. @type domain: C{unicode} @ivar domain: The canonical name of the website and the domain part used when creating users. """ domain = u'example.com' def setUp(self): """ Create a L{Store} with a L{WebSite} in it. Get a protocol factory from the website and save it for tests to use. Patch L{twisted.web.http} and L{nevow.guard} so that they don't create garbage timed calls that have to be cleaned up. """ self.store = Store(filesdir=self.mktemp()) # See #2484 Mantissa().installSite(self.store, self.domain, u'', False) # See #2483 self.site = self.store.findUnique(SiteConfiguration) self.login = self.store.findUnique(LoginSystem) # Ports should be offering installation parameters. This assumes a # TCPPort and an SSLPort are created by Mantissa.installSite. See # #538. -exarkun self.store.query(SSLPort, SSLPort.factory == self.site).deleteFromStore() self.factory = self.site.getFactory() self.origFunctions = (http._logDateTimeStart, GuardSession.checkExpired.im_func, athena.ReliableMessageDelivery) http._logDateTimeStart = lambda: None GuardSession.checkExpired = lambda self: None athena.ReliableMessageDelivery = lambda *a, **kw: None def tearDown(self): """ Restore the patched functions to their original state. """ http._logDateTimeStart = self.origFunctions[0] GuardSession.checkExpired = self.origFunctions[1] athena.ReliableMessageDelivery = self.origFunctions[2] del self.origFunctions
class MantissaSSHCommandTests(TestCase, CommandStubMixin): """ Tests for the C{axiomatic mantissa ssh} command. """ def setUp(self): """ Create a store to use in tests. """ self.filesdir = self.mktemp() self.store = Store(filesdir=self.filesdir) def test_rotate(self): """ The C{keyrotate} subcommand replaces the host key with a new one. """ options = Mantissa() options.parent = self options.installSite(self.store, u'example.com', u'', False) oldKey = self.store.findUnique(SecureShellConfiguration).hostKey options.parseOptions(['ssh', 'keyrotate']) newKey = self.store.findUnique(SecureShellConfiguration).hostKey self.assertNotEqual(oldKey, newKey)
class InstallationTest(TestCase): def setUp(self): self.s = Store() self.product = Product() self.product.types = [ n.decode('ascii') for n in [qual(Foo), qual(Baz)] ] self.product.installProductOn(self.s) self.i = self.s.findUnique(Installation) def test_install(self): """ Ensure that Installation installs instances of the types it is created with. """ self.assertNotEqual(IFoo(self.s, None), None) self.assertNotEqual(IBaz(self.s, None), None) self.assertEqual(list(self.i.items), [self.s.findUnique(t) for t in [Foo, Baz]]) def test_uninstall(self): """ Ensure that Installation properly uninstalls all of the items it controls. """ self.product.removeProductFrom(self.s) self.assertEqual(IFoo(self.s, None), None) self.assertEqual(IBaz(self.s, None), None) self.assertEqual(list(self.s.query(Installation)), [])
class InstallationTest(TestCase): def setUp(self): self.s = Store() self.product = Product() self.product.types = [n.decode('ascii') for n in [qual(Foo), qual(Baz)]] self.product.installProductOn(self.s) self.i = self.s.findUnique(Installation) def test_install(self): """ Ensure that Installation installs instances of the types it is created with. """ self.assertNotEqual(IFoo(self.s, None), None) self.assertNotEqual(IBaz(self.s, None), None) self.assertEqual(list(self.i.items), [self.s.findUnique(t) for t in [Foo, Baz]]) def test_uninstall(self): """ Ensure that Installation properly uninstalls all of the items it controls. """ self.product.removeProductFrom(self.s) self.assertEqual(IFoo(self.s, None), None) self.assertEqual(IBaz(self.s, None), None) self.assertEqual(list(self.s.query(Installation)), [])
class IntegrationTestsMixin: """ L{TestCase} mixin defining setup and teardown such that requests can be made against a site strongly resembling an actual one. @type store: L{Store} @ivar store: The site store. @type web: L{WebSite} @ivar web: The site store's web site. @type login: L{LoginSystem} @ivar login: The site store's login system. @ivar site: A protocol factory created by the site store's L{WebSite}. This is probably a L{NevowSite}, but that should be an irrelevant detail. @type domain: C{unicode} @ivar domain: The canonical name of the website and the domain part used when creating users. """ domain = u"example.com" def setUp(self): """ Create a L{Store} with a L{WebSite} in it. Get a protocol factory from the website and save it for tests to use. Patch L{twisted.web.http} and L{nevow.guard} so that they don't create garbage timed calls that have to be cleaned up. """ self.store = Store(filesdir=self.mktemp()) # See #2484 Mantissa().installSite(self.store, self.domain, u"", False) # See #2483 self.site = self.store.findUnique(SiteConfiguration) self.login = self.store.findUnique(LoginSystem) # Ports should be offering installation parameters. This assumes a # TCPPort and an SSLPort are created by Mantissa.installSite. See # #538. -exarkun self.store.query(SSLPort, SSLPort.factory == self.site).deleteFromStore() self.factory = self.site.getFactory() self.origFunctions = (http._logDateTimeStart, GuardSession.checkExpired.im_func, athena.ReliableMessageDelivery) http._logDateTimeStart = lambda: None GuardSession.checkExpired = lambda self: None athena.ReliableMessageDelivery = lambda *a, **kw: None def tearDown(self): """ Restore the patched functions to their original state. """ http._logDateTimeStart = self.origFunctions[0] GuardSession.checkExpired = self.origFunctions[1] athena.ReliableMessageDelivery = self.origFunctions[2] del self.origFunctions
def setUp(self): """ Create a store as described in the test case docstring. """ site = Store(self.mktemp()) Mantissa().installSite(site, u"example.com", u"", False) Mantissa().installAdmin(site, u"admin", u"example.com", u"asdf") anonsite = site.findUnique(AnonymousSite) user = site.findUnique(LoginSystem).accountByAddress(u"admin", u"example.com").avatars.open() self.website = user.findUnique(WebSite) self.privapp = user.findUnique(PrivateApplication) self.site = site
class SubSchedulerTests(SchedTest, TestCase): """ Tests for the substore implementation of IScheduler. """ def setUp(self): """ Create a site store for the substore which will contain the IScheduler being tested. Start its IService so any scheduled events will run. """ self.storePath = filepath.FilePath(self.mktemp()) self.siteStore = Store(self.storePath) super(SubSchedulerTests, self).setUp() substoreItem = SubStore.createNew(self.siteStore, ['scheduler_test']) self.substore = substoreItem.open() self.scheduler = scheduler = SubScheduler(store=self.substore) self.stubTime(scheduler) installOn(scheduler, self.substore) self.store = self.substore def test_scheduleAfterParentHookError(self): """ A transient error during a L{_SubSchedulerParentHook} run (such as failing to open the substore for whatever reason) should not disable subsequent scheduling. """ runnable = TestEvent(store=self.store) # Schedule runnable, but fail the _SubSchedulerParentHook run. self.scheduler.schedule(runnable, self.now() + timedelta(seconds=1)) hook = self.siteStore.findUnique(_SubSchedulerParentHook) def stumble(): raise IOError('Denied') object.__setattr__(hook, 'run', stumble) self.clock.advance(1) object.__delattr__(hook, 'run') self.assertEquals( self.siteStore.findUnique(TimedEventFailureLog).runnable, hook) [err] = self.flushLoggedErrors(IOError) self.assertEquals(str(err.value), 'Denied') self.assertEquals(runnable.runCount, 0) # Schedule runnable again. The restored hook in the site store should # trigger both scheduled runs in the substore now. self.scheduler.schedule(runnable, self.now() + timedelta(seconds=1)) self.clock.advance(1) self.assertEquals(runnable.runCount, 2)
def setUp(self): """ Create a store as described in the test case docstring. """ site = Store(self.mktemp()) Mantissa().installSite(site, u"example.com", u"", False) Mantissa().installAdmin(site, u'admin', u'example.com', u'asdf') anonsite = site.findUnique(AnonymousSite) user = site.findUnique(LoginSystem).accountByAddress( u"admin", u"example.com").avatars.open() self.website = user.findUnique(WebSite) self.privapp = user.findUnique(PrivateApplication) self.site = site
def test_appStoreLinkTo(self): """ When L{websharing.linkTo} is called on a shared item in an app store, it returns an URL with a single path segment consisting of the app's name. """ s = Store(dbdir=self.mktemp()) Mantissa().installSite(s, u"localhost", u"", False) Mantissa().installAdmin(s, u'admin', u'localhost', u'asdf') off = offering.Offering( name=u'test_offering', description=u'Offering for creating a sample app store', siteRequirements=[], appPowerups=[TestAppPowerup], installablePowerups=[], loginInterfaces=[], themes=[], ) userbase = s.findUnique(LoginSystem) adminAccount = userbase.accountByAddress(u'admin', u'localhost') conf = adminAccount.avatars.open().findUnique( offering.OfferingConfiguration) conf.installOffering(off, None) ss = userbase.accountByAddress(off.name, None).avatars.open() sharedItem = sharing.getEveryoneRole(ss).getShare( websharing.getDefaultShareID(ss)) linkURL = websharing.linkTo(sharedItem) self.failUnless(isinstance(linkURL, url.URL), "linkTo should return a nevow.url.URL, not %r" % (type(linkURL))) self.assertEquals(str(linkURL), '/test_offering/')
class ProductTest(TestCase): def setUp(self): """ Create a pseudo site store and a pseudo user store in it. """ self.siteStore = Store() self.userStore = Store() self.userStore.parent = self.siteStore def test_product(self): self.product = Product(store=self.siteStore) self.product.types = [ n.decode('ascii') for n in [qual(Foo), qual(Baz)] ] self.product.installProductOn(self.userStore) i = self.userStore.findUnique(Installation) self.assertEqual(i.types, self.product.types) def test_createProduct(self): """ Verify that L{ProductConfiguration.createProduct} creates a correctly configured L{Product} and returns it. """ conf = ProductConfiguration(store=self.userStore) product = conf.createProduct([Foo, Baz]) self.assertEqual(product.types, [qual(Foo), qual(Baz)])
class ProductTest(TestCase): def setUp(self): """ Create a pseudo site store and a pseudo user store in it. """ self.siteStore = Store() self.userStore = Store() self.userStore.parent = self.siteStore def test_product(self): self.product = Product(store=self.siteStore) self.product.types = [ n.decode('ascii') for n in [qual(Foo), qual(Baz)]] self.product.installProductOn(self.userStore) i = self.userStore.findUnique(Installation) self.assertEqual(i.types, self.product.types) def test_createProduct(self): """ Verify that L{ProductConfiguration.createProduct} creates a correctly configured L{Product} and returns it. """ conf = ProductConfiguration(store=self.userStore) product = conf.createProduct([Foo, Baz]) self.assertEqual(product.types, [qual(Foo), qual(Baz)])
def test_appStoreLinkTo(self): """ When L{websharing.linkTo} is called on a shared item in an app store, it returns an URL with a single path segment consisting of the app's name. """ s = Store(dbdir=self.mktemp()) Mantissa().installSite(s, u"localhost", u"", False) Mantissa().installAdmin(s, u'admin', u'localhost', u'asdf') off = offering.Offering( name=u'test_offering', description=u'Offering for creating a sample app store', siteRequirements=[], appPowerups=[TestAppPowerup], installablePowerups=[], loginInterfaces=[], themes=[], ) userbase = s.findUnique(LoginSystem) adminAccount = userbase.accountByAddress(u'admin', u'localhost') conf = adminAccount.avatars.open().findUnique( offering.OfferingConfiguration) conf.installOffering(off, None) ss = userbase.accountByAddress(off.name, None).avatars.open() sharedItem = sharing.getEveryoneRole(ss).getShare( websharing.getDefaultShareID(ss)) linkURL = websharing.linkTo(sharedItem) self.failUnless( isinstance(linkURL, url.URL), "linkTo should return a nevow.url.URL, not %r" % (type(linkURL))) self.assertEquals(str(linkURL), '/test_offering/')
def test_buildTerminalProtocol(self): """ L{ImaginaryApp.buildTerminalProtocol} returns a L{CharacterSelectionTextServer} instance with a role representing the store it is in, a reference to the L{ImaginaryWorld} installed on the Imaginary application store, and a list of L{Thing} items shared to the role. """ # XXX This is too many stores for a unit test to need to create. siteStore = Store(filesdir=FilePath(self.mktemp())) Mantissa().installSite(siteStore, u'example.com', u'', False) installOffering(siteStore, imaginaryOffering, {}) login = siteStore.findUnique(LoginSystem) account = login.addAccount(u'alice', u'example.com', u'password') userStore = account.avatars.open() app = ImaginaryApp(store=userStore) installOn(app, userStore) imaginary = login.accountByAddress(u'Imaginary', None).avatars.open() world = imaginary.findUnique(ImaginaryWorld) # Alice connects to her own ImaginaryApp (all that is possible at the # moment). viewer = _AuthenticatedShellViewer(getAccountNames(userStore)) proto = app.buildTerminalProtocol(viewer) self.assertIdentical(proto.world, world) self.assertEqual(proto.role.externalID, u'*****@*****.**') self.assertEqual(proto.choices, [])
def testBadReferenceNoneRevert(self): store = Store() referee = Referee(store=store, topSecret=0) referent = SimpleReferent(store=store, ref=referee) def txn(): referee.deleteFromStore() self.assertEqual(referent.ref, None) 1 / 0 self.assertRaises(ZeroDivisionError, store.transact, txn) self.assertEqual(referent.ref, referee) referent = None referee = None gc.collect() referent = store.findUnique(SimpleReferent) referee = store.findUnique(Referee) self.assertEqual(referent.ref, referee)
class APIKeyTestCase(TestCase): """ Tests for L{APIKey}. """ def setUp(self): """ Make a store. """ self.store = Store() def test_getKeyForAPINone(self): """ If there is no existing key for the named API, L{APIKey.getKeyForAPI} should return C{None}. """ self.assertIdentical( APIKey.getKeyForAPI(self.store, u'this is an API name.'), None) def test_getKeyForAPIExisting(self): """ If there is an existing key for the named API, L{APIKey.getKeyForAPI} should return it. """ theAPIName = u'this is an API name.' existingAPIKey = APIKey(store=self.store, apiName=theAPIName, apiKey=u'this is an API key.') self.assertIdentical(existingAPIKey, APIKey.getKeyForAPI(self.store, theAPIName)) def test_setKeyForAPINew(self): """ If there is no existing key for the named API, L{APIKey.setKeyForAPI} should create a new L{APIKey} item. """ theAPIKey = u'this is an API key.' theAPIName = u'this is an API name.' apiKey = APIKey.setKeyForAPI(self.store, theAPIName, theAPIKey) self.assertIdentical(apiKey, self.store.findUnique(APIKey)) self.assertEqual(theAPIKey, apiKey.apiKey) self.assertEqual(theAPIName, apiKey.apiName) def test_setKeyForAPIExisting(self): """ If there is an existing for the named API, L{APIKey.setKeyForAPI} should update its I{apiKey} attribute. """ theAPIKey = u'this is an API key.' theAPIName = u'this is an API name.' existingAPIKey = APIKey(store=self.store, apiName=theAPIName, apiKey=theAPIKey) newAPIKey = u'this is a new API key' returnedAPIKey = APIKey.setKeyForAPI(self.store, theAPIName, newAPIKey) self.assertIdentical(existingAPIKey, returnedAPIKey) self.assertEqual(existingAPIKey.apiName, theAPIName) self.assertEqual(existingAPIKey.apiKey, newAPIKey)
def test_createsItem(self): """ Verify that L{websharing.addDefaultShareID} creates a L{websharing._DefaultShareID} item. """ store = Store() websharing.addDefaultShareID(store, u'share id', -22) item = store.findUnique(websharing._DefaultShareID) self.assertEqual(item.shareID, u'share id') self.assertEqual(item.priority, -22)
def test_createSession(self): """ L{PersistentSessionWrapper.createSessionForKey} creates a persistent session in the database for the given session ID. """ store = Store() resource = PersistentSessionWrapper(store, None) resource.createSessionForKey(b'key', b'username@domain') session = store.findUnique(PersistentSession) self.assertEqual(session.sessionKey, b'key') self.assertEqual(session.authenticatedAs, b'username@domain')
class ActionsTestCase(TestCase): """ Tests to verify that actions behave as expected. @ivar siteStore: A site store containing an administrative user's account. @ivar siteAccount: The L{axiom.userbase.LoginAccount} for the administrator, in the site store. @ivar siteMethod: The single L{axiom.userbase.LoginMethod} for the administrator, in the site store. @ivar localUserBrowserFragment: A L{LocalUserBrowserFragment} examining the administrator's L{LocalUserBrowser} powerup. """ def setUp(self): """ Construct a site and user store with an administrator that can invoke the web administrative tools, setting the instance variables described in this class's docstring. """ self.siteStore = Store(filesdir=self.mktemp()) Mantissa().installSite(self.siteStore, u"localhost", u"", False) Mantissa().installAdmin(self.siteStore, u'admin', u'localhost', u'asdf') self.siteMethod = self.siteStore.findUnique( LoginMethod, LoginMethod.localpart == u'admin') self.siteAccount = self.siteMethod.account userStore = self.siteAccount.avatars.open() lub = userStore.findUnique(LocalUserBrowser) self.localUserBrowserFragment = LocalUserBrowserFragment(lub) def test_actionTypes(self): """ Verify that all the action methods expose the appropriate fragment objects, with their attributes set to indicate the correct objects to manipulate. """ myRowID = self.localUserBrowserFragment.linkToItem(self.siteMethod) actionMap = [('installOn', EndowFragment), ('uninstallFrom', DepriveFragment), ('suspend', SuspendFragment), ('unsuspend', UnsuspendFragment)] for action, fragmentType in actionMap: resultFragment = self.localUserBrowserFragment.performAction( action, myRowID) self.failUnless(isinstance(resultFragment, fragmentType), "%s does not return a %s" % (action, fragmentType)) self.assertEquals(resultFragment.fragmentParent, self.localUserBrowserFragment) self.assertEquals(resultFragment.account, self.siteAccount)
class _UserIdentificationMixin: def setUp(self): self.siteStore = Store(filesdir=self.mktemp()) Mantissa().installSite(self.siteStore, u"localhost", u"", False) Mantissa().installAdmin(self.siteStore, u'admin', u'localhost', '') self.loginSystem = self.siteStore.findUnique(LoginSystem) self.adminStore = self.loginSystem.accountByAddress( u'admin', u'localhost').avatars.open() sc = self.adminStore.findUnique(signup.SignupConfiguration) self.signup = sc.createSignup( u'testuser@localhost', signup.UserInfoSignup, {'prefixURL': u''}, product.Product(store=self.siteStore, types=[]), u'', u'')
class ActionsTestCase(TestCase): """ Tests to verify that actions behave as expected. @ivar siteStore: A site store containing an administrative user's account. @ivar siteAccount: The L{axiom.userbase.LoginAccount} for the administrator, in the site store. @ivar siteMethod: The single L{axiom.userbase.LoginMethod} for the administrator, in the site store. @ivar localUserBrowserFragment: A L{LocalUserBrowserFragment} examining the administrator's L{LocalUserBrowser} powerup. """ def setUp(self): """ Construct a site and user store with an administrator that can invoke the web administrative tools, setting the instance variables described in this class's docstring. """ self.siteStore = Store(filesdir=self.mktemp()) Mantissa().installSite(self.siteStore, u"localhost", u"", False) Mantissa().installAdmin(self.siteStore, u"admin", u"localhost", u"asdf") self.siteMethod = self.siteStore.findUnique(LoginMethod, LoginMethod.localpart == u"admin") self.siteAccount = self.siteMethod.account userStore = self.siteAccount.avatars.open() lub = userStore.findUnique(LocalUserBrowser) self.localUserBrowserFragment = LocalUserBrowserFragment(lub) def test_actionTypes(self): """ Verify that all the action methods expose the appropriate fragment objects, with their attributes set to indicate the correct objects to manipulate. """ myRowID = self.localUserBrowserFragment.linkToItem(self.siteMethod) actionMap = [ ("installOn", EndowFragment), ("uninstallFrom", DepriveFragment), ("suspend", SuspendFragment), ("unsuspend", UnsuspendFragment), ] for action, fragmentType in actionMap: resultFragment = self.localUserBrowserFragment.performAction(action, myRowID) self.failUnless( isinstance(resultFragment, fragmentType), "%s does not return a %s" % (action, fragmentType) ) self.assertEquals(resultFragment.fragmentParent, self.localUserBrowserFragment) self.assertEquals(resultFragment.account, self.siteAccount)
def setUp(self): """ Set up a fake objects and methods for the password reset tests. """ siteStore = Store(filesdir=self.mktemp()) Mantissa().installSite(siteStore, u"divmod.com", u"", False) self.loginSystem = siteStore.findUnique(userbase.LoginSystem) self.site = siteStore.findUnique(SiteConfiguration) la = self.loginSystem.addAccount( u'joe', u'divmod.com', u'secret', internal=True) la.addLoginMethod( u'joe', u'external.com', protocol=u'zombie dance', verified=False, internal=False) # create an account with no external mail address account = self.loginSystem.addAccount( u'jill', u'divmod.com', u'secret', internal=True) account.addLoginMethod( u'jill', u'divmod.com', protocol=u'zombie dance', verified=True, internal=True) self.siteStore = siteStore # Set up the user store to have all the elements necessary to redirect # in the case where the user is already logged in. substore = la.avatars.open() installOn(PrivateApplication(store=substore), substore) self.userStore = substore self.loginAccount = la self.nonExternalAccount = account self.reset = PasswordResetResource(self.siteStore)
def test_sessionCleanup(self): """ Expired sessions are cleaned up every C{sessionCleanFrequency} seconds. """ clock = Clock() store = Store() portal = Portal(_TrivialRealm()) portal.registerChecker(AllowAnonymousAccess(), IAnonymous) request = FakeRequest(headers={'host': 'example.com'}) resource = PersistentSessionWrapper( store, portal, domains=['example.org', 'example.com'], clock=clock) session = GuardSession(resource, b'uid') # Create two sessions resource.createSessionForKey(b'key1', b'username@domain') resource.createSessionForKey(b'key2', b'username@domain') self.assertEqual(store.query(PersistentSession).count(), 2) # Session shouldn't be cleaned yet resource.login(request, session, Anonymous(), ()) self.assertEqual(store.query(PersistentSession).count(), 2) # First session is expired and it's time for a clean ps = store.findUnique(PersistentSession, PersistentSession.sessionKey == b'key1') ps.lastUsed -= timedelta(seconds=PERSISTENT_SESSION_LIFETIME + 1) clock.advance(SESSION_CLEAN_FREQUENCY + 1) resource.login(request, session, Anonymous(), ()) self.assertEqual( list(store.query(PersistentSession).getColumn('sessionKey')), [b'key2']) # Now we expire the second session ps2 = store.findUnique(PersistentSession, PersistentSession.sessionKey == b'key2') ps2.lastUsed -= timedelta(seconds=PERSISTENT_SESSION_LIFETIME + 1) clock.advance(SESSION_CLEAN_FREQUENCY + 1) resource.login(request, session, Anonymous(), ()) self.assertEqual(store.query(PersistentSession).count(), 0)
def test_sessionCleanup(self): """ Expired sessions are cleaned up every C{sessionCleanFrequency} seconds. """ clock = Clock() store = Store() portal = Portal(_TrivialRealm()) portal.registerChecker(AllowAnonymousAccess(), IAnonymous) request = FakeRequest(headers={'host': 'example.com'}) resource = PersistentSessionWrapper( store, portal, domains=['example.org', 'example.com'], clock=clock) session = GuardSession(resource, b'uid') # Create two sessions resource.createSessionForKey(b'key1', b'username@domain') resource.createSessionForKey(b'key2', b'username@domain') self.assertEqual(store.query(PersistentSession).count(), 2) # Session shouldn't be cleaned yet resource.login(request, session, Anonymous(), ()) self.assertEqual(store.query(PersistentSession).count(), 2) # First session is expired and it's time for a clean ps = store.findUnique( PersistentSession, PersistentSession.sessionKey == b'key1') ps.lastUsed -= timedelta(seconds=PERSISTENT_SESSION_LIFETIME + 1) clock.advance(SESSION_CLEAN_FREQUENCY + 1) resource.login(request, session, Anonymous(), ()) self.assertEqual( list(store.query(PersistentSession).getColumn('sessionKey')), [b'key2']) # Now we expire the second session ps2 = store.findUnique( PersistentSession, PersistentSession.sessionKey == b'key2') ps2.lastUsed -= timedelta(seconds=PERSISTENT_SESSION_LIFETIME + 1) clock.advance(SESSION_CLEAN_FREQUENCY + 1) resource.login(request, session, Anonymous(), ()) self.assertEqual(store.query(PersistentSession).count(), 0)
def test_cleanOnStart(self): """ L{PersistentSessionWrapper} immediately cleans expired sessions on instantiation. """ store = Store() resource = PersistentSessionWrapper(store, None) resource.createSessionForKey(b'key', b'username@domain') ps = store.findUnique(PersistentSession) ps.lastUsed -= timedelta(seconds=PERSISTENT_SESSION_LIFETIME + 1) PersistentSessionWrapper(store, None) self.assertEqual(store.query(PersistentSession).count(), 0)
def createStore(testCase): dbpath = testCase.mktemp() axiomatic.main(['-d', dbpath, 'mantissa', '--admin-password', 'password']) store = Store(dbpath) _userbase = store.findUnique(userbase.LoginSystem) adminAccount = _userbase.accountByAddress(u'admin', u'localhost') adminStore = adminAccount.avatars.open() conf = adminStore.findUnique(offering.OfferingConfiguration) conf.installOffering(getQuotientOffering(), None) return store
def tryRoundtrip(self, value): """ Attempt to roundtrip a value through a database store and load, to ensure the representation is not lossy. """ s = Store() tlt = TaggedListyThing(store=s, strlist=value) self.assertEqual(tlt.strlist, value) # Force it out of the cache, so it gets reloaded from the store del tlt tlt = s.findUnique(TaggedListyThing) self.assertEqual(tlt.strlist, value)
def buildWorld(testCase): """ Build a L{TestWorld}. """ # XXX This is too many stores for a unit test to need to create. siteStore = Store(filesdir=FilePath(testCase.mktemp())) Mantissa().installSite(siteStore, u'example.com', u'', False) installOffering(siteStore, imaginaryOffering, {}) login = siteStore.findUnique(LoginSystem) account = login.addAccount(u'alice', u'example.com', u'password') userStore = account.avatars.open() app = ImaginaryApp(store=userStore) installOn(app, userStore) imaginary = login.accountByAddress(u'Imaginary', None).avatars.open() world = imaginary.findUnique(ImaginaryWorld) # Alice connects to her own ImaginaryApp (all that is possible at the # moment). viewer = _AuthenticatedShellViewer(getAccountNames(userStore)) return TestWorld(proto=app.buildTerminalProtocol(viewer), world=world)
def insertUserStore(siteStore, userStorePath): """ Move the SubStore at the indicated location into the given site store's directory and then hook it up to the site store's authentication database. @type siteStore: C{Store} @type userStorePath: C{FilePath} """ # The following may, but does not need to be in a transaction, because it # is merely an attempt to guess a reasonable filesystem name to use for # this avatar. The user store being operated on is expected to be used # exclusively by this process. ls = siteStore.findUnique(LoginSystem) unattachedSubStore = Store(userStorePath) for lm in unattachedSubStore.query( LoginMethod, LoginMethod.account == unattachedSubStore.findUnique(LoginAccount), sort=LoginMethod.internal.descending): if ls.accountByAddress(lm.localpart, lm.domain) is None: localpart, domain = lm.localpart, lm.domain break else: raise AllNamesConflict() unattachedSubStore.close() insertLocation = siteStore.newFilePath('account', domain, localpart + '.axiom') insertParentLoc = insertLocation.parent() if not insertParentLoc.exists(): insertParentLoc.makedirs() if insertLocation.exists(): raise DatabaseDirectoryConflict() userStorePath.moveTo(insertLocation) ss = SubStore(store=siteStore, storepath=insertLocation) attachedStore = ss.open() # migrateUp() manages its own transactions because it interacts with two # different stores. attachedStore.findUnique(LoginAccount).migrateUp()
def insertUserStore(siteStore, userStorePath): """ Move the SubStore at the indicated location into the given site store's directory and then hook it up to the site store's authentication database. @type siteStore: C{Store} @type userStorePath: C{FilePath} """ # The following may, but does not need to be in a transaction, because it # is merely an attempt to guess a reasonable filesystem name to use for # this avatar. The user store being operated on is expected to be used # exclusively by this process. ls = siteStore.findUnique(LoginSystem) unattachedSubStore = Store(userStorePath) for lm in unattachedSubStore.query(LoginMethod, LoginMethod.account == unattachedSubStore.findUnique(LoginAccount), sort=LoginMethod.internal.descending): if ls.accountByAddress(lm.localpart, lm.domain) is None: localpart, domain = lm.localpart, lm.domain break else: raise AllNamesConflict() unattachedSubStore.close() insertLocation = siteStore.newFilePath('account', domain, localpart + '.axiom') insertParentLoc = insertLocation.parent() if not insertParentLoc.exists(): insertParentLoc.makedirs() if insertLocation.exists(): raise DatabaseDirectoryConflict() userStorePath.moveTo(insertLocation) ss = SubStore(store=siteStore, storepath=insertLocation) attachedStore = ss.open() # migrateUp() manages its own transactions because it interacts with two # different stores. attachedStore.findUnique(LoginAccount).migrateUp()
def test_addPerson(self): """ Test that adding a person via the Quotient version of C{AddPersonFragment} works. """ def keyword(contactType): return contactType.uniqueIdentifier().encode('ascii') store = Store() self.organizer = Organizer(store=store) installOn(self.organizer, store) addPersonFrag = AddPersonFragment(self.organizer) name = u'Captain P.' email = u'foo@bar' fragment = addPersonFrag.addPerson(name, email) self.assertTrue(isinstance(fragment, PersonFragment)) person = fragment.person self.assertIdentical( store.findUnique( Person, Person.storeID != self.organizer.storeOwnerPerson.storeID), person) self.assertEqual(person.name, name) self.assertEqual(person.getEmailAddress(), email)
from bdm.donate import Donator if '__main__' == __name__: parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--store', metavar='<dir>', type=str, required=True, help='An Axiom store directory') parser.add_argument('--steamid', metavar='steamID', type=int, required=True, help='64bit representation of a Steam ID.') parser.add_argument( '--anonymous', action='store_true', help='Use this flag if the user should be marked as anonymous.') args = parser.parse_args() store = Store(args.store) try: donator = store.findUnique( Donator, AND(Donator.steamID == unicode(args.steamid))) except ItemNotFound: donator = Donator(store=store, steamID=unicode(args.steamid), anonymous=args.anonymous) print donator
class HyperbolaTestMixin: """ Mixin class providing various Hyperbola-specific test utilities """ def _setUpStore(self): """ Set up a store, install a L{HyperbolaPublicPresence} and its dependencies, and create a role """ self.siteStore = Store(filesdir=self.mktemp()) Mantissa().installSite( self.siteStore, u"localhost", u"", generateCert=False) # Make it standard so there's no port number in the generated URL. # This kind of sucks. I don't want people assuming SSLPorts are # created by Mantissa().installSite(). Oh right, I should add a better # API for initializing a Mantissa server. -exarkun site = self.siteStore.findUnique(SiteConfiguration) ssls = list(site.store.query(SSLPort)) ssls[0].portNumber = 443 self.loginSystem = self.siteStore.findUnique(LoginSystem) product = Product(store=self.siteStore, types=[qual(HyperbolaPublicPresence)]) acct = self.loginSystem.addAccount( u'user', u'localhost', u'asdf', internal=True) self.userStore = acct.avatars.open() product.installProductOn(self.userStore) self.publicPresence = self.userStore.findUnique( HyperbolaPublicPresence) self.role = sharing.Role( store=self.userStore, externalID=u'foo@host', description=u'foo') 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) def _shareAndGetProxy(self, blurb): """ Share C{blurb} to everyone and return a shared proxy @param blurb: a blurb @type blurb: L{hyperbola.hyperblurb.Blurb} @rtype: L{xmantissa.sharing.SharedProxy} """ share = sharing.shareItem(blurb) return sharing.getShare( self.userStore, sharing.getEveryoneRole(self.userStore), share.shareID)
class MantissaCommandTests(TestCase, CommandStubMixin): """ Tests for L{Mantissa}. """ def setUp(self): """ Create a store to use in tests. """ self.filesdir = self.mktemp() self.siteStore = Store(filesdir=self.filesdir) def test_baseOffering(self): """ L{Mantissa.installSite} installs the Mantissa base offering. """ options = Mantissa() options.installSite(self.siteStore, u"example.com", u"", False) self.assertEqual( IOfferingTechnician(self.siteStore).getInstalledOfferingNames(), [baseOffering.name]) def test_httpPorts(self): """ L{Mantissa.installSite} creates a TCP port and an SSL port for the L{SiteConfiguration} which comes with the base offering it installs. """ options = Mantissa() options.installSite(self.siteStore, u"example.com", u"", False) site = self.siteStore.findUnique(SiteConfiguration) tcps = list(self.siteStore.query(TCPPort, TCPPort.factory == site)) ssls = list(self.siteStore.query(SSLPort, SSLPort.factory == site)) self.assertEqual(len(tcps), 1) self.assertEqual(tcps[0].portNumber, 8080) self.assertEqual(len(ssls), 1) self.assertEqual(ssls[0].portNumber, 8443) self.assertNotEqual(ssls[0].certificatePath, None) def test_hostname(self): """ L{Mantissa.installSite} sets the C{hostname} of the L{SiteConfiguration} to the domain name it is called with. """ options = Mantissa() options.installSite(self.siteStore, u"example.net", u"", False) site = self.siteStore.findUnique(SiteConfiguration) self.assertEqual(site.hostname, u"example.net") def test_sshPorts(self): """ L{Mantissa.installSite} creates a TCP port for the L{SecureShellConfiguration} which comes with the base offering it installs. """ options = Mantissa() options.installSite(self.siteStore, u"example.com", u"", False) shell = self.siteStore.findUnique(SecureShellConfiguration) tcps = list(self.siteStore.query(TCPPort, TCPPort.factory == shell)) self.assertEqual(len(tcps), 1) self.assertEqual(tcps[0].portNumber, 8022)
class SiteTestsMixin(object): """ Tests that apply to both subclasses of L{SiteRootMixin}, L{WebSite} and L{AnonymousSite}. @ivar store: a store containing something that inherits from L{SiteRootMixin}. @ivar resource: the result of adapting the given L{SiteRootMixin} item to L{IResource}. """ def setUp(self): """ Set up a site store with the base offering installed. """ self.siteStore = Store() installOffering(self.siteStore, baseOffering, {}) def addUser(self, username=u'nobody', domain=u'nowhere'): """ Add a user to the site store, and install a L{PrivateApplication}. @return: the user store of the added user. """ userStore = self.siteStore.findUnique(LoginSystem).addAccount( username, domain, u'asdf', internal=True).avatars.open() installOn(PrivateApplication(store=userStore), userStore) return userStore def test_crummyOldSiteRootPlugin(self): """ L{SiteRootMixin.locateChild} queries for L{ISiteRootPlugin} providers and returns the result of their C{resourceFactory} method if it is not C{None}. """ result = object() calledWith = [] class SiteRootPlugin(object): def resourceFactory(self, segments): calledWith.append(segments) return result self.store.inMemoryPowerUp(SiteRootPlugin(), ISiteRootPlugin) self.assertIdentical( self.resource.locateChild( FakeRequest(headers={"host": "example.com"}), ("foo", "bar")), result) self.assertEqual(calledWith, [("foo", "bar")]) def test_shinyNewSiteRootPlugin(self): """ L{SiteRootMixin.locateChild} queries for L{ISiteRootPlugin} providers and returns the result of their C{produceResource} methods. """ navthing = object() result = object() calledWith = [] class GoodSiteRootPlugin(object): implements(ISiteRootPlugin) def produceResource(self, req, segs, webViewer): calledWith.append((req, segs, webViewer)) return result self.store.inMemoryPowerUp(GoodSiteRootPlugin(), ISiteRootPlugin) self.store.inMemoryPowerUp(navthing, IWebViewer) req = FakeRequest(headers={ 'host': 'localhost'}) self.resource.locateChild(req, ("foo", "bar")) self.assertEqual(calledWith, [(req, ("foo", "bar"), navthing)]) def test_confusedNewPlugin(self): """ When L{SiteRootMixin.locateChild} finds a L{ISiteRootPlugin} that implements both C{produceResource} and C{resourceFactory}, it should prefer the new-style C{produceResource} method. """ navthing = object() result = object() calledWith = [] test = self class ConfusedSiteRootPlugin(object): implements(ISiteRootPlugin) def produceResource(self, req, segs, webViewer): calledWith.append((req, segs, webViewer)) return result def resourceFactory(self, segs): test.fail("resourceFactory called.") self.store.inMemoryPowerUp(ConfusedSiteRootPlugin(), ISiteRootPlugin) self.store.inMemoryPowerUp(navthing, IWebViewer) req = FakeRequest(headers={ 'host': 'localhost'}) self.resource.locateChild(req, ("foo", "bar")) self.assertEqual(calledWith, [(req, ("foo", "bar"), navthing)]) def test_virtualHosts(self): """ When a virtual host of the form (x.y) is requested from a site root resource where 'y' is a known domain for that server, a L{SharingIndex} for the user identified as 'x@y' should be returned. """ # Let's make sure we're looking at the correct store for our list of # domains first... self.assertIdentical(self.resource.siteStore, self.siteStore) somebody = self.addUser(u'somebody', u'example.com') req = FakeRequest(headers={'host': 'somebody.example.com'}) res, segs = self.resource.locateChild(req, ('',)) self.assertIsInstance(res, SharingIndex) # :( self.assertIdentical(res.userStore, somebody)
class AMPConfigurationSubStoreTests(TestCase): """ Tests for L{AMPConfiguration} which require a substore. """ def setUp(self): """ Create an in-memory L{Store} with an L{AMPConfiguration} in it, and a substore. """ self.store = Store() self.conf = AMPConfiguration(store=self.store) installOn(self.conf, self.store) self.localpart = u'alice' self.domain = u'example.org' self.password = u'foobar' loginSystem = self.store.findUnique(LoginSystem) account = loginSystem.addAccount( self.localpart, self.domain, self.password, internal=True) self.subStore = account.avatars.open() def _testPortalLogin(self, credentials): factory = self.conf.getFactory() protocol = factory.buildProtocol(None) portal = protocol.portal class IDummy(Interface): pass avatar = object() self.subStore.inMemoryPowerUp(avatar, IDummy) login = portal.login(credentials, None, IDummy) def cbLoggedIn(result): self.assertIdentical(IDummy, result[0]) self.assertIdentical(avatar, result[1]) login.addCallback(cbLoggedIn) return login def test_portal(self): """ L{AMPConfiguration.getFactory} returns a factory which creates protocols which have a C{portal} attribute which is a L{Portal} which authenticates and authorizes using L{axiom.userbase}. """ return self._testPortalLogin( UsernamePassword( '%s@%s' % (self.localpart.encode('ascii'), self.domain.encode('ascii')), self.password),) def test_portalOneTimePad(self): """ L{AMPConfiguration.getFactory} returns a factory which creates protocols which have a C{portal} attribute which is a L{Portal} which can authenticate using one-time pads. """ object.__setattr__(self.conf, 'callLater', lambda x, y: None) PAD = self.conf.generateOneTimePad(self.subStore) class OTP: implements(IOneTimePad) padValue = PAD return self._testPortalLogin(OTP())
class SubSchedulerTests(SchedTest, TestCase): """ Tests for the substore implementation of IScheduler. """ def setUp(self): """ Create a site store for the substore which will contain the IScheduler being tested. Start its IService so any scheduled events will run. """ self.storePath = filepath.FilePath(self.mktemp()) self.siteStore = Store(self.storePath) super(SubSchedulerTests, self).setUp() substoreItem = SubStore.createNew(self.siteStore, ['scheduler_test']) self.substore = substoreItem.open() self.scheduler = scheduler = IScheduler(self.substore) self.stubTime(scheduler) self.store = self.substore 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())) def test_scheduleAfterParentHookError(self): """ A transient error during a L{_SubSchedulerParentHook} run (such as failing to open the substore for whatever reason) should not disable subsequent scheduling. """ runnable = TestEvent(store=self.store) # Schedule runnable, but fail the _SubSchedulerParentHook run. self.scheduler.schedule(runnable, self.now() + timedelta(seconds=1)) hook = self.siteStore.findUnique(_SubSchedulerParentHook) def stumble(): raise IOError('Denied') object.__setattr__(hook, 'run', stumble) self.clock.advance(1) object.__delattr__(hook, 'run') self.assertEquals( self.siteStore.findUnique(TimedEventFailureLog).runnable, hook) [err] = self.flushLoggedErrors(IOError) self.assertEquals(str(err.value), 'Denied') self.assertEquals(runnable.runCount, 0) # Schedule runnable again. The restored hook in the site store should # trigger both scheduled runs in the substore now. self.scheduler.schedule(runnable, self.now() + timedelta(seconds=1)) self.clock.advance(1) self.assertEquals(runnable.runCount, 2)
class SubStoreMigrationTestCase(unittest.TestCase): IMPORTANT_VALUE = 159 localpart = 'testuser' domain = 'example.com' def setUp(self): self.dbdir = FilePath(self.mktemp()) self.store = Store(self.dbdir) self.ls = userbase.LoginSystem(store=self.store) self.scheduler = IScheduler(self.store) self.account = self.ls.addAccount( self.localpart, self.domain, 'PASSWORD') self.accountStore = self.account.avatars.open() self.ss = IScheduler(self.accountStore) self.origdir = self.accountStore.dbdir self.destdir = FilePath(self.mktemp()) 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() def test_noTimedEventsExtraction(self): """ Ensure that user store extraction works correctly if no timed events are present. """ userbase.extractUserStore(self.account, self.destdir) self.assertEqual( self.ls.accountByAddress(self.localpart, self.domain), None) self.assertFalse(list(self.store.query(SubStore, SubStore.storepath == self.origdir))) self.origdir.restat(False) self.assertFalse(self.origdir.exists()) self.assertFalse(list(self.store.query(_SubSchedulerParentHook))) def test_noTimedEventsInsertion(self): """ Test that inserting a user store succeeds if it contains no timed events. """ self.test_noTimedEventsExtraction() self._testInsertion() def test_insertion(self, _deleteDomainDirectory=False): """ Test that inserting a user store succeeds and that the right items are placed in the site store as a result. """ self.test_extraction() self._testInsertion(_deleteDomainDirectory) insertedStore = self.ls.accountByAddress(self.localpart, self.domain).avatars.open() self.assertEqual( insertedStore.findUnique(ThingThatMovesAround).superValue, self.IMPORTANT_VALUE) siteStoreSubRef = self.store.getItemByID(insertedStore.idInParent) ssph = self.store.findUnique(_SubSchedulerParentHook, _SubSchedulerParentHook.subStore == siteStoreSubRef, default=None) self.assertTrue(ssph) self.assertTrue(self.store.findUnique(TimedEvent, TimedEvent.runnable == ssph)) def _testInsertion(self, _deleteDomainDirectory=False): """ Helper method for inserting a user store. """ if _deleteDomainDirectory: self.store.filesdir.child('account').child(self.domain).remove() userbase.insertUserStore(self.store, self.destdir) def test_insertionWithNoDomainDirectory(self): """ Test that inserting a user store succeeds even if it is the first one in that domain to be inserted. """ self.test_insertion(True)
class LoginPageTests(TestCase): """ Tests for functionality related to login. """ domain = u"example.com" def setUp(self): """ Create a L{Store}, L{WebSite} and necessary request-related objects to test L{LoginPage}. """ self.siteStore = Store(filesdir=self.mktemp()) Mantissa().installSite(self.siteStore, self.domain, u"", False) self.site = self.siteStore.findUnique(SiteConfiguration) installOn( TCPPort(store=self.siteStore, factory=self.site, portNumber=80), self.siteStore) self.context = WebContext() self.request = FakeRequest() self.context.remember(self.request) def test_fromRequest(self): """ L{LoginPage.fromRequest} should return a two-tuple of the class it is called on and an empty tuple. """ request = FakeRequest( uri='/foo/bar/baz', currentSegments=['foo'], args={'quux': ['corge']}) class StubLoginPage(LoginPage): def __init__(self, store, segments, arguments): self.store = store self.segments = segments self.arguments = arguments page = StubLoginPage.fromRequest(self.siteStore, request) self.assertTrue(isinstance(page, StubLoginPage)) self.assertIdentical(page.store, self.siteStore) self.assertEqual(page.segments, ['foo', 'bar']) self.assertEqual(page.arguments, {'quux': ['corge']}) def test_staticShellContent(self): """ The L{IStaticShellContent} adapter for the C{store} argument to L{LoginPage.__init__} should become its C{staticContent} attribute. """ originalInterface = publicweb.IStaticShellContent adaptions = [] result = object() def stubInterface(object, default): adaptions.append((object, default)) return result publicweb.IStaticShellContent = stubInterface try: page = LoginPage(self.siteStore) finally: publicweb.IStaticShellContent = originalInterface self.assertEqual(len(adaptions), 1) self.assertIdentical(adaptions[0][0], self.siteStore) self.assertIdentical(page.staticContent, result) def test_segments(self): """ L{LoginPage.beforeRender} should fill the I{login-action} slot with an L{URL} which includes all the segments given to the L{LoginPage}. """ segments = ('foo', 'bar') page = LoginPage(self.siteStore, segments) page.beforeRender(self.context) loginAction = self.context.locateSlotData('login-action') expectedLocation = URL.fromString('/') for segment in (LOGIN_AVATAR,) + segments: expectedLocation = expectedLocation.child(segment) self.assertEqual(loginAction, expectedLocation) def test_queryArguments(self): """ L{LoginPage.beforeRender} should fill the I{login-action} slot with an L{URL} which includes all the query arguments given to the L{LoginPage}. """ args = {'foo': ['bar']} page = LoginPage(self.siteStore, (), args) page.beforeRender(self.context) loginAction = self.context.locateSlotData('login-action') expectedLocation = URL.fromString('/') expectedLocation = expectedLocation.child(LOGIN_AVATAR) expectedLocation = expectedLocation.add('foo', 'bar') self.assertEqual(loginAction, expectedLocation) def test_locateChildPreservesSegments(self): """ L{LoginPage.locateChild} should create a new L{LoginPage} with segments extracted from the traversal context. """ segments = ('foo', 'bar') page = LoginPage(self.siteStore) child, remaining = page.locateChild(self.context, segments) self.assertTrue(isinstance(child, LoginPage)) self.assertEqual(remaining, ()) self.assertEqual(child.segments, segments) def test_locateChildPreservesQueryArguments(self): """ L{LoginPage.locateChild} should create a new L{LoginPage} with query arguments extracted from the traversal context. """ self.request.args = {'foo': ['bar']} page = LoginPage(self.siteStore) child, remaining = page.locateChild(self.context, None) self.assertTrue(isinstance(child, LoginPage)) self.assertEqual(child.arguments, self.request.args)
class DependencyTest(unittest.TestCase): def setUp(self): self.store = Store() def test_dependsOn(self): """ Ensure that classes with dependsOn attributes set up the dependency map properly. """ foo = Blender(store=self.store) depBlob = dependency._globalDependencyMap.get(Blender, None)[0] self.assertEqual(depBlob[0], PowerStrip) self.assertEqual(depBlob[1], powerstripSetup) self.assertEqual(depBlob[2], Blender.__dict__['powerStrip']) def test_classDependsOn(self): """ Ensure that classDependsOn sets up the dependency map properly. """ dependency.classDependsOn(Blender2, PowerStrip, powerstripSetup, Blender2.__dict__['powerStrip']) depBlob = dependency._globalDependencyMap.get(Blender2, None)[0] self.assertEqual(depBlob[0], PowerStrip) self.assertEqual(depBlob[1], powerstripSetup) self.assertEqual(depBlob[2], Blender2.__dict__['powerStrip']) def test_basicInstall(self): """ If a Toaster gets installed in a Kitchen, make sure that the required dependencies get instantiated and installed too. """ foo = Kitchen(store=self.store) e = Toaster(store=self.store) self.assertEquals(e.powerStrip, None) dependency.installOn(e, foo) e.toast() ps = self.store.findUnique(PowerStrip, default=None) bb = self.store.findUnique(Breadbox, default=None) self.failIfIdentical(ps, None) self.failIfIdentical(bb, None) self.assertEquals(e.powerStrip, ps) self.assertEquals(ps.voltage, 110) self.assertEquals(e.breadFactory, bb) self.assertEquals(set(dependency.installedRequirements(e, foo)), set([ps, bb])) self.assertEquals(list(dependency.installedDependents(ps, foo)), [e]) def test_basicUninstall(self): """ Ensure that uninstallation removes the adapter from the former install target and all orphaned dependencies. """ foo = Kitchen(store=self.store) e = Toaster(store=self.store) dependency.installOn(e, foo) dependency.uninstallFrom(e, foo) self.assertEqual(dependency.installedOn(e), None) self.assertEqual(dependency.installedOn(e.powerStrip), None) def test_wrongUninstall(self): """ Ensure that attempting to uninstall an item that something else depends on fails. """ foo = Kitchen(store=self.store) e = Toaster(store=self.store) dependency.installOn(e, foo) ps = self.store.findUnique(PowerStrip) self.failUnlessRaises(dependency.DependencyError, dependency.uninstallFrom, ps, foo) def test_properOrphaning(self): """ If two installed items both depend on a third, it should be removed as soon as both installed items are removed, but no sooner. """ foo = Kitchen(store=self.store) e = Toaster(store=self.store) dependency.installOn(e, foo) ps = self.store.findUnique(PowerStrip) bb = self.store.findUnique(Breadbox) f = Blender(store=self.store) dependency.installOn(f, foo) self.assertEquals(list(self.store.query(PowerStrip)), [ps]) #XXX does ordering matter? self.assertEquals(set(dependency.installedDependents(ps, foo)), set([e, f])) self.assertEquals(set(dependency.installedRequirements(e, foo)), set([bb, ps])) self.assertEquals(list(dependency.installedRequirements(f, foo)), [ps]) dependency.uninstallFrom(e, foo) self.assertEquals(dependency.installedOn(ps), foo) dependency.uninstallFrom(f, foo) self.assertEquals(dependency.installedOn(ps), None) def test_installedUniqueRequirements(self): """ Ensure that installedUniqueRequirements lists only powerups depended on by exactly one installed powerup. """ foo = Kitchen(store=self.store) e = Toaster(store=self.store) dependency.installOn(e, foo) ps = self.store.findUnique(PowerStrip) bb = self.store.findUnique(Breadbox) f = Blender(store=self.store) dependency.installOn(f, foo) self.assertEquals(list(dependency.installedUniqueRequirements(e, foo)), [bb]) def test_customizerCalledOnce(self): """ The item customizer defined for a dependsOn attribute should only be called if an item is created implicitly to satisfy the dependency. """ foo = Kitchen(store=self.store) ps = PowerStrip(store=self.store) dependency.installOn(ps, foo) ps.voltage = 115 e = Toaster(store=self.store) dependency.installOn(e, foo) self.assertEqual(ps.voltage, 115) def test_explicitInstall(self): """ If an item is explicitly installed, it should not be implicitly uninstalled. Also, dependsOn attributes should be filled in properly even if a dependent item is not installed automatically. """ foo = Kitchen(store=self.store) ps = PowerStrip(store=self.store) dependency.installOn(ps, foo) e = Toaster(store=self.store) dependency.installOn(e, foo) self.assertEqual(e.powerStrip, ps) dependency.uninstallFrom(e, foo) self.assertEquals(dependency.installedOn(ps), foo) def test_doubleInstall(self): """ Make sure that installing two instances of a class on the same target fails, if something depends on that class, and succeeds otherwise. """ foo = Kitchen(store=self.store) e = Toaster(store=self.store) dependency.installOn(e, foo) ps = PowerStrip(store=self.store) self.failUnlessRaises(dependency.DependencyError, dependency.installOn, ps, foo) e2 = Toaster(store=self.store) dependency.installOn(e2, foo) def test_recursiveInstall(self): """ Installing an item should install all of its dependencies, and all of its dependencies, and so forth. """ foo = Kitchen(store=self.store) ic = IceCrusher(store=self.store) dependency.installOn(ic, foo) blender = self.store.findUnique(Blender) ps = self.store.findUnique(PowerStrip) self.assertEquals(dependency.installedOn(blender), foo) self.assertEquals(dependency.installedOn(ps), foo) self.assertEquals(list(dependency.installedRequirements(ic, foo)), [blender]) def test_recursiveUninstall(self): """ Removal of items should recursively remove orphaned dependencies. """ foo = Kitchen(store=self.store) ic = IceCrusher(store=self.store) dependency.installOn(ic, foo) blender = self.store.findUnique(Blender) ps = self.store.findUnique(PowerStrip) dependency.uninstallFrom(ic, foo) self.failIf(dependency.installedOn(blender)) self.failIf(dependency.installedOn(ps)) self.failIf(dependency.installedOn(ic)) def test_wrongDependsOn(self): """ dependsOn should raise an error if used outside a class definition. """ self.assertRaises(TypeError, dependency.dependsOn, Toaster) def test_referenceArgsPassthrough(self): """ dependsOn should accept (most of) attributes.reference's args. """ self.failUnless("power source" in Toaster.powerStrip.doc) self.assertEquals(Toaster.breadFactory.whenDeleted, reference.CASCADE) def test_powerupInterfaces(self): """ Make sure interfaces are powered up and down properly. """ foo = Kitchen(store=self.store) e = Toaster(store=self.store) f = Blender(store=self.store) dependency.installOn(e, foo) dependency.installOn(f, foo) self.assertEquals(IAppliance(foo), e) self.assertEquals(IBreadConsumer(foo), e) dependency.uninstallFrom(e, foo) self.assertEquals(IAppliance(foo), f) dependency.uninstallFrom(f, foo) self.assertRaises(TypeError, IAppliance, foo) def test_callbacks(self): """ 'installed' and 'uninstalled' callbacks should fire on install/uninstall. """ foo = Kitchen(store=self.store) e = Toaster(store=self.store) self.installCallbackCalled = False e.callback = lambda _: setattr(self, 'installCallbackCalled', True) dependency.installOn(e, foo) self.failUnless(self.installCallbackCalled) self.uninstallCallbackCalled = False e.callback = lambda _: setattr(self, 'uninstallCallbackCalled', True) dependency.uninstallFrom(e, foo) self.failUnless(self.uninstallCallbackCalled) def test_onlyInstallPowerups(self): """ Make sure onlyInstallPowerups doesn't load dependencies or prohibit multiple calls. """ foo = Kitchen(store=self.store) e = Toaster(store=self.store) f = Toaster(store=self.store) dependency.onlyInstallPowerups(e, foo) dependency.onlyInstallPowerups(f, foo) self.assertEquals(list(foo.powerupsFor(IBreadConsumer)), [e, f]) self.assertEquals( list(self.store.query(dependency._DependencyConnector)), [])
class PublicFrontPageTests(TestCase, CommandStubMixin): """ Tests for Mantissa's top-level web resource. """ def setUp(self): """ Set up a store with an installed offering. """ self.siteStore = Store(dbdir=self.mktemp()) Mantissa().installSite(self.siteStore, u"localhost", u"", False) off = Offering( name=u"test_offering", description=u"Offering for creating a sample app store", siteRequirements=[], appPowerups=[TestAppPowerup], installablePowerups=[], loginInterfaces=[], themes=[], ) self.installedOffering = installOffering(self.siteStore, off, None) self.app = self.installedOffering.application self.substore = self.app.open() sharedItem = getEveryoneRole(self.substore).getShare(getDefaultShareID(self.substore)) self.frontPage = self.siteStore.findUnique(FrontPage) self.webViewer = IWebViewer(self.siteStore) def test_offeringChild(self): """ Installing an offering makes its shared items accessible under a child of L{_PublicFrontPage} with the offering's name. """ frontPage = FrontPage(store=self.siteStore) resource = _PublicFrontPage(frontPage, self.webViewer) request = FakeRequest() result, segments = resource.locateChild(request, ("test_offering",)) self.assertIdentical(result.userStore, self.substore) self.assertTrue(IWebViewer.providedBy(result.webViewer)) def test_nonExistentChild(self): """ L{_PublicFrontPage.locateChild} returns L{rend.NotFound} for a child segment which does not exist. """ store = Store() frontPage = FrontPage(store=store) resource = _PublicFrontPage(frontPage, IWebViewer(self.siteStore)) request = FakeRequest() ctx = context.WebContext() ctx.remember(request, inevow.IRequest) result = resource.locateChild(ctx, ("foo",)) self.assertIdentical(result, rend.NotFound) def test_rootChild(self): """ When no default offering has been selected, L{PublicFrontPage.locateChild} returns an L{_OfferingsFragment} wrapped by the L{IWebViewer}. """ frontPage = FrontPage(store=self.siteStore) resource = _PublicFrontPage(frontPage, self.webViewer) request = FakeRequest() ctx = context.WebContext() ctx.remember(request, inevow.IRequest) result, segments = resource.locateChild(ctx, ("",)) self.assertIsInstance(result, PublicPage) self.assertIsInstance(result.fragment, _OfferingsFragment) def test_rootChildWithDefaultApp(self): """ The root resource provided by L{_PublicFrontPage} when a primary application has been selected is that application's L{SharingIndex}. """ resource, segments = self.frontPage.produceResource(None, ("",), IWebViewer(self.siteStore)) self.assertEqual(segments, ("",)) self.frontPage.defaultApplication = self.app result, segments = resource.locateChild(None, ("",)) self.assertIsInstance(result, PublicPage) self.assertIsInstance(result.fragment, TestAppElement) def getStore(self): return self.siteStore def test_switchFrontPage(self): """ 'axiomatic frontpage <offeringName>' switches the primary application (i.e., the one whose front page will be displayed on the site's root resource) to the one belonging to the named offering. """ off2 = Offering( name=u"test_offering2", description=u"Offering for creating a sample app store", siteRequirements=[], appPowerups=[TestAppPowerup], installablePowerups=[], loginInterfaces=[], themes=[], ) installedOffering2 = installOffering(self.siteStore, off2, None) sfp = SetFrontPage() sfp.parent = self sfp.parseOptions(["test_offering"]) resource, segments = self.frontPage.produceResource(None, ("",), self.webViewer) result, segs = resource.locateChild(None, [""]) self.assertIdentical(result.fragment.original.store, self.substore) self.assertEqual(segs, []) sfp.parseOptions(["test_offering2"]) resource, moreSegs = self.frontPage.produceResource(None, ("",), self.webViewer) result, segs = resource.locateChild(None, [""]) self.assertEqual(segs, []) self.assertIdentical(result.fragment.original.store, installedOffering2.application.open()) self.assertRaises(UsageError, sfp.parseOptions, []) self.assertRaises(UsageError, sfp.parseOptions, ["nonexistent"])
class SubStoreSchedulerReentrancy(TestCase): """ Test re-entrant scheduling calls on an item run by a SubScheduler. """ 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() def tearDown(self): return IService(self.store).stopService() 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 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)]) 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.subStore == self.substoreItem) self.assertEqual( list(self.scheduler.scheduledTimes(hook)), [Time.fromPOSIXTimestamp(20)]) 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)]) 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)])
class ComposeActionsTestCase(TestCase): """ Tests for the compose-related actions of L{xquotient.exmess.MessageDetail} (reply, forward, etc) and related functionality """ def setUp(self): # XXX Incorrect setup. See xquotient.test.test_compose.CompositionTestMixin self.store = Store(self.mktemp()) LoginMethod(store=self.store, internal=False, protocol=u'email', localpart=u'recipient', domain=u'host', verified=True, account=self.store) self.fromAddr = smtpout.FromAddress(address=u'recipient@host', store=self.store) self.inbox = inbox.Inbox(store=self.store) installOn(self.inbox, self.store) self.composer = compose.Composer(store=self.store) installOn(self.composer, self.store) self.defaultFromAddress = self.store.findUnique( smtpout.FromAddress, smtpout.FromAddress._address == None) self.message = testMessageFactory( store=self.store, spam=False, impl=DummyMessageImplWithABunchOfAddresses(store=self.store)) self.messageDetail = MessageDetail(self.message) def _recipientsToStrings(self, recipients): """ Convert a mapping of "strings to lists of L{xquotient.mimeutil.EmailAddress} instances" into a mapping of "strings to lists of string email addresses" """ result = {} for (k, v) in recipients.iteritems(): result[k] = list(e.email for e in v) return result def test_replyToAll(self): """ Test L{xquotient.exmess.MessageDetail.replyAll} """ self.assertEquals( self._recipientsToStrings( self.messageDetail.replyAll().recipients), { 'bcc': ['blind-copy@host'], 'cc': ['copy@host'], 'to': ['sender@host', 'recipient2@host'] }) def test_replyToAllFromAddress(self): """ Test that L{xquotient.exmess.MessageDetail.replyAll} doesn't include addresses of L{xquotient.smtpout.FromAddress} items that exist in the same store as the message that is being replied to """ addrs = set( u'blind-copy@host copy@host sender@host recipient2@host'.split()) for addr in addrs: fromAddr = smtpout.FromAddress(address=addr, store=self.message.store) gotAddrs = set() for l in self.messageDetail.replyAll().recipients.itervalues(): gotAddrs.update(e.email for e in l) self.assertEquals(gotAddrs, addrs - set([addr])) fromAddr.deleteFromStore() def test_createDraftComposeFragment(self): """ Verify that an instance of L{DraftComposeFragment} which refers to the correct draft item is returned by L{InboxScreen.editDraft}. """ fragment = self.messageDetail.editDraft() self.failUnless( isinstance(fragment, compose.DraftComposeFragment), "Got %r instead of DraftComposeFragment" % (fragment, )) self.assertIdentical(fragment._savedDraft, self.message) def test_slotData(self): """ Verify that L{DraftComposeFragment.slotData} returns a dictionary which reflects the message which was used as the draft. """ subject = u'subject text' body = u'hello, world?\n' to = u'*****@*****.**' cc = u'*****@*****.**' bcc = u'*****@*****.**' message = createMessage( self.composer, None, None, self.defaultFromAddress, [mimeutil.EmailAddress(to, mimeEncoded=False)], subject, body, [mimeutil.EmailAddress(cc, mimeEncoded=False)], [mimeutil.EmailAddress(bcc, mimeEncoded=False)], [], ) fragment = self.messageDetail._composeSomething(draft=message) slotData = fragment.slotData() self.assertEqual(slotData['to'], to) self.assertEqual(slotData['from'][0], self.defaultFromAddress) self.assertEqual(slotData['subject'], subject) self.assertEqual(slotData['message-body'], body) self.assertEqual(slotData['cc'], cc) # XXX This assertion should succeed. # self.assertEqual(slotData['bcc'], bcc) def test_addPersonForm(self): """ Test that the add-person form is created correctly. """ installOn(people.AddPerson(store=self.store), self.store) apf = self.messageDetail.render_addPersonFragment(None, None) self.assertEquals(apf.organizer, self.store.findUnique(people.Organizer))
class SiteTestsMixin(object): """ Tests that apply to both subclasses of L{SiteRootMixin}, L{WebSite} and L{AnonymousSite}. @ivar store: a store containing something that inherits from L{SiteRootMixin}. @ivar resource: the result of adapting the given L{SiteRootMixin} item to L{IResource}. """ def setUp(self): """ Set up a site store with the base offering installed. """ self.siteStore = Store() installOffering(self.siteStore, baseOffering, {}) def addUser(self, username=u'nobody', domain=u'nowhere'): """ Add a user to the site store, and install a L{PrivateApplication}. @return: the user store of the added user. """ userStore = self.siteStore.findUnique(LoginSystem).addAccount( username, domain, u'asdf', internal=True).avatars.open() installOn(PrivateApplication(store=userStore), userStore) return userStore def test_crummyOldSiteRootPlugin(self): """ L{SiteRootMixin.locateChild} queries for L{ISiteRootPlugin} providers and returns the result of their C{resourceFactory} method if it is not C{None}. """ result = object() calledWith = [] class SiteRootPlugin(object): def resourceFactory(self, segments): calledWith.append(segments) return result self.store.inMemoryPowerUp(SiteRootPlugin(), ISiteRootPlugin) self.assertIdentical( self.resource.locateChild( FakeRequest(headers={"host": "example.com"}), ("foo", "bar")), result) self.assertEqual(calledWith, [("foo", "bar")]) def test_shinyNewSiteRootPlugin(self): """ L{SiteRootMixin.locateChild} queries for L{ISiteRootPlugin} providers and returns the result of their C{produceResource} methods. """ navthing = object() result = object() calledWith = [] class GoodSiteRootPlugin(object): implements(ISiteRootPlugin) def produceResource(self, req, segs, webViewer): calledWith.append((req, segs, webViewer)) return result self.store.inMemoryPowerUp(GoodSiteRootPlugin(), ISiteRootPlugin) self.store.inMemoryPowerUp(navthing, IWebViewer) req = FakeRequest(headers={'host': 'localhost'}) self.resource.locateChild(req, ("foo", "bar")) self.assertEqual(calledWith, [(req, ("foo", "bar"), navthing)]) def test_confusedNewPlugin(self): """ When L{SiteRootMixin.locateChild} finds a L{ISiteRootPlugin} that implements both C{produceResource} and C{resourceFactory}, it should prefer the new-style C{produceResource} method. """ navthing = object() result = object() calledWith = [] test = self class ConfusedSiteRootPlugin(object): implements(ISiteRootPlugin) def produceResource(self, req, segs, webViewer): calledWith.append((req, segs, webViewer)) return result def resourceFactory(self, segs): test.fail("resourceFactory called.") self.store.inMemoryPowerUp(ConfusedSiteRootPlugin(), ISiteRootPlugin) self.store.inMemoryPowerUp(navthing, IWebViewer) req = FakeRequest(headers={'host': 'localhost'}) self.resource.locateChild(req, ("foo", "bar")) self.assertEqual(calledWith, [(req, ("foo", "bar"), navthing)]) def test_virtualHosts(self): """ When a virtual host of the form (x.y) is requested from a site root resource where 'y' is a known domain for that server, a L{SharingIndex} for the user identified as 'x@y' should be returned. """ # Let's make sure we're looking at the correct store for our list of # domains first... self.assertIdentical(self.resource.siteStore, self.siteStore) somebody = self.addUser(u'somebody', u'example.com') req = FakeRequest(headers={'host': 'somebody.example.com'}) res, segs = self.resource.locateChild(req, ('', )) self.assertIsInstance(res, SharingIndex) # :( self.assertIdentical(res.userStore, somebody)
class SecureShellConfigurationTests(TestCase): """ Tests for L{xmantissa.shell.SecureShellConfiguration} which defines how to create an SSH server. """ _hostKey = ( "-----BEGIN RSA PRIVATE KEY-----\n" "MIIByAIBAAJhAM/dftm59mJJ1JVy0bsq8J7fp4WUecgaJukRyf637d76ywxRYGdw\n" "47hkBiJaDYgaE9HMlh2eSow3b2YCyom4FLlh/7Buq58A9IofR7ZiNVYv0ZDppbDg\n" "FN+Gl2ZFLFB3dwIBIwJgC+DFa4b4It+lv2Wllaquqf4m1G7iYzSxxCzm+JzLw5lN\n" "bmsM0rX+Yk7bx3LcM6m34vyvhY6p/kQyjHo7/CkpaSQg4bnpOcqEq3oMf8E0c0lp\n" "TQ1TdtfnKKrZZPTaVr7rAjEA7O19/tSLK6by1BpE1cb6W07GK1WcafYLxQLT64o+\n" "GKxbrlsossc8gWJ8GDRjE2S5AjEA4JkYfYkgfucH941r9yDFrhr6FuOdwbLXDESZ\n" "DyLhW/7DHiVIXlaLFnY+51PcTwWvAjBzFESDFsdBFpMz0j6w+j8WaBccXMhQuVYs\n" "fbdjxs20NnWsdWuKCQAhljxGRVSxpfMCMBmrGL3jyTMTFtp2j/78bl0KZbl5GVf3\n" "LoUPJ29xs1r4i1PnAPTWsM9d+I93TGDNcwIxAMRz4KO02tiLXG2igwDw/WWszrkr\n" "r4ggaFDlt4QqoNz0l4tayqzbDV1XceLgP4cXcQ==\n" "-----END RSA PRIVATE KEY-----\n") def setUp(self): """ Create an in-memory L{Store} with a L{SecureShellConfiguration} in it. """ self.store = Store() self.shell = SecureShellConfiguration( store=self.store, hostKey=self._hostKey) installOn(self.shell, self.store) def test_interfaces(self): """ L{SecureShellConfiguration} implements L{IProtocolFactoryFactory}. """ self.assertTrue(verifyObject(IProtocolFactoryFactory, self.shell)) def test_powerup(self): """ L{installOn} powers up the target for L{IProtocolFactoryFactory} with L{SecureShellConfiguration}. """ self.assertIn( self.shell, list(self.store.powerupsFor(IProtocolFactoryFactory))) def test_repr(self): """ The result of C{repr} on a L{SecureShellConfiguration} instance includes only a fingerprint of the private key, not the entire value. """ self.assertEqual( repr(self.shell), "SecureShellConfiguration(storeID=%d, " % (self.shell.storeID,) + "hostKeyFingerprint='68cc7060bb6394060672467e7c4d8f3b')") def assertHostKey(self, shell, factory): """ Assert that the public and private keys provided by C{factory} match those specified by C{shell} and that they are L{Key} instances. """ privateKey = Key.fromString(shell.hostKey) self.assertEqual( factory.publicKeys, {'ssh-rsa': privateKey.public()}) self.assertEqual(factory.privateKeys, {'ssh-rsa': privateKey}) def test_getFactory(self): """ L{SecureShellConfiguration.getFactory} returns an L{SSHFactory} with keys from L{SecureShellConfiguration.hostKey}. """ factory = self.shell.getFactory() self.assertHostKey(self.shell, factory) def test_keyGeneration(self): """ L{SecureShellConfiguration} generates its own key pair if one is not supplied to C{__init__}. """ store = Store() shell = SecureShellConfiguration(store=store) installOn(shell, store) factory = shell.getFactory() self.assertHostKey(shell, factory) def test_portal(self): """ The factory returned by L{SecureShellConfiguration.getFactory} has a C{portal} attribute which allows logins authenticated in the usual L{axiom.userbase} manner. """ localpart = u'foo bar' domain = u'example.com' password = u'baz quux' loginSystem = self.store.findUnique(LoginSystem) account = loginSystem.addAccount( localpart, domain, password, internal=True) subStore = account.avatars.open() avatar = object() subStore.inMemoryPowerUp(avatar, IConchUser) factory = self.shell.getFactory() login = factory.portal.login( UsernamePassword( '%s@%s' % (localpart.encode('ascii'), domain.encode('ascii')), password), None, IConchUser) def cbLoggedIn(result): self.assertIdentical(IConchUser, result[0]) self.assertIdentical(avatar, result[1]) login.addCallback(cbLoggedIn) return login
import sys from axiom.store import Store from eridanus.bot import IRCBotService db = Store(sys.argv[1]) svc = db.findUnique(IRCBotService, IRCBotService.serviceID == sys.argv[2]) svc.config.name = sys.argv[3].decode('utf-8')
class LoginPageTests(TestCase): """ Tests for functionality related to login. """ domain = u"example.com" def setUp(self): """ Create a L{Store}, L{WebSite} and necessary request-related objects to test L{LoginPage}. """ self.siteStore = Store(filesdir=self.mktemp()) Mantissa().installSite(self.siteStore, self.domain, u"", False) self.site = self.siteStore.findUnique(SiteConfiguration) installOn( TCPPort(store=self.siteStore, factory=self.site, portNumber=80), self.siteStore) self.context = WebContext() self.request = FakeRequest() self.context.remember(self.request) def test_fromRequest(self): """ L{LoginPage.fromRequest} should return a two-tuple of the class it is called on and an empty tuple. """ request = FakeRequest(uri='/foo/bar/baz', currentSegments=['foo'], args={'quux': ['corge']}) class StubLoginPage(LoginPage): def __init__(self, store, segments, arguments): self.store = store self.segments = segments self.arguments = arguments page = StubLoginPage.fromRequest(self.siteStore, request) self.assertTrue(isinstance(page, StubLoginPage)) self.assertIdentical(page.store, self.siteStore) self.assertEqual(page.segments, ['foo', 'bar']) self.assertEqual(page.arguments, {'quux': ['corge']}) def test_staticShellContent(self): """ The L{IStaticShellContent} adapter for the C{store} argument to L{LoginPage.__init__} should become its C{staticContent} attribute. """ originalInterface = publicweb.IStaticShellContent adaptions = [] result = object() def stubInterface(object, default): adaptions.append((object, default)) return result publicweb.IStaticShellContent = stubInterface try: page = LoginPage(self.siteStore) finally: publicweb.IStaticShellContent = originalInterface self.assertEqual(len(adaptions), 1) self.assertIdentical(adaptions[0][0], self.siteStore) self.assertIdentical(page.staticContent, result) def test_segments(self): """ L{LoginPage.beforeRender} should fill the I{login-action} slot with an L{URL} which includes all the segments given to the L{LoginPage}. """ segments = ('foo', 'bar') page = LoginPage(self.siteStore, segments) page.beforeRender(self.context) loginAction = self.context.locateSlotData('login-action') expectedLocation = URL.fromString('/') for segment in (LOGIN_AVATAR, ) + segments: expectedLocation = expectedLocation.child(segment) self.assertEqual(loginAction, expectedLocation) def test_queryArguments(self): """ L{LoginPage.beforeRender} should fill the I{login-action} slot with an L{URL} which includes all the query arguments given to the L{LoginPage}. """ args = {'foo': ['bar']} page = LoginPage(self.siteStore, (), args) page.beforeRender(self.context) loginAction = self.context.locateSlotData('login-action') expectedLocation = URL.fromString('/') expectedLocation = expectedLocation.child(LOGIN_AVATAR) expectedLocation = expectedLocation.add('foo', 'bar') self.assertEqual(loginAction, expectedLocation) def test_locateChildPreservesSegments(self): """ L{LoginPage.locateChild} should create a new L{LoginPage} with segments extracted from the traversal context. """ segments = ('foo', 'bar') page = LoginPage(self.siteStore) child, remaining = page.locateChild(self.context, segments) self.assertTrue(isinstance(child, LoginPage)) self.assertEqual(remaining, ()) self.assertEqual(child.segments, segments) def test_locateChildPreservesQueryArguments(self): """ L{LoginPage.locateChild} should create a new L{LoginPage} with query arguments extracted from the traversal context. """ self.request.args = {'foo': ['bar']} page = LoginPage(self.siteStore) child, remaining = page.locateChild(self.context, None) self.assertTrue(isinstance(child, LoginPage)) self.assertEqual(child.arguments, self.request.args)