示例#1
0
    def __call__(self, environ, start_response):
        """
        Dispatches WSGI requests
        """
        logger = logging.getLogger("genesis2")
        logger.debug('Dispatching %s' % environ['PATH_INFO'])
        self.environ = environ
        self.status = '200 OK'
        self.headers = [('Content-type', 'text/html')]
        self.session = environ['app.session']
        appmgr = AppManager()

        content = 'Sorry, no content for you'
        for handler in appmgr.grab_apps(IURLHandler):
            if handler.match_url(environ):
                try:
                    content = handler.url_handler(self.environ, self.start_response)
                except Exception, e:
                    try:
                        # content = format_error(self, e)
                        pass
                    except:
                        content = 'Fatal error occured:\n' + traceback.format_exc()
                finally:
                    break
示例#2
0
def run_server(config_file=""):
    if config_file != "":
        config_dir = os.path.dirname(config_file)
        if (not os.path.exists(config_dir)) or (not os.path.isdir(config_dir)):
            print "Error in the config file."
    else:
        config_dir = os.getcwd() + "/configs"
        config_file = config_dir + "/genesis2.conf"

    make_log(config_dir)
    logger = logging.getLogger("genesis2")
    logger.info("Genesis %s" % version())
    if os.path.isfile(config_file):
        logger.info("Using config file %s" % config_file)
    else:
        # Shutdown
        logger.critical("The %s is not a file." % config_file)
        exit(-1)

    # Read config
    config = Config()
    if os.path.exists(config_file) and os.path.isfile(config_file):
        config.load(config_file)
    else:
        logger.critical("The %s doesn't exist" % config_file)
        exit(-1)

    # (kudrom) TODO: I should delete the GenesisManager and substitute it with a Plugin
    GenesisManager(config)

    platform = detect_platform()
    logger.info("Detected platform: %s" % platform)

    # Load plugins
    import genesis2.plugins

    # Load apps
    path_apps = config.get("genesis2", "path_apps", None)
    if path_apps is None:
        path_apps = os.getcwd() + "/apps"
    logger.info("Using %s as path apps." % path_apps)
    appmgr = AppManager(path_apps=path_apps)
    appmgr.load_apps()

    # (kudrom) TODO: Register a new ComponentMgr

    # (kudrom) TODO: we should use an iptables plugin
    # Make sure correct kernel modules are enabled
    # genesis2.utils.shell('modprobe ip_tables')

    if not hasattr(genesis2.apis, "PGenesis2Server"):
        logger.error("There's no plugin for PGenesis2Server registered in the system")
        exit(-1)

    # The server is a plugin to ease its replacement
    logger.info("Starting server")
    server = getattr(genesis2.apis, "PGenesis2Server")
    server.initialize(config)
    server.serve_forever()
示例#3
0
文件: tests.py 项目: kudrom/genesis2
class TestIntegration(TestCase):
    def setUp(self):
        plugin_loader = PluginLoader()
        plugin_loader.load_plugins('genesis2/core/tests')
        self.appmgr = AppManager("/".join((__file__.split("/")[:-1])) + "/apps")
        self.appmgr.path_apps = "/".join((__file__.split("/")[:-1])) + "/apps"
        self.appmgr.load_apps()

    def test_app_plugin(self):
        apps = self.appmgr.grab_apps(IFakeInterface, flt=lambda app: app.name == "IntegrationApp")
        self.assertEqual(len(apps), 1)
        app = apps[0]
        self.assertEqual(app.instance.required(), "f*****g awesome: I agree")

    def test_app_plugin_control_access(self):
        apps = self.appmgr.grab_apps(IAnotherInterface)
        self.assertEqual(len(apps), 1)
        app = apps[0]
        with self.assertRaises(AccessDenied):
            app.instance.required()
示例#4
0
文件: tests.py 项目: kudrom/genesis2
    def setUp(self):
        class MyApp(App):
            def __init__(self):
                super(MyApp, self).__init__()
                self._uses.append(IFakeInterface)

            def required(self):
                return "it worked"

        class MyApp2(App):
            def __init__(self):
                super(MyApp2, self).__init__()
                self._uses.append(IFakeInterface)

            def required(self):
                return "it worked"

        # Mocks the package/module metadata
        class MockMetadata(object):
            def __init__(self):
                self.AUTHOR = "kudrom"
                self.PKGNAME = "Testing"
                self.VERSION = 'v1.1'
                self.DESCRIPTION = "An awesome app"
                self.HOMEPAGE = "http://www.example.com"
                self.ICON = "hello-icon"

        # Constructors
        self.my_app = MyApp
        self.my_app2 = MyApp2
        self.fake_interface = IFakeInterface

        # Initializing the appmanager
        self.appmgr = AppManager(path_apps="/".join((__file__.split("/")[:-1])) + "/apps")
        self.appmgr._metadata = MockMetadata()

        # The mocking of the app.__init__.py file
        self.mockmetadata = MockMetadata
示例#5
0
    def refresh_plugin_data(self):
        """
        Rescans plugins for JS, CSS, LESS, XSLT widgets and XML templates.
        """
        self.template_path = []
        self.less_styles = []
        self.woff_fonts = []
        self.eot_fonts = []
        self.svg_fonts = []
        self.ttf_fonts = []
        self.template_styles = []
        self.template_scripts = []
        self.layouts = {}
        includes = []
        functions = {}
        appmgr = AppManager()

        for f in appmgr.grab_apps(IXSLTFunctionProvider):
            functions.update(f.get_funcs())

        # Get path for static content and templates
        apps = appmgr.grab_apps()

        for app in apps:
            path = os.path.join(app.file_path, app)

            fp = os.path.join(path, 'files')
            if os.path.exists(fp):
                self.template_styles.extend([
                    '/dl/'+app+'/'+s
                    for s in os.listdir(fp)
                    if s.endswith('.css')
                ])
                self.less_styles.extend([
                    '/dl/'+app+'/'+s
                    for s in os.listdir(fp)
                    if s.endswith('.less')
                ])
                self.woff_fonts.extend([
                    '/dl/'+app+'/'+s
                    for s in os.listdir(fp)
                    if s.endswith('.woff')
                ])
                self.eot_fonts.extend([
                    '/dl/'+app+'/'+s
                    for s in os.listdir(fp)
                    if s.endswith('.eot')
                ])
                self.svg_fonts.extend([
                    '/dl/'+app+'/'+s
                    for s in os.listdir(fp)
                    if s.endswith('.svg')
                ])
                self.ttf_fonts.extend([
                    '/dl/'+app+'/'+s
                    for s in os.listdir(fp)
                    if s.endswith('.ttf')
                ])
                self.template_scripts.extend([
                    '/dl/'+app+'/'+s
                    for s in os.listdir(fp)
                    if s.endswith('.js')
                ])

            wp = os.path.join(path, 'widgets')
            if os.path.exists(wp):
                includes.extend([
                    os.path.join(wp, s)
                    for s in os.listdir(wp)
                    if s.endswith('.xslt')
                ])

            lp = os.path.join(path, 'layout')
            if os.path.exists(lp):
                for s in os.listdir(lp):
                    if s.endswith('.xml'):
                        self.layouts['%s:%s' % (app, s)] = os.path.join(lp, s)

            tp = os.path.join(path, 'templates')
            if os.path.exists(tp):
                self.template_path.append(tp)
示例#6
0
文件: tests.py 项目: kudrom/genesis2
 def setUp(self):
     plugin_loader = PluginLoader()
     plugin_loader.load_plugins('genesis2/core/tests')
     self.appmgr = AppManager("/".join((__file__.split("/")[:-1])) + "/apps")
     self.appmgr.path_apps = "/".join((__file__.split("/")[:-1])) + "/apps"
     self.appmgr.load_apps()
示例#7
0
文件: tests.py 项目: kudrom/genesis2
class TestApp(TestCase):
    def setUp(self):
        class MyApp(App):
            def __init__(self):
                super(MyApp, self).__init__()
                self._uses.append(IFakeInterface)

            def required(self):
                return "it worked"

        class MyApp2(App):
            def __init__(self):
                super(MyApp2, self).__init__()
                self._uses.append(IFakeInterface)

            def required(self):
                return "it worked"

        # Mocks the package/module metadata
        class MockMetadata(object):
            def __init__(self):
                self.AUTHOR = "kudrom"
                self.PKGNAME = "Testing"
                self.VERSION = 'v1.1'
                self.DESCRIPTION = "An awesome app"
                self.HOMEPAGE = "http://www.example.com"
                self.ICON = "hello-icon"

        # Constructors
        self.my_app = MyApp
        self.my_app2 = MyApp2
        self.fake_interface = IFakeInterface

        # Initializing the appmanager
        self.appmgr = AppManager(path_apps="/".join((__file__.split("/")[:-1])) + "/apps")
        self.appmgr._metadata = MockMetadata()

        # The mocking of the app.__init__.py file
        self.mockmetadata = MockMetadata

    def tearDown(self):
        # To ensure that the loading of apps in one test doesn't misleads the results in other
        self.appmgr._instance_apps = {}
        self.appmgr._apps = {}
        self.appmgr._metadata = self.mockmetadata()

    def test_appmgr_singleton(self):
        appmgr2 = AppManager()
        self.assertEqual(self.appmgr, appmgr2)
        self.assertEqual(self.appmgr.path_apps, "/".join(__file__.split("/")[:-1]) + "/apps")

    def test_requirements_app(self):
        fake_interface = self.fake_interface

        class MyApp(App):
            def __init__(self):
                super(MyApp, self).__init__()
                self._uses.append(fake_interface)

        with self.assertRaises(AppInterfaceImplError):
            MyApp()

    def test_singleton_app(self):
        myapp = self.my_app()
        myapp2 = self.my_app()
        self.assertEqual(id(myapp), id(myapp2))

    def test_register_app(self):
        with patch('genesis2.core.core.AppManager') as manager:
            myapp = self.my_app()
            manager().register.assert_called_once_with(myapp, self.fake_interface)

    def test_observable_register(self):
        notify_observers_mock = MagicMock()
        self.appmgr.notify_observers = notify_observers_mock
        self.my_app()
        app = self.appmgr.grab_apps()[0]
        calls = [call("register", app, IFakeInterface)]
        notify_observers_mock.assert_has_calls(calls)

    def test_unregister_app(self):
        apps = self.appmgr.grab_apps()
        self.assertEqual(len(apps), 0)

        myapp = self.my_app()
        apps = self.appmgr.grab_apps()
        self.assertEqual(len(apps), 1)
        self.assertEqual(id(myapp), id(apps[0].instance))

        self.appmgr.unregister(apps[0])
        apps = self.appmgr.grab_apps()
        self.assertEqual(len(apps), 0)

        self.my_app()
        apps = self.appmgr.grab_apps()
        self.assertEqual(len(apps), 1)
        self.my_app2()
        apps = self.appmgr.grab_apps()
        self.assertEqual(len(apps), 2)
        self.appmgr.unregister(apps[0])
        apps = self.appmgr.grab_apps()
        self.assertEqual(len(apps), 1)

    def test_observable_unregister(self):
        notify_observers_mock = MagicMock()
        self.appmgr.notify_observers = notify_observers_mock

        self.my_app()
        app = self.appmgr.grab_apps()[0]
        self.appmgr.unregister(app)
        calls = [call("unregister", app, self.fake_interface)]
        notify_observers_mock.assert_has_calls(calls)

    def test_grab_apps(self):
        apps = self.appmgr.grab_apps(self.fake_interface)
        self.assertEqual(len(apps), 0)

        myapp = self.my_app()
        apps = self.appmgr.grab_apps(self.fake_interface)
        self.assertEqual(len(apps), 1)
        self.assertEqual(myapp.required(), "it worked")
        self.assertEqual(apps[0].instance, myapp)

        myapp2 = self.my_app2()
        apps = self.appmgr.grab_apps(self.fake_interface)
        self.assertEqual(len(apps), 2)

    def test_grab_filter(self):
        myapp = self.my_app()
        self.appmgr._metadata.AUTHOR = "PinkyWinky"
        myapp2 = self.my_app2()
        apps = self.appmgr.grab_apps(self.fake_interface, flt=lambda app: app.author == "kudrom")
        self.assertEqual(len(apps), 1)
        self.assertEqual(apps[0].instance, myapp)

    def test_app_info(self):
        class AppTesting(object):
            def __init__(self):
                self._uses = [IFakeInterface]
        instance = AppTesting()
        metadata = self.mockmetadata()
        app = AppInfo(instance, metadata)
        self.assertEqual(app.instance, instance)
        self.assertEqual(app.author, metadata.AUTHOR)
        self.assertEqual(app.pkgname, metadata.PKGNAME)
        self.assertEqual(app.version, metadata.VERSION)
        self.assertEqual(app.name, 'AppTesting')
        self.assertEqual(app.description, metadata.DESCRIPTION)
        self.assertEqual(app.homepage, metadata.HOMEPAGE)
        self.assertEqual(app.icon, metadata.ICON)
        self.assertEqual(app.interfaces, [IFakeInterface])

    def test_app_info_name(self):
        class AppTesting(object):
            def __init__(self):
                self._uses = [IFakeInterface]
                self.NAME = 'RandomName'
        instance = AppTesting()
        metadata = self.mockmetadata()
        app = AppInfo(instance, metadata)
        self.assertEqual(app.instance, instance)
        self.assertEqual(app.author, metadata.AUTHOR)
        self.assertEqual(app.pkgname, metadata.PKGNAME)
        self.assertEqual(app.version, metadata.VERSION)
        self.assertEqual(app.name, 'RandomName')
        self.assertEqual(app.description, metadata.DESCRIPTION)
        self.assertEqual(app.homepage, metadata.HOMEPAGE)
        self.assertEqual(app.icon, metadata.ICON)
        self.assertEqual(app.interfaces, [IFakeInterface])

    def test_load_apps(self):
        load_app_mock = MagicMock()
        self.appmgr.path_apps = "/".join((__file__.split("/")[:-1])) + "/apps"
        old_load = self.appmgr.load_app
        self.appmgr.load_app = load_app_mock
        notify_observers_mock = MagicMock()
        self.appmgr.notify_observers = notify_observers_mock
        self.appmgr.load_apps()
        calls = [call("app1"), call("app2"), call("appIntegration")]
        load_app_mock.assert_has_calls(calls, any_order=True)
        calls = [call("load_apps")]
        notify_observers_mock.assert_has_calls(calls)

        self.appmgr.load_app = old_load

    def test_load_app(self):
        genesis2.apis.PFakeInterface = object()
        self.appmgr.load_app("app1")
        apps = self.appmgr.grab_apps()
        self.assertEqual(len(apps), 1)
        app = apps[0]
        self.assertEqual(app.author, "kudrom")

        del genesis2.apis.PFakeInterface

    def test_load_app_with_not_implemented_interface(self):
        self.appmgr.path_apps = os.path.join(os.path.dirname(__file__), "test_app_apps")
        with self.assertRaises(AppRequirementError):
            self.appmgr.load_app("requirementErrorApp")