예제 #1
0
class ImportManagerTestCase(unittest.TestCase):
    """ Tests for the import manager. """
    def setUp(self):
        """ Prepares the test fixture before each test method is called. """

        # We do all of the testing via the application to make sure it offers
        # the same interface!
        self.import_manager = Application(import_manager=ImportManager())

    def test_import_dotted_symbol(self):
        """ import dotted symbol """

        import tarfile

        symbol = self.import_manager.import_symbol("tarfile.TarFile")
        self.assertEqual(symbol, tarfile.TarFile)

    def test_import_nested_symbol(self):
        """ import nested symbol """

        import tarfile

        symbol = self.import_manager.import_symbol("tarfile:TarFile.open")
        self.assertEqual(symbol, tarfile.TarFile.open)

    def test_import_dotted_module(self):
        """ import dotted module """

        symbol = self.import_manager.import_symbol(
            "envisage.api:ImportManager")
        self.assertEqual(symbol, ImportManager)
    def setUp(self):
        """ Prepares the test fixture before each test method is called. """

        # We do all of the testing via the application to make sure it offers
        # the same interface!
        self.import_manager = Application(import_manager=ImportManager())

        return
예제 #3
0
    def test_no_recursion(self):
        """ Regression test for #119. """
        class PluginA(Plugin):
            id = "A"
            x = ExtensionPoint(List, id="bob")

        application = Application(plugins=[PluginA()])
        application.get_extensions("bob")
예제 #4
0
    def test_no_recursion(self):
        """ Regression test for #119. """

        class PluginA(Plugin):
            id = 'A'
            x  = ExtensionPoint(List, id='bob')

        application = Application(plugins=[PluginA()])
        application.get_extensions('bob')
    def setUp(self):
        # We do all of the testing via the application to make sure it offers
        # the same interface!
        registry = Application(extension_registry=ExtensionRegistry())
        extension_point = ExtensionPoint(id="my.ep", trait_type=List())
        registry.add_extension_point(extension_point)
        self.registry = registry

        # A place to record events that listeners receive.
        self.events = []
예제 #6
0
class ImportManagerTestCase(unittest.TestCase):
    """ Tests for the import manager. """

    ###########################################################################
    # 'TestCase' interface.
    ###########################################################################

    def setUp(self):
        """ Prepares the test fixture before each test method is called. """

        # We do all of the testing via the application to make sure it offers
        # the same interface!
        self.import_manager = Application(import_manager=ImportManager())

        return

    def tearDown(self):
        """ Called immediately after each test method has been called. """

        return

    ###########################################################################
    # Tests.
    ###########################################################################

    def test_import_dotted_symbol(self):
        """ import dotted symbol """

        import tarfile

        symbol = self.import_manager.import_symbol('tarfile.TarFile')
        self.assertEqual(symbol, tarfile.TarFile)

        return

    def test_import_nested_symbol(self):
        """ import nested symbol """

        import tarfile

        symbol = self.import_manager.import_symbol('tarfile:TarFile.open')
        self.assertEqual(symbol, tarfile.TarFile.open)

        return

    def test_import_dotted_module(self):
        """ import dotted module """

        symbol = self.import_manager.import_symbol(
            'envisage.api:ImportManager'
        )
        self.assertEqual(symbol, ImportManager)

        return
예제 #7
0
def main():
    from envisage.api import Application
    from motd.plugins.motd_startup import MOTDStartupPlugin
    from motd.plugins.messages import MessagesPlugin

    application = Application(id='motd_startup',
                              plugins=[MOTDStartupPlugin(),
                                       MessagesPlugin()])

    # Run it!
    application.run()
예제 #8
0
    def setUp(self):
        """ Prepares the test fixture before each test method is called. """

        # We do all of the testing via the application to make sure it offers
        # the same interface!
        self.service_registry = Application(service_registry=ServiceRegistry())

        # module 'foo' need to be cleared out when this test is run,
        # because other tests also import foo.
        if PKG + '.foo' in sys.modules:
            del sys.modules[PKG + '.foo']
예제 #9
0
파일: run.py 프로젝트: skailasa/envisage
def main():
    """ Run the application. """

    # Create an application containing the appropriate plugins.
    application = Application(
        id      = 'acme.motd',
        plugins = [CorePlugin(), MOTDPlugin(), SoftwareQuotesPlugin()]
    )

    # Run it!
    return application.run()
class ImportManagerTestCase(unittest.TestCase):
    """ Tests for the import manager. """

    ###########################################################################
    # 'TestCase' interface.
    ###########################################################################

    def setUp(self):
        """ Prepares the test fixture before each test method is called. """

        # We do all of the testing via the application to make sure it offers
        # the same interface!
        self.import_manager = Application(import_manager=ImportManager())

        return

    def tearDown(self):
        """ Called immediately after each test method has been called. """

        return

    ###########################################################################
    # Tests.
    ###########################################################################

    def test_import_dotted_symbol(self):
        """ import dotted symbol """

        import tarfile

        symbol = self.import_manager.import_symbol('tarfile.TarFile')
        self.assertEqual(symbol, tarfile.TarFile)

        return

    def test_import_nested_symbol(self):
        """ import nested symbol """

        import tarfile

        symbol = self.import_manager.import_symbol('tarfile:TarFile.open')
        self.assertEqual(symbol, tarfile.TarFile.open)

        return

    def test_import_dotted_module(self):
        """ import dotted module """

        symbol = self.import_manager.import_symbol(
            'envisage.api:ImportManager')
        self.assertEqual(symbol, ImportManager)

        return
    def setUp(self):
        """ Prepares the test fixture before each test method is called. """

        # We do all of the testing via the application to make sure it offers
        # the same interface!
        self.registry = Application(extension_registry=ExtensionRegistry())

        return
예제 #12
0
def main():
    """ Run the application. """
    # Import here so that this script can be run from anywhere without
    # having to install the packages.
    from acme.motd.motd_plugin import MOTDPlugin
    from acme.motd.software_quotes.software_quotes_plugin import (
        SoftwareQuotesPlugin, )
    # Create an application containing the appropriate plugins.
    application = Application(
        id="acme.motd",
        plugins=[CorePlugin(),
                 MOTDPlugin(),
                 SoftwareQuotesPlugin()],
    )

    # Run it!
    return application.run()
예제 #13
0
    def setUp(self):
        """ Prepares the test fixture before each test method is called. """

        # We do all of the testing via the application to make sure it offers
        # the same interface!
        self.import_manager = Application(import_manager=ImportManager())

        return
예제 #14
0
    def setUp(self):
        """ Prepares the test fixture before each test method is called. """

        # We do all of the testing via the application to make sure it offers
        # the same interface!
        self.registry = Application(extension_registry=ExtensionRegistry())

        # Set the extension registry used by the test classes.
        TestBase.extension_registry = self.registry
예제 #15
0
def main():
    from envisage.api import Application
    from envisage.core_plugin import CorePlugin
    from motd.plugins.motd_service import MOTDServicePlugin, MOTDStartupPlugin
    from motd.plugins.messages import MessagesPlugin
    
    application = Application(
        id='motd_startup',
        plugins=[
            CorePlugin(),
            MOTDServicePlugin(),
            MessagesPlugin(),
            MOTDStartupPlugin()
        ]
    )

    # Run it!
    application.run()
예제 #16
0
def run():
    """ The function that starts your application. """

    # Enthought library imports.
    #
    # We do the imports here in case the Enthought eggs are loaded dyanmically
    # via the 'EGG_PATH'.
    from envisage.api import Application, EggPluginManager

    # Create a plugin manager that ignores all eggs except the ones that we
    # need for this example.
    plugin_manager = EggPluginManager(
        include=['envisage.core', 'acme.motd', 'acme.motd.software_quotes'])

    # Create an application that uses the egg plugin manager to find its
    # plugins.
    application = Application(id='acme.motd', plugin_manager=plugin_manager)

    # Run it!
    return application.run()
    def setUp(self):
        """ Prepares the test fixture before each test method is called. """

        # We do all of the testing via the application to make sure it offers
        # the same interface!
        self.service_registry = Application(service_registry=ServiceRegistry())

        # module 'foo' need to be cleared out when this test is run by nose,
        # because other tests also import foo.
        if PKG + '.foo' in sys.modules:
            del sys.modules[PKG + '.foo']

        return
예제 #18
0
파일: run.py 프로젝트: LRFrank/envisage
def run():
    """ The function that starts your application. """

    # Enthought library imports.
    #
    # We do the imports here in case the Enthought eggs are loaded dyanmically
    # via the 'EGG_PATH'.
    from envisage.api import Application, EggPluginManager

    # Create a plugin manager that ignores all eggs except the ones that we
    # need for this example.
    plugin_manager = EggPluginManager(
        include = [
            'envisage.core', 'acme.motd', 'acme.motd.software_quotes'
        ]
    )

    # Create an application that uses the egg plugin manager to find its
    # plugins.
    application = Application(id='acme.motd', plugin_manager=plugin_manager)

    # Run it!
    return application.run()
예제 #19
0
    def test_kernel_namespace_extension_point(self):
        class NamespacePlugin(Plugin):
            kernel_namespace = List(contributes_to=IPYTHON_NAMESPACE)

            def _kernel_namespace_default(self):
                return [('y', 'hi')]

        plugins = [CorePlugin(), IPythonKernelPlugin(), NamespacePlugin()]
        app = Application(plugins=plugins, id='test')

        app.start()
        try:
            kernel = app.get_service(IPYTHON_KERNEL_PROTOCOL)
            kernel.init_ipkernel(gui_backend=None)
            self.assertIn('y', kernel.namespace)
            self.assertEqual(kernel.namespace['y'], 'hi')
        finally:
            app.stop()
예제 #20
0
    def test_kernel_service(self):
        # See that we can get the IPython kernel service when the plugin is
        # there.
        plugins = [CorePlugin(), IPythonKernelPlugin()]
        app = Application(plugins=plugins, id='test')

        # Starting the app starts the kernel plugin. The IPython kernel
        # service should now be available.
        app.start()
        kernel = app.get_service(IPYTHON_KERNEL_PROTOCOL)
        self.assertIsNotNone(kernel)
        self.assertIsInstance(kernel, InternalIPKernel)

        # Initialize the kernel. Normally, the application does it when
        # it starts.
        kernel.init_ipkernel(gui_backend=None)

        # Stopping the application should shut the kernel down.
        app.stop()
        self.assertIsNone(kernel.ipkernel)
예제 #21
0
    def test_kernel_namespace_extension_point(self):
        class NamespacePlugin(Plugin):
            kernel_namespace = List(contributes_to=IPYTHON_NAMESPACE)

            def _kernel_namespace_default(self):
                return [('y', 'hi')]

        plugins = [CorePlugin(), IPythonKernelPlugin(), NamespacePlugin()]
        app = Application(plugins=plugins, id='test')

        app.start()
        try:
            kernel = app.get_service(IPYTHON_KERNEL_PROTOCOL)
            kernel.init_ipkernel(gui_backend=None)
            self.assertIn('y', kernel.namespace)
            self.assertEqual(kernel.namespace['y'], 'hi')
        finally:
            app.stop()
예제 #22
0
    def test_kernel_service(self):
        # See that we can get the IPython kernel service when the plugin is
        # there.
        plugins = [CorePlugin(), IPythonKernelPlugin()]
        app = Application(plugins=plugins, id='test')

        # Starting the app starts the kernel plugin. The IPython kernel
        # service should now be available.
        app.start()
        kernel = app.get_service(IPYTHON_KERNEL_PROTOCOL)
        self.assertIsNotNone(kernel)
        self.assertIsInstance(kernel, InternalIPKernel)

        # Initialize the kernel. Normally, the application does it when
        # it starts.
        kernel.init_ipkernel(gui_backend=None)

        # Stopping the application should shut the kernel down.
        app.stop()
        self.assertIsNone(kernel.ipkernel)
예제 #23
0
    def running_app(self, plugins=None):
        """
        Returns a context manager that provides a running application.

        Parameters
        ----------
        plugins : list of Plugin, optional
            Plugins to use in the application, other than the CorePlugin
            (which is always included). If not given, an IPythonKernelPlugin
            is instantiated and used.
        """
        if plugins is None:
            plugins = [IPythonKernelPlugin(init_ipkernel=True)]

        app = Application(plugins=[CorePlugin()] + plugins, id="test")
        app.start()
        try:
            yield app
        finally:
            app.stop()
class ServiceRegistryTestCase(unittest.TestCase):
    """ Tests for the service registry. """

    ###########################################################################
    # 'TestCase' interface.
    ###########################################################################

    def setUp(self):
        """ Prepares the test fixture before each test method is called. """

        # We do all of the testing via the application to make sure it offers
        # the same interface!
        self.service_registry = Application(service_registry=ServiceRegistry())

        # module 'foo' need to be cleared out when this test is run by nose,
        # because other tests also import foo.
        if PKG + '.foo' in sys.modules:
            del sys.modules[PKG + '.foo']

        return

    def tearDown(self):
        """ Called immediately after each test method has been called. """

        return

    ###########################################################################
    # Tests.
    ###########################################################################

    def test_imported_service_factory(self):
        """ imported service factory """

        class IFoo(Interface):
            price = Int

        # Register a service factory.
        self.service_registry.register_service(
            HasTraits,
            PKG + '.service_registry_test_case.service_factory',
            {'price' : 100}
        )

        # Create a query that matches the registered object.
        service = self.service_registry.get_service(HasTraits, 'price <= 100')
        self.assertNotEqual(None, service)
        self.assertEqual(HasTraits, type(service))

        # This shows that the properties were passed in to the factory.
        self.assertEqual(100, service.price)

        # Make sure that the object created by the factory is cached (i.e. we
        # get the same object back from now on!).
        service2 = self.service_registry.get_service(HasTraits, 'price <= 100')
        self.assert_(service is service2)

        return

    def test_function_service_factory(self):
        """ function service factory """

        class IFoo(Interface):
            price = Int

        class Foo(HasTraits):
            implements(IFoo)

            price = Int

        def foo_factory(**properties):
            """ A factory for foos. """

            return Foo(**properties)

        # Register a service factory.
        self.service_registry.register_service(
            IFoo, foo_factory, {'price' : 100}
        )

        # Create a query that matches the registered object.
        service = self.service_registry.get_service(IFoo, 'price <= 100')
        self.assertNotEqual(None, service)
        self.assertEqual(Foo, type(service))

        # Make sure that the object created by the factory is cached (i.e. we
        # get the same object back from now on!).
        service2 = self.service_registry.get_service(IFoo, 'price <= 100')
        self.assert_(service is service2)

        return

    def test_lazy_function_service_factory(self):
        """ lazy function service factory """

        # Register a service factory by name.
        def foo_factory(**properties):
            """ A factory for foos. """

            from envisage.tests.foo import Foo

            foo_factory.foo = Foo()

            return foo_factory.foo

        i_foo = PKG + '.i_foo.IFoo'
        foo   = PKG + '.foo'

        self.service_registry.register_service(i_foo, foo_factory)

        # Get rid of the 'foo' module (used in other tests).
        if foo in sys.modules:
            del sys.modules[foo]

        # Make sure that we haven't imported the 'foo' module.
        self.assert_(foo not in sys.modules)

        # Look up a non-existent service.
        services = self.service_registry.get_services('bogus.IBogus')

        # Make sure that we *still* haven't imported the 'foo' module.
        self.assert_(foo not in sys.modules)

        # Look it up again.
        services = self.service_registry.get_services(i_foo)
        self.assertEqual([foo_factory.foo], services)
        self.assert_(foo in sys.modules)

        # Clean up!
        del sys.modules[foo]

        return

    def test_lazy_bound_method_service_factory(self):
        """ lazy bound method service factory """

        i_foo = PKG + '.i_foo.IFoo'
        foo   = PKG + '.foo'

        class ServiceProvider(HasTraits):
            """ A class that provides a service.

            This is used to make sure a bound method can be used as a service
            factory.

            """

            # Register a service factory by name.
            def foo_factory(self, **properties):
                """ A factory for foos. """

                from envisage.tests.foo import Foo

                self.foo = Foo()

                return self.foo

        sp = ServiceProvider()
        self.service_registry.register_service(i_foo, sp.foo_factory)

        # Get rid of the 'foo' module (used in other tests).
        if foo in sys.modules:
            del sys.modules[foo]

        # Make sure that we haven't imported the 'foo' module.
        self.assert_(foo not in sys.modules)

        # Look up a non-existent service.
        services = self.service_registry.get_services('bogus.IBogus')

        # Make sure that we *still* haven't imported the 'foo' module.
        self.assert_(foo not in sys.modules)

        # Look up the service.
        services = self.service_registry.get_services(i_foo)
        self.assertEqual([sp.foo], services)
        self.assert_(foo in sys.modules)

        # Clean up!
        del sys.modules[foo]

        return

    def test_get_services(self):
        """ get services """

        class IFoo(Interface):
            pass

        class Foo(HasTraits):
            implements(IFoo)

        # Register two services.
        foo = Foo()
        self.service_registry.register_service(IFoo, foo)

        foo = Foo()
        self.service_registry.register_service(IFoo, foo)

        # Look it up again.
        services = self.service_registry.get_services(IFoo)
        self.assertEqual(2, len(services))

        class IBar(Interface):
            pass

        # Lookup a non-existent service.
        services = self.service_registry.get_services(IBar)
        self.assertEqual([], services)

        return

    def test_get_services_with_strings(self):
        """ get services with strings """

        from envisage.tests.foo import Foo

        # Register a couple of services using a string protocol name.
        protocol_name = 'envisage.tests.foo.IFoo'

        self.service_registry.register_service(protocol_name, Foo())
        self.service_registry.register_service(protocol_name, Foo())

        # Look them up using the same string!
        services = self.service_registry.get_services(protocol_name)
        self.assertEqual(2, len(services))

        return

    def test_get_services_with_query(self):
        """ get services with query """

        class IFoo(Interface):
            price = Int

        class Foo(HasTraits):
            implements(IFoo)

            price = Int

        # Register two services.
        #
        # This one shows how the object's attributes are used when evaluating
        # a query.
        foo = Foo(price=100)
        self.service_registry.register_service(IFoo, foo)

        # This one shows how properties can be specified that *take precedence*
        # over the object's attributes when evaluating a query.
        goo = Foo(price=10)
        self.service_registry.register_service(IFoo, goo, {'price' : 200})

        # Create a query that doesn't match any registered object.
        services = self.service_registry.get_services(IFoo, 'color == "red"')
        self.assertEqual([], services)

        # Create a query that matches one of the registered objects.
        services = self.service_registry.get_services(IFoo, 'price <= 100')
        self.assertEqual([foo], services)

        # Create a query that matches both registered objects.
        services = self.service_registry.get_services(IFoo, 'price >= 100')
        self.assert_(foo in services)
        self.assert_(goo in services)
        self.assertEqual(2, len(services))

        class IBar(Interface):
            pass

        # Lookup a non-existent service.
        services = self.service_registry.get_services(IBar, 'price <= 100')
        self.assertEqual([], services)

        return

    def test_get_service(self):
        """ get service """

        class IFoo(Interface):
            pass

        class Foo(HasTraits):
            implements(IFoo)

        # Register a couple of services.
        foo = Foo()
        self.service_registry.register_service(IFoo, foo)

        goo = Foo()
        self.service_registry.register_service(IFoo, goo)

        # Look up one of them!
        service = self.service_registry.get_service(IFoo)
        self.assert_(foo is service or goo is service)

        class IBar(Interface):
            pass

        # Lookup a non-existent service.
        service = self.service_registry.get_service(IBar)
        self.assertEqual(None, service)

        return

    def test_get_service_with_query(self):
        """ get service with query """

        class IFoo(Interface):
            price = Int

        class Foo(HasTraits):
            implements(IFoo)

            price = Int

        # Register two services.
        #
        # This one shows how the object's attributes are used when evaluating
        # a query.
        foo = Foo(price=100)
        self.service_registry.register_service(IFoo, foo)

        # This one shows how properties can be specified that *take precedence*
        # over the object's attributes when evaluating a query.
        goo = Foo(price=10)
        self.service_registry.register_service(IFoo, goo, {'price' : 200})

        # Create a query that doesn't match any registered object.
        service = self.service_registry.get_service(IFoo, 'price < 100')
        self.assertEqual(None, service)

        # Create a query that matches one of the registered objects.
        service = self.service_registry.get_service(IFoo, 'price <= 100')
        self.assertEqual(foo, service)

        # Create a query that matches both registered objects.
        service = self.service_registry.get_service(IFoo, 'price >= 100')
        self.assert_(foo is service or goo is service)

        class IBar(Interface):
            pass

        # Lookup a non-existent service.
        service = self.service_registry.get_service(IBar, 'price <= 100')
        self.assertEqual(None, service)

        return

    def test_get_and_set_service_properties(self):
        """ get and set service properties """

        class IFoo(Interface):
            price = Int

        class Foo(HasTraits):
            implements(IFoo)

            price = Int

        # Register two services.
        #
        # This one has no properties.
        foo = Foo(price=100)
        foo_id = self.service_registry.register_service(IFoo, foo)

        # This one has properties.
        goo = Foo(price=10)
        goo_id = self.service_registry.register_service(
            IFoo, goo, {'price' : 200}
        )

        # Get the properties.
        foo_properties = self.service_registry.get_service_properties(foo_id)
        self.assertEqual({}, foo_properties)

        goo_properties = self.service_registry.get_service_properties(goo_id)
        self.assertEqual(200, goo_properties['price'])

        # Update the properties.
        foo_properties['price'] = 300
        goo_properties['price'] = 500

        # Set the properties.
        self.service_registry.set_service_properties(foo_id, foo_properties)
        self.service_registry.set_service_properties(goo_id, goo_properties)

        # Get the properties again.
        foo_properties = self.service_registry.get_service_properties(foo_id)
        self.assertEqual(300, foo_properties['price'])

        goo_properties = self.service_registry.get_service_properties(goo_id)
        self.assertEqual(500, goo_properties['price'])

        # Try to get the properties of a non-existent service.
        self.failUnlessRaises(
            ValueError, self.service_registry.get_service_properties, -1
        )

        # Try to set the properties of a non-existent service.
        self.failUnlessRaises(
            ValueError, self.service_registry.set_service_properties, -1, {}
        )

        return

    def test_unregister_service(self):
        """ unregister service """

        class IFoo(Interface):
            price = Int

        class Foo(HasTraits):
            implements(IFoo)

            price = Int

        # Register two services.
        #
        # This one shows how the object's attributes are used when evaluating
        # a query.
        foo = Foo(price=100)
        foo_id = self.service_registry.register_service(IFoo, foo)

        # This one shows how properties can be specified that *take precedence*
        # over the object's attributes when evaluating a query.
        goo = Foo(price=10)
        goo_id = self.service_registry.register_service(
            IFoo, goo, {'price' : 200}
        )

        # Create a query that doesn't match any registered object.
        service = self.service_registry.get_service(IFoo, 'price < 100')
        self.assertEqual(None, service)

        # Create a query that matches one of the registered objects.
        service = self.service_registry.get_service(IFoo, 'price <= 100')
        self.assertEqual(foo, service)

        # Create a query that matches both registered objects.
        service = self.service_registry.get_service(IFoo, 'price >= 100')
        self.assert_(foo is service or goo is service)

        #### Now do some unregistering! ####

        # Unregister 'foo'.
        self.service_registry.unregister_service(foo_id)

        # This query should no longer match any of the registered objects.
        service = self.service_registry.get_service(IFoo, 'price <= 100')
        self.assertEqual(None, service)

        # Unregister 'goo'.
        self.service_registry.unregister_service(goo_id)

        # This query should no longer match any of the registered objects.
        service = self.service_registry.get_service(IFoo, 'price >= 100')
        self.assertEqual(None, service)

        # Try to unregister a non-existent service.
        self.failUnlessRaises(
            ValueError, self.service_registry.unregister_service, -1
        )

        return

    def test_minimize_and_maximize(self):
        """ minimize and maximize """

        class IFoo(Interface):
            price = Int

        class Foo(HasTraits):
            implements(IFoo)

            price = Int

        # Register some objects with various prices.
        x = Foo(price=10)
        y = Foo(price=5)
        z = Foo(price=100)

        for foo in [x, y, z]:
            self.service_registry.register_service(IFoo, foo)

        # Find the service with the lowest price.
        service = self.service_registry.get_service(IFoo, minimize='price')
        self.assertNotEqual(None, service)
        self.assertEqual(Foo, type(service))
        self.assertEqual(y, service)

        # Find the service with the highest price.
        service = self.service_registry.get_service(IFoo, maximize='price')
        self.assertNotEqual(None, service)
        self.assertEqual(Foo, type(service))
        self.assertEqual(z, service)

        return
예제 #25
0
    # This shows how you can use a standard trait initializer to populate the
    # list dynamically.
    def _greetings_default(self):
        """ Trait initializer. """

        extensions = [
            'The %s application says %s' % (self.application.id, greeting)

            for greeting in ['Bonjour', 'Hola']
        ]

        return extensions


# Application entry point.
if __name__ == '__main__':

    # Create the application.
    #
    # An application is simply a collection of plugins. In this case we
    # specify the plugins explicitly, but the mechanism for finding plugins
    # is configurable by setting the application's 'plugin_manager' trait.
    application = Application(
        id='hello.world', plugins=[HelloWorld(), Greetings(), MoreGreetings()]
    )

    # Run it!
    application.run()

#### EOF ######################################################################
예제 #26
0
class ServiceRegistryTestCase(unittest.TestCase):
    """ Tests for the service registry. """

    ###########################################################################
    # 'TestCase' interface.
    ###########################################################################

    def setUp(self):
        """ Prepares the test fixture before each test method is called. """

        # We do all of the testing via the application to make sure it offers
        # the same interface!
        self.service_registry = Application(service_registry=ServiceRegistry())

        # module 'foo' need to be cleared out when this test is run,
        # because other tests also import foo.
        if PKG + '.foo' in sys.modules:
            del sys.modules[PKG + '.foo']

    ###########################################################################
    # Tests.
    ###########################################################################

    def test_should_get_required_service(self):
        class Foo(HasTraits):
            price = Int

        foo = Foo()

        # Register a service factory.
        self.service_registry.register_service(Foo, foo)

        service = self.service_registry.get_required_service(Foo)
        self.assertIs(foo, service)

    def test_should_get_exception_if_required_service_is_missing(self):
        class IFoo(Interface):
            price = Int

        with self.assertRaises(NoSuchServiceError):
            self.service_registry.get_required_service(IFoo)

    def test_imported_service_factory(self):
        """ imported service factory """
        class IFoo(Interface):
            price = Int

        # Register a service factory.
        self.service_registry.register_service(
            HasTraits, PKG + '.test_service_registry.service_factory',
            {'price': 100})

        # Create a query that matches the registered object.
        service = self.service_registry.get_service(HasTraits, 'price <= 100')
        self.assertNotEqual(None, service)
        self.assertEqual(HasTraits, type(service))

        # This shows that the properties were passed in to the factory.
        self.assertEqual(100, service.price)

        # Make sure that the object created by the factory is cached (i.e. we
        # get the same object back from now on!).
        service2 = self.service_registry.get_service(HasTraits, 'price <= 100')
        self.assertTrue(service is service2)

    def test_function_service_factory(self):
        """ function service factory """
        class IFoo(Interface):
            price = Int

        @provides(IFoo)
        class Foo(HasTraits):
            price = Int

        def foo_factory(**properties):
            """ A factory for foos. """

            return Foo(**properties)

        # Register a service factory.
        self.service_registry.register_service(IFoo, foo_factory,
                                               {'price': 100})

        # Create a query that matches the registered object.
        service = self.service_registry.get_service(IFoo, 'price <= 100')
        self.assertNotEqual(None, service)
        self.assertEqual(Foo, type(service))

        # Make sure that the object created by the factory is cached (i.e. we
        # get the same object back from now on!).
        service2 = self.service_registry.get_service(IFoo, 'price <= 100')
        self.assertTrue(service is service2)

    def test_lazy_function_service_factory(self):
        """ lazy function service factory """

        # Register a service factory by name.
        def foo_factory(**properties):
            """ A factory for foos. """

            from envisage.tests.foo import Foo

            foo_factory.foo = Foo()

            return foo_factory.foo

        i_foo = PKG + '.i_foo.IFoo'
        foo = PKG + '.foo'

        self.service_registry.register_service(i_foo, foo_factory)

        # Get rid of the 'foo' module (used in other tests).
        if foo in sys.modules:
            del sys.modules[foo]

        # Make sure that we haven't imported the 'foo' module.
        self.assertTrue(foo not in sys.modules)

        # Look up a non-existent service.
        services = self.service_registry.get_services('bogus.IBogus')

        # Make sure that we *still* haven't imported the 'foo' module.
        self.assertTrue(foo not in sys.modules)

        # Look it up again.
        services = self.service_registry.get_services(i_foo)
        self.assertEqual([foo_factory.foo], services)
        self.assertTrue(foo in sys.modules)

        # Clean up!
        del sys.modules[foo]

    def test_lazy_bound_method_service_factory(self):
        """ lazy bound method service factory """

        i_foo = PKG + '.i_foo.IFoo'
        foo = PKG + '.foo'

        class ServiceProvider(HasTraits):
            """ A class that provides a service.

            This is used to make sure a bound method can be used as a service
            factory.

            """

            # Register a service factory by name.
            def foo_factory(self, **properties):
                """ A factory for foos. """

                from envisage.tests.foo import Foo

                self.foo = Foo()

                return self.foo

        sp = ServiceProvider()
        self.service_registry.register_service(i_foo, sp.foo_factory)

        # Get rid of the 'foo' module (used in other tests).
        if foo in sys.modules:
            del sys.modules[foo]

        # Make sure that we haven't imported the 'foo' module.
        self.assertTrue(foo not in sys.modules)

        # Look up a non-existent service.
        services = self.service_registry.get_services('bogus.IBogus')

        # Make sure that we *still* haven't imported the 'foo' module.
        self.assertTrue(foo not in sys.modules)

        # Look up the service.
        services = self.service_registry.get_services(i_foo)
        self.assertEqual([sp.foo], services)
        self.assertTrue(foo in sys.modules)

        # Clean up!
        del sys.modules[foo]

    def test_get_services(self):
        """ get services """
        class IFoo(Interface):
            pass

        @provides(IFoo)
        class Foo(HasTraits):
            pass

        # Register two services.
        foo = Foo()
        self.service_registry.register_service(IFoo, foo)

        foo = Foo()
        self.service_registry.register_service(IFoo, foo)

        # Look it up again.
        services = self.service_registry.get_services(IFoo)
        self.assertEqual(2, len(services))

        class IBar(Interface):
            pass

        # Lookup a non-existent service.
        services = self.service_registry.get_services(IBar)
        self.assertEqual([], services)

    def test_get_services_with_strings(self):
        """ get services with strings """

        from envisage.tests.foo import Foo

        # Register a couple of services using a string protocol name.
        protocol_name = 'envisage.tests.foo.IFoo'

        self.service_registry.register_service(protocol_name, Foo())
        self.service_registry.register_service(protocol_name, Foo())

        # Look them up using the same string!
        services = self.service_registry.get_services(protocol_name)
        self.assertEqual(2, len(services))

    def test_get_services_with_query(self):
        """ get services with query """
        class IFoo(Interface):
            price = Int

        @provides(IFoo)
        class Foo(HasTraits):
            price = Int

        # Register two services.
        #
        # This one shows how the object's attributes are used when evaluating
        # a query.
        foo = Foo(price=100)
        self.service_registry.register_service(IFoo, foo)

        # This one shows how properties can be specified that *take precedence*
        # over the object's attributes when evaluating a query.
        goo = Foo(price=10)
        self.service_registry.register_service(IFoo, goo, {'price': 200})

        # Create a query that doesn't match any registered object.
        services = self.service_registry.get_services(IFoo, 'color == "red"')
        self.assertEqual([], services)

        # Create a query that matches one of the registered objects.
        services = self.service_registry.get_services(IFoo, 'price <= 100')
        self.assertEqual([foo], services)

        # Create a query that matches both registered objects.
        services = self.service_registry.get_services(IFoo, 'price >= 100')
        self.assertTrue(foo in services)
        self.assertTrue(goo in services)
        self.assertEqual(2, len(services))

        class IBar(Interface):
            pass

        # Lookup a non-existent service.
        services = self.service_registry.get_services(IBar, 'price <= 100')
        self.assertEqual([], services)

    def test_get_service(self):
        """ get service """
        class IFoo(Interface):
            pass

        @provides(IFoo)
        class Foo(HasTraits):
            pass

        # Register a couple of services.
        foo = Foo()
        self.service_registry.register_service(IFoo, foo)

        goo = Foo()
        self.service_registry.register_service(IFoo, goo)

        # Look up one of them!
        service = self.service_registry.get_service(IFoo)
        self.assertTrue(foo is service or goo is service)

        class IBar(Interface):
            pass

        # Lookup a non-existent service.
        service = self.service_registry.get_service(IBar)
        self.assertEqual(None, service)

    def test_get_service_with_query(self):
        """ get service with query """
        class IFoo(Interface):
            price = Int

        @provides(IFoo)
        class Foo(HasTraits):
            price = Int

        # Register two services.
        #
        # This one shows how the object's attributes are used when evaluating
        # a query.
        foo = Foo(price=100)
        self.service_registry.register_service(IFoo, foo)

        # This one shows how properties can be specified that *take precedence*
        # over the object's attributes when evaluating a query.
        goo = Foo(price=10)
        self.service_registry.register_service(IFoo, goo, {'price': 200})

        # Create a query that doesn't match any registered object.
        service = self.service_registry.get_service(IFoo, 'price < 100')
        self.assertEqual(None, service)

        # Create a query that matches one of the registered objects.
        service = self.service_registry.get_service(IFoo, 'price <= 100')
        self.assertEqual(foo, service)

        # Create a query that matches both registered objects.
        service = self.service_registry.get_service(IFoo, 'price >= 100')
        self.assertTrue(foo is service or goo is service)

        class IBar(Interface):
            pass

        # Lookup a non-existent service.
        service = self.service_registry.get_service(IBar, 'price <= 100')
        self.assertEqual(None, service)

    def test_get_and_set_service_properties(self):
        """ get and set service properties """
        class IFoo(Interface):
            price = Int

        @provides(IFoo)
        class Foo(HasTraits):
            price = Int

        # Register two services.
        #
        # This one has no properties.
        foo = Foo(price=100)
        foo_id = self.service_registry.register_service(IFoo, foo)

        # This one has properties.
        goo = Foo(price=10)
        goo_id = self.service_registry.register_service(
            IFoo, goo, {'price': 200})

        # Get the properties.
        foo_properties = self.service_registry.get_service_properties(foo_id)
        self.assertEqual({}, foo_properties)

        goo_properties = self.service_registry.get_service_properties(goo_id)
        self.assertEqual(200, goo_properties['price'])

        # Update the properties.
        foo_properties['price'] = 300
        goo_properties['price'] = 500

        # Set the properties.
        self.service_registry.set_service_properties(foo_id, foo_properties)
        self.service_registry.set_service_properties(goo_id, goo_properties)

        # Get the properties again.
        foo_properties = self.service_registry.get_service_properties(foo_id)
        self.assertEqual(300, foo_properties['price'])

        goo_properties = self.service_registry.get_service_properties(goo_id)
        self.assertEqual(500, goo_properties['price'])

        # Try to get the properties of a non-existent service.
        with self.assertRaises(ValueError):
            self.service_registry.get_service_properties(-1)

        # Try to set the properties of a non-existent service.
        with self.assertRaises(ValueError):
            self.service_registry.set_service_properties(-1, {})

    def test_unregister_service(self):
        """ unregister service """
        class IFoo(Interface):
            price = Int

        @provides(IFoo)
        class Foo(HasTraits):
            price = Int

        # Register two services.
        #
        # This one shows how the object's attributes are used when evaluating
        # a query.
        foo = Foo(price=100)
        foo_id = self.service_registry.register_service(IFoo, foo)

        # This one shows how properties can be specified that *take precedence*
        # over the object's attributes when evaluating a query.
        goo = Foo(price=10)
        goo_id = self.service_registry.register_service(
            IFoo, goo, {'price': 200})

        # Create a query that doesn't match any registered object.
        service = self.service_registry.get_service(IFoo, 'price < 100')
        self.assertEqual(None, service)

        # Create a query that matches one of the registered objects.
        service = self.service_registry.get_service(IFoo, 'price <= 100')
        self.assertEqual(foo, service)

        # Create a query that matches both registered objects.
        service = self.service_registry.get_service(IFoo, 'price >= 100')
        self.assertTrue(foo is service or goo is service)

        #### Now do some unregistering! ####

        # Unregister 'foo'.
        self.service_registry.unregister_service(foo_id)

        # This query should no longer match any of the registered objects.
        service = self.service_registry.get_service(IFoo, 'price <= 100')
        self.assertEqual(None, service)

        # Unregister 'goo'.
        self.service_registry.unregister_service(goo_id)

        # This query should no longer match any of the registered objects.
        service = self.service_registry.get_service(IFoo, 'price >= 100')
        self.assertEqual(None, service)

        # Try to unregister a non-existent service.
        with self.assertRaises(ValueError):
            self.service_registry.unregister_service(-1)

    def test_minimize_and_maximize(self):
        """ minimize and maximize """
        class IFoo(Interface):
            price = Int

        @provides(IFoo)
        class Foo(HasTraits):
            price = Int

        # Register some objects with various prices.
        x = Foo(price=10)
        y = Foo(price=5)
        z = Foo(price=100)

        for foo in [x, y, z]:
            self.service_registry.register_service(IFoo, foo)

        # Find the service with the lowest price.
        service = self.service_registry.get_service(IFoo, minimize='price')
        self.assertNotEqual(None, service)
        self.assertEqual(Foo, type(service))
        self.assertEqual(y, service)

        # Find the service with the highest price.
        service = self.service_registry.get_service(IFoo, maximize='price')
        self.assertNotEqual(None, service)
        self.assertEqual(Foo, type(service))
        self.assertEqual(z, service)
예제 #27
0
    greetings = List(contributes_to="greetings")

    # This shows how you can use a standard trait initializer to populate the
    # list dynamically.
    def _greetings_default(self):
        """ Trait initializer. """

        extensions = [
            "The %s application says %s" % (self.application.id, greeting)
            for greeting in ["Bonjour", "Hola"]
        ]

        return extensions


# Application entry point.
if __name__ == "__main__":

    # Create the application.
    #
    # An application is simply a collection of plugins. In this case we
    # specify the plugins explicitly, but the mechanism for finding plugins
    # is configurable by setting the application's 'plugin_manager' trait.
    application = Application(
        id="hello.world", plugins=[HelloWorld(),
                                   Greetings(),
                                   MoreGreetings()])

    # Run it!
    application.run()