Ejemplo n.º 1
0
    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])
Ejemplo n.º 2
0
    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, [])
Ejemplo n.º 3
0
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]
Ejemplo n.º 4
0
 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/')
Ejemplo n.º 5
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))
Ejemplo n.º 6
0
 def _store(self):
     store = Store(self.mktemp())
     store.inMemoryPowerUp(NullUploadScheduler(), IUploadScheduler)
     contentStore = ContentStore(store=store)
     store.powerUp(contentStore, IContentStore)
     object.__setattr__(contentStore, '_deferToThreadPool', execute)
     return contentStore
Ejemplo n.º 7
0
    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])
Ejemplo n.º 8
0
 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])
Ejemplo n.º 9
0
 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"))
     self.assertSuccessStatus(
         self._makeConfig(store),
         ["delete",
          "--port-identifier", str(deleteTCP.storeID),
          "--port-identifier", str(deleteSSL.storeID)])
     self.assertEqual("Deleted.\n", sys.stdout.getvalue())
     self.assertEqual(list(store.query(TCPPort)), [keepTCP])
     self.assertEqual(list(store.query(SSLPort)), [keepSSL])
Ejemplo n.º 10
0
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)
Ejemplo n.º 11
0
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)
Ejemplo n.º 12
0
 def testReferenceQuery(self):
     store = Store()
     referee = Referee(store=store, topSecret=0)
     self.assertEqual(
         list(store.query(SimpleReferent,
                          SimpleReferent.ref == Referee.storeID)),
         [])
Ejemplo n.º 13
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)
Ejemplo n.º 14
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])
Ejemplo n.º 15
0
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)), [])
Ejemplo n.º 16
0
    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
Ejemplo n.º 17
0
    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))
Ejemplo n.º 18
0
def initialize(db: store.Store, options: usage.Options):
    initializers = []
    initializePermissions(db)
    adm = IEmployee(1, None)
    if not adm:
        adm = IEmployee(NULL)
        adm.employee_id = 1
        adm.alternate_authentication = StaticAuthenticationMethod(store=adm.store).setPassword("xyzzy")
        adm1 = IAdministrator(NULL)
        adm1.employee = adm
        adm.powerUp(adm1, IAdministrator)

    if db.filesdir:
        l = Logger(store=db.store)

        l.file = File(store=db.store, path=db.store.filesdir.child('Commands.log').path)
        l.flags = 1 | 2 | 4 | 8
        l.name = "Command Logger"
        IEventBus("Commands").powerUp(l, ICommandEvent)
        initializers = [initializeCommands, initializeAPIs]

    if Solomon.pymssql:
        initializers.append(initializeSubAccounts)
        initializers.append(initializeWorkLocations)
        initializers.append(lambda d: initializeDB(d, options))
    else:
        wl = IWorkLocation(NULL)
        wl.description = 'test'
        wl.workLocationID = "TST"
        sa = ISubAccount(NULL)
        sa.name = 'test'
        sa.sub = 1
    db.transact(lambda: [i(db) for i in initializers])
Ejemplo n.º 19
0
    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)))
Ejemplo n.º 20
0
    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)
Ejemplo n.º 21
0
    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
Ejemplo n.º 22
0
 def testRoundTrip(self):
     s = Store()
     DecimalDoodad(store=s, integral=19947,
                   money=Decimal("4.3"),
                   otherMoney=Decimal("-17.94"))
     self.assertEqual(s.findFirst(DecimalDoodad).integral, 19947)
     self.assertEqual(s.findFirst(DecimalDoodad).money, Decimal("4.3"))
     self.assertEqual(s.findFirst(DecimalDoodad).otherMoney, Decimal("-17.9400"))
Ejemplo n.º 23
0
 def test_storeIDAccessor(self):
     """
     Test that the __get__ of the IColumn implementation for storeID works
     the same as that for normal attributes.
     """
     s = Store()
     dummy = FullImplementationDummyClass(store=s)
     self.assertIdentical(s.getItemByID(dummy.storeID), dummy)
Ejemplo n.º 24
0
 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))
Ejemplo n.º 25
0
 def testReferenceDeletion(self):
     store = Store()
     referee = Referee(store=store, topSecret=0)
     dep = DependentReferent(store=store,
                             ref=referee)
     sid = dep.storeID
     self.assertIdentical(store.getItemByID(sid), dep) # sanity
     referee.deleteFromStore()
     self.assertRaises(KeyError, store.getItemByID, sid)
Ejemplo n.º 26
0
def main():
    s = Store("TEMPORARY.axiom")
    def txn():
        for x in range(10000):
            AB(a=x, b=unicode(x), store=s)

    benchmark.start()
    s.transact(txn)
    benchmark.stop()
Ejemplo n.º 27
0
 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()
Ejemplo n.º 28
0
 def test_powerItUp(self):
     """
     Powering up a store with an C{AboutPlugin} results in it being installed
     as an L{ISiteRootPlugin} powerup.
     """
     s = Store()
     ap = self.aboutpage.AboutPlugin(store=s)
     s.powerUp(ap)
     self.assertEquals([ap], list(s.powerupsFor(ISiteRootPlugin)))
Ejemplo n.º 29
0
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
Ejemplo n.º 30
0
 def testStoreServicePowerup(self):
     s = Store()
     ss = SillyService(store=s)
     s.powerUp(ss, IService)
     IService(s).startService()
     IService(s).stopService()
     self.assertEquals(ss.started, 1)
     self.assertEquals(ss.stopped, 1)
     self.assertEquals(ss.running, 0)
Ejemplo n.º 31
0
 def setUp(self):
     """
     Set up the tests by creating a store and a substore and opening them
     both.
     """
     self.topdb = topdb = Store(filepath.FilePath(self.mktemp()))
     self.ssitem = ssitem = SubStore.createNew(
         topdb, ["dontstartme", "really"])
     self.ss = ssitem.open()
     self.serviceStarted = False
Ejemplo n.º 32
0
    def test_makeService(self):
        """The service maker grabs the store from the options, and passes it
        to ``service.Service``.

        """
        maker = service.ServiceMaker()
        store = Store()
        svc = maker.makeService({"store": store})
        self.assertTrue(isinstance(svc, service.Service))
        self.assertIdentical(svc.store, store)
Ejemplo n.º 33
0
    def test_insertEmpty(self):
        """
        Inserting a value that is empty after normalization instead deletes
        the entry.
        """
        s = Store()

        def _tx():
            SearchEntry.insert(s, SearchClasses.EXACT, u'e', u'i', u'RESULT',
                               u'type', u'. /')
            self.assertThat(s.query(SearchEntry).count(), Equals(0))
            SearchEntry.insert(s, SearchClasses.EXACT, u'e', u'i', u'RESULT',
                               u'type', u'yo')
            self.assertThat(s.query(SearchEntry).count(), Equals(1))
            SearchEntry.insert(s, SearchClasses.EXACT, u'e', u'i', u'RESULT',
                               u'type', u'. /')
            self.assertThat(s.query(SearchEntry).count(), Equals(0))

        s.transact(_tx)
Ejemplo n.º 34
0
    def test_uniqueSerial(self):
        """
        Test that 'axiomatic mantissa' generates SSL certificates with a
        different unique serial on each invocation.
        """
        m = Mantissa()
        m.parent = self

        self.dbdir = self.mktemp()
        self.store = Store(self.dbdir)
        m.parseOptions(['--admin-password', 'foo'])
        cert1 = self._getCert()

        self.dbdir = self.mktemp()
        self.store = Store(self.dbdir)
        m.parseOptions(['--admin-password', 'foo'])
        cert2 = self._getCert()

        self.assertNotEqual(cert1.serialNumber(), cert2.serialNumber())
Ejemplo n.º 35
0
 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)
Ejemplo n.º 36
0
 def makeService(cls, options):
     """
     Create an L{IService} for the database specified by the given
     configuration.
     """
     from axiom.store import Store
     store = Store(options['dbdir'], debug=options['debug'])
     service = IService(store)
     _CheckSystemVersion(store).setServiceParent(service)
     return service
Ejemplo n.º 37
0
 def test_logoffButton(self):
     """
     L{ShellServer._logoffButton} returns a L{Button} which, when activated,
     disconnects the terminal.
     """
     terminal = FakeTerminal()
     server = ShellServer(Store())
     server.makeConnection(terminal)
     server._logoffButton().onPress()
     self.assertTrue(terminal.disconnected)
Ejemplo n.º 38
0
 def test_retrieveSession(self):
     """
     L{PersistentSessionWrapper.authenticatedUserForKey} returns the user to
     whom a session belongs.
     """
     store = Store()
     resource = PersistentSessionWrapper(store, None)
     resource.createSessionForKey(b'key', b'username@domain')
     user = resource.authenticatedUserForKey(b'key')
     self.assertEqual(user, b'username@domain')
Ejemplo n.º 39
0
 def test_badAttribute(self):
     """
     L{Item} should not allow setting undeclared attributes.
     """
     s = Store()
     err = self.failUnlessRaises(AttributeError,
                                 FunkyItem,
                                 store=s,
                                 name=u"foo")
     self.assertEquals(str(err), "'FunkyItem' can't set attribute 'name'")
Ejemplo n.º 40
0
 def test_finds_success(self):
     """
     L{randomEntry} returns the only result available.
     """
     store = Store()
     self.useFixture(FullTextIndexerFixture(store))
     manager = linkdb.LinkManager(store=store, channel=u'foo')
     entry = manager.createEntry(u'bar', u'baz', u'title')
     result = manager.randomEntry()
     self.assertIs(result, entry)
Ejemplo n.º 41
0
 def setUp(self):
     self.store = Store()
     # Cheat so getSelfRole will work...
     lm = LoginMethod(store=self.store,
                      localpart=u'me',
                      domain=u'here',
                      internal=True,
                      protocol=u'*',
                      account=self.store,
                      verified=True)
Ejemplo n.º 42
0
 def test_createNewStringPath(self):
     """
     Passing a string instead of a sequence of strings to
     L{SubStore.createNew} results in an exception.
     """
     s = Store()
     e = self.assertRaises(
         ValueError, SubStore.createNew, s, 'notasequence')
     self.assertEqual(
         e.args[0], "Received 'notasequence' instead of a sequence")
Ejemplo n.º 43
0
    def test_createSSLPortNonExistentKeyFile(self):
        """
        Specifying a private key file which does not exist when creating an SSL
        port with I{axiomatic port create} causes a short error message to be
        written to stdout.
        """
        pemPath = FilePath(self.mktemp())
        pemPath.setContent(CERTIFICATE_DATA)

        store = Store()
        factory = DummyFactory(store=store)
        self.assertFailStatus(1, self._makeConfig(store), [
            "create", "--strport", "ssl:8443:privateKey=quux:certKey=" +
            pemPath.path, "--factory-identifier",
            str(factory.storeID)
        ])
        self.assertEqual("Specified private key file does not exist.\n",
                         sys.stdout.getvalue())
        self.assertEqual(store.query(SSLPort).count(), 0)
Ejemplo n.º 44
0
 def test_roleIn(self):
     """
     L{_AuthenticatedShellViewer.roleIn} returns a L{Role} for one of the
     account names passed to L{_AuthenticatedShellViewer.__init__}.
     """
     store = Store()
     viewer = _AuthenticatedShellViewer([(u"alice", u"example.com")])
     role = viewer.roleIn(store)
     self.assertEquals(role.externalID, u"*****@*****.**")
     self.assertIdentical(role.store, store)
Ejemplo n.º 45
0
 def testItemServicePowerup(self):
     s = Store()
     sm = Summer(store=s)
     ss = SillyService(store=s)
     sm.powerUp(ss, IService)
     IService(sm).startService()
     IService(sm).stopService()
     self.assertEquals(ss.started, 1)
     self.assertEquals(ss.stopped, 1)
     self.assertEquals(ss.running, 0)
Ejemplo n.º 46
0
    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()
Ejemplo n.º 47
0
def blog():
    """
    Create a L{hyperbola.hyperblurb.BlurbViewerViewer}, looking at a
    blog with some posts in it.
    """
    store = Store(mktemp())
    blog = populate(store)
    fragment = BlogBlurbViewer(blog)
    _docFactorify(fragment)
    return fragment
Ejemplo n.º 48
0
    def testMostRecentMessages(self):
        s = Store()

        o = Organizer(store=s)
        installOn(o, s)

        def makePerson(name, address):
            return EmailAddress(store=s,
                                address=address,
                                person=Person(store=s,
                                              organizer=o,
                                              name=name)).person

        p11 = makePerson(u'11 Message Person', u'11@person')
        p2  = makePerson(u'2 Message Person', u'2@person')

        def makeMessages(n, email):
            return list(reversed(list(
                        testMessageFactory(store=s,
                                           subject=u'Message %d' % (i,),
                                           sender=email,
                                           spam=False,
                                           receivedWhen=Time())
                        for i in xrange(n))))

        p11messages = makeMessages(11, u'11@person')
        p2messages  = makeMessages(2, u'2@person')

        lister = MessageLister(store=s)

        getMessages = lambda person, count: list(
            lister.mostRecentMessages(person, count))

        self.assertEquals(getMessages(p2, 3), p2messages)
        self.assertEquals(getMessages(p2, 2), p2messages)
        self.assertEquals(getMessages(p2, 1), p2messages[:-1])

        self.assertEquals(getMessages(p11, 12), p11messages)
        self.assertEquals(getMessages(p11, 11), p11messages)
        self.assertEquals(getMessages(p11, 10), p11messages[:-1])

        p11messages[0].trainSpam()

        self.assertEquals(getMessages(p11, 11), p11messages[1:])

        # Used to be:
        # p11messages[1].draft = True
        # but this is now a nonsensical transition.
        p11messages[1].trainSpam()

        self.assertEquals(getMessages(p11, 11), p11messages[2:])

        p11messages[2].moveToTrash()

        self.assertEquals(getMessages(p11, 11), p11messages[3:])
Ejemplo n.º 49
0
    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
Ejemplo n.º 50
0
class TestSiteTemplateResolver(TestCase):
    """
    Tests for L{SiteTemplateResolver}
    """
    def setUp(self):
        """
        Create a L{Store} with a fake L{IOfferingTechnician} powerup which
        allows fine-grained control of template name resolution.
        """
        self.offeringTech = FakeOfferingTechnician()
        self.store = Store()
        self.store.inMemoryPowerUp(self.offeringTech, IOfferingTechnician)
        self.siteResolver = SiteTemplateResolver(self.store)

    def getDocFactoryWithoutCaching(self, templateName):
        """
        Use C{self.siteResolver} to get a loader for the named template,
        flushing the template cache first in order to make the result reflect
        any changes which in offering or theme availability which may have
        happened since the last call.
        """
        webtheme.theThemeCache.emptyCache()
        return self.siteResolver.getDocFactory(templateName)

    def test_getDocFactory(self):
        """
        L{SiteTemplateResolver.getDocFactory} should return only installed
        themes for its store.
        """
        class FakeTheme(object):
            priority = 0

            def getDocFactory(self, templateName, default=None):
                if templateName == 'shell':
                    return object()
                return default

        self.assertIdentical(self.getDocFactoryWithoutCaching('shell'), None)
        self.offeringTech.installOffering(
            Offering(u'an offering', None, [], [], [], [], [FakeTheme()]))
        self.assertNotIdentical(self.getDocFactoryWithoutCaching('shell'),
                                None)
Ejemplo n.º 51
0
 def open(self, debug=False):
     if hasattr(self, 'substore'):
         return self.substore
     else:
         s = self.substore = Store(self.storepath.path,
                                   parent=self.store,
                                   idInParent=self.storeID,
                                   debug=debug)
         s._openSubStore = self  # don't fall out of cache as long as the
         # store is alive!
         return s
Ejemplo n.º 52
0
    def test_moreThanOneColumnSort(self):
        """
        Verify that paginate works with queries that have complex sort expressions.

        Note: it doesn't.
        """
        s = Store()

        x = MultiColumnSortHelper(store=s, columnOne=1, columnTwo=9)
        y1 = MultiColumnSortHelper(store=s, columnOne=2, columnTwo=1)
        y2 = MultiColumnSortHelper(store=s, columnOne=2, columnTwo=2)
        y3 = MultiColumnSortHelper(store=s, columnOne=2, columnTwo=3)
        y4 = MultiColumnSortHelper(store=s, columnOne=2, columnTwo=4)
        z = MultiColumnSortHelper(store=s, columnOne=3, columnTwo=5)
        self.assertEquals(list(
                s.query(MultiColumnSortHelper,
                        sort=[MultiColumnSortHelper.columnOne.ascending,
                              MultiColumnSortHelper.columnTwo.ascending]
                        ).paginate(pagesize=1)),
                          [x, y1, y2, y3, y4, z])
Ejemplo n.º 53
0
 def test_buildTerminalProtocol(self):
     """
     L{TerminalManhole.buildTerminalProtocol} returns a L{ColoredManhole}
     with a namespace including the store the L{TerminalManhole} is in.
     """
     store = Store()
     factory = TerminalManhole(store=store)
     viewer = object()
     protocol = factory.buildTerminalProtocol(viewer)
     self.assertTrue(isinstance(protocol, ColoredManhole))
     self.assertEqual(protocol.namespace, {'db': store, 'viewer': viewer})
Ejemplo n.º 54
0
    def testRelocatingPaths(self):
        spath = self.mktemp()
        npath = self.mktemp()
        s = Store(spath)
        rel = s.newFile("test", "123")
        TEST_STR = "test 123"

        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)

        return rel.close().addCallback(cb)
Ejemplo n.º 55
0
 def test_placeholderComparisonArgs(self):
     """
     Test that the result of L{IComparison.getArgs} on an attribute
     retrieved from a Placeholder returns the right values for the
     comparison.
     """
     s = Store()
     p = Placeholder(PlaceholderTestItem)
     value = 0
     args = (p.attr > value).getArgs(s)
     self.assertEquals(args, [0])
Ejemplo n.º 56
0
 def test_placeholderQuery(self):
     """
     Test that a BaseQuery can be created with Placeholder instances and the
     SQL it emits as a result correctly assigns and uses table aliases.
     """
     s = Store()
     p = Placeholder(PlaceholderTestItem)
     sql, args = ItemQuery(s, p)._sqlAndArgs('SELECT', '*')
     self.assertEquals(
         sql, 'SELECT * FROM %s AS placeholder_0' %
         (PlaceholderTestItem.getTableName(s), ))
Ejemplo n.º 57
0
 def setUp(self):
     """
     Create a store with a scheduler installed on it and hook the C{now} and
     C{callLater} methods of that scheduler so their behavior can be
     controlled by these tests.
     """
     self.calls = []
     self.store = Store(filepath.FilePath(self.mktemp()))
     self.siteScheduler = Scheduler(store=self.store)
     installOn(self.siteScheduler, self.store)
     self.siteScheduler.callLater = self._callLater
Ejemplo n.º 58
0
    def setUp(self):
        self.store = Store(dbdir=self.mktemp())

        installOn(inbox.Inbox(store=self.store), self.store)
        self.composer = compose.Composer(store=self.store)
        installOn(self.composer, self.store)

        LoginMethod(store=self.store,
                    internal=False,
                    protocol=u'email',
                    localpart=u'recipient',
                    domain=u'host',
                    verified=True,
                    account=self.store)

        self.msg = testMessageFactory(
            store=self.store,
            spam=False,
            impl=DummyMessageImplWithABunchOfAddresses(store=self.store))
        self.msgDetail = MessageDetail(self.msg)
Ejemplo n.º 59
0
 def test_sourceTracking(self):
     """
     Test that message sources added with L{addMessageSource} can be
     retrieved with L{getMessageSources} in alphabetical order.
     """
     s = Store()
     _addMessageSource(s, u"one")
     _addMessageSource(s, u"two")
     _addMessageSource(s, u"three")
     self.assertEquals(list(getMessageSources(s)),
                       [u"one", u"three", u"two"])
Ejemplo n.º 60
0
    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)