def test_queryComparisons(self): """ Querying with an inequality on a L{RecordAttribute} should yield the same results as querying on its AND'ed component attributes. """ s = Store() RARc = RecordAttributeRequired.create x = RARc(store=s, sigma=Sigma(left=u'x', right=1)) y = RARc(store=s, sigma=Sigma(left=u'y', right=2)) z = RARc(store=s, sigma=Sigma(left=u'z', right=3)) a = RARc(store=s, sigma=Sigma(left=u'a', right=4)) self.assertEqual(list(s.query( RecordAttributeRequired, RecordAttributeRequired.sigma == Sigma(u'z', 3))), [z]) self.assertEqual(list(s.query( RecordAttributeRequired, RecordAttributeRequired.sigma == Sigma(u'z', 9))), []) self.assertEqual(list(s.query( RecordAttributeRequired, RecordAttributeRequired.sigma != Sigma(u'y', 2), sort=RecordAttributeRequired.storeID.ascending)), [x, z, a])
def test_deletePorts(self): """ I{axiomatic port delete} deletes each ports with a C{storeID} which is specified. """ store = Store(filesdir=self.mktemp()) factory = DummyFactory(store=store) deleteTCP = TCPPort( store=store, factory=factory, portNumber=10, interface=u"foo") keepTCP = TCPPort( store=store, factory=factory, portNumber=10, interface=u"bar") deleteSSL = SSLPort( store=store, factory=factory, portNumber=10, interface=u"baz", certificatePath=store.filesdir.child("baz")) keepSSL = SSLPort( store=store, factory=factory, portNumber=10, interface=u"quux", certificatePath=store.filesdir.child("quux")) deleteEndpoint = StringEndpointPort( store=store, factory=factory, description=u'tcp:1234') keepEndpoint = StringEndpointPort( store=store, factory=factory, description=u'tcp:1235') self.assertSuccessStatus( self._makeConfig(store), ["delete", "--port-identifier", str(deleteTCP.storeID), "--port-identifier", str(deleteSSL.storeID), "--port-identifier", str(deleteEndpoint.storeID)]) self.assertEqual("Deleted.\n", sys.stdout.getvalue()) self.assertEqual(list(store.query(TCPPort)), [keepTCP]) self.assertEqual(list(store.query(SSLPort)), [keepSSL]) self.assertEqual(list(store.query(StringEndpointPort)), [keepEndpoint])
def test_storeIDTiebreaker(self): """ Verify that items whose sort column are identical are all returned and deterministically ordered. """ s = Store() x = [SingleColumnSortHelper(store=s, mainColumn=1234) for nothing in range(10)] first = SingleColumnSortHelper(store=s, mainColumn=1233) last = SingleColumnSortHelper(store=s, mainColumn=1235) # This is sensitive to page size, so let's test it at lots of places # where edge-cases are likely to develop in the implementation. for pagesize in range(1, 30) + [1000]: # The ordering here in the asserts might look a little weird - that we # ascend by storeID in both cases regardless of the order of the sort, # but it's intentional. The storeID is merely to be a tiebreaker to # provide a stable sort. You could be sorting by any number of # compound columns, 'ascending' for your particular column might mean # something odd or contradictory to 'ascending' for storeID's # 'ascending'. If you want guaranteed stability on storeID, do that. self.assertEqual( list(s.query( SingleColumnSortHelper, sort=SingleColumnSortHelper.mainColumn.descending ).paginate(pagesize=pagesize)), [last] + x + [first]) self.assertEqual( list(s.query( SingleColumnSortHelper, sort=SingleColumnSortHelper.mainColumn.ascending ).paginate(pagesize=pagesize)), [first] + x + [last])
def testDisallowedComparisons(self): # These tests should go away; it's (mostly) possible to support # comparison of different precisions: # sqlite> select 1/3; # 0 # sqlite> select 3/1; # 3 # sqlite> select 3/2; # 1 s = Store() DecimalDoodad(store=s, integral=1, money=1) self.assertRaises(TypeError, lambda : s.query( DecimalDoodad, DecimalDoodad.integral == DecimalDoodad.money)) self.assertRaises(TypeError, lambda : s.query( DecimalDoodad, DecimalDoodad.integral == DecimalDoodad.extraintegral))
class Application (application.Application): def started(self): # database handling print self.path("db").path self.store = Store(self.path("db").child("storage").path) p = self.path("db").child("audio") if not p.exists(): p.createDirectory() # start AGI service f = fastagi.FastAGIFactory(self.connected) reactor.listenTCP( 4573, f, 50, '127.0.0.1') def connected(self, agi): print "current recordings:", list(self.store.query(Recording)) CallerSession(self, agi) def getIdleRecordings(self): r = list(self.store.query(Recording, Recording.filename == u"audio/idle")) if r: return r rec = Recording(store=self.store, filename=u'audio/idle') return [rec]
def test_storeIDTiebreaker(self): """ Verify that items whose sort column are identical are all returned and deterministically ordered. """ s = Store() x = [SingleColumnSortHelper(store=s, mainColumn=1234) for nothing in range(10)] first = SingleColumnSortHelper(store=s, mainColumn=1233) last = SingleColumnSortHelper(store=s, mainColumn=1235) # This is sensitive to page size, so let's test it at lots of places # where edge-cases are likely to develop in the implementation. for pagesize in list(range(1, 30)) + [1000]: # The ordering here in the asserts might look a little weird - that we # ascend by storeID in both cases regardless of the order of the sort, # but it's intentional. The storeID is merely to be a tiebreaker to # provide a stable sort. You could be sorting by any number of # compound columns, 'ascending' for your particular column might mean # something odd or contradictory to 'ascending' for storeID's # 'ascending'. If you want guaranteed stability on storeID, do that. self.assertEqual( list(s.query( SingleColumnSortHelper, sort=SingleColumnSortHelper.mainColumn.descending ).paginate(pagesize=pagesize)), [last] + x + [first]) self.assertEqual( list(s.query( SingleColumnSortHelper, sort=SingleColumnSortHelper.mainColumn.ascending ).paginate(pagesize=pagesize)), [first] + x + [last])
def test_queryComparisons(self): """ Querying with an inequality on a L{RecordAttribute} should yield the same results as querying on its AND'ed component attributes. """ s = Store() RARc = RecordAttributeRequired.create x = RARc(store=s, sigma=Sigma(left=u'x', right=1)) y = RARc(store=s, sigma=Sigma(left=u'y', right=2)) z = RARc(store=s, sigma=Sigma(left=u'z', right=3)) a = RARc(store=s, sigma=Sigma(left=u'a', right=4)) self.assertEqual( list( s.query(RecordAttributeRequired, RecordAttributeRequired.sigma == Sigma(u'z', 3))), [z]) self.assertEqual( list( s.query(RecordAttributeRequired, RecordAttributeRequired.sigma == Sigma(u'z', 9))), []) self.assertEqual( list( s.query(RecordAttributeRequired, RecordAttributeRequired.sigma != Sigma(u'y', 2), sort=RecordAttributeRequired.storeID.ascending)), [x, z, a])
def test_deletePorts(self): """ I{axiomatic port delete} deletes each ports with a C{storeID} which is specified. """ store = Store(filesdir=self.mktemp()) factory = DummyFactory(store=store) deleteTCP = TCPPort(store=store, factory=factory, portNumber=10, interface=u"foo") keepTCP = TCPPort(store=store, factory=factory, portNumber=10, interface=u"bar") deleteSSL = SSLPort( store=store, factory=factory, portNumber=10, interface=u"baz", certificatePath=store.filesdir.child("baz") ) keepSSL = SSLPort( store=store, factory=factory, portNumber=10, interface=u"quux", certificatePath=store.filesdir.child("quux") ) deleteEndpoint = StringEndpointPort(store=store, factory=factory, description=u"tcp:1234") keepEndpoint = StringEndpointPort(store=store, factory=factory, description=u"tcp:1235") self.assertSuccessStatus( self._makeConfig(store), [ "delete", "--port-identifier", str(deleteTCP.storeID), "--port-identifier", str(deleteSSL.storeID), "--port-identifier", str(deleteEndpoint.storeID), ], ) self.assertEqual("Deleted.\n", sys.stdout.getvalue()) self.assertEqual(list(store.query(TCPPort)), [keepTCP]) self.assertEqual(list(store.query(SSLPort)), [keepSSL]) self.assertEqual(list(store.query(StringEndpointPort)), [keepEndpoint])
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 testCompoundSort(self): s = Store() L = [] r10 = list(range(10)) random.shuffle(r10) L.append(SortedItem(store=s, goingUp=0, goingDown=1000, theSame=8)) for x in r10: L.append(SortedItem(store=s, goingUp=10+x, goingDown=10-x, theSame=7)) for colnms in [['goingUp'], ['goingUp', 'storeID'], ['goingUp', 'theSame'], ['theSame', 'goingUp'], ['theSame', 'storeID']]: LN = L[:] LN.sort(key=lambda si: tuple([getattr(si, colnm) for colnm in colnms])) ascsort = [getattr(SortedItem, colnm).ascending for colnm in colnms] descsort = [getattr(SortedItem, colnm).descending for colnm in colnms] self.assertEqual(LN, list(s.query(SortedItem, sort=ascsort))) LN.reverse() self.assertEqual(LN, list(s.query(SortedItem, sort=descsort)))
class CalendarDatabase: """ Database object for calendar""" def __init__(self): self.store = Store('/usr/local/tcs/tums/calendar.axiom') def createEntry(self, owner, date, stTime, enTime, descrip, email=False, repeat=0, vacation=False, private=False): day, month, year = date hourS, minuteS = stTime hourE, minuteE = enTime ehash = sha.sha('%s:%s:%s:%s%s' % (time.time(), day, month, year, owner)).hexdigest() calEnt = self.store.findOrCreate(CalendarEntry, owner=owner, day=day, month=month, year=year, hourS=hourS, minuteS=minuteS, hourE=hourE, minuteE=minuteE, descrip=descrip, emailAlert=email, repeats=repeat, vacation=vacation, private=private, ehash=ehash) return calEnt def getEntriesMonth(self, owner, month, year): viewers = [ i.owner for i in self.store.query( CalendarShareMapper, CalendarShareMapper.viewer == owner) ] owned = [owner] owned.extend(viewers) return self.store.query( CalendarEntry, AND(CalendarEntry.owner in owned, CalendarEntry.month == month, CalendarEntry.year == year)) def getEntriesDay(self, owner, day, month, year): return self.store.query( CalendarEntry, AND(CalendarEntry.owner == owner, CalendarEntry.day == day, CalendarEntry.month == month, CalendarEntry.year == year))
def testSanity(self): store = Store() for i in xrange(self.ntimes): SimpleReferent(store=store, ref=Referee(store=store, topSecret=i)) (referee,) = list(store.query(Referee)) (referent,) = list(store.query(SimpleReferent)) self.assertEqual(referent.ref.topSecret, referee.topSecret) referee.deleteFromStore() referent.deleteFromStore()
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 testSanity(self): store = Store() for i in xrange(self.ntimes): SimpleReferent(store=store, ref=Referee(store=store, topSecret=i)) (referee, ) = list(store.query(Referee)) (referent, ) = list(store.query(SimpleReferent)) self.assertEqual(referent.ref.topSecret, referee.topSecret) referee.deleteFromStore() referent.deleteFromStore()
def testFPSumsAreBrokenSoDontUseThem(self): s = Store() for x in range(10): Number(store=s, value=0.1) self.assertNotEquals(s.query(Number).getColumn("value").sum(), 1.0) # This isn't really a unit test. It's documentation. self.assertEquals( s.query(Number).getColumn("value").sum(), 0.99999999999999989)
def testBatchReferenceDeletion(self): """ Test that batch deletion removes dependent items correctly. """ store = Store() referee = Referee(store=store, topSecret=0) dep = DependentReferent(store=store, ref=referee) sid = dep.storeID store.query(Referee).deleteFromStore() self.assertRaises(KeyError, store.getItemByID, sid)
def test_removeSession(self): """ L{PersistentSessionWrapper.removeSessionWithKey} removes an existing session with the given key. """ store = Store() resource = PersistentSessionWrapper(store, None) resource.createSessionForKey(b'key', b'username@domain') self.assertEqual(store.query(PersistentSession).count(), 1) resource.removeSessionWithKey(b'key') self.assertEqual(store.query(PersistentSession).count(), 0)
def testFPSumsAreBrokenSoDontUseThem(self): s = Store() for x in range(10): Number(store=s, value=0.1) self.assertNotEqual(s.query(Number).getColumn("value").sum(), 1.0) # This isn't really a unit test. It's documentation. self.assertEqual(s.query(Number).getColumn("value").sum(), 0.99999999999999989)
def test_logoutRemovesSession(self): """ Logging out explicitly removes your persistent session. """ store = Store() resource = PersistentSessionWrapper(store, None) session = GuardSession(resource, b'uid') resource.createSessionForKey(session.uid, b'username@domain') self.assertEqual(store.query(PersistentSession).count(), 1) resource.explicitLogout(session) self.assertEqual(store.query(PersistentSession).count(), 0)
def testSum(self): s = Store() for x in range(10): DecimalDoodad(store=s, money=Decimal("0.10")) self.assertEqual(s.query(DecimalDoodad).getColumn("money").sum(), 1)
def testComparisons(self): s = Store() DecimalDoodad(store=s, money=Decimal("19947.000000"), otherMoney=19947) self.assertEquals( s.query(DecimalDoodad, DecimalDoodad.money == DecimalDoodad.otherMoney).count(), 1) self.assertEquals( s.query(DecimalDoodad, DecimalDoodad.money != DecimalDoodad.otherMoney).count(), 0) self.assertEquals( s.query(DecimalDoodad, DecimalDoodad.money == 19947).count(), 1) self.assertEquals( s.query(DecimalDoodad, DecimalDoodad.money == Decimal("19947")).count(), 1)
def test_createSSLPortInconsistentCertificateAndKeyFiles(self): """ If different values are specified for the certificate file and the private key file when creating an SSL port with I{axiomatic port create}, a short error message is written to standard output. This reflects an implementation limitation which may be lifted in the future. """ certPath = FilePath(self.mktemp()) certPath.setContent(CERTIFICATE_DATA) keyPath = FilePath(self.mktemp()) keyPath.setContent(PRIVATEKEY_DATA) store = Store() factory = DummyFactory(store=store) self.assertFailStatus( 1, self._makeConfig(store), ["create", "--strport", "ssl:8443:privateKey=" + keyPath.path + ":certKey=" + certPath.path, "--factory-identifier", str(factory.storeID)]) self.assertEqual( "You must specify the same file for certKey and privateKey.\n", sys.stdout.getvalue()) self.assertEqual(store.query(SSLPort).count(), 0)
def test_moreItemsNotMoreWork(self): """ Verify that each step of a paginate does not become more work as items are added. """ s = Store() self._checkEfficiency(s.query(SingleColumnSortHelper))
class DraftCorrespondentTestCase(TestCase): """ Test that L{xquotient.exmess.Correspondent} items are created for the related addresses of draft messages at creation time """ def setUp(self): """ Make a draft message using an L{xquotient.iquotient.IMessageData} with a bunch of related addresses """ self.store = Store() self.messageData = DummyMessageImplWithABunchOfAddresses( store=self.store) self.message = Message.createDraft(self.store, self.messageData, u'test') def test_correspondents(self): """ Test that the correspondent items in the store match the related addresses of our L{xquotient.iquotient.IMessageData} """ for (rel, addr) in self.messageData.relatedAddresses(): self.assertEqual( self.store.query( Correspondent, AND(Correspondent.relation == rel, Correspondent.address == addr.email, Correspondent.message == self.message)).count(), 1, 'no Correspondent for rel %r with addr %r' % (rel, addr.email))
def test_createSSLPortInconsistentCertificateAndKeyFiles(self): """ If different values are specified for the certificate file and the private key file when creating an SSL port with I{axiomatic port create}, a short error message is written to standard output. This reflects an implementation limitation which may be lifted in the future. """ certPath = FilePath(self.mktemp()) certPath.setContent(CERTIFICATE_DATA) keyPath = FilePath(self.mktemp()) keyPath.setContent(PRIVATEKEY_DATA) store = Store() factory = DummyFactory(store=store) self.assertFailStatus(1, self._makeConfig(store), [ "create", "--strport", "ssl:8443:privateKey=" + keyPath.path + ":certKey=" + certPath.path, "--factory-identifier", str(factory.storeID) ]) self.assertEqual( "You must specify the same file for certKey and privateKey.\n", sys.stdout.getvalue()) self.assertEqual(store.query(SSLPort).count(), 0)
def testUserLoginMethodCreator(self): dbdir = FilePath(self.mktemp()) s = Store(dbdir) ls = userbase.LoginSystem(store=s) acc = ls.addAccount('username', 'example.com', 'password') ss = acc.avatars.open() subStoreLoginAccount = ss.findUnique(userbase.LoginAccount) # Do everything twice to make sure repeated calls don't corrupt state # somehow for i in [0, 1]: subStoreLoginAccount.addLoginMethod( localpart='anothername', domain='example.org', verified=True, protocol='test', internal=False) loginMethods = s.query( userbase.LoginMethod, sort=userbase.LoginMethod.storeID.ascending) subStoreLoginMethods = ss.query( userbase.LoginMethod, sort=userbase.LoginMethod.storeID.ascending) self.assertEqual(loginMethods.count(), 2) self.assertEqual( [pvals(m) for m in loginMethods], [pvals(m) for m in subStoreLoginMethods])
def test_createSSLPort(self): """ If a given valid strport description of an SSL port and the storeID of an extant factory, I{axiomatic port create} creates a new L{SSLPort} with the specified configuration and referring to that factory. The certificate file specified is copied to a path inside the Store's files directory. The port is also powered up on the store for L{IService}. """ pemPath = FilePath(self.mktemp()) pemPath.setContent(CERTIFICATE_DATA + PRIVATEKEY_DATA) store = Store(filesdir=self.mktemp()) factory = DummyFactory(store=store) self.assertSuccessStatus(self._makeConfig(store), [ "create", "--strport", "ssl:8443:certKey=" + pemPath.path + ":privateKey=" + pemPath.path, "--factory-identifier", str(factory.storeID) ]) self.assertEqual("Created.\n", sys.stdout.getvalue()) [ssl] = list(store.query(SSLPort)) self.assertEqual(ssl.portNumber, 8443) self.assertEqual(ssl.certificatePath.getContent(), CERTIFICATE_DATA + PRIVATEKEY_DATA) self.assertIdentical(ssl.factory, factory) self.assertEqual(pemPath.getContent(), CERTIFICATE_DATA + PRIVATEKEY_DATA) self.assertEqual(list(store.interfacesFor(ssl)), [IService])
def testReferenceQuery(self): store = Store() referee = Referee(store=store, topSecret=0) self.assertEqual( list(store.query(SimpleReferent, SimpleReferent.ref == Referee.storeID)), [])
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)), [])
def testReferenceQuery(self): store = Store() referee = Referee(store=store, topSecret=0) self.assertEqual( list( store.query(SimpleReferent, SimpleReferent.ref == Referee.storeID)), [])
class DraftCorrespondentTestCase(TestCase): """ Test that L{xquotient.exmess.Correspondent} items are created for the related addresses of draft messages at creation time """ def setUp(self): """ Make a draft message using an L{xquotient.iquotient.IMessageData} with a bunch of related addresses """ self.store = Store() self.messageData = DummyMessageImplWithABunchOfAddresses( store=self.store) self.message = Message.createDraft( self.store, self.messageData, u'test') def test_correspondents(self): """ Test that the correspondent items in the store match the related addresses of our L{xquotient.iquotient.IMessageData} """ for (rel, addr) in self.messageData.relatedAddresses(): self.assertEqual( self.store.query( Correspondent, AND(Correspondent.relation == rel, Correspondent.address == addr.email, Correspondent.message == self.message)).count(), 1, 'no Correspondent for rel %r with addr %r' % (rel, addr.email))
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)), [])
def test_createSSLPort(self): """ If a given valid strport description of an SSL port and the storeID of an extant factory, I{axiomatic port create} creates a new L{SSLPort} with the specified configuration and referring to that factory. The certificate file specified is copied to a path inside the Store's files directory. The port is also powered up on the store for L{IService}. """ pemPath = FilePath(self.mktemp()) pemPath.setContent(CERTIFICATE_DATA + PRIVATEKEY_DATA) store = Store(filesdir=self.mktemp()) factory = DummyFactory(store=store) self.assertSuccessStatus( self._makeConfig(store), ["create", "--strport", "ssl:8443:certKey=" + pemPath.path + ":privateKey=" + pemPath.path, "--factory-identifier", str(factory.storeID)]) self.assertEqual("Created.\n", sys.stdout.getvalue()) [ssl] = list(store.query(SSLPort)) self.assertEqual(ssl.portNumber, 8443) self.assertEqual( ssl.certificatePath.getContent(), CERTIFICATE_DATA + PRIVATEKEY_DATA) self.assertIdentical(ssl.factory, factory) self.assertEqual( pemPath.getContent(), CERTIFICATE_DATA + PRIVATEKEY_DATA) self.assertEqual(list(store.interfacesFor(ssl)), [IService])
def test_moreItemsNotMoreWorkSorted(self): """ Verify that each step of a paginate does not become more work as more items are added even if a sort is given. """ s = Store() self._checkEfficiency(s.query(SingleColumnSortHelper, sort=SingleColumnSortHelper.mainColumn.ascending))
def main(): s = Store("TEMPORARY.axiom") rows = [(x, unicode(x)) for x in xrange(10000)] s.transact(lambda: s.batchInsert(AB, (AB.a, AB.b), rows)) benchmark.start() s.transact(s.query(AB).deleteFromStore) benchmark.stop()
def test_checkSystemVersion(self): """ The L{IService} returned by L{AxiomaticStart.makeService} calls L{checkSystemVersion} with its store when it is started. This is done for I{axiomatic start} rather than somewhere in the implementation of L{Store} so that it happens only once per server startup. The overhead of doing it whenever a store is opened is non-trivial. """ dbdir = self.mktemp() store = Store(dbdir) service = AxiomaticStart.makeService({'dbdir': dbdir, 'debug': False}) self.assertEqual(store.query(SystemVersion).count(), 0) service.startService() self.assertEqual(store.query(SystemVersion).count(), 1) return service.stopService()
def test_cannotDeleteOtherStuff(self): """ I{axiomatic port delete} will not delete something which is neither a L{TCPPort} nor an L{SSLPort} and does not delete anything if an invalid port identifier is present in the command. """ store = Store() factory = DummyFactory(store=store) tcp = TCPPort(store=store, factory=factory, interface=u"foo", portNumber=1234) self.assertFailStatus( 1, self._makeConfig(store), ["delete", "--port-identifier", str(tcp.storeID), "--port-identifier", str(factory.storeID)], ) self.assertEqual("%d does not identify a port.\n" % (factory.storeID,), sys.stdout.getvalue()) self.assertEqual(list(store.query(DummyFactory)), [factory]) self.assertEqual(list(store.query(TCPPort)), [tcp])
def testExtraction(self): s = Store() part = SimplePart(store=s, myText=u'this is simple text') mesg = exmess.Message(store=s, impl=part) origRegex = extract.EmailAddressExtract.regex try: extract.EmailAddressExtract.regex = re.compile('simple') extract.EmailAddressExtract.extract(mesg) (theExtract, ) = list(s.query(extract.EmailAddressExtract)) def checkExtract(e): self.assertEqual(e.text, 'simple') self.assertEqual('this is simple text'[e.start:e.end], 'simple') self.assertIdentical(e.message, mesg) checkExtract(theExtract) # and again extract.EmailAddressExtract.extract(mesg) (theSameExtract, ) = list(s.query(extract.EmailAddressExtract)) self.assertIdentical(theExtract, theSameExtract) checkExtract(theSameExtract) extract.EmailAddressExtract.regex = re.compile('complicated') part = SimplePart(store=s, myText=u'life is complicated') mesg2 = exmess.Message(store=s, impl=part) extract.EmailAddressExtract.extract(mesg2) (theOldExtract, theNewExtract) = list( s.query(extract.EmailAddressExtract, sort=extract.EmailAddressExtract.timestamp.asc)) checkExtract(theOldExtract) self.assertEqual(theNewExtract.text, 'complicated') self.assertEqual( 'life is complicated'[theNewExtract.start:theNewExtract.end], 'complicated') self.assertIdentical(theNewExtract.message, mesg2) finally: extract.EmailAddressExtract.regex = origRegex
def test_query(self): """ Verify that queries tell you something about their target and comparison. """ s = Store() R = repr(s.query(ReprTesterItemClass, ReprTesterItemClass.intattr == 1)) self.assertIn('intattr', R) self.assertIn(ReprTesterItemClass.__name__, R)
def testBrokenReferenceDisallow(self): """ Test that deleting an item referred to by a whenDeleted == DISALLOW reference raises an exception. """ store = Store() referee = Referee(store=store, topSecret=0) referent = DisallowReferent(store=store, ref=referee) self.assertRaises(DeletionDisallowed, referee.deleteFromStore) self.assertRaises(DeletionDisallowed, store.query(Referee).deleteFromStore)
def cb(fpath): fpath.open("w").write(TEST_STR) PathTesterItem(store=s, relpath=fpath) s.close() os.rename(spath, npath) s2 = Store(npath) pti = list(s2.query(PathTesterItem))[0] self.assertEquals(pti.relpath.open().read(), TEST_STR)
def testBadReferenceNone(self): store = Store() referee = Referee(store=store, topSecret=0) referent = SimpleReferent(store=store, ref=referee) referee.deleteFromStore() referee = None gc.collect() (referent,) = list(store.query(SimpleReferent)) self.assertEqual(referent.ref, None)
def cb(fpath): fpath.setContent(TEST_STR) PathTesterItem(store=s, relpath=fpath) s.close() os.rename(spath, npath) s2 = Store(npath) pti = list(s2.query(PathTesterItem))[0] self.assertEquals(pti.relpath.getContent(), TEST_STR)
def cb(fpath): fpath.setContent(TEST_STR) PathTesterItem(store=s, relpath=fpath) s.close() os.rename(spath, npath) s2 = Store(npath) pti = list(s2.query(PathTesterItem))[0] self.assertEqual(pti.relpath.getContent(), TEST_STR)
def testComparisons(self): s = Store() DecimalDoodad(store=s, money=Decimal("19947.000000"), otherMoney=19947) self.assertEqual( s.query(DecimalDoodad, DecimalDoodad.money == DecimalDoodad.otherMoney).count(), 1) self.assertEqual( s.query(DecimalDoodad, DecimalDoodad.money != DecimalDoodad.otherMoney).count(), 0) self.assertEqual( s.query(DecimalDoodad, DecimalDoodad.money == 19947).count(), 1) self.assertEqual( s.query(DecimalDoodad, DecimalDoodad.money == Decimal("19947")).count(), 1)
class UserTest(TestCase): def setUp(self): self.store = Store() def test_attrs(self): """ Should have these attributes """ u = User(store=self.store) self.assertEqual(u.store, self.store) self.assertEqual(u.name, None) def test_createAvatar(self): """ Creates a Thing that can act on my behalf in the World """ u = User(store=self.store, name=u'bojimbo') a = u.createAvatar() self.assertIsInstance(a, Thing) self.assertEqual(a.store, self.store) self.assertEqual(a.name, 'bojimbo') self.assertEqual(a.owner, u) actor = IActor(a) self.assertEqual(actor.user, u) self.assertEqual(actor.thing, a) def test_avatars(self): """ Should return the list of all created avatars. """ u = User(store=self.store) self.assertEqual(list(u.avatars()), []) a1 = u.createAvatar() self.assertEqual(list(u.avatars()), [a1]) a2 = u.createAvatar() them = list(u.avatars()) self.assertTrue(a1 in them) self.assertTrue(a2 in them) self.assertEqual(len(them), 2) a2.deleteFromStore() self.assertEqual(list(u.avatars()), [a1]) self.assertEqual(self.store.query(UserActor).count(), 1, "Should delete" "from the store")
def test_separateTransactions(self): """ Verify that 'paginate' is iterable in separate transactions. """ s = Store() b1 = SingleColumnSortHelper(store=s, mainColumn=1) b2 = SingleColumnSortHelper(store=s, mainColumn=2) b3 = SingleColumnSortHelper(store=s, mainColumn=3) itr = s.transact(lambda : iter(s.query(SingleColumnSortHelper).paginate())) self.assertIdentical(s.transact(itr.__next__), b1) self.assertEqual(s.transact(lambda : (next(itr), next(itr))), (b2, b3)) self.assertRaises(StopIteration, lambda : s.transact(itr.__next__))