Beispiel #1
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
Beispiel #2
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)
 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)))
 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)))
Beispiel #5
0
 def testStoreServicePowerup(self):
     s = Store()
     ss = SillyService(store=s)
     s.powerUp(ss, IService)
     IService(s).startService()
     IService(s).stopService()
     self.assertEqual(ss.started, 1)
     self.assertEqual(ss.stopped, 1)
     self.assertEqual(ss.running, 0)
 def test_powerUp(self):
     """
     L{Calendar} is an L{IMessageReceiver} powerup.
     """
     store = Store()
     calendar = self.cal.Calendar(store=store)
     self.assertTrue(verifyObject(IMessageReceiver, calendar))
     store.powerUp(calendar)
     self.assertEquals(list(store.powerupsFor(IMessageReceiver)),
                       [calendar])
Beispiel #7
0
 def test_automaticPowerDown(self):
     """
     Powerups with 'powerupInterfaces' attributes can be powered
     down automatically on the interfaces they specify.
     """
     s = Store()
     p = PlusTwo(store=s)
     s.powerUp(p)
     s.powerDown(p)
     self.assertEquals(len(list(s.powerupsFor(IValueHaver))), 0)
Beispiel #8
0
 def test_listUnlisteningFactory(self):
     """
     I{axiomatic port list} displays factories even if they aren't associate
     with any port.
     """
     store = Store()
     factory = DummyFactory(store=store)
     store.powerUp(factory, IProtocolFactoryFactory)
     self.assertSuccessStatus(self._makeConfig(store), ["list"])
     self.assertEqual("%d) %r is not listening.\n" % (factory.storeID, factory), sys.stdout.getvalue())
 def test_powerUp(self):
     """
     L{Calendar} is an L{IMessageReceiver} powerup.
     """
     store = Store()
     calendar = self.cal.Calendar(store=store)
     self.assertTrue(verifyObject(IMessageReceiver, calendar))
     store.powerUp(calendar)
     self.assertEquals(
         list(store.powerupsFor(IMessageReceiver)), [calendar])
Beispiel #10
0
 def test_automaticPowerDown(self):
     """
     Powerups with 'powerupInterfaces' attributes can be powered
     down automatically on the interfaces they specify.
     """
     s = Store()
     p = PlusTwo(store=s)
     s.powerUp(p)
     s.powerDown(p)
     self.assertEqual(len(list(s.powerupsFor(IValueHaver))), 0)
Beispiel #11
0
 def test_automaticDynamicPowerDown(self):
     """
     Powerups with '__getPowerupInterfaces__' methods can be powered
     down automatically on the interfaces they specify.
     """
     s = Store()
     p = PlusOneTimesFour(store=s)
     s.powerUp(p)
     s.powerDown(p)
     self.assertEqual(len(list(s.powerupsFor(IValueHaver))), 0)
     self.assertEqual(len(list(s.powerupsFor(IScalingFactor))), 0)
Beispiel #12
0
 def testIndirectedPowerups(self):
     """
     Powerups which implement L{IPowerupIndirector} should not be returned
     directly, the values that they return from indirect() should be
     returned directly.
     """
     s = Store()
     mm = Summer(store=s)
     s.powerUp(SubtractThree(store=s, valueHaver=SumContributor(store=s, value=5)), IValueHaver)
     self.assertEquals(mm.doSum(), 2)
     s.close()
Beispiel #13
0
 def test_automaticDynamicPowerDown(self):
     """
     Powerups with '__getPowerupInterfaces__' methods can be powered
     down automatically on the interfaces they specify.
     """
     s = Store()
     p = PlusOneTimesFour(store=s)
     s.powerUp(p)
     s.powerDown(p)
     self.assertEquals(len(list(s.powerupsFor(IValueHaver))), 0)
     self.assertEquals(len(list(s.powerupsFor(IScalingFactor))), 0)
Beispiel #14
0
 def test_listUnlisteningFactory(self):
     """
     I{axiomatic port list} displays factories even if they aren't associate
     with any port.
     """
     store = Store()
     factory = DummyFactory(store=store)
     store.powerUp(factory, IProtocolFactoryFactory)
     self.assertSuccessStatus(self._makeConfig(store), ["list"])
     self.assertEqual(
         "%d) %r is not listening.\n" % (factory.storeID, factory),
         sys.stdout.getvalue())
Beispiel #15
0
    def test_dynamicAutomaticPowerupInstall(self):
        """
        Powerups with '__getPowerupInterfaces__' methods can be
        installed on the interfaces in the iterable that method
        returns.
        """
        s = Store()
        mm = Summer(store=s)
        s.powerUp(mm, ISumProducer)
        p = PlusOneTimesFour(store=s)
        s.powerUp(p)

        self.assertEqual(mm.doSum(), 4)
Beispiel #16
0
    def test_automaticPowerupInstall(self):
        """
        Powerups with 'powerupInterfaces' attributes can be installed
        on those interfaces without the caller needing to refer to
        them directly.
        """
        s = Store()
        mm = Summer(store=s)
        s.powerUp(mm, ISumProducer)
        p = PlusTwo(store=s)
        s.powerUp(p)

        self.assertEqual(mm.doSum(), 2)
 def test_notOtherResources(self):
     """
     C{AboutPlugin} will only respond to about.php, not every page on the
     site.
     """
     s = Store(self.mktemp())
     s.powerUp(self.aboutpage.AboutPlugin(store=s))
     s.powerUp(AnonymousSite(store=s))
     root = IMantissaSite(s)
     viewer = StubViewer()
     result = root.siteProduceResource(FakeRequest(), tuple(['undefined']),
                                       viewer)
     self.assertIdentical(result, None)
Beispiel #18
0
 def test_dynamicAutomaticPowerupFailure(self):
     """
     Powerups with '__getPowerupInterfaces__' methods that don't return
     iterables of pairs report an informative error message when powered up.
     """
     s = Store()
     mm = Summer(store=s)
     s.powerUp(mm, ISumProducer)
     p = BrokenPowerup(store=s)
     err = self.assertRaises(ValueError, s.powerUp, p)
     self.assertEquals(
         str(err), "return value from %r.__getPowerupInterfaces__" " not an iterable of 2-tuples" % (p,)
     )
Beispiel #19
0
    def test_dynamicAutomaticPowerupInstall(self):
        """
        Powerups with '__getPowerupInterfaces__' methods can be
        installed on the interfaces in the iterable that method
        returns.
        """
        s = Store()
        mm = Summer(store=s)
        s.powerUp(mm, ISumProducer)
        p = PlusOneTimesFour(store=s)
        s.powerUp(p)

        self.assertEquals(mm.doSum(), 4)
Beispiel #20
0
 def test_dynamicAutomaticPowerupFailure(self):
     """
     Powerups with '__getPowerupInterfaces__' methods that don't return
     iterables of pairs report an informative error message when powered up.
     """
     s = Store()
     mm = Summer(store=s)
     s.powerUp(mm, ISumProducer)
     p = BrokenPowerup(store=s)
     err = self.assertRaises(ValueError, s.powerUp, p)
     self.assertEqual(
         str(err), 'return value from %r.__getPowerupInterfaces__'
         ' not an iterable of 2-tuples' % (p, ))
Beispiel #21
0
    def test_automaticPowerupInstall(self):
        """
        Powerups with 'powerupInterfaces' attributes can be installed
        on those interfaces without the caller needing to refer to
        them directly.
        """
        s = Store()
        mm = Summer(store=s)
        s.powerUp(mm, ISumProducer)
        p = PlusTwo(store=s)
        s.powerUp(p)

        self.assertEquals(mm.doSum(), 2)
 def test_notOtherResources(self):
     """
     C{AboutPlugin} will only respond to about.php, not every page on the
     site.
     """
     s = Store(self.mktemp())
     s.powerUp(self.aboutpage.AboutPlugin(store=s))
     s.powerUp(AnonymousSite(store=s))
     root = IMantissaSite(s)
     viewer = StubViewer()
     result = root.siteProduceResource(FakeRequest(),
                                       tuple(['undefined']),
                                       viewer)
     self.assertIdentical(result, None)
Beispiel #23
0
 def testIndirectedPowerups(self):
     """
     Powerups which implement L{IPowerupIndirector} should not be returned
     directly, the values that they return from indirect() should be
     returned directly.
     """
     s = Store()
     mm = Summer(store=s)
     s.powerUp(
         SubtractThree(store=s, valueHaver=SumContributor(store=s,
                                                          value=5)),
         IValueHaver)
     self.assertEqual(mm.doSum(), 2)
     s.close()
 def test_adminRedirect(self):
     """
     When the admin redirect is installed on a store, it should return an
     URL which should redirect to /private.
     """
     s = Store(self.mktemp())
     s.powerUp(self.adminpage.RedirectPlugin(store=s))
     m = Mantissa()
     m.installSite(s, u'localhost', u'', False)
     root = IMantissaSite(s)
     viewer = StubViewer()
     result, segments = root.siteProduceResource(FakeRequest(),
                                                 tuple(['admin.php']),
                                                 viewer)
     self.assertEquals(result, URL.fromString("http://localhost/private"))
 def test_adminRedirect(self):
     """
     When the admin redirect is installed on a store, it should return an
     URL which should redirect to /private.
     """
     s = Store(self.mktemp())
     s.powerUp(self.adminpage.RedirectPlugin(store=s))
     m = Mantissa()
     m.installSite(s, u'localhost', u'', False)
     root = IMantissaSite(s)
     viewer = StubViewer()
     result, segments = root.siteProduceResource(FakeRequest(),
                                                 tuple(['admin.php']),
                                                 viewer)
     self.assertEquals(result, URL.fromString("http://localhost/private"))
Beispiel #26
0
class AMPAvatarTests(TestCase):
    """
    Tests for L{AMPAvatar} which provides an L{IBoxReceiver} implementation
    that supports routing messages to other L{IBoxReceiver} implementations.
    """
    def setUp(self):
        """
        Create a L{Store} with an L{AMPAvatar} installed on it.
        """
        self.store = Store()
        self.avatar = AMPAvatar(store=self.store)
        installOn(self.avatar, self.store)
        self.factory = StubBoxReceiverFactory(
            store=self.store, protocol=u"bar")
        self.store.powerUp(self.factory, IBoxReceiverFactory)


    def test_interface(self):
        """
        L{AMPAvatar} powers up the item on which it is installed for
        L{IBoxReceiver} and indirects that interface to the real router
        implementation of L{IBoxReceiver}.
        """
        router = IBoxReceiver(self.store)
        self.assertTrue(verifyObject(IBoxReceiver, router))
        self.assertNotIdentical(self.avatar, router)


    def test_connectorStarted(self):
        """
        L{AMPAvatar.indirect} returns a L{Router} with a started route
        connector as its default receiver.
        """
        receiver = SomeReceiver()
        self.avatar.__dict__['connectorFactory'] = lambda router: receiver
        router = self.avatar.indirect(IBoxReceiver)
        router.startReceivingBoxes(object())
        self.assertTrue(receiver.started)


    def test_reactor(self):
        """
        L{AMPAvatar.connectorFactory} returns a L{_RouteConnector} constructed
        using the global reactor.
        """
        connector = self.avatar.connectorFactory(object())
        self.assertIdentical(connector.reactor, reactor)
Beispiel #27
0
class MigrationManagerTests(TestCase):
    """
    Tests for L{MigrationManager}.
    """
    def setUp(self):
        self.store = Store()
        self.manager = MigrationManager(store=self.store)


    def test_installService(self):
        """
        The service is started when it is installed into a running store, and
        stopped when it is deleted.
        """
        IService(self.store).startService()
        installOn(self.manager, self.store)
        self.assertTrue(self.manager.running)
        self.manager.deleteFromStore()
        self.assertFalse(self.manager.running)


    def test_serviceRunsMigrations(self):
        """
        Starting the service runs all existing migrations.
        """
        m1 = TestMigration(store=self.store)
        m2 = TestMigration(store=self.store)
        self.store.powerUp(m1)
        self.store.powerUp(m2)
        self.assertEquals(m1.ran, 0)
        self.assertEquals(m2.ran, 0)
        self.manager.startService()
        self.assertEquals(m1.ran, 1)
        self.assertEquals(m2.ran, 1)


    def test_startMigration(self):
        """
        Starting a migration invokes the implementation on the source store.
        """
        source = MockContentStore()
        destination = MockContentStore(store=self.store)
        result = self.manager.migrate(source, destination)
        self.assertEquals(result.ran, 1)
        self.assertEquals(source.migrationDestination, destination)
        self.assertEquals(IMigration(self.store), result)
 def test_produceAboutResource(self):
     """
     When C{AboutPlugin} is installed on a site store created by 'axiomatic
     mantissa', requests for 'about.php' will be responded to by a helpful
     message wrapped in a shell page.
     """
     s = Store(self.mktemp())
     s.powerUp(self.aboutpage.AboutPlugin(store=s))
     m = Mantissa()
     m.installSite(s, u"localhost", u"", False)
     root = IMantissaSite(s)
     viewer = StubViewer()
     result, segments = root.siteProduceResource(FakeRequest(),
                                                 tuple(['about.php']),
                                                 viewer)
     self.assertIdentical(result, viewer.shell)
     self.assertIsInstance(result.model, self.aboutpage.AboutText)
 def test_produceAboutResource(self):
     """
     When C{AboutPlugin} is installed on a site store created by 'axiomatic
     mantissa', requests for 'about.php' will be responded to by a helpful
     message wrapped in a shell page.
     """
     s = Store(self.mktemp())
     s.powerUp(self.aboutpage.AboutPlugin(store=s))
     m = Mantissa()
     m.installSite(s, u"localhost", u"", False)
     root = IMantissaSite(s)
     viewer = StubViewer()
     result, segments = root.siteProduceResource(FakeRequest(),
                                                 tuple(['about.php']),
                                                 viewer)
     self.assertIdentical(result, viewer.shell)
     self.assertIsInstance(result.model, self.aboutpage.AboutText)
Beispiel #30
0
    def test_makeService(self):
        """
        L{AxiomaticStart.makeService} returns the L{IService} powerup of the
        L{Store} at the directory in the options object it is passed.
        """
        dbdir = FilePath(self.mktemp())
        store = Store(dbdir)
        recorder = RecorderService(store=store)
        self.assertFalse(recorder.started)
        store.powerUp(recorder, IService)
        store.close()

        service = AxiomaticStart.makeService({"dbdir": dbdir, "debug": False})
        service.startService()
        service.stopService()

        store = Store(dbdir)
        self.assertTrue(store.getItemByID(recorder.storeID).started)
Beispiel #31
0
    def test_makeService(self):
        """
        L{AxiomaticStart.makeService} returns the L{IService} powerup of the
        L{Store} at the directory in the options object it is passed.
        """
        dbdir = FilePath(self.mktemp())
        store = Store(dbdir)
        recorder = RecorderService(store=store)
        self.assertFalse(recorder.started)
        store.powerUp(recorder, IService)
        store.close()

        service = AxiomaticStart.makeService({"dbdir": dbdir, "debug": False})
        service.startService()
        service.stopService()

        store = Store(dbdir)
        self.assertTrue(store.getItemByID(recorder.storeID).started)
Beispiel #32
0
class AMPAvatarTests(TestCase):
    """
    Tests for L{AMPAvatar} which provides an L{IBoxReceiver} implementation
    that supports routing messages to other L{IBoxReceiver} implementations.
    """
    def setUp(self):
        """
        Create a L{Store} with an L{AMPAvatar} installed on it.
        """
        self.store = Store()
        self.avatar = AMPAvatar(store=self.store)
        installOn(self.avatar, self.store)
        self.factory = StubBoxReceiverFactory(store=self.store,
                                              protocol=u"bar")
        self.store.powerUp(self.factory, IBoxReceiverFactory)

    def test_interface(self):
        """
        L{AMPAvatar} powers up the item on which it is installed for
        L{IBoxReceiver} and indirects that interface to the real router
        implementation of L{IBoxReceiver}.
        """
        router = IBoxReceiver(self.store)
        self.assertTrue(verifyObject(IBoxReceiver, router))
        self.assertNotIdentical(self.avatar, router)

    def test_connectorStarted(self):
        """
        L{AMPAvatar.indirect} returns a L{Router} with a started route
        connector as its default receiver.
        """
        receiver = SomeReceiver()
        self.avatar.__dict__['connectorFactory'] = lambda router: receiver
        router = self.avatar.indirect(IBoxReceiver)
        router.startReceivingBoxes(object())
        self.assertTrue(receiver.started)

    def test_reactor(self):
        """
        L{AMPAvatar.connectorFactory} returns a L{_RouteConnector} constructed
        using the global reactor.
        """
        connector = self.avatar.connectorFactory(object())
        self.assertIdentical(connector.reactor, reactor)
Beispiel #33
0
class DeletionTestCase(TestCase):
    """
    Tests for the interaction between message deletion and the indexer.
    """
    def setUp(self):
        """
        Create a Store with a Message in it.
        """
        self.store = Store()
        self.message = Message(store=self.store)


    def test_deletionNotification(self):
        """
        Test that when a Message is deleted, all L{ixmantissa.IFulltextIndexer}
        powerups on that message's store are notified of the event.
        """
        indexers = []
        for i in range(2):
            indexers.append(DummyIndexer(store=self.store))
            self.store.powerUp(indexers[-1], ixmantissa.IFulltextIndexer)
            self.assertEqual(indexers[-1].removed, [])

        self.message.deleteFromStore()

        for i in range(2):
            self.assertEqual(indexers[i].removed, [self.message])


    def test_deletionWithoutIndexers(self):
        """
        Test that deletion of a message can succeed even if there are no
        L{ixmantissa.IFulltextIndexer} powerups on the message's store.
        """
        self.message.deleteFromStore()
        self.assertEqual(list(self.store.query(Message)), [])
Beispiel #34
0
    def testBasicPowerups(self):
        # tests an interaction between __conform__ and other stuff

        s = Store()
        mm = Summer(store=s)
        s.powerUp(mm, ISumProducer)

        s.powerUp(SumContributor(store=s, value=1), IValueHaver)
        s.powerUp(SumContributor(store=s, value=2), IValueHaver)
        s.powerUp(SumContributor(store=s, value=3), IValueHaver)

        self.assertEquals(mm.doSum(), 6)

        s.close()
Beispiel #35
0
    def testBasicPowerups(self):
        # tests an interaction between __conform__ and other stuff

        s = Store()
        mm = Summer(store=s)
        s.powerUp(mm, ISumProducer)

        s.powerUp(SumContributor(store=s, value=1), IValueHaver)
        s.powerUp(SumContributor(store=s, value=2), IValueHaver)
        s.powerUp(SumContributor(store=s, value=3), IValueHaver)

        self.assertEqual(mm.doSum(), 6)

        s.close()
Beispiel #36
0
    def testPowerupIdentity(self):
        s = Store()
        mm = Summer(store=s)
        s.powerUp(mm, ISumProducer)

        sc3 = SumContributor(store=s, value=3)

        s.powerUp(SumContributor(store=s, value=1), IValueHaver)
        s.powerUp(SumContributor(store=s, value=2), IValueHaver)
        s.powerUp(sc3, IValueHaver)
        s.powerUp(sc3, IValueHaver)

        self.assertEquals(mm.doSum(), 6)

        s.close()
Beispiel #37
0
    def testPowerupIdentity(self):
        s = Store()
        mm = Summer(store=s)
        s.powerUp(mm, ISumProducer)

        sc3 = SumContributor(store=s, value=3)

        s.powerUp(SumContributor(store=s, value=1), IValueHaver)
        s.powerUp(SumContributor(store=s, value=2), IValueHaver)
        s.powerUp(sc3, IValueHaver)
        s.powerUp(sc3, IValueHaver)

        self.assertEqual(mm.doSum(), 6)

        s.close()
Beispiel #38
0
from axiom.store import Store

from twisted.application.service import IService

from squeal.web.service import WebService
from squeal.net.slimproto import SlimService
from squeal.net.discovery import DiscoveryService
from squeal.playlist.service import Playlist
from squeal.event import EventReactor
from squeal.extension import PluginManager

from squeal.isqueal import *

store = Store("db")

services = (
    EventReactor,
    WebService,
    SlimService,
    DiscoveryService,
    Playlist,
    PluginManager,
)

for srv in services:
    s = srv(store=store)
    for iface in s.powerupInterfaces:
        store.powerUp(s, iface)
    store.powerUp(s, IService)
def initializeAPIs(Store: store.Store):
    PublicAPI = Store.findOrCreate(API, name="Public API")
    Store.powerUp(PublicAPI, IAPI)

    EmployeeAPI = Store.findOrCreate(API, name="Employee API")
    Store.powerUp(EmployeeAPI, IAPI)

    SupervisorAPI = Store.findOrCreate(API, name="Supervisor API")
    Store.powerUp(SupervisorAPI, IAPI)

    AdministratorAPI = Store.findOrCreate(API, name="Administrator API")
    Store.powerUp(AdministratorAPI, IAPI)
    findCommand = commandFinder(Store)
    PublicAPI.powerUp(findCommand("Login"), ICommand)
    PublicAPI.powerUp(findCommand("AsyncLogin"), ICommand)

    AdministratorAPI.powerUp(findCommand("MakeAdministrator"), ICommand)
    AdministratorAPI.powerUp(findCommand("MakeSupervisor"), ICommand)
    AdministratorAPI.powerUp(findCommand("AddToArea"), ICommand)
    AdministratorAPI.powerUp(findCommand("CheckForNewEmployees"), ICommand)
    AdministratorAPI.powerUp(findCommand("NewArea"), ICommand)
    AdministratorAPI.powerUp(findCommand("ApproveTime"), ICommand)
    AdministratorAPI.powerUp(findCommand("EditTime"), ICommand)
    AdministratorAPI.powerUp(findCommand("ClockOut"), ICommand)
    AdministratorAPI.powerUp(findCommand("ViewHours"), ICommand)
    AdministratorAPI.powerUp(findCommand("ViewAverageHours"), ICommand)
    AdministratorAPI.powerUp(findCommand("ViewEmployees"), ICommand)
    AdministratorAPI.powerUp(findCommand("AssumeRole"), ICommand)
    AdministratorAPI.powerUp(findCommand("ClockIn"), ICommand)
    AdministratorAPI.powerUp(findCommand("SetSupervisor"), ICommand)
    AdministratorAPI.powerUp(findCommand("SetWorkLocations"), ICommand)
    AdministratorAPI.powerUp(findCommand("SetSubAccounts"), ICommand)
    AdministratorAPI.powerUp(findCommand("ChangePassword"), ICommand)
    AdministratorAPI.powerUp(findCommand("ViewReports"), ICommand)
    AdministratorAPI.powerUp(findCommand("AssignTask"), ICommand)
    AdministratorAPI.powerUp(findCommand("CreateTask"), ICommand)
    AdministratorAPI.powerUp(findCommand("ManageSubAccounts"), ICommand)
    AdministratorAPI.powerUp(findCommand("ManageWorkLocations"), ICommand)
    AdministratorAPI.powerUp(findCommand("ScheduleTimeOff"), ICommand)
    AdministratorAPI.powerUp(findCommand("ApproveTimeOff"), ICommand)
    AdministratorAPI.powerUp(findCommand("ViewBenefits"), ICommand)
    AdministratorAPI.powerUp(findCommand("SetSupervisorSubAccounts"), ICommand)
    sv = findCommand("ScheduleVacation")
    if sv:
        for api in [AdministratorAPI, EmployeeAPI, SupervisorAPI]:
            if sv in api.powerupsFor(ICommand):
                api.powerDown(sv, ICommand)
        sv.deleteFromStore(Store)
    sv = findCommand("ApproveVacation")
    if sv:
        for api in [AdministratorAPI, EmployeeAPI, SupervisorAPI]:
            if sv in api.powerupsFor(ICommand):
                api.powerDown(sv, ICommand)
        sv.deleteFromStore(Store)

    EmployeeAPI.powerUp(findCommand("ClockIn"), ICommand)
    EmployeeAPI.powerUp(findCommand("ClockOut"), ICommand)
    EmployeeAPI.powerUp(findCommand("ViewHours"), ICommand)
    EmployeeAPI.powerUp(findCommand("ViewAverageHours"), ICommand)
    EmployeeAPI.powerUp(findCommand("ChangePassword"), ICommand)
    EmployeeAPI.powerUp(findCommand("ScheduleTimeOff"), ICommand)
    EmployeeAPI.powerUp(findCommand("ViewBenefits"), ICommand)

    SupervisorAPI.powerUp(findCommand("ClockOut"), ICommand)
    SupervisorAPI.powerUp(findCommand("ViewHours"), ICommand)
    SupervisorAPI.powerUp(findCommand("ViewAverageHours"), ICommand)
    # SupervisorAPI.powerUp(findCommand("ViewEmployees"), ICommand)
    SupervisorAPI.powerUp(findCommand("AssumeRole"), ICommand)
    SupervisorAPI.powerUp(findCommand("ClockIn"), ICommand)
    SupervisorAPI.powerUp(findCommand("EditTime"), ICommand)
    SupervisorAPI.powerUp(findCommand("ApproveTime"), ICommand)
    SupervisorAPI.powerUp(findCommand("ChangePassword"), ICommand)
    SupervisorAPI.powerUp(findCommand("AssignTask"), ICommand)
    SupervisorAPI.powerUp(findCommand("CreateTask"), ICommand)
    SupervisorAPI.powerUp(findCommand("ScheduleTimeOff"), ICommand)
    SupervisorAPI.powerUp(findCommand("ApproveTimeOff"), ICommand)
    SupervisorAPI.powerUp(findCommand("ViewBenefits"), ICommand)
Beispiel #40
0
class StoreBackendTests(TestCase):
    """
    Tests for content store backend functionality.
    """
    def setUp(self):
        self.store = Store(self.mktemp())
        self.contentStore1 = ContentStore(store=self.store)
        object.__setattr__(self.contentStore1, '_deferToThreadPool', execute)
        self.contentStore1.storeObject(content='somecontent',
                                       contentType=u'application/octet-stream')
        self.testObject = self.store.findUnique(ImmutableObject)

        self.contentStore2 = ContentStore(store=self.store)
        object.__setattr__(self.contentStore2, '_deferToThreadPool', execute)


    def test_getSiblingExists(self):
        """
        Calling getSiblingObject with an object ID that is present in the local
        store just returns the local object.
        """
        d = self.contentStore1.getSiblingObject(self.testObject.objectId)
        def _cb(o):
            self.o = o
        d.addCallback(_cb)
        self.assertIdentical(self.o, self.testObject)


    def _retrievalTest(self):
        o = self.successResultOf(
            self.contentStore2.getSiblingObject(self.testObject.objectId))
        self.assertEquals(
            self.successResultOf(o.getContent()), 'somecontent')
        o2 = self.successResultOf(
            self.contentStore2.getObject(self.testObject.objectId))
        self.assertIdentical(o, o2)


    def test_getSiblingExistsRemote(self):
        """
        Calling getSiblingObject with an object ID that is missing locally, but
        present in one of the sibling stores, will retrieve the object, as well
        as inserting it into the local store.
        """
        self.store.powerUp(self.contentStore1, ISiblingStore)
        self._retrievalTest()


    def test_getSiblingExistsBackend(self):
        """
        If an object is missing in local and sibling stores, but present in a
        backend store, the object will be retrieved from the backend store.
        """
        self.store.powerUp(self.contentStore1, IBackendStore)
        self._retrievalTest()


    def test_siblingBeforeBackend(self):
        """
        When looking for a missing object, sibling stores are tried before
        backend stores.
        """
        events = []

        siblingStore = MockContentStore(store=self.store, events=events)
        self.store.powerUp(siblingStore, ISiblingStore)

        backendStore = MockContentStore(store=self.store, events=events)
        self.store.powerUp(backendStore, IBackendStore)

        def _cb(e):
            self.assertEquals(
                events,
                [('getObject', siblingStore, u'sha256:aoeuaoeu'),
                 ('getObject', backendStore, u'sha256:aoeuaoeu')])
        return self.assertFailure(
            self.contentStore2.getSiblingObject(u'sha256:aoeuaoeu'),
            NonexistentObject).addCallback(_cb)


    def test_getSiblingMissing(self):
        """
        Calling getSiblingObject with an object ID that is missing everywhere
        raises L{NonexistentObject}.
        """
        self.store.powerUp(self.contentStore1, ISiblingStore)
        objectId = u'sha256:NOSUCHOBJECT'
        d = self.contentStore2.getSiblingObject(objectId)
        return self.assertFailure(d, NonexistentObject
            ).addCallback(lambda e: self.assertEquals(e.objectId, objectId))


    def test_storeObject(self):
        """
        Storing an object also causes it to be scheduled for storing in all
        backend stores.
        """
        contentStore = ContentStore(store=self.store)
        backendStore = MockContentStore(store=self.store)
        self.store.powerUp(backendStore, IBackendStore)
        backendStore2 = MockContentStore(store=self.store)
        self.store.powerUp(backendStore2, IBackendStore)
        scheduler = MockUploadScheduler()
        self.store.inMemoryPowerUp(scheduler, IUploadScheduler)

        contentStore.storeObject(content='somecontent',
                                 contentType=u'application/octet-stream')
        testObject = self.store.findUnique(ImmutableObject)
        pu = scheduler.uploads
        self.assertEquals(len(pu), 2)
        self.assertEquals(pu[0][0], testObject.objectId)
        self.assertEquals(pu[1][0], testObject.objectId)
        for objectId, backend in pu:
            if backend is backendStore:
                break
        else:
            self.fail('No pending upload for backendStore')

        for objectId, backend in pu:
            if backend is backendStore2:
                break
        else:
            self.fail('No pending upload for backendStore2')
Beispiel #41
0
class _PendingUploadTests(TestCase):
    """
    Tests for L{_PendingUpload}.
    """
    def setUp(self):
        self.store = Store(self.mktemp())
        self.contentStore = ContentStore(store=self.store)
        object.__setattr__(self.contentStore, '_deferToThreadPool', execute)
        self.store.powerUp(self.contentStore, IContentStore)
        self.contentStore.storeObject(content='somecontent',
                                      contentType=u'application/octet-stream')
        self.testObject = self.store.findUnique(ImmutableObject)
        self.backendStore = MockContentStore(store=self.store)
        self.pendingUpload = _PendingUpload(store=self.store,
                                            objectId=self.testObject.objectId,
                                            backend=self.backendStore)


    def test_successfulUpload(self):
        """
        When an upload attempt is made, the object is stored to the backend
        store. If this succeeds, the L{_PendingUpload} item is deleted.
        """
        def _cb(ign):
            self.assertEquals(
                self.backendStore.events,
                [('storeObject',
                  self.backendStore,
                  'somecontent',
                  u'application/octet-stream',
                  {},
                  self.testObject.created,
                  self.testObject.objectId)])
            self.assertRaises(ItemNotFound,
                              self.store.findUnique,
                              _PendingUpload)
        return self.pendingUpload.attemptUpload().addCallback(_cb)


    def test_failedUpload(self):
        """
        When an upload attempt is made, the object is stored to the backend
        store. If this fails, the L{_PendingUpload} item has its scheduled time
        updated.
        """
        def _storeObject(content, contentType, metadata={}, created=None,
                         objectId=None):
            raise ValueError('blah blah')
        object.__setattr__(self.backendStore, 'storeObject', _storeObject)

        nextScheduled = self.pendingUpload.scheduled + timedelta(minutes=5)
        def _nextAttempt():
            return nextScheduled
        object.__setattr__(self.pendingUpload, '_nextAttempt', _nextAttempt)

        self.successResultOf(self.pendingUpload.attemptUpload())
        self.assertIdentical(self.store.findUnique(_PendingUpload),
                             self.pendingUpload)
        self.assertEquals(self.pendingUpload.scheduled,
                          nextScheduled)
        errors = self.flushLoggedErrors(ValueError)
        self.assertEquals(len(errors), 1)
Beispiel #42
0
class RouteConnectorTests(TestCase):
    """
    Tests for L{_RouteConnector}.
    """
    def setUp(self):
        """
        Create a L{Store} with an L{AMPAvatar} installed on it.
        """
        self.clock = Clock()
        self.store = Store()
        self.factory = StubBoxReceiverFactory(store=self.store,
                                              protocol=u"bar")
        self.store.powerUp(self.factory, IBoxReceiverFactory)
        self.router = Router()
        self.sender = CollectingSender()
        self.connector = _RouteConnector(self.clock, self.store, self.router)
        self.router.startReceivingBoxes(self.sender)
        self.router.bindRoute(self.connector, None).connectTo(None)

    def test_accept(self):
        """
        L{_RouteConnector.accept} returns a C{dict} with a C{'route'} key
        associated with a new route identifier which may be used to send AMP
        boxes to a new instance of the L{IBoxReceiver} indicated by the
        C{protocol} argument passed to C{connect}.
        """
        firstIdentifier = self.connector.accept("first origin",
                                                u"bar")['route']
        firstReceiver = self.factory.receivers.pop()
        secondIdentifier = self.connector.accept("second origin",
                                                 u"bar")['route']
        secondReceiver = self.factory.receivers.pop()
        self.clock.advance(0)

        self.router.ampBoxReceived({_ROUTE: firstIdentifier, 'foo': 'bar'})
        self.router.ampBoxReceived({_ROUTE: secondIdentifier, 'baz': 'quux'})

        self.assertEqual(firstReceiver.boxes, [{'foo': 'bar'}])
        self.assertEqual(secondReceiver.boxes, [{'baz': 'quux'}])

    def test_acceptResponseBeforeApplicationBox(self):
        """
        If the protocol L{_RouteConnector.accept} binds to a new route sends a
        box in its C{startReceivingBoxes} method, that box is sent to the
        network after the I{Connect} response is sent.
        """
        earlyBox = {'foo': 'bar'}

        class EarlyReceiver:
            def startReceivingBoxes(self, sender):
                sender.sendBox(earlyBox)

        object.__setattr__(self.factory, 'receiverFactory', EarlyReceiver)
        self.connector.ampBoxReceived({
            COMMAND: Connect.commandName,
            ASK: 'unique-identifier',
            'origin': 'an origin',
            'protocol': 'bar'
        })
        self.clock.advance(0)
        self.assertEqual(len(self.sender.boxes), 2)
        route, app = self.sender.boxes
        expectedBox = earlyBox.copy()
        expectedBox[_ROUTE] = 'an origin'
        self.assertEqual(app, expectedBox)

    def test_unknownProtocol(self):
        """
        L{_RouteConnector.accept} raises L{ProtocolUnknown} if passed the name
        of a protocol for which no factory can be found.
        """
        self.assertRaises(ProtocolUnknown, self.connector.accept, "origin",
                          u"foo")

    def test_originRoute(self):
        """
        The L{IBoxReceiver}s created by L{_RouteConnector.accept} are started with
        L{IBoxSender}s which are associated with the origin route specified to
        C{accept}.
        """
        origin = u'origin route'
        self.connector.accept(origin, u'bar')
        self.clock.advance(0)

        [bar] = self.factory.receivers
        self.assertTrue(bar.started)
        bar.sender.sendBox({'foo': 'bar'})
        self.assertEqual(self.sender.boxes, [{_ROUTE: origin, 'foo': 'bar'}])

        bar.sender.unhandledError(Failure(RuntimeError("test failure")))
        self.assertEqual(self.sender.errors, ["test failure"])
Beispiel #43
0
class RouteConnectorTests(TestCase):
    """
    Tests for L{_RouteConnector}.
    """
    def setUp(self):
        """
        Create a L{Store} with an L{AMPAvatar} installed on it.
        """
        self.clock = Clock()
        self.store = Store()
        self.factory = StubBoxReceiverFactory(
            store=self.store, protocol=u"bar")
        self.store.powerUp(self.factory, IBoxReceiverFactory)
        self.router = Router()
        self.sender = CollectingSender()
        self.connector = _RouteConnector(self.clock, self.store, self.router)
        self.router.startReceivingBoxes(self.sender)
        self.router.bindRoute(self.connector, None).connectTo(None)


    def test_accept(self):
        """
        L{_RouteConnector.accept} returns a C{dict} with a C{'route'} key
        associated with a new route identifier which may be used to send AMP
        boxes to a new instance of the L{IBoxReceiver} indicated by the
        C{protocol} argument passed to C{connect}.
        """
        firstIdentifier = self.connector.accept(
            "first origin", u"bar")['route']
        firstReceiver = self.factory.receivers.pop()
        secondIdentifier = self.connector.accept(
            "second origin", u"bar")['route']
        secondReceiver = self.factory.receivers.pop()
        self.clock.advance(0)

        self.router.ampBoxReceived(
            {_ROUTE: firstIdentifier, 'foo': 'bar'})
        self.router.ampBoxReceived(
            {_ROUTE: secondIdentifier, 'baz': 'quux'})

        self.assertEqual(firstReceiver.boxes, [{'foo': 'bar'}])
        self.assertEqual(secondReceiver.boxes, [{'baz': 'quux'}])


    def test_acceptResponseBeforeApplicationBox(self):
        """
        If the protocol L{_RouteConnector.accept} binds to a new route sends a
        box in its C{startReceivingBoxes} method, that box is sent to the
        network after the I{Connect} response is sent.
        """
        earlyBox = {'foo': 'bar'}

        class EarlyReceiver:
            def startReceivingBoxes(self, sender):
                sender.sendBox(earlyBox)

        object.__setattr__(self.factory, 'receiverFactory', EarlyReceiver)
        self.connector.ampBoxReceived({
                COMMAND: Connect.commandName,
                ASK: 'unique-identifier',
                'origin': 'an origin',
                'protocol': 'bar'})
        self.clock.advance(0)
        self.assertEqual(len(self.sender.boxes), 2)
        route, app = self.sender.boxes
        expectedBox = earlyBox.copy()
        expectedBox[_ROUTE] = 'an origin'
        self.assertEqual(app, expectedBox)


    def test_unknownProtocol(self):
        """
        L{_RouteConnector.accept} raises L{ProtocolUnknown} if passed the name
        of a protocol for which no factory can be found.
        """
        self.assertRaises(
            ProtocolUnknown, self.connector.accept, "origin", u"foo")


    def test_originRoute(self):
        """
        The L{IBoxReceiver}s created by L{_RouteConnector.accept} are started with
        L{IBoxSender}s which are associated with the origin route specified to
        C{accept}.
        """
        origin = u'origin route'
        self.connector.accept(origin, u'bar')
        self.clock.advance(0)

        [bar] = self.factory.receivers
        self.assertTrue(bar.started)
        bar.sender.sendBox({'foo': 'bar'})
        self.assertEqual(self.sender.boxes, [{_ROUTE: origin, 'foo': 'bar'}])

        bar.sender.unhandledError(Failure(RuntimeError("test failure")))
        self.assertEqual(self.sender.errors, ["test failure"])
def initializeCommands(Store: store.Store):
    Store.powerUp(Store.findOrCreate(MakeSupervisor, name="Make Supervisor"), ICommand)
    Store.powerUp(Store.findOrCreate(MakeAdministrator, name="Make Administrator"), ICommand)
    Store.powerUp(Store.findOrCreate(AddToArea, name="Add to SubAccount"), ICommand)
    Store.powerUp(Store.findOrCreate(CheckForNewEmployees, name="Check For New Employees"), ICommand)
    Store.powerUp(Store.findOrCreate(ClockIn, name="Clock In"), ICommand)
    Store.powerUp(Store.findOrCreate(NewArea, name="New SubAccount"), ICommand)
    Store.powerUp(Store.findOrCreate(ClockOut, name="Clock Out"), ICommand)
    Store.powerUp(Store.findOrCreate(ApproveTime, name="Approve Time"), ICommand)
    Store.powerUp(Store.findOrCreate(Login, name="Login"), ICommand)
    Store.powerUp(Store.findOrCreate(AsyncLogin), ICommand)
    Store.powerUp(Store.findOrCreate(EditTime, name="Edit Time"), ICommand)
    Store.powerUp(Store.findOrCreate(ViewHours, name="View Hours"), ICommand)
    Store.powerUp(Store.findOrCreate(ViewAverageHours, name="View Average Hours"), ICommand)
    Store.powerUp(Store.findOrCreate(ViewEmployees, name="View Employees"), ICommand)
    Store.powerUp(Store.findOrCreate(AssumeRole, name="Assume Role"), ICommand)
    Store.powerUp(Store.findOrCreate(SetSupervisor, name="Set Supervisor"), ICommand)
    Store.powerUp(Store.findOrCreate(SetWorkLocations, name="Set Work Locations"), ICommand)
    Store.powerUp(Store.findOrCreate(SetSubAccounts, name="Set Sub Accounts"), ICommand)
    Store.powerUp(Store.findOrCreate(ChangeAuthentication, name="Change Password"), ICommand)
    Store.powerUp(Store.findOrCreate(ViewReports, name="View Reports"), ICommand)
    Store.powerUp(Store.findOrCreate(ManageSubAccounts, name="Manage Sub Accounts"), ICommand)
    Store.powerUp(Store.findOrCreate(ManageWorkLocations, name="Manage Work Locations"), ICommand)
    Store.powerUp(Store.findOrCreate(CreateTask), ICommand)
    Store.powerUp(Store.findOrCreate(AssignTask), ICommand)
    Store.powerUp(Store.findOrCreate(ScheduleTimeOff), ICommand)
    Store.powerUp(Store.findOrCreate(ApproveTimeOff), ICommand)
    Store.powerUp(Store.findOrCreate(ViewBenefits), ICommand)
    Store.powerUp(Store.findOrCreate(SetSupervisorSubAccounts), ICommand)