def test_reactorSelectionShortOptionStyle(self): """ L{AxiomaticStart} optionally takes the name of a reactor in the form -r [shortName] and installs it instead of the default reactor. """ axiomatic = self._getAxiomaticScript() # Create a store for the child process to use and put an item in it. # This will force an import of the module that defines that item's # class when the child process starts. The module imports the default # reactor at the top-level, making this the worst-case for the reactor # selection code. storePath = self.mktemp() store = Store(storePath) SomeItem(store=store) store.close() # Install select reactor because it is available on all platforms, and # it is still an error to try to install the select reactor even if # the already installed reactor was the select reactor. argv = [ sys.executable, axiomatic, "-d", storePath, "start", "-r", "select", "-n" ] expected = [ "reactor class: twisted.internet.selectreactor.SelectReactor.", "reactor class: <class 'twisted.internet.selectreactor.SelectReactor'>" ] proto, complete = AxiomaticStartProcessProtocol.protocolAndDeferred( expected) environ = os.environ.copy() reactor.spawnProcess(proto, sys.executable, argv, env=environ) return complete
def testBasicQuery(self): s = Store() def entesten(): c1 = C(store=s, name=u'yes') c2 = C(store=s, name=u'no') A(store=s, reftoc=c1, type=u'testc') A(store=s, reftoc=c2, type=u'testc') A(store=s, reftoc=c1, type=u'testx') yesb = B(store=s, cref=c1, name=u'correct') B(store=s, cref=c2, name=u'not correct') s.checkpoint() q = list( s.query( B, AND(AND(C.name == u'yes', A.type == u'testc'), AND(C.storeID == B.cref, A.reftoc == C.storeID)), )) self.assertEquals(q, [yesb]) s.transact(entesten) s.close()
def test_reactorSelectionShortOptionStyle(self): """ L{AxiomaticStart} optionally takes the name of a reactor in the form -r [shortName] and installs it instead of the default reactor. """ axiomatic = self._getAxiomaticScript() # Create a store for the child process to use and put an item in it. # This will force an import of the module that defines that item's # class when the child process starts. The module imports the default # reactor at the top-level, making this the worst-case for the reactor # selection code. storePath = self.mktemp() store = Store(storePath) SomeItem(store=store) store.close() # Install select reactor because it is available on all platforms, and # it is still an error to try to install the select reactor even if # the already installed reactor was the select reactor. argv = [ sys.executable, axiomatic, "-d", storePath, "start", "-r", "select", "-n"] expected = [ "reactor class: twisted.internet.selectreactor.SelectReactor.", "reactor class: <class 'twisted.internet.selectreactor.SelectReactor'>"] proto, complete = AxiomaticStartProcessProtocol.protocolAndDeferred(expected) environ = os.environ.copy() reactor.spawnProcess(proto, sys.executable, argv, env=environ) return complete
def saveStub(funcobj, revision): """ Create a stub database and populate it using the given function. @param funcobj: A one-argument callable which will be invoked with an Axiom Store instance and should add to it the old state which will be used to test an upgrade. @param revision: An SVN revision of trunk at which it was possible it is possible for funcobj to create the necessary state. """ # You may notice certain files don't pass the second argument. They don't # work any more. Please feel free to update them with the revision number # they were created at. filename = inspect.getfile(funcobj) dbfn = os.path.join( os.path.dirname(filename), os.path.basename(filename).split("stub_")[1].split('.py')[0]+'.axiom') s = Store(dbfn) s.transact(funcobj, s) s.close() tarball = tarfile.open(dbfn+'.tbz2', 'w:bz2') tarball.add(os.path.basename(dbfn)) tarball.close() shutil.rmtree(dbfn)
def saveStub(funcobj, revision): """ Create a stub database and populate it using the given function. @param funcobj: A one-argument callable which will be invoked with an Axiom Store instance and should add to it the old state which will be used to test an upgrade. @param revision: An SVN revision of trunk at which it was possible it is possible for funcobj to create the necessary state. """ # You may notice certain files don't pass the second argument. They don't # work any more. Please feel free to update them with the revision number # they were created at. filename = inspect.getfile(funcobj) dbfn = os.path.join( os.path.dirname(filename), os.path.basename(filename).split("stub_")[1].split('.py')[0]+'.axiom') s = Store(dbfn) s.transact(funcobj, s) s.close() tarball = tarfile.open(dbfn+'.tbz2', 'w:bz2') tarball.add(os.path.basename(dbfn)) tarball.close() shutil.rmtree(dbfn)
def test_reactorSelection(self): """ L{AxiomaticStart} optionally takes the name of a reactor and installs it instead of the default reactor. """ # Since this process is already hopelessly distant from the state in # which I{axiomatic start} operates, it would make no sense to try a # functional test of this behavior in this process. Since the # behavior being tested involves lots of subtle interactions between # lots of different pieces of code (the reactor might get installed # at the end of a ten-deep chain of imports going through as many # different projects), it also makes no sense to try to make this a # unit test. So, start a child process and try to use the alternate # reactor functionality there. here = FilePath(__file__) # Try to find it relative to the source of this test. bin = here.parent().parent().parent().child("bin") axiomatic = bin.child("axiomatic") if axiomatic.exists(): # Great, use that one. axiomatic = axiomatic.path else: # Try to find it on the path, instead. axiomatics = which("axiomatic") if axiomatics: # Great, it was on the path. axiomatic = axiomatics[0] else: # Nope, not there, give up. raise SkipTest( "Could not find axiomatic script on path or at %s" % ( axiomatic.path,)) # Create a store for the child process to use and put an item in it. # This will force an import of the module that defines that item's # class when the child process starts. The module imports the default # reactor at the top-level, making this the worst-case for the reactor # selection code. storePath = self.mktemp() store = Store(storePath) SomeItem(store=store) store.close() # Install select reactor because it available on all platforms, and # it is still an error to try to install the select reactor even if # the already installed reactor was the select reactor. argv = [ sys.executable, axiomatic, "-d", storePath, "start", "--reactor", "select", "-n"] expected = [ "reactor class: twisted.internet.selectreactor.SelectReactor.", "reactor class: <class 'twisted.internet.selectreactor.SelectReactor'>"] proto, complete = AxiomaticStartProcessProtocol.protocolAndDeferred(expected) environ = os.environ.copy() reactor.spawnProcess(proto, sys.executable, argv, env=environ) return complete
def testUserBaseInstall(self): dbdir = self.mktemp() axiomatic.main(['-d', dbdir, 'userbase', 'install']) s = Store(dbdir) IRealm(s) ICredentialsChecker(s) s.close()
class Options(usage.Options): def subCommands(): def get(self): yield ("start", None, Start, "Launch the given Axiom database") if not platform.isWinNT(): yield ("stop", None, Stop, "Stop the server running from the given Axiom database") yield ("status", None, Status, "Report whether a server is running from the given Axiom database") from axiom import plugins for plg in plugin.getPlugins(iaxiom.IAxiomaticCommand, plugins): try: yield (plg.name, None, plg, plg.description) except AttributeError: raise RuntimeError("Maldefined plugin: %r" % (plg,)) return (get,) subCommands = property(*subCommands()) optParameters = [("dbdir", "d", None, "Path containing axiom database to configure/create")] optFlags = [("debug", "b", "Enable Axiom-level debug logging")] store = None def usedb(self, potentialdb): yn = raw_input("Use database %r? (Y/n) " % (potentialdb,)) if yn.lower() in ("y", "yes", ""): self["dbdir"] = potentialdb else: raise usage.UsageError("Select another database with the -d option, then.") def getStoreDirectory(self): if self["dbdir"] is None: possibilities = glob.glob("*.axiom") if len(possibilities) > 1: raise usage.UsageError( "Multiple databases found here, please select one with " "the -d option: %s" % (" ".join(possibilities),) ) elif len(possibilities) == 1: self.usedb(possibilities[0]) else: self.usedb(self.subCommand + ".axiom") return self["dbdir"] def getStore(self): from axiom.store import Store if self.store is None: self.store = Store(self.getStoreDirectory(), debug=self["debug"]) return self.store def postOptions(self): if self.store is not None: self.store.close()
class Options(usage.Options): def subCommands(): def get(self): yield ('start', None, Start, 'Launch the given Axiom database') if not platform.isWindows(): yield ('stop', None, Stop, 'Stop the server running from the given Axiom database') yield ('status', None, Status, 'Report whether a server is running from the given Axiom database') from axiom import plugins for plg in getPlugins(IAxiomaticCommand, plugins): try: yield (plg.name, None, plg, plg.description) except AttributeError: raise RuntimeError("Maldefined plugin: %r" % (plg,)) return get, subCommands = property(*subCommands()) optParameters = [ ('dbdir', 'd', None, 'Path containing axiom database to configure/create'), ] optFlags = [ ('debug', 'b', 'Enable Axiom-level debug logging')] store = None def usedb(self, potentialdb): yn = raw_input("Use database %r? (Y/n) " % (potentialdb,)) if yn.lower() in ('y', 'yes', ''): self['dbdir'] = potentialdb else: raise usage.UsageError('Select another database with the -d option, then.') def getStoreDirectory(self): if self['dbdir'] is None: possibilities = glob.glob('*.axiom') if len(possibilities) > 1: raise usage.UsageError( "Multiple databases found here, please select one with " "the -d option: %s" % (' '.join(possibilities),)) elif len(possibilities) == 1: self.usedb(possibilities[0]) else: self.usedb(self.subCommand + '.axiom') return self['dbdir'] def getStore(self): from axiom.store import Store if self.store is None: self.store = Store(self.getStoreDirectory(), debug=self['debug']) return self.store def postOptions(self): if self.store is not None: self.store.close()
class Options(usage.Options): def subCommands(): def get(self): yield ('start', None, Start, 'Launch the given Axiom database') if not platform.isWindows(): yield ('stop', None, Stop, 'Stop the server running from the given Axiom database') yield ('status', None, Status, 'Report whether a server is running from the given Axiom database') from axiom import plugins for plg in getPlugins(IAxiomaticCommand, plugins): try: yield (plg.name, None, plg, plg.description) except AttributeError: raise RuntimeError("Maldefined plugin: %r" % (plg,)) return get, subCommands = property(*subCommands()) optParameters = [ ('dbdir', 'd', None, 'Path containing axiom database to configure/create'), ] optFlags = [ ('debug', 'b', 'Enable Axiom-level debug logging')] store = None def usedb(self, potentialdb): yn = raw_input("Use database %r? (Y/n) " % (potentialdb,)) if yn.lower() in ('y', 'yes', ''): self['dbdir'] = potentialdb else: raise usage.UsageError('Select another database with the -d option, then.') def getStoreDirectory(self): if self['dbdir'] is None: possibilities = glob.glob('*.axiom') if len(possibilities) > 1: raise usage.UsageError( "Multiple databases found here, please select one with " "the -d option: %s" % (' '.join(possibilities),)) elif len(possibilities) == 1: self.usedb(possibilities[0]) else: self.usedb(self.subCommand + '.axiom') return self['dbdir'] def getStore(self): from axiom.store import Store if self.store is None: self.store = Store(self.getStoreDirectory(), debug=self['debug']) return self.store def postOptions(self): if self.store is not None: self.store.close()
def testAttributeQueryCount(self): s = Store() def entesten(): E(store=s, name=u'a', amount=123) E(store=s, name=u'b', amount=456) E(store=s, name=u'c') # no amount given self.assertEquals(s.query(E).getColumn("amount").count(), 2) s.transact(entesten) s.close()
def testIndirectedPowerups(self): """ Powerups which implement L{IPowerupIndirector} should not be returned directly, the values that they return from indirect() should be returned directly. """ s = Store() mm = Summer(store=s) s.powerUp(SubtractThree(store=s, valueHaver=SumContributor(store=s, value=5)), IValueHaver) self.assertEquals(mm.doSum(), 2) s.close()
def testAttributeQueries(self): s = Store() def entesten(): E(store=s, name=u'b', amount=456) E(store=s, name=u'a', amount=123) E(store=s, name=u'c', amount=789) self.assertEquals( list(s.query(E, sort=E.name.ascending).getColumn("amount")), [123, 456, 789]) s.transact(entesten) s.close()
def testBasicPowerups(self): # tests an interaction between __conform__ and other stuff s = Store() mm = Summer(store=s) s.powerUp(mm, ISumProducer) s.powerUp(SumContributor(store=s, value=1), IValueHaver) s.powerUp(SumContributor(store=s, value=2), IValueHaver) s.powerUp(SumContributor(store=s, value=3), IValueHaver) self.assertEquals(mm.doSum(), 6) s.close()
def testBasicPowerups(self): # tests an interaction between __conform__ and other stuff s = Store() mm = Summer(store=s) s.powerUp(mm, ISumProducer) s.powerUp(SumContributor(store=s, value=1), IValueHaver) s.powerUp(SumContributor(store=s, value=2), IValueHaver) s.powerUp(SumContributor(store=s, value=3), IValueHaver) self.assertEqual(mm.doSum(), 6) s.close()
def testIndirectedPowerups(self): """ Powerups which implement L{IPowerupIndirector} should not be returned directly, the values that they return from indirect() should be returned directly. """ s = Store() mm = Summer(store=s) s.powerUp( SubtractThree(store=s, valueHaver=SumContributor(store=s, value=5)), IValueHaver) self.assertEqual(mm.doSum(), 2) s.close()
def testPowerupIdentity(self): s = Store() mm = Summer(store=s) s.powerUp(mm, ISumProducer) sc3 = SumContributor(store=s, value=3) s.powerUp(SumContributor(store=s, value=1), IValueHaver) s.powerUp(SumContributor(store=s, value=2), IValueHaver) s.powerUp(sc3, IValueHaver) s.powerUp(sc3, IValueHaver) self.assertEqual(mm.doSum(), 6) s.close()
def testPowerupIdentity(self): s = Store() mm = Summer(store=s) s.powerUp(mm, ISumProducer) sc3 = SumContributor(store=s, value=3) s.powerUp(SumContributor(store=s, value=1), IValueHaver) s.powerUp(SumContributor(store=s, value=2), IValueHaver) s.powerUp(sc3, IValueHaver) s.powerUp(sc3, IValueHaver) self.assertEquals(mm.doSum(), 6) s.close()
def testAttributeQueryDistinct(self): s = Store() def entesten(): E(store=s, name=u'a', amount=123) E(store=s, name=u'b', amount=789) E(store=s, name=u'a', amount=456) self.assertEquals( list( s.query( E, sort=E.name.ascending).getColumn("name").distinct()), [u"a", u"b"]) s.transact(entesten) s.close()
def testAggregateQueries(self): s = Store() def entesten(): self.assertEquals(s.query(E).count(), 0) self.assertEquals(s.query(E).getColumn("amount").sum(), 0) e1 = E(store=s, name=u'widgets', amount=37) e2 = E(store=s, name=u'widgets', amount=63) e3 = E(store=s, name=u'quatloos', amount=99, transaction=u'yes') s.checkpoint() q = s.count(E, E.name == u'widgets') self.failUnlessEqual(q, 2) q = s.sum(E.amount, E.name == u'widgets') self.failUnlessEqual(q, 100) s.transact(entesten) s.close()
def test_makeService(self): """ L{AxiomaticStart.makeService} returns the L{IService} powerup of the L{Store} at the directory in the options object it is passed. """ dbdir = FilePath(self.mktemp()) store = Store(dbdir) recorder = RecorderService(store=store) self.assertFalse(recorder.started) store.powerUp(recorder, IService) store.close() service = AxiomaticStart.makeService({"dbdir": dbdir, "debug": False}) service.startService() service.stopService() store = Store(dbdir) self.assertTrue(store.getItemByID(recorder.storeID).started)
def test_makeService(self): """ L{AxiomaticStart.makeService} returns the L{IService} powerup of the L{Store} at the directory in the options object it is passed. """ dbdir = FilePath(self.mktemp()) store = Store(dbdir) recorder = RecorderService(store=store) self.assertFalse(recorder.started) store.powerUp(recorder, IService) store.close() service = AxiomaticStart.makeService({"dbdir": dbdir, "debug": False}) service.startService() service.stopService() store = Store(dbdir) self.assertTrue(store.getItemByID(recorder.storeID).started)
def test_reactorSelection(self): """ L{AxiomaticStart} optionally takes the name of a reactor in the form --reactor [shortName] and installs it instead of the default reactor. """ # Since this process is already hopelessly distant from the state in # which I{axiomatic start} operates, it would make no sense to try a # functional test of this behavior in this process. Since the # behavior being tested involves lots of subtle interactions between # lots of different pieces of code (the reactor might get installed # at the end of a ten-deep chain of imports going through as many # different projects), it also makes no sense to try to make this a # unit test. So, start a child process and try to use the alternate # reactor functionality there. axiomatic = self._getAxiomaticScript() # Create a store for the child process to use and put an item in it. # This will force an import of the module that defines that item's # class when the child process starts. The module imports the default # reactor at the top-level, making this the worst-case for the reactor # selection code. storePath = self.mktemp() store = Store(storePath) SomeItem(store=store) store.close() # Install select reactor because it is available on all platforms, and # it is still an error to try to install the select reactor even if # the already installed reactor was the select reactor. argv = [ sys.executable, axiomatic, "-d", storePath, "start", "--reactor", "select", "-n" ] expected = [ "reactor class: twisted.internet.selectreactor.SelectReactor.", "reactor class: <class 'twisted.internet.selectreactor.SelectReactor'>" ] proto, complete = AxiomaticStartProcessProtocol.protocolAndDeferred( expected) environ = os.environ.copy() reactor.spawnProcess(proto, sys.executable, argv, env=environ) return complete
def testAttributeQueryMinMax(self): s = Store() def entesten(): E(store=s, amount=-4) E(store=s, amount=10) E(store=s, amount=99) E(store=s, amount=456) self.assertEquals(s.query(E).getColumn("amount").min(), -4) self.assertEquals(s.query(E).getColumn("amount").max(), 456) self.assertRaises(ValueError, s.query(D).getColumn("id").max) self.assertRaises(ValueError, s.query(D).getColumn("id").min) self.assertEquals(s.query(D).getColumn("id").min(default=41), 41) self.assertEquals(s.query(D).getColumn("id").max(default=42), 42) s.transact(entesten) s.close()
def testOneThing(self): topdb = self.mktemp() s = Store(topdb) ss = SubStore.createNew(s, ['account', '*****@*****.**']) s2 = ss.open() ssd = SubStored(store=s2, a=u'hello world', b='what, its text') oid = ss.storeID oid2 = ssd.storeID s2.close() s.close() reopens = Store(topdb) reopenss = reopens.getItemByID(oid) reopens2 = reopenss.open() reopenssd = reopens2.getItemByID(oid2) self.assertEquals(reopenssd.a, u'hello world') self.assertEquals(reopenssd.b, 'what, its text')
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 testOneThing(self): """ Ensure that items can be inserted into substores and subsequently retrieved. """ topdb = filepath.FilePath(self.mktemp()) s = Store(topdb) ss = SubStore.createNew(s, ['account', '*****@*****.**']) s2 = ss.open() ssd = SubStored(store=s2, a=u'hello world', b='what, its text') oid = ss.storeID oid2 = ssd.storeID s2.close() s.close() reopens = Store(topdb) reopenss = reopens.getItemByID(oid) reopens2 = reopenss.open() reopenssd = reopens2.getItemByID(oid2) self.assertEquals(reopenssd.a, u'hello world') self.assertEquals(reopenssd.b, 'what, its text')
def testOneThing(self): """ Ensure that items can be inserted into substores and subsequently retrieved. """ topdb = filepath.FilePath(self.mktemp()) s = Store(topdb) ss = SubStore.createNew(s, ['account', '*****@*****.**']) s2 = ss.open() ssd = SubStored(store=s2, a=u'hello world', b='what, its text') oid = ss.storeID oid2 = ssd.storeID s2.close() s.close() reopens = Store(topdb) reopenss = reopens.getItemByID(oid) reopens2 = reopenss.open() reopenssd = reopens2.getItemByID(oid2) self.assertEquals(reopenssd.a, u'hello world') self.assertEquals(reopenssd.b, 'what, its text')
print 'Lending', book.title, 'to', borrower book.lentTo = self.getBorrower(borrower) def main(s): for ll in s.query(LendingLibrary): print 'found existing library' break else: print 'creating new library' ll = LendingLibrary(store=s) ll.initialize() ll.displayBooks() print '***' ll.shuffleLending() print '---' ll.displayBooks() print '***' ll.shuffleLending() print '---' print s.count(Book, AND (Book.author == u'Stephen King', Book.title == u'The Lions of al-Rassan')) print s.count(Book, OR (Book.author == u'Stephen King', Book.title == u'The Lions of al-Rassan')) if __name__ == '__main__': s = Store('testdb') s.transact(main, s) s.close()
def test_reactorSelection(self): """ L{AxiomaticStart} optionally takes the name of a reactor and installs it instead of the default reactor. """ # Since this process is already hopelessly distant from the state in # which I{axiomatic start} operates, it would make no sense to try a # functional test of this behavior in this process. Since the # behavior being tested involves lots of subtle interactions between # lots of different pieces of code (the reactor might get installed # at the end of a ten-deep chain of imports going through as many # different projects), it also makes no sense to try to make this a # unit test. So, start a child process and try to use the alternate # reactor functionality there. here = FilePath(__file__) # Try to find it relative to the source of this test. bin = here.parent().parent().parent().child("bin") axiomatic = bin.child("axiomatic") if axiomatic.exists(): # Great, use that one. axiomatic = axiomatic.path else: # Try to find it on the path, instead. axiomatics = which("axiomatic") if axiomatics: # Great, it was on the path. axiomatic = axiomatics[0] else: # Nope, not there, give up. raise SkipTest( "Could not find axiomatic script on path or at %s" % (axiomatic.path, )) # Create a store for the child process to use and put an item in it. # This will force an import of the module that defines that item's # class when the child process starts. The module imports the default # reactor at the top-level, making this the worst-case for the reactor # selection code. storePath = self.mktemp() store = Store(storePath) SomeItem(store=store) store.close() # Install select reactor because it available on all platforms, and # it is still an error to try to install the select reactor even if # the already installed reactor was the select reactor. argv = [ sys.executable, axiomatic, "-d", storePath, "start", "--reactor", "select", "-n" ] expected = [ "reactor class: twisted.internet.selectreactor.SelectReactor.", "reactor class: <class 'twisted.internet.selectreactor.SelectReactor'>" ] proto, complete = AxiomaticStartProcessProtocol.protocolAndDeferred( expected) # Make sure the version of Axiom under test is found by the child # process. import axiom, epsilon environ = os.environ.copy() environ['PYTHONPATH'] = os.pathsep.join([ FilePath(epsilon.__file__).parent().parent().path, FilePath(axiom.__file__).parent().parent().path, environ['PYTHONPATH'] ]) reactor.spawnProcess(proto, sys.executable, argv, env=environ) return complete
for ll in s.query(LendingLibrary): print 'found existing library' break else: print 'creating new library' ll = LendingLibrary(store=s) ll.initialize() ll.displayBooks() print '***' ll.shuffleLending() print '---' ll.displayBooks() print '***' ll.shuffleLending() print '---' print s.count( Book, AND(Book.author == u'Stephen King', Book.title == u'The Lions of al-Rassan')) print s.count( Book, OR(Book.author == u'Stephen King', Book.title == u'The Lions of al-Rassan')) if __name__ == '__main__': s = Store('testdb') s.transact(main, s) s.close()
def testStringQueries(self): s = Store() def createAndStuff(): text1 = u'Hello, \u1234 world.' text2 = u'ThIs sTrInG iS nOt cAsE sEnSiTIvE. \u4567' bytes1 = '\x00, punk' x = ThingWithCharacterAndByteStrings( store=s, characterString=text1, caseInsensitiveCharString=text2, byteString=bytes1) x.checkpoint() q = list( s.query( ThingWithCharacterAndByteStrings, ThingWithCharacterAndByteStrings.characterString == text1.lower(), )) self.failIf(q, q) q = list( s.query( ThingWithCharacterAndByteStrings, ThingWithCharacterAndByteStrings.characterString == text1.upper(), )) self.failIf(q, q) q = list( s.query( ThingWithCharacterAndByteStrings, ThingWithCharacterAndByteStrings.characterString == text1, )) self.assertEquals(q, [x]) q = list( s.query( ThingWithCharacterAndByteStrings, ThingWithCharacterAndByteStrings.caseInsensitiveCharString == text2, )) self.assertEquals(q, [x]) q = list( s.query( ThingWithCharacterAndByteStrings, ThingWithCharacterAndByteStrings.caseInsensitiveCharString == text2.lower(), )) self.assertEquals(q, [x]) q = list( s.query( ThingWithCharacterAndByteStrings, ThingWithCharacterAndByteStrings.caseInsensitiveCharString == text2.upper(), )) self.assertEquals(q, [x]) q = list( s.query( ThingWithCharacterAndByteStrings, ThingWithCharacterAndByteStrings.byteString == bytes1, )) self.assertEquals(q, [x]) q = list( s.query( ThingWithCharacterAndByteStrings, ThingWithCharacterAndByteStrings.byteString == bytes1.upper(), )) self.failIf(q, q) s.transact(createAndStuff) s.close()
class CommandTestCase(unittest.TestCase): """ Integration tests for the 'axiomatic userbase' command. """ def setUp(self): self.dbdir = FilePath(self.mktemp()) self.store = Store(self.dbdir) def tearDown(self): self.store.close() def _login(self, avatarId, password): cc = ICredentialsChecker(self.store) p = Portal(IRealm(self.store), [cc]) return p.login(UsernamePassword(avatarId, password), None, lambda orig, default: orig) def assertImplements(self, obj, interface): """ Assert that C{obj} can be adapted to C{interface}. @param obj: Any Python object. @param interface: A L{zope.interface.Interface} that C{obj} should implement. """ self.assertTrue(interface.providedBy(interface(obj, None))) def userbase(self, *args): """ Run 'axiomatic userbase' with the given arguments on database at C{dbdir}. @return: A list of lines printed to stdout by the axiomatic command. """ output = io.StringIO() sys.stdout, stdout = output, sys.stdout try: axiomatic.main(['-d', self.dbdir.path, 'userbase'] + list(args)) finally: sys.stdout = stdout return output.getvalue().splitlines() def test_install(self): """ Create a database, install userbase and check that the store implements L{IRealm} and L{ICredentialsChecker}. i.e. that userbase has been installed. This is an integration test. """ self.userbase('install') self.assertImplements(self.store, IRealm) self.assertImplements(self.store, ICredentialsChecker) def test_userCreation(self): """ Create a user on a store, implicitly installing userbase, then try to log in with the user. This is an integration test. """ self.userbase('create', 'alice', 'localhost', SECRET) def cb(xxx_todo_changeme1): (interface, avatar, logout) = xxx_todo_changeme1 ss = avatar.avatars.open() self.assertEqual(list(userbase.getAccountNames(ss)), [('alice', 'localhost')]) self.assertEqual(avatar.password, SECRET) logout() d = self._login('alice@localhost', SECRET) return d.addCallback(cb) def test_listOnClean(self): """ Check that we are given friendly and informative output when we use 'userbase list' on a fresh store. """ output = self.userbase('list') self.assertEqual(output, ['No accounts']) def test_list(self): """ When users exist, 'userbase list' should print their IDs one to a line. """ self.userbase('create', 'alice', 'localhost', SECRET) self.userbase('create', 'bob', 'localhost', SECRET) output = self.userbase('list') self.assertEqual(output, ['alice@localhost', 'bob@localhost']) def test_listWithDisabled(self): """ Check that '[DISABLED]' is printed after the ID of users with disabled accounts. """ self.userbase('create', 'alice', 'localhost', SECRET) self.userbase('create', 'bob', 'localhost', SECRET) def cb(xxx_todo_changeme2): (interface, avatar, logout) = xxx_todo_changeme2 avatar.disabled = 1 output = self.userbase('list') self.assertEqual(output, ['alice@localhost', 'bob@localhost [DISABLED]']) return self._login('bob@localhost', SECRET).addCallback(cb) def test_listOffering(self): """ Mantissa offerings are added as users with a 'username' but no domain. Check that the 'list' command prints these correctly. """ name = 'offering-name' self.userbase('install') realm = IRealm(self.store) substoreItem = SubStore.createNew(self.store, ('app', name)) realm.addAccount(name, None, None, internal=True, avatars=substoreItem) output = self.userbase('list') self.assertEqual(output, [name])
class SystemVersionTests(unittest.TestCase, CommandStubMixin): """ Tests for recording the versions of software used to open a store throughout its lifetime. """ def setUp(self): """ Create an on-disk store. """ self.dbdir = self.mktemp() self.store = Store(self.dbdir) def _reopenStore(self): """ Close the store and reopen it. """ self.store.close() self.store = Store(self.dbdir) def test_getSystemVersions(self): """ L{getSystemVersions} returns all the version plugins it finds. """ someVersions = [Version("foo", 1, 2, 3), Version("baz", 0, 0, 1)] def getSomeVersions(iface, package): return someVersions self.assertEqual(getSystemVersions(getSomeVersions), someVersions) def test_checkSystemVersion(self): """ Calling checkSystemVersion: 1. Doesn't duplicate the system version when called with the same software package versions. 2. Creates a new system version when one of the software package versions has changed. 3. Notices and creates a new system version when the system config has reverted to a previous state. """ versions = [Version("foo", 1, 2, 3)] checkSystemVersion(self.store, versions) checkSystemVersion(self.store, versions) query_results = list(self.store.query(SystemVersion)) self.assertEquals(len(query_results), 1) # Adjust a version number and try again. v = versions[0] versions[0] = Version(v.package, v.major, v.minor + 1, v.micro) checkSystemVersion(self.store, versions) query_results = list(self.store.query(SystemVersion)) self.assertEquals(len(query_results), 2) # Revert the version number and try again. versions[0] = v checkSystemVersion(self.store, versions) query_results = list(self.store.query(SystemVersion)) self.assertEquals(len(query_results), 3) # Reopening the store does not duplicate the version. self._reopenStore() query_results = list(self.store.query(SystemVersion)) self.assertEquals(len(query_results), 3) def test_commandLine(self): """ L{ListVersions} will list versions of code used in this store when invoked as an axiomatic subcommand. """ checkSystemVersion(self.store) out = StringIO.StringIO() self.patch(sys, 'stdout', out) lv = ListVersions() lv.parent = self lv.parseOptions([]) result = out.getvalue() self.assertSubstring("axiom: " + axiom_version.short(), result) def test_axiomaticSubcommand(self): """ L{ListVersions} is available as a subcommand of I{axiomatic}. """ subCommands = AxiomaticOptions().subCommands [options] = [cmd[2] for cmd in subCommands if cmd[0] == 'list-version'] self.assertIdentical(options, ListVersions)
class SystemVersionTests(unittest.TestCase, CommandStubMixin): """ Tests for recording the versions of software used to open a store throughout its lifetime. """ def setUp(self): """ Create an on-disk store. """ self.dbdir = self.mktemp() self.store = Store(self.dbdir) def _reopenStore(self): """ Close the store and reopen it. """ self.store.close() self.store = Store(self.dbdir) def test_getSystemVersions(self): """ L{getSystemVersions} returns all the version plugins it finds. """ someVersions = [Version("foo", 1, 2, 3), Version("baz", 0, 0, 1)] def getSomeVersions(iface, package): return someVersions self.assertEqual(getSystemVersions(getSomeVersions), someVersions) def test_checkSystemVersion(self): """ Calling checkSystemVersion: 1. Doesn't duplicate the system version when called with the same software package versions. 2. Creates a new system version when one of the software package versions has changed. 3. Notices and creates a new system version when the system config has reverted to a previous state. """ versions = [Version("foo", 1, 2, 3)] checkSystemVersion(self.store, versions) checkSystemVersion(self.store, versions) query_results = list(self.store.query(SystemVersion)) self.assertEquals(len(query_results), 1) # Adjust a version number and try again. v = versions[0] versions[0] = Version(v.package, v.major, v.minor + 1, v.micro) checkSystemVersion(self.store, versions) query_results = list(self.store.query(SystemVersion)) self.assertEquals(len(query_results), 2) # Revert the version number and try again. versions[0] = v checkSystemVersion(self.store, versions) query_results = list(self.store.query(SystemVersion)) self.assertEquals(len(query_results), 3) # Reopening the store does not duplicate the version. self._reopenStore() query_results = list(self.store.query(SystemVersion)) self.assertEquals(len(query_results), 3) def test_commandLine(self): """ L{ListVersions} will list versions of code used in this store when invoked as an axiomatic subcommand. """ checkSystemVersion(self.store) out = StringIO.StringIO() self.patch(sys, "stdout", out) lv = ListVersions() lv.parent = self lv.parseOptions([]) result = out.getvalue() self.assertSubstring("axiom: " + axiom_version.short(), result) def test_axiomaticSubcommand(self): """ L{ListVersions} is available as a subcommand of I{axiomatic}. """ subCommands = AxiomaticOptions().subCommands [options] = [cmd[2] for cmd in subCommands if cmd[0] == "list-version"] self.assertIdentical(options, ListVersions)