Esempio n. 1
0
    def test_argsForwarded(self):
        """
        Test that the search aggregator forwards arguments given to C{search}
        to L{xmantissa.ixmantissa.ISearchProvider}s
        """

        s = Store()

        installOn(ArgumentPassthroughSearchProvider(store=s), s)

        agg = search.SearchAggregator(store=s)
        installOn(agg, s)

        args = (((u'foo', {
            u'bar': u'baz'
        }), {
            'sortAscending': False
        }), ((u'bar', {
            u'foo': u'oof'
        }), {
            'sortAscending': True
        }), ((u'', {}), {
            'sortAscending': True,
            'count': 5,
            'offset': 1
        }))

        def checkArgs(gotArgs):
            for ((success, gotArgset), expectedArgset) in zip(gotArgs, args):
                self.assertEquals(gotArgset[0], expectedArgset)

        dl = defer.DeferredList([agg.search(*a[0], **a[1]) for a in args])
        dl.addCallback(checkArgs)
        return dl
Esempio n. 2
0
 def setUp(self):
     """
     Create an in-memory L{Store} with an L{AMPConfiguration} in it.
     """
     self.store = Store()
     self.conf = AMPConfiguration(store=self.store)
     installOn(self.conf, self.store)
Esempio n. 3
0
    def postOptions(self):
        s = self.parent.getStore()

        didSomething = False

        if self['admin']:
            didSomething = True
            if self['disable']:
                for app in s.query(webadmin.AdminStatsApplication):
                    app.deleteFromStore()
                    break
                else:
                    raise UsageError('Administrator controls already disabled.')
            else:
                installOn(webadmin.AdminStatsApplication(store=s), s)

        if self['developer']:
            didSomething = True
            if self['disable']:
                for app in s.query(webadmin.DeveloperApplication):
                    app.deleteFromStore()
                    break
                else:
                    raise UsageError('Developer controls already disabled.')
            else:
                installOn(webadmin.DeveloperApplication(store=s), s)

        if not didSomething:
            raise UsageError("Specify something or I won't do anything.")
Esempio n. 4
0
    def setUp(self):
        self.store = Store()
        privApp = PrivateApplication(store=self.store)
        installOn(privApp, self.store)

        # Create some data to test with in an order which is not naturally
        # sorted in any way.

        # 4 1s, 4 0s, 4 2s
        self.data = []
        for number in [1, 0, 2, 2, 0, 1, 1, 0, 2, 0, 2, 1]:
            self.data.append(DataThunk(store=self.store, a=number))

        # But order it for the sake of simplicity while testing.
        self.data.sort(key=lambda item: (item.a, item.storeID))

        self.model = TestableInequalityModel(
            self.store,
            DataThunk,
            None,
            [DataThunk.a,
             DataThunk.b,
             DataThunk.c],
            DataThunk.a,
            True)
Esempio n. 5
0
    def setUp(self):
        self.clock = Clock()

        scheduler = Scheduler(store=self.siteStore)
        self.stubTime(scheduler)
        installOn(scheduler, self.siteStore)
        IService(self.siteStore).startService()
Esempio n. 6
0
    def setUp(self):
        # XXX Incorrect setup.  See xquotient.test.test_compose.CompositionTestMixin
        self.store = Store(self.mktemp())

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

        self.fromAddr = smtpout.FromAddress(address=u'recipient@host',
                                            store=self.store)
        self.inbox = inbox.Inbox(store=self.store)
        installOn(self.inbox, self.store)
        self.composer = compose.Composer(store=self.store)
        installOn(self.composer, self.store)
        self.defaultFromAddress = self.store.findUnique(
            smtpout.FromAddress, smtpout.FromAddress._address == None)

        self.message = testMessageFactory(
            store=self.store,
            spam=False,
            impl=DummyMessageImplWithABunchOfAddresses(store=self.store))
        self.messageDetail = MessageDetail(self.message)
Esempio n. 7
0
    def postOptions(self):
        strport = self['strport']
        factoryIdentifier = self['factory-identifier']
        if strport is None or factoryIdentifier is None:
            self.opt_help()

        store = self.parent.parent.getStore()
        storeID = int(factoryIdentifier)
        try:
            factory = store.getItemByID(storeID)
        except KeyError:
            print "%d does not identify an item." % (storeID,)
            raise SystemExit(1)
        else:
            if not IProtocolFactoryFactory.providedBy(factory):
                print "%d does not identify a factory." % (storeID,)
                raise SystemExit(1)
            else:
                description = self.decodeCommandLine(strport)
                try:
                    serverFromString(reactor, description.encode('ascii'))
                except ValueError:
                    print "%r is not a valid port description." % (strport,)
                    raise SystemExit(1)
                port = StringEndpointPort(
                    store=store, description=description, factory=factory)
                installOn(port, store)
                print "Created."
        raise SystemExit(0)
Esempio n. 8
0
    def testAvatarStoreState(self):
        """
        You can only pass an 'avatars' argument if it doesn't already have an
        account in it.  Some accounts want to have their stores in slightly odd
        places (like offering.py) but you can't have two accounts added which
        both point to the same store.
        """
        dbdir = FilePath(self.mktemp())
        s = Store(dbdir)
        ls = userbase.LoginSystem(store=s)
        dependency.installOn(ls, s)
        acc = ls.addAccount('alice', 'dom.ain', 'password')

        # this is allowed, if weird
        unrelatedAccount = ls.addAccount(
            'elseice', 'dom.ain', 'password',
            avatars=SubStore.createNew(s, ('crazy', 'what')))

        # this is not allowed.
        self.assertRaises(errors.DuplicateUniqueItem,
                          ls.addAccount,
                          'bob', 'ain.dom', 'xpassword',
                          avatars=acc.avatars)

        # Make sure that our stupid call to addAccount did not corrupt
        # anything, because we are stupid
        self.assertEqual(acc.avatars.open().query(userbase.LoginAccount).count(), 1)
Esempio n. 9
0
    def test_retrain(self):
        """
        Verify that retraining a few messages will tell our new test filter to
        learn about a bunch of new messages.
        """
        f = Filter(store=self.store)
        installOn(f, self.store)
        tf = TestFilter(store=self.store, test=self)
        installOn(tf, self.store)
        COUNT = 10
        for j in range(2):
            for x in range(COUNT):
                msg = Message.createIncoming(
                    self.store, DummyMessageImplementation(store=self.store), u"test://retrain"
                )
                _spamState(msg, (x % 2), j)

        # This isn't quite correct.  We're relying on the fact that the batch
        # processor is supposed to run in a subprocess (which isn't going) so
        # the callback is only going to be triggered for our set of messages
        # during the test.  Bleah.

        def _(ign):
            self.assertEquals(tf.trainCount, COUNT)

        return f.retrain().addCallback(_)
Esempio n. 10
0
    def setUp(self):
        """
        Make a store, an account/substore, an indexer, and call startService()
        on the superstore's IService so the batch process interactions that
        happen in fulltext.py work
        """
        self.dbdir = self.mktemp()
        self.path = u'index'

        superstore = store.Store(self.dbdir)

        loginSystem = LoginSystem(store=superstore)
        installOn(loginSystem, superstore)

        account = loginSystem.addAccount(u'testuser', u'example.com', None)
        substore = account.avatars.open()

        self.store = substore
        self.indexer = self.createIndexer()

        self.svc = IService(superstore)
        self.svc.startService()

        # Make sure the indexer is actually available
        writer = self.openWriteIndex()
        writer.close()
Esempio n. 11
0
def inbox5to6(old):
    """
    Copy over all attributes except C{scheduler}.
    """
    new = old.upgradeVersion(
        Inbox.typeName, 5, 6,
        privateApplication=old.privateApplication,
        messageSource=old.messageSource,
        quotientPrefs=old.quotientPrefs,
        messageDisplayPrefs=old.messageDisplayPrefs,
        deliveryAgent=old.deliveryAgent,
        uiComplexity=old.uiComplexity,
        showMoreDetail=old.showMoreDetail,
        filter=old.filter,
        focus=old.focus)

    # If the old item was original schema version 5 in the database, focus and
    # filter have already been installed, because the 4 to 5 upgrader used to
    # install them.  However, now that 5 is not the newest version of Inbox, it
    # cannot do that.  Only the upgrader to the newest version can.  So do it
    # here, instead, if it is necessary (which is when the original schema
    # version was older than 5).
    if installedOn(new.filter) is None:
        installOn(new.filter, new.store)
    if installedOn(new.focus) is None:
        installOn(new.focus, new.store)
    return new
Esempio n. 12
0
    def test_requiresFromSiteInSiteStore(self):
        """
        L{axiom.dependency.requiresFromSite} should use the
        C{siteDefaultFactory} rather than the C{defaultFactory} to satisfy the
        dependency for items stored in a site store.  It should use this
        default whether or not any item which could satisfy the requirement is
        installed on the site store.

        This behavior is important because some powerup interfaces are provided
        for site and user stores with radically different behaviors; for
        example, the substore implementation of L{IScheduler} depends on the
        site implementation of L{IScheduler}; if a user's substore were opened
        accidentally as a site store (i.e. with no parent) then the failure of
        the scheduler API should be obvious and immediate so that it can
        compensate; it should not result in an infinite recursion as the
        scheduler is looking for its parent.

        Items which wish to be stored in a site store and also depend on items
        in the site store can specifically adapt to the appropriate interface
        in the C{siteDefaultFactory} supplied to
        L{dependency.requiresFromSite}.
        """
        plant = PowerPlant(store=self.store)
        self.assertEquals(plant.grid.siteStore, self.store)
        self.assertEquals(plant.grid.draw(100), FAKE_POWER)
        dependency.installOn(RealGrid(store=self.store), self.store)
        self.assertEquals(plant.grid.siteStore, self.store)
        self.assertEquals(plant.grid.draw(100), FAKE_POWER)
Esempio n. 13
0
    def test_properOrphaning(self):
        """
        If two installed items both depend on a third, it should be
        removed as soon as both installed items are removed, but no
        sooner.
        """

        foo = Kitchen(store=self.store)
        e = Toaster(store=self.store)
        dependency.installOn(e, foo)
        ps = self.store.findUnique(PowerStrip)
        bb = self.store.findUnique(Breadbox)
        f = Blender(store=self.store)
        dependency.installOn(f, foo)

        self.assertEquals(list(self.store.query(PowerStrip)), [ps])
        #XXX does ordering matter?
        self.assertEquals(set(dependency.installedDependents(ps, foo)),
                          set([e, f]))
        self.assertEquals(set(dependency.installedRequirements(e, foo)),
                          set([bb, ps]))
        self.assertEquals(list(dependency.installedRequirements(f, foo)),
                          [ps])

        dependency.uninstallFrom(e, foo)
        self.assertEquals(dependency.installedOn(ps), foo)

        dependency.uninstallFrom(f, foo)
        self.assertEquals(dependency.installedOn(ps), None)
Esempio n. 14
0
 def setUp(self):
     """
     Create an in-memory L{Store} with a L{ShellAccount} in it.
     """
     self.store = Store()
     self.account = ShellAccount(store=self.store)
     installOn(self.account, self.store)
Esempio n. 15
0
    def test_authenticatedApplicationNavigation(self):
        """
        The I{applicationNavigation} renderer should add primary navigation
        elements to the tag it is passed if it is called on a
        L{_PublicPageMixin} being rendered for an authenticated user.
        """
        navigable = FakeNavigableElement(store=self.userStore)
        installOn(navigable, self.userStore)
        navigable.tabs = [Tab('foo', 123, 0, [Tab('bar', 432, 0)])]
        request = FakeRequest()

        page = self.createPage(self.username)
        navigationPattern = div[
            span(id='app-tab', pattern='app-tab'),
            span(id='tab-contents', pattern='tab-contents')]
        ctx = context.WebContext(tag=navigationPattern)
        ctx.remember(request)
        tag = page.render_applicationNavigation(ctx, None)
        self.assertEqual(tag.tagName, 'div')
        self.assertEqual(tag.attributes, {})
        children = [child for child in tag.children if child.pattern is None]
        self.assertEqual(children, [])
        self.assertEqual(len(tag.slotData['tabs']), 1)
        fooTab = tag.slotData['tabs'][0]
        self.assertEqual(fooTab.attributes, {'id': 'app-tab'})
        self.assertEqual(fooTab.slotData['name'], 'foo')
        fooContent = fooTab.slotData['tab-contents']
        self.assertEqual(fooContent.attributes, {'id': 'tab-contents'})
        self.assertEqual(fooContent.slotData['href'],
                         self.privateApp.linkTo(123))
Esempio n. 16
0
 def setUp(self):
     """
     Create an in-memory L{Store} with an L{AMPConfiguration} in it.
     """
     self.store = Store()
     self.conf = AMPConfiguration(store=self.store)
     installOn(self.conf, self.store)
Esempio n. 17
0
def upgradeProcessor1to2(oldProcessor):
    """
    Batch processors stopped polling at version 2, so they no longer needed the
    idleInterval attribute.  They also gained a scheduled attribute which
    tracks their interaction with the scheduler.  Since they stopped polling,
    we also set them up as a timed event here to make sure that they don't
    silently disappear, never to be seen again: running them with the scheduler
    gives them a chance to figure out what's up and set up whatever other state
    they need to continue to run.

    Since this introduces a new dependency of all batch processors on a powerup
    for the IScheduler, install a Scheduler or a SubScheduler if one is not
    already present.
    """
    newProcessor = oldProcessor.upgradeVersion(
        oldProcessor.typeName, 1, 2,
        busyInterval=oldProcessor.busyInterval)
    newProcessor.scheduled = extime.Time()

    s = newProcessor.store
    sch = iaxiom.IScheduler(s, None)
    if sch is None:
        if s.parent is None:
            # Only site stores have no parents.
            sch = Scheduler(store=s)
        else:
            # Substores get subschedulers.
            sch = SubScheduler(store=s)
        installOn(sch, s)

    # And set it up to run.
    sch.schedule(newProcessor, newProcessor.scheduled)
    return newProcessor
Esempio n. 18
0
 def postOptions(self):
     store = self.getStore()
     fact = store.findOrCreate(IRCBotFactoryFactory)
     svc = store.findOrCreate(IRCBotService,
                              serviceID=self['id'],
                              factory=fact)
     installOn(svc, store)
Esempio n. 19
0
    def _testPartDisplayerScrubbing(self, input, scrub=True):
        """
        Set up a store, a PartItem with a body of C{input},
        pass it to the PartDisplayer, render it, and return
        a deferred that'll fire with the string result of
        the rendering.

        @param scrub: if False, the noscrub URL arg will
                      be added to the PartDisplayer request
        """
        s = Store()
        installOn(PrivateApplication(store=s), s)

        part = PartItem(store=s,
                        contentType=u'text/html',
                        body=input)

        pd = PartDisplayer(None)
        pd.item = part

        req = makeRequest()
        if not scrub:
            req.args = {'noscrub': True}

        return deferredRender(pd, req)
Esempio n. 20
0
    def setUp(self):
        """
        Set up an inequality model (by way of L{TestableInequalityModel}) backed by
        a user store with some sample data, and an L{IWebTranslator} powerup,
        to provide a somewhat realistic test setup.

        The data provided has some duplicates in the sort column, and it is
        intentionally inserted out of order, so that storeID order and sort
        column ordering will not coincide.
        """
        self.store = Store()
        privApp = PrivateApplication(store=self.store)
        installOn(privApp, self.store)

        self.data = []
        for a, b, c in [
            (9, 1928, u'nine'),
            (1, 983, u'one'),
            (8, 843, u'eight'),
            (2, 827, u'two'),
                # (8, 1874, u'eight (DUP)'), (2, 294, u'two (DUP)'),
            (7, 18, u'seven'),
            (3, 19, u'three'),
            (6, 218, u'six'),
            (4, 2198, u'four'),
            (5, 1982, u'five'),
            (0, 10, u'zero')
        ]:
            self.data.append(DataThunk(store=self.store, a=a, b=b, c=c))
        self.data.sort(key=lambda item: (item.a, item.storeID))

        self.model = TestableInequalityModel(
            self.store, DataThunk, None,
            [DataThunk.a, DataThunk.b, DataThunk.c], DataThunk.a, True)
Esempio n. 21
0
    def postOptions(self):
        strport = self['strport']
        factoryIdentifier = self['factory-identifier']
        if strport is None or factoryIdentifier is None:
            self.opt_help()

        store = self.parent.parent.getStore()
        storeID = int(factoryIdentifier)
        try:
            factory = store.getItemByID(storeID)
        except KeyError:
            print "%d does not identify an item." % (storeID, )
            raise SystemExit(1)
        else:
            if not IProtocolFactoryFactory.providedBy(factory):
                print "%d does not identify a factory." % (storeID, )
                raise SystemExit(1)
            else:
                description = self.decodeCommandLine(strport)
                try:
                    serverFromString(reactor, description.encode('ascii'))
                except ValueError:
                    print "%r is not a valid port description." % (strport, )
                    raise SystemExit(1)
                port = StringEndpointPort(store=store,
                                          description=description,
                                          factory=factory)
                installOn(port, store)
                print "Created."
        raise SystemExit(0)
Esempio n. 22
0
def upgradeMailTransferAgent3to4(oldMTA):
    """
    Create TCPPort and SSLPort items as appropriate.
    """
    if isinstance(oldMTA, MailDeliveryAgent):
        return oldMTA
    newMTA = oldMTA.upgradeVersion(
        MailTransferAgent.typeName, 3, 4,
        userbase=oldMTA.userbase,
        certificateFile=oldMTA.certificateFile,
        messageCount=oldMTA.messageCount,
        domain=oldMTA.domain)

    if oldMTA.portNumber is not None:
        port = TCPPort(store=newMTA.store, portNumber=oldMTA.portNumber, factory=newMTA)
        installOn(port, newMTA.store)

    securePortNumber = oldMTA.securePortNumber
    certificateFile = oldMTA.certificateFile
    if securePortNumber is not None and certificateFile:
        oldCertPath = newMTA.store.dbdir.preauthChild(certificateFile)
        if oldCertPath.exists():
            newCertPath = newMTA.store.newFilePath('mta.pem')
            oldCertPath.copyTo(newCertPath)
            port = SSLPort(store=newMTA.store, portNumber=securePortNumber, certificatePath=newCertPath, factory=newMTA)
            installOn(port, newMTA.store)

    newMTA.store.powerDown(newMTA, IService)

    return newMTA
Esempio n. 23
0
    def test_incompleteUsername(self):
        """
        Test that a login attempt using a username without a domain part
        results in a customized authentication failure message which points
        out that a domain part should be included in the username.
        """
        mta = mail.MailTransferAgent(store=self.store)
        installOn(mta, self.store)
        factory = mta.getFactory()
        protocol = factory.buildProtocol(('192.168.1.1', 12345))
        transport = StringTransport()
        transport.getHost = lambda: IPv4Address('TCP', '192.168.1.1', 54321)
        transport.getPeer = lambda: IPv4Address('TCP', '192.168.1.1', 12345)
        protocol.makeConnection(transport)
        protocol.dataReceived('EHLO example.net\r\n')
        protocol.dataReceived('AUTH LOGIN\r\n')
        protocol.dataReceived('testuser'.encode('base64') + '\r\n')
        transport.clear()
        protocol.dataReceived('password'.encode('base64') + '\r\n')
        written = transport.value()
        protocol.connectionLost(failure.Failure(error.ConnectionDone()))

        self.assertEquals(
            written,
            '535 Authentication failure [Username without domain name (ie '
            '"yourname" instead of "yourname@yourdomain") not allowed; try '
            'with a domain name.]\r\n')
Esempio n. 24
0
    def setUp(self):
        """
        Set up an inequality model (by way of L{TestableInequalityModel}) backed by
        a user store with some sample data, and an L{IWebTranslator} powerup,
        to provide a somewhat realistic test setup.

        The data provided has some duplicates in the sort column, and it is
        intentionally inserted out of order, so that storeID order and sort
        column ordering will not coincide.
        """
        self.store = Store()
        privApp = PrivateApplication(store=self.store)
        installOn(privApp, self.store)

        self.data = []
        for a, b, c in [(9, 1928, u'nine'), (1, 983, u'one'),
                        (8, 843, u'eight'), (2, 827, u'two'),
                        # (8, 1874, u'eight (DUP)'), (2, 294, u'two (DUP)'),
                        (7, 18, u'seven'), (3, 19, u'three'),
                        (6, 218, u'six'), (4, 2198, u'four'),
                        (5, 1982, u'five'), (0, 10, u'zero')]:
            self.data.append(DataThunk(store=self.store, a=a, b=b, c=c))
        self.data.sort(key=lambda item: (item.a, item.storeID))

        self.model = TestableInequalityModel(
            self.store,
            DataThunk,
            None,
            [DataThunk.a,
             DataThunk.b,
             DataThunk.c],
            DataThunk.a,
            True)
Esempio n. 25
0
    def setUp(self):
        """
        Extend L{_MessageRetrievalMixin.setUp} to also install an
        L{Organizer}, L{Person} and L{EmailAddress}, and an L{Message} from
        that person
        """
        super(MessagesByPersonRetrievalTestCase, self).setUp()

        self.organizer = Organizer(store=self.store)
        installOn(self.organizer, self.store)

        self.person = Person(store=self.store,
                             organizer=self.organizer,
                             name=u'The Person')

        EmailAddress(store=self.store,
                     address=u'the@person',
                     person=self.person)

        self.messageFromPerson = testMessageFactory(
            store=self.store,
            read=False,
            spam=False,
            receivedWhen=Time(),
            sender=u'the@person')
Esempio n. 26
0
    def testPolicy(self):
        """
        Test that only internal or verified L{userbase.LoginMethod}s with
        protocol=email are considered candidates for from addresses
        """
        s = store.Store(self.mktemp())
        ls = userbase.LoginSystem(store=s)
        installOn(ls, s)

        acc = ls.addAccount('username', 'dom.ain', 'password', protocol=u'not email')
        ss = acc.avatars.open()

        # not verified or internal, should explode
        self.assertRaises(
            RuntimeError, lambda: smtpout._getFromAddressFromStore(ss))

        # ANY_PROTOCOL
        acc.addLoginMethod(u'yeah', u'x.z', internal=True)

        # should work
        self.assertEquals(
            '[email protected]',
            smtpout._getFromAddressFromStore(ss))

        ss.findUnique(
            userbase.LoginMethod,
            userbase.LoginMethod.localpart == u'yeah').deleteFromStore()

        # external, verified
        acc.addLoginMethod(u'yeah', u'z.a', internal=False, verified=True)

        # should work
        self.assertEquals(
            '[email protected]',
            smtpout._getFromAddressFromStore(ss))
Esempio n. 27
0
def createDatabase(store):
    scheduler = Scheduler(store=store)
    installOn(scheduler, store)
    installOn(
        _SubSchedulerParentHook(
            store=store, loginAccount=SubStore(store=store)),
        store)
Esempio n. 28
0
def pop3listener2to3(oldPOP3):
    """
    Create TCPPort and SSLPort items as appropriate.
    """
    newPOP3 = oldPOP3.upgradeVersion(POP3Listener.typeName,
                                     2,
                                     3,
                                     userbase=oldPOP3.userbase,
                                     certificateFile=oldPOP3.certificateFile)

    if oldPOP3.portNumber is not None:
        port = TCPPort(store=newPOP3.store,
                       portNumber=oldPOP3.portNumber,
                       factory=newPOP3)
        installOn(port, newPOP3.store)

    securePortNumber = oldPOP3.securePortNumber
    certificateFile = oldPOP3.certificateFile
    if securePortNumber is not None and certificateFile:
        oldCertPath = newPOP3.store.dbdir.preauthChild(certificateFile)
        if oldCertPath.exists():
            newCertPath = newPOP3.store.newFilePath('pop3.pem')
            oldCertPath.copyTo(newCertPath)
            port = SSLPort(store=newPOP3.store,
                           portNumber=oldPOP3.securePortNumber,
                           certificatePath=newCertPath,
                           factory=newPOP3)
            installOn(port, newPOP3.store)

    newPOP3.store.powerDown(newPOP3, IService)

    return newPOP3
Esempio n. 29
0
    def test_retrain(self):
        """
        Verify that retraining a few messages will tell our new test filter to
        learn about a bunch of new messages.
        """
        f = Filter(store=self.store)
        installOn(f, self.store)
        tf = TestFilter(store=self.store, test=self)
        installOn(tf, self.store)
        COUNT = 10
        for j in range(2):
            for x in range(COUNT):
                msg = Message.createIncoming(
                    self.store, DummyMessageImplementation(store=self.store),
                    u'test://retrain')
                _spamState(msg, (x % 2), j)

        # This isn't quite correct.  We're relying on the fact that the batch
        # processor is supposed to run in a subprocess (which isn't going) so
        # the callback is only going to be triggered for our set of messages
        # during the test.  Bleah.

        def _(ign):
            self.assertEquals(tf.trainCount, COUNT)

        return f.retrain().addCallback(_)
Esempio n. 30
0
    def setUp(self):
        """
        Make a store, an account/substore, an indexer, and call startService()
        on the superstore's IService so the batch process interactions that
        happen in fulltext.py work
        """
        self.dbdir = self.mktemp()
        self.path = u'index'

        superstore = store.Store(self.dbdir)

        loginSystem = LoginSystem(store=superstore)
        installOn(loginSystem, superstore)

        account = loginSystem.addAccount(u'testuser', u'example.com', None)
        substore = account.avatars.open()

        self.store = substore
        self.indexer = self.createIndexer()

        self.svc = IService(superstore)
        self.svc.startService()

        # Make sure the indexer is actually available
        writer = self.openWriteIndex()
        writer.close()
Esempio n. 31
0
    def doRendering(self, fragmentClass):
        """
        Verify that the given fragment class will render without raising an
        exception.
        """
        siteStore = Store()

        loginSystem = LoginSystem(store=siteStore)
        installOn(loginSystem, siteStore)
        p = Product(
            store=siteStore, types=["xmantissa.webadmin.LocalUserBrowser", "xmantissa.signup.SignupConfiguration"]
        )
        account = loginSystem.addAccount(u"testuser", u"localhost", None)
        p.installProductOn(account.avatars.open())
        f = fragmentClass(None, u"testuser", account)

        p = LivePage(docFactory=stan(html[head(render=directive("liveglue")), body(render=lambda ctx, data: f)]))
        f.setFragmentParent(p)

        ctx = WovenContext()
        req = FakeRequest()
        ctx.remember(req, IRequest)

        d = p.renderHTTP(ctx)

        def rendered(ign):
            p.action_close(None)

        d.addCallback(rendered)
        return d
Esempio n. 32
0
 def setUp(self):
     """
     Create an in-memory L{Store} with a L{ShellAccount} in it.
     """
     self.store = Store()
     self.account = ShellAccount(store=self.store)
     installOn(self.account, self.store)
Esempio n. 33
0
    def postOptions(self):
        store = self.parent.getStore()

        util.setAPIKey(store, SuperfeedrService.apiKeyName, self['key'])

        svc = store.findOrCreate(SuperfeedrService)
        installOn(svc, store)
Esempio n. 34
0
    def testGetLoginMethods(self):
        """
        Test L{userbase.getLoginMethods}
        """
        dbdir = FilePath(self.mktemp())
        s = Store(dbdir)
        ls = userbase.LoginSystem(store=s)
        dependency.installOn(ls, s)

        acc = ls.addAccount('username', 'dom.ain', 'password', protocol='speech')
        ss = acc.avatars.open()

        for protocol in (None, 'speech'):
            self.assertEqual(list(userbase.getAccountNames(ss, protocol)),
                              [('username', 'dom.ain')])

        # defaults to ANY_PROTOCOL
        acc.addLoginMethod('username2', 'dom.ain')

        # check that searching for protocol=speech also gives us the
        # ANY_PROTOCOL LoginMethod
        for protocol in (None, 'speech'):
            self.assertEqual(sorted(userbase.getAccountNames(ss, protocol)),
                              [('username', 'dom.ain'),
                               ('username2', 'dom.ain')])
Esempio n. 35
0
 def postOptions(self):
     store = self.getStore()
     fact = store.findOrCreate(IRCBotFactoryFactory)
     svc = store.findOrCreate(IRCBotService,
                              serviceID=self['id'],
                              factory=fact)
     installOn(svc, store)
Esempio n. 36
0
    def postOptions(self):
        store = self.parent.getStore()

        util.setAPIKey(store, SuperfeedrService.apiKeyName, self['key'])

        svc = store.findOrCreate(SuperfeedrService)
        installOn(svc, store)
Esempio n. 37
0
    def doRendering(self, fragmentClass):
        """
        Verify that the given fragment class will render without raising an
        exception.
        """
        siteStore = Store()

        loginSystem = LoginSystem(store=siteStore)
        installOn(loginSystem, siteStore)
        p = Product(store=siteStore, types=["xmantissa.webadmin.LocalUserBrowser",
                                            "xmantissa.signup.SignupConfiguration"])
        account = loginSystem.addAccount(u'testuser', u'localhost', None)
        p.installProductOn(account.avatars.open())
        f = fragmentClass(None, u'testuser', account)

        p = LivePage(
            docFactory=stan(
                html[
                    head(render=directive('liveglue')),
                    body(render=lambda ctx, data: f)]))
        f.setFragmentParent(p)

        ctx = WovenContext()
        req = FakeRequest()
        ctx.remember(req, IRequest)

        d = p.renderHTTP(ctx)
        def rendered(ign):
            p.action_close(None)
        d.addCallback(rendered)
        return d
Esempio n. 38
0
    def test_authenticatedApplicationNavigation(self):
        """
        The I{applicationNavigation} renderer should add primary navigation
        elements to the tag it is passed if it is called on a
        L{_PublicPageMixin} being rendered for an authenticated user.
        """
        navigable = FakeNavigableElement(store=self.userStore)
        installOn(navigable, self.userStore)
        navigable.tabs = [Tab("foo", 123, 0, [Tab("bar", 432, 0)])]
        request = FakeRequest()

        page = self.createPage(self.username)
        navigationPattern = div[span(id="app-tab", pattern="app-tab"), span(id="tab-contents", pattern="tab-contents")]
        ctx = context.WebContext(tag=navigationPattern)
        ctx.remember(request)
        tag = page.render_applicationNavigation(ctx, None)
        self.assertEqual(tag.tagName, "div")
        self.assertEqual(tag.attributes, {})
        children = [child for child in tag.children if child.pattern is None]
        self.assertEqual(children, [])
        self.assertEqual(len(tag.slotData["tabs"]), 1)
        fooTab = tag.slotData["tabs"][0]
        self.assertEqual(fooTab.attributes, {"id": "app-tab"})
        self.assertEqual(fooTab.slotData["name"], "foo")
        fooContent = fooTab.slotData["tab-contents"]
        self.assertEqual(fooContent.attributes, {"id": "tab-contents"})
        self.assertEqual(fooContent.slotData["href"], self.privateApp.linkTo(123))
Esempio n. 39
0
def inbox5to6(old):
    """
    Copy over all attributes except C{scheduler}.
    """
    new = old.upgradeVersion(
        Inbox.typeName,
        5,
        6,
        privateApplication=old.privateApplication,
        messageSource=old.messageSource,
        quotientPrefs=old.quotientPrefs,
        messageDisplayPrefs=old.messageDisplayPrefs,
        deliveryAgent=old.deliveryAgent,
        uiComplexity=old.uiComplexity,
        showMoreDetail=old.showMoreDetail,
        filter=old.filter,
        focus=old.focus,
    )

    # If the old item was original schema version 5 in the database, focus and
    # filter have already been installed, because the 4 to 5 upgrader used to
    # install them.  However, now that 5 is not the newest version of Inbox, it
    # cannot do that.  Only the upgrader to the newest version can.  So do it
    # here, instead, if it is necessary (which is when the original schema
    # version was older than 5).
    if installedOn(new.filter) is None:
        installOn(new.filter, new.store)
    if installedOn(new.focus) is None:
        installOn(new.focus, new.store)
    return new
Esempio n. 40
0
 def test_orphanedSubSchedule(self):
     """
     The same as test_scheduler, except using a subscheduler that is orphaned.
     """
     subscheduler = SubScheduler(store=self.store)
     installOn(subscheduler, self.store)
     return self._testSchedule(subscheduler)
Esempio n. 41
0
    def test_authenticatedApplicationNavigation(self):
        """
        The I{applicationNavigation} renderer should add primary navigation
        elements to the tag it is passed if it is called on a
        L{_PublicPageMixin} being rendered for an authenticated user.
        """
        navigable = FakeNavigableElement(store=self.userStore)
        installOn(navigable, self.userStore)
        navigable.tabs = [Tab('foo', 123, 0, [Tab('bar', 432, 0)])]
        request = FakeRequest()

        page = self.createPage(self.username)
        navigationPattern = div[
            span(id='app-tab', pattern='app-tab'),
            span(id='tab-contents', pattern='tab-contents')]
        ctx = context.WebContext(tag=navigationPattern)
        ctx.remember(request)
        tag = page.render_applicationNavigation(ctx, None)
        self.assertEqual(tag.tagName, 'div')
        self.assertEqual(tag.attributes, {})
        children = [child for child in tag.children if child.pattern is None]
        self.assertEqual(children, [])
        self.assertEqual(len(tag.slotData['tabs']), 1)
        fooTab = tag.slotData['tabs'][0]
        self.assertEqual(fooTab.attributes, {'id': 'app-tab'})
        self.assertEqual(fooTab.slotData['name'], 'foo')
        fooContent = fooTab.slotData['tab-contents']
        self.assertEqual(fooContent.attributes, {'id': 'tab-contents'})
        self.assertEqual(
            fooContent.slotData['href'], self.privateApp.linkTo(123))
Esempio n. 42
0
    def test_partDisplayerScrubbedContentLength(self):
        """
        Test that L{PartDisplayer} sets the C{Content-Length} header
        to the length of the content after it has been transformed by
        the scrubber.
        """
        s = Store()
        installOn(PrivateApplication(store=s), s)
        body = u'<div><script>haha</script>this is ok</div>'
        part = PartItem(store=s,
                        contentType=u'text/html',
                        bodyLength=len(body),
                        body=body)
        partDisplayer = PartDisplayer(None)
        partDisplayer.item = part

        req = makeRequest()
        D = deferredRender(partDisplayer, req)

        def checkLength(renderedBody):
            self.assertEqual(int(req.headers.get('content-length')),
                             len(renderedBody))

        D.addCallback(checkLength)
        return D
Esempio n. 43
0
    def createPort(self, portNumber, ssl, certPath, factory, interface=u''):
        """
        Create a new listening port.

        @type portNumber: C{int}
        @param portNumber: Port number on which to listen.

        @type ssl: C{bool}
        @param ssl: Indicates whether this should be an SSL port or not.

        @type certPath: C{str}
        @param ssl: If C{ssl} is true, a path to a certificate file somewhere
        within the site store's files directory.  Ignored otherwise.

        @param factory: L{Item} which provides L{IProtocolFactoryFactory} which
        will be used to get a protocol factory to associate with this port.

        @return: C{None}
        """
        store = self.store.parent
        if ssl:
            port = SSLPort(store=store, portNumber=portNumber,
                           certificatePath=FilePath(certPath), factory=factory,
                           interface=interface)
        else:
            port = TCPPort(store=store, portNumber=portNumber, factory=factory,
                           interface=interface)
        installOn(port, store)
Esempio n. 44
0
    def setUp(self):
        s = Store()
        installOn(QuotientPreferenceCollection(store=s), s)
        installOn(people.Organizer(store=s), s)

        self.store = s
        self.md = MessageDetail(Message(store=s, subject=u'a/b/c', sender=u''))
Esempio n. 45
0
    def testPolicy(self):
        """
        Test that only internal or verified L{userbase.LoginMethod}s with
        protocol=email are considered candidates for from addresses
        """
        s = store.Store(self.mktemp())
        ls = userbase.LoginSystem(store=s)
        installOn(ls, s)

        acc = ls.addAccount('username',
                            'dom.ain',
                            'password',
                            protocol=u'not email')
        ss = acc.avatars.open()

        # not verified or internal, should explode
        self.assertRaises(RuntimeError,
                          lambda: smtpout._getFromAddressFromStore(ss))

        # ANY_PROTOCOL
        acc.addLoginMethod(u'yeah', u'x.z', internal=True)

        # should work
        self.assertEquals('[email protected]', smtpout._getFromAddressFromStore(ss))

        ss.findUnique(
            userbase.LoginMethod,
            userbase.LoginMethod.localpart == u'yeah').deleteFromStore()

        # external, verified
        acc.addLoginMethod(u'yeah', u'z.a', internal=False, verified=True)

        # should work
        self.assertEquals('[email protected]', smtpout._getFromAddressFromStore(ss))
Esempio n. 46
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, [])
Esempio n. 47
0
def upgradeProcessor1to2(oldProcessor):
    """
    Batch processors stopped polling at version 2, so they no longer needed the
    idleInterval attribute.  They also gained a scheduled attribute which
    tracks their interaction with the scheduler.  Since they stopped polling,
    we also set them up as a timed event here to make sure that they don't
    silently disappear, never to be seen again: running them with the scheduler
    gives them a chance to figure out what's up and set up whatever other state
    they need to continue to run.

    Since this introduces a new dependency of all batch processors on a powerup
    for the IScheduler, install a Scheduler or a SubScheduler if one is not
    already present.
    """
    newProcessor = oldProcessor.upgradeVersion(
        oldProcessor.typeName, 1, 2,
        busyInterval=oldProcessor.busyInterval)
    newProcessor.scheduled = extime.Time()

    s = newProcessor.store
    sch = iaxiom.IScheduler(s, None)
    if sch is None:
        if s.parent is None:
            # Only site stores have no parents.
            sch = Scheduler(store=s)
        else:
            # Substores get subschedulers.
            sch = SubScheduler(store=s)
        installOn(sch, s)

    # And set it up to run.
    sch.schedule(newProcessor, newProcessor.scheduled)
    return newProcessor
Esempio n. 48
0
    def test_requiresFromSiteInSiteStore(self):
        """
        L{axiom.dependency.requiresFromSite} should use the
        C{siteDefaultFactory} rather than the C{defaultFactory} to satisfy the
        dependency for items stored in a site store.  It should use this
        default whether or not any item which could satisfy the requirement is
        installed on the site store.

        This behavior is important because some powerup interfaces are provided
        for site and user stores with radically different behaviors; for
        example, the substore implementation of L{IScheduler} depends on the
        site implementation of L{IScheduler}; if a user's substore were opened
        accidentally as a site store (i.e. with no parent) then the failure of
        the scheduler API should be obvious and immediate so that it can
        compensate; it should not result in an infinite recursion as the
        scheduler is looking for its parent.

        Items which wish to be stored in a site store and also depend on items
        in the site store can specifically adapt to the appropriate interface
        in the C{siteDefaultFactory} supplied to
        L{dependency.requiresFromSite}.
        """
        plant = PowerPlant(store=self.store)
        self.assertEquals(plant.grid.siteStore, self.store)
        self.assertEquals(plant.grid.draw(100), FAKE_POWER)
        dependency.installOn(RealGrid(store=self.store), self.store)
        self.assertEquals(plant.grid.siteStore, self.store)
        self.assertEquals(plant.grid.draw(100), FAKE_POWER)
Esempio n. 49
0
    def test_properOrphaning(self):
        """
        If two installed items both depend on a third, it should be
        removed as soon as both installed items are removed, but no
        sooner.
        """

        foo = Kitchen(store=self.store)
        e = Toaster(store=self.store)
        dependency.installOn(e, foo)
        ps = self.store.findUnique(PowerStrip)
        bb = self.store.findUnique(Breadbox)
        f = Blender(store=self.store)
        dependency.installOn(f, foo)

        self.assertEquals(list(self.store.query(PowerStrip)), [ps])
        #XXX does ordering matter?
        self.assertEquals(set(dependency.installedDependents(ps, foo)),
                          set([e, f]))
        self.assertEquals(set(dependency.installedRequirements(e, foo)),
                          set([bb, ps]))
        self.assertEquals(list(dependency.installedRequirements(f, foo)), [ps])

        dependency.uninstallFrom(e, foo)
        self.assertEquals(dependency.installedOn(ps), foo)

        dependency.uninstallFrom(f, foo)
        self.assertEquals(dependency.installedOn(ps), None)
Esempio n. 50
0
    def test_incompleteUsername(self):
        """
        Test that a login attempt using a username without a domain part
        results in a customized authentication failure message which points
        out that a domain part should be included in the username.
        """
        mta = mail.MailTransferAgent(store=self.store)
        installOn(mta, self.store)
        factory = mta.getFactory()
        protocol = factory.buildProtocol(("192.168.1.1", 12345))
        transport = StringTransport()
        transport.getHost = lambda: IPv4Address("TCP", "192.168.1.1", 54321)
        transport.getPeer = lambda: IPv4Address("TCP", "192.168.1.1", 12345)
        protocol.makeConnection(transport)
        protocol.dataReceived("EHLO example.net\r\n")
        protocol.dataReceived("AUTH LOGIN\r\n")
        protocol.dataReceived("testuser".encode("base64") + "\r\n")
        transport.clear()
        protocol.dataReceived("password".encode("base64") + "\r\n")
        written = transport.value()
        protocol.connectionLost(failure.Failure(error.ConnectionDone()))

        self.assertEquals(
            written,
            "535 Authentication failure [Username without domain name (ie "
            '"yourname" instead of "yourname@yourdomain") not allowed; try '
            "with a domain name.]\r\n",
        )
Esempio n. 51
0
def pop3listener2to3(oldPOP3):
    """
    Create TCPPort and SSLPort items as appropriate.
    """
    newPOP3 = oldPOP3.upgradeVersion(
        POP3Listener.typeName, 2, 3,
        userbase=oldPOP3.userbase,
        certificateFile=oldPOP3.certificateFile)

    if oldPOP3.portNumber is not None:
        port = TCPPort(store=newPOP3.store, portNumber=oldPOP3.portNumber, factory=newPOP3)
        installOn(port, newPOP3.store)

    securePortNumber = oldPOP3.securePortNumber
    certificateFile = oldPOP3.certificateFile
    if securePortNumber is not None and certificateFile:
        oldCertPath = newPOP3.store.dbdir.preauthChild(certificateFile)
        if oldCertPath.exists():
            newCertPath = newPOP3.store.newFilePath('pop3.pem')
            oldCertPath.copyTo(newCertPath)
            port = SSLPort(store=newPOP3.store, portNumber=oldPOP3.securePortNumber, certificatePath=newCertPath, factory=newPOP3)
            installOn(port, newPOP3.store)

    newPOP3.store.powerDown(newPOP3, IService)

    return newPOP3
Esempio n. 52
0
 def setUp(self):
     self.store = Store()
     self.scheduler = IScheduler(self.store)
     self.inbox = Inbox(store=self.store)
     installOn(self.inbox, self.store)
     self.translator = self.inbox.privateApplication
     self.inboxScreen = InboxScreen(self.inbox)
     self.viewSelection = dict(self.inboxScreen.viewSelection)
Esempio n. 53
0
 def installOn(self, other):
     # XXX check installation on other, not store
     for ls in self.store.query(userbase.LoginSystem):
         raise usage.UsageError("UserBase already installed")
     else:
         ls = userbase.LoginSystem(store=self.store)
         dependency.installOn(ls, other)
         return ls
Esempio n. 54
0
    def test_service(self):
        """
        Test that C{self.portType} becomes a service on the store it is installed on.
        """
        port = self.port(store=self.store)
        installOn(port, self.store)

        self.assertEqual(list(self.store.powerupsFor(IService)), [port])
Esempio n. 55
0
 def installOn(self, other):
     # XXX check installation on other, not store
     for ls in self.store.query(userbase.LoginSystem):
         raise usage.UsageError("UserBase already installed")
     else:
         ls = userbase.LoginSystem(store=self.store)
         dependency.installOn(ls, other)
         return ls