Example #1
0
        def wrapper(self):
            from anyblok.registry import RegistryManager
            name = self.__name__
            if name in cls.declaration_types:
                raise DeclarationsException(
                    "The declaration type %r is already defined" % name)

            cls.declaration_types[name] = self

            setattr(self, '__registry_name__', name)
            setattr(self, '__declaration_type__', name)
            setattr(cls, name, self)

            if isAnEntry:
                assemble_callback = initialize_callback = None
                if assemble and hasattr(self, assemble):
                    assemble_callback = getattr(self, assemble)

                if initialize and hasattr(self, initialize):
                    initialize_callback = getattr(self, initialize)

                RegistryManager.declare_entry(
                    name, assemble_callback=assemble_callback,
                    initialize_callback=initialize_callback)

            # All declaration type can need to be unload declarated values
            if unload and hasattr(self, unload):
                RegistryManager.declare_unload_callback(
                    name, getattr(self, unload))

            return self
Example #2
0
    def test_add_core(self):
        class test:
            pass

        RegistryManager.add_core_in_register('test', test)
        self.assertInCore(test)
        assert RegistryManager.has_core_in_register('testCore', 'test')
Example #3
0
 def reload_blokmanager(cls, **kwargs):
     """Reload all the  bloks with their code sources"""
     RegistryManager.clear()  # close all the registry
     BlokManager.reload()  # reload all the blok code
     # FIXME BlokManager.reload should close all the registry and
     # forbidden load registry during the reload
     return [{'type': 'RELOAD'}]
Example #4
0
    def imports(self):
        """ Imports modules and / or packages listed in the blok path"""
        from anyblok.blok import BlokManager
        from anyblok.registry import RegistryManager

        RegistryManager.init_blok(self.blok)
        b = BlokManager.get(self.blok)
        b.import_declaration_module()
Example #5
0
    def add_testCore(self, request, bloks_loaded):
        def reset():
            EnvironmentManager.set('current_blok', None)
            del RegistryManager.loaded_bloks['testCore' + self._corename]

        request.addfinalizer(reset)
        RegistryManager.init_blok('testCore' + self._corename)
        EnvironmentManager.set('current_blok', 'testCore' + self._corename)
Example #6
0
    def imports(self):
        """ Imports modules and / or packages listed in the blok path"""
        from anyblok.blok import BlokManager
        from anyblok.registry import RegistryManager

        RegistryManager.init_blok(self.blok)
        b = BlokManager.get(self.blok)
        b.import_declaration_module()
Example #7
0
    def test_add_entry(self):
        class test:
            pass

        RegistryManager.add_entry_in_register('Other', 'test', test)
        self.assertInEntry('test', test)
        assert RegistryManager.has_entry_in_register('testEntry', 'Other',
                                                     'test')
Example #8
0
    def unregister(self, entry, cls_):
        """ Remove the Interface from the registry

        :param entry: entry declaration of the model where the ``cls_``
            must be removed
        :param cls_: Class Interface to remove in the declaration
        """
        RegistryManager.remove_in_register(cls_)
Example #9
0
    def unregister(self, entry, cls_):
        """ Remove the Interface from the registry

        :param entry: entry declaration of the model where the ``cls_``
            must be removed
        :param cls_: Class Interface to remove in registry
        """
        RegistryManager.remove_in_register(cls_)
Example #10
0
    def tearDown(self):
        """ Clear the registry, unload the blok manager and  drop the database
        """
        if self.registry:
            self.registry.close()

        RegistryManager.clear()
        BlokManager.unload()
        super(DBTestCase, self).tearDown()
Example #11
0
    def test_add_core(self):
        class test:
            pass

        RegistryManager.add_core_in_register('test', test)
        self.assertInCore(test)
        self.assertEqual(
            RegistryManager.has_core_in_register('testCore', 'test'),
            True)
Example #12
0
    def init_env(self, request):

        def revert():
            EnvironmentManager.set('current_blok', None)
            del RegistryManager.loaded_bloks['testModel']

        request.addfinalizer(revert)
        RegistryManager.init_blok('testModel')
        EnvironmentManager.set('current_blok', 'testModel')
Example #13
0
    def init_env(self, request):
        def revert():
            EnvironmentManager.set('current_blok', None)
            del RegistryManager.loaded_bloks['testCore']
            RegistryManager.undeclare_core('test')

        request.addfinalizer(revert)
        RegistryManager.declare_core('test')
        RegistryManager.init_blok('testCore')
        EnvironmentManager.set('current_blok', 'testCore')
 def test_update_query(self):
     registry = RegistryManager.get(Configuration.get('db_name'))
     registry.upgrade(install=('test-me-blok2',))
     registry.commit()
     self.assertTrue(registry.System.Blok.query().all_name())
     self.assertTrue(registry.System.Blok.query().all())
     registry.close()
     registry = RegistryManager.get(Configuration.get('db_name'))
     self.assertTrue(registry.System.Blok.query().all_name())
     self.assertTrue(registry.System.Blok.query().all())
 def tearDown(self):
     """ Clear the registry, unload the blok manager and  drop the database
     """
     registry = RegistryManager.get(Configuration.get('db_name'))
     registry.close()
     RegistryManager.clear()
     BlokManager.unload()
     clear_mappers()
     self.__class__.dropdb()
     super(TestBlok, self).tearDown()
Example #16
0
    def tearDown(self):
        """ Clear the registry, unload the blok manager and  drop the database
        """
        if self.registry:
            self.registry.close()

        RegistryManager.clear()
        BlokManager.unload()
        clear_mappers()
        super(DBTestCase, self).tearDown()
Example #17
0
    def test_add_entry(self):
        class test:
            pass

        RegistryManager.add_entry_in_register('Other', 'test', test)
        self.assertInEntry('test', test)
        self.assertEqual(
            RegistryManager.has_entry_in_register('testEntry', 'Other',
                                                  'test'),
            True)
Example #18
0
    def test_get_entry_properties_in_register(self):
        class test:
            pass

        RegistryManager.add_entry_in_register('Other', 'test', test,
                                              property1='test')
        properties = RegistryManager.get_entry_properties_in_register(
            'Other', 'test')

        hasproperty1 = 'property1' in properties
        self.assertTrue(hasproperty1)
        self.assertEqual(properties['property1'], 'test')
Example #19
0
    def test_get_entry_properties_in_register(self):
        class test:
            pass

        RegistryManager.add_entry_in_register('Other',
                                              'test',
                                              test,
                                              property1='test')
        properties = RegistryManager.get_entry_properties_in_register(
            'Other', 'test')

        hasproperty1 = 'property1' in properties
        assert hasproperty1
        assert properties['property1'] == 'test'
Example #20
0
    def test_init_blok(self):
        RegistryManager.init_blok('newblok')
        is_exist = 'newblok' in RegistryManager.loaded_bloks
        self.assertEqual(is_exist, True)
        for core in ('Base', 'SqlBase', 'SqlViewBase', 'Session', 'Query',
                     'InstrumentedList'):
            self.assertIn(
                core, RegistryManager.loaded_bloks['newblok']['Core'].keys())
            self.assertEqual(
                RegistryManager.loaded_bloks['newblok']['Core'][core], [])

        self.assertEqual(RegistryManager.loaded_bloks['newblok']['Model'],
                         {'registry_names': []})
        self.assertEqual(RegistryManager.loaded_bloks['newblok']['Mixin'],
                         {'registry_names': []})
Example #21
0
    def test_init_blok(self):
        RegistryManager.init_blok('newblok')
        is_exist = 'newblok' in RegistryManager.loaded_bloks
        self.assertEqual(is_exist, True)
        for core in ('Base', 'SqlBase', 'SqlViewBase', 'Session', 'Query',
                     'InstrumentedList'):
            self.assertIn(
                core, RegistryManager.loaded_bloks['newblok']['Core'].keys())
            self.assertEqual(
                RegistryManager.loaded_bloks['newblok']['Core'][core], [])

        self.assertEqual(RegistryManager.loaded_bloks['newblok']['Model'],
                         {'registry_names': []})
        self.assertEqual(RegistryManager.loaded_bloks['newblok']['Mixin'],
                         {'registry_names': []})
Example #22
0
    def register(self, parent, name, cls_, **kwargs):
        """ Add new sub registry in the registry

        :param parent: Existing declaration
        :param name: Name of the new declaration to add it
        :param cls_: Class Interface to add in the declaration
        """
        if not hasattr(parent, name):
            core = type(name, tuple(), {})
            setattr(parent, name, core)

        if parent == Declarations:
            return

        RegistryManager.add_core_in_register(name, cls_)
Example #23
0
    def register(self, parent, name, cls_, **kwargs):
        """ Add new sub registry in the registry

        :param parent: Existing declaration
        :param name: Name of the new declaration to add it
        :param cls_: Class Interface to add in the declaration
        """
        if not hasattr(parent, name):
            core = type(name, tuple(), {})
            setattr(parent, name, core)

        if parent == Declarations:
            return

        RegistryManager.add_core_in_register(name, cls_)
Example #24
0
    def test_add_entry(self):
        RegistryManager.declare_entry('Other')
        RegistryManager.init_blok('newblok')
        is_exist = 'newblok' in RegistryManager.loaded_bloks
        self.assertEqual(is_exist, True)
        for entry in ('Base', 'SqlBase', 'SqlViewBase', 'Session', 'Query',
                      'InstrumentedList'):
            self.assertEqual(
                RegistryManager.loaded_bloks['newblok']['Core'][entry], [])

        self.assertEqual(RegistryManager.loaded_bloks['newblok']['Model'],
                         {'registry_names': []})
        self.assertEqual(RegistryManager.loaded_bloks['newblok']['Mixin'],
                         {'registry_names': []})
        self.assertEqual(RegistryManager.loaded_bloks['newblok']['Other'],
                         {'registry_names': []})
Example #25
0
    def test_init_blok(self):
        RegistryManager.init_blok('newblok')
        is_exist = 'newblok' in RegistryManager.loaded_bloks
        assert is_exist
        for core in ('Base', 'SqlBase', 'SqlViewBase', 'Session', 'Query',
                     'InstrumentedList'):
            assert core in RegistryManager.loaded_bloks['newblok'][
                'Core'].keys()
            assert RegistryManager.loaded_bloks['newblok']['Core'][core] == []

        assert RegistryManager.loaded_bloks['newblok']['Model'] == {
            'registry_names': []
        }
        assert RegistryManager.loaded_bloks['newblok']['Mixin'] == {
            'registry_names': []
        }
Example #26
0
def createdb(application, configuration_groups, **kwargs):
    """ Create a database and install blok from config

    :param application: name of the application
    :param configuration_groups: list configuration groupe to load
    :param \**kwargs: ArgumentParser named arguments
    """
    format_configuration(configuration_groups,
                         'create_db', 'install-bloks',
                         'install-or-update-bloks')
    load_init_function_from_entry_points()
    Configuration.load(application, configuration_groups=configuration_groups,
                       **kwargs)
    BlokManager.load()
    db_name = Configuration.get('db_name')
    db_template_name = Configuration.get('db_template_name', None)
    url = Configuration.get('get_url')(db_name=db_name)
    create_database(url, template=db_template_name)
    registry = RegistryManager.get(db_name)
    if registry is None:
        return

    if Configuration.get('install_all_bloks'):
        bloks = registry.System.Blok.list_by_state('uninstalled')
    else:
        install_bloks = Configuration.get('install_bloks') or []
        iou_bloks = Configuration.get('install_or_update_bloks') or []
        bloks = list(set(install_bloks + iou_bloks))

    registry.upgrade(install=bloks)
    registry.commit()
    registry.close()
Example #27
0
def init_registry_with_bloks(bloks, function, **kwargs):
    if bloks is None:
        bloks = []
    if isinstance(bloks, tuple):
        bloks = list(bloks)
    if isinstance(bloks, str):
        bloks = [bloks]

    anyblok_test_name = 'anyblok-test'
    if anyblok_test_name not in bloks:
        bloks.append(anyblok_test_name)

    loaded_bloks = deepcopy(RegistryManager.loaded_bloks)
    if function is not None:
        EnvironmentManager.set('current_blok', anyblok_test_name)
        try:
            function(**kwargs)
        finally:
            EnvironmentManager.set('current_blok', None)
    try:
        registry = RegistryManager.get(Configuration.get('db_name'),
                                       unittest=True)

        # update required blok
        registry_bloks = registry.get_bloks_by_states('installed', 'toinstall')
        toinstall = [x for x in bloks if x not in registry_bloks]
        toupdate = [x for x in bloks if x in registry_bloks]
        registry.upgrade(install=toinstall, update=toupdate)
    finally:
        RegistryManager.loaded_bloks = loaded_bloks

    return registry
Example #28
0
    def load_registry(self):
        if self.enabled and self.registryLoaded is False:
            # Load the registry here not in configuration,
            # because the configuration are not load in order of score
            self.registryLoaded = True
            BlokManager.load()
            load_init_function_from_entry_points(unittest=True)
            Configuration.load_config_for_test()
            Configuration.parse_options(self.AnyBlokOptions, ('bloks',))
            db_name = Configuration.get('db_name')
            if not db_name:
                raise Exception("No database defined to run Test")

            registry = RegistryManager.get(db_name)
            if registry:
                installed_bloks = registry.System.Blok.list_by_state(
                    "installed")
                selected_bloks = Configuration.get('selected_bloks')
                if not selected_bloks:
                    selected_bloks = installed_bloks

                unwanted_bloks = Configuration.get('unwanted_bloks')
                if unwanted_bloks is None:
                    unwanted_bloks = []

                self.bloks_path = [BlokManager.getPath(x)
                                   for x in BlokManager.ordered_bloks]

                self.authoried_bloks_test_files = [
                    path for blok in installed_bloks
                    if blok in selected_bloks and blok not in unwanted_bloks
                    for path in [join(BlokManager.getPath(blok), 'tests')]
                    if exists(path)]
                registry.close()  # free the registry to force create it again
Example #29
0
def get_registry_for(dbname, loadwithoutmigration=True, log_repeat=False):
    settings = {
        'anyblok.session.event': [register],
    }
    return RegistryManager.get(
        dbname, loadwithoutmigration=loadwithoutmigration,
        log_repeat=log_repeat, **settings)
Example #30
0
    def test_remove_entry(self):
        class test:
            pass

        def has_test_in_removed():
            core = RegistryManager.loaded_bloks['testEntry']['removed']
            if test in core:
                return True

            return False

        RegistryManager.add_entry_in_register('Other', 'test', test)
        self.assertInEntry('test', test)
        self.assertFalse(has_test_in_removed())
        RegistryManager.remove_in_register(test)
        self.assertTrue(has_test_in_removed())
Example #31
0
    def createdb(cls, keep_existing=False, with_demo=False):
        """Create the database specified in configuration.

        ::

            cls.init_configuration_manager()
            cls.createdb()

        :param keep_existing: If false drop the previous db before create it
        """
        url = Configuration.get('get_url')()
        db_template_name = Configuration.get('db_template_name', None)
        if database_exists(url):
            if keep_existing:
                return False

            drop_database(url)

        create_database(url, template=db_template_name)

        registry = RegistryManager.get(Configuration.get('db_name', None))
        if registry is None:
            return

        registry.System.Parameter.set(
            "with-demo", Configuration.get('with_demo', with_demo))

        return True
Example #32
0
    def test_remove_core(self):
        class test:
            pass

        def has_test_in_removed():
            core = RegistryManager.loaded_bloks['testCore']['removed']
            if test in core:
                return True

            return False

        RegistryManager.add_core_in_register('test', test)
        self.assertInCore(test)
        self.assertEqual(has_test_in_removed(), False)
        RegistryManager.remove_in_register(test)
        self.assertEqual(has_test_in_removed(), True)
Example #33
0
def anyblok_createdb():
    """Create a database and install blok from config"""
    load_init_function_from_entry_points()
    Configuration.load('createdb')
    configuration_post_load()
    BlokManager.load()
    db_name = get_db_name()

    db_template_name = Configuration.get('db_template_name', None)
    url = Configuration.get('get_url')(db_name=db_name)
    create_database(url, template=db_template_name)
    anyblok_registry = RegistryManager.get(db_name)
    if anyblok_registry is None:
        return

    anyblok_registry.System.Parameter.set(
        "with-demo", Configuration.get('with_demo', False))

    if Configuration.get('install_all_bloks'):
        bloks = anyblok_registry.System.Blok.list_by_state('uninstalled')
    else:
        install_bloks = Configuration.get('install_bloks') or []
        iou_bloks = Configuration.get('install_or_update_bloks') or []
        bloks = list(set(install_bloks + iou_bloks))

    anyblok_registry.upgrade(install=bloks)
    anyblok_registry.commit()
    anyblok_registry.close()
Example #34
0
    def test_remove_core(self):
        class test:
            pass

        def has_test_in_removed():
            core = RegistryManager.loaded_bloks['testCore']['removed']
            if test in core:
                return True

            return False

        RegistryManager.add_core_in_register('test', test)
        self.assertInCore(test)
        assert not has_test_in_removed()
        RegistryManager.remove_in_register(test)
        assert has_test_in_removed()
Example #35
0
    def test_add_entry(self):
        RegistryManager.declare_entry('Other')
        RegistryManager.init_blok('newblok')
        is_exist = 'newblok' in RegistryManager.loaded_bloks
        self.assertEqual(is_exist, True)
        for entry in ('Base', 'SqlBase', 'SqlViewBase', 'Session', 'Query',
                      'InstrumentedList'):
            self.assertEqual(
                RegistryManager.loaded_bloks['newblok']['Core'][entry], [])

        self.assertEqual(RegistryManager.loaded_bloks['newblok']['Model'],
                         {'registry_names': []})
        self.assertEqual(RegistryManager.loaded_bloks['newblok']['Mixin'],
                         {'registry_names': []})
        self.assertEqual(RegistryManager.loaded_bloks['newblok']['Other'],
                         {'registry_names': []})
Example #36
0
    def before_process_message(self, broker, message):
        """Called before process message

        Invalid the cache, this is mean that if a cache have to be invalidated
        then it will be invalidated else nothing is done

        If the message is in the ``Model.Dramatiq.Message`` then
        the status will be change to **running**

        :param broker: the broker used
        :param message: the message send in the broker
        """
        registry = RegistryManager.get(Configuration.get('db_name'))
        logger.debug("[before_process_message] %s: update message(%s) status ",
                     id(registry.session), message.message_id)
        # cache may have change, then we do the invalidation in the dramatiq
        # side
        registry.System.Cache.clear_invalidate_cache()

        M = registry.Dramatiq.Message
        m = M.get_instance_of(message)
        if m:
            m.update_status(M.STATUS_RUNNING)
            registry.commit()
            EnvironmentManager.set('is_called_by_dramatiq_actor', True)
Example #37
0
def load_client(request):
    """ Return the client main page """
    database = request.session.get('database')
    login = request.session.get('login')
    password = request.session.get('password')
    state = request.session.get('state')

    if not(database and login and password and state == "connected"):
        logout(request)
        return HTTPFound(location=request.route_url('homepage'))

    try:
        registry = RegistryManager.get(database)
        assert registry.Web.Login.check_authentification(login, password)
    except:
        logout(request)
        return HTTPFound(location=request.route_url('homepage'))

    css = registry.Web.get_css()
    js = registry.Web.get_js()
    js_babel = registry.Web.get_js_babel()
    # TODO see in system.parmeter if they are no data for title
    title = Configuration.get('app_name', 'ERPBlok')
    templates = registry.Web.get_templates()
    return render_to_response('erpblok:client.mak',
                              {'title': title,
                               'css': css,
                               'js': js,
                               'js_babel': js_babel,
                               'templates': templates,
                               }, request=request)
Example #38
0
def anyblok_createdb():
    """Create a database and install blok from config"""
    load_init_function_from_entry_points()
    Configuration.load('createdb')
    configuration_post_load()
    BlokManager.load()
    db_name = get_db_name()

    db_template_name = Configuration.get('db_template_name', None)
    url = Configuration.get('get_url')(db_name=db_name)
    create_database(url, template=db_template_name)
    registry = RegistryManager.get(db_name)
    if registry is None:
        return

    if Configuration.get('install_all_bloks'):
        bloks = registry.System.Blok.list_by_state('uninstalled')
    else:
        install_bloks = Configuration.get('install_bloks') or []
        iou_bloks = Configuration.get('install_or_update_bloks') or []
        bloks = list(set(install_bloks + iou_bloks))

    registry.upgrade(install=bloks)
    registry.commit()
    registry.close()
Example #39
0
def get_registry_for(dbname, loadwithoutmigration=True, log_repeat=False):
    settings = {
        'anyblok.session.event': [register],
    }
    return RegistryManager.get(dbname,
                               loadwithoutmigration=loadwithoutmigration,
                               log_repeat=log_repeat,
                               **settings)
 def setUp(self):
     super(TestBlok, self).setUp()
     self.__class__.init_configuration_manager()
     self.__class__.createdb(keep_existing=False)
     BlokManager.load(entry_points=('bloks', 'test_bloks'))
     registry = RegistryManager.get(Configuration.get('db_name'))
     registry.commit()
     registry.close()
Example #41
0
def webserver(request, configuration_loaded, init_session):
    with TestClient(
            create_app(
                RegistryManager.get(
                    Configuration.get("db_name"),
                    loadwithoutmigration=True,
                ))) as client:
        yield client
Example #42
0
    def test_add_entry(self):
        RegistryManager.declare_entry('Other')
        RegistryManager.init_blok('newblok')
        is_exist = 'newblok' in RegistryManager.loaded_bloks
        assert is_exist
        for entry in ('Base', 'SqlBase', 'SqlViewBase', 'Session', 'Query',
                      'InstrumentedList'):
            assert RegistryManager.loaded_bloks['newblok']['Core'][entry] == []

        assert RegistryManager.loaded_bloks['newblok']['Model'] == {
            'registry_names': []
        }
        assert RegistryManager.loaded_bloks['newblok']['Mixin'] == {
            'registry_names': []
        }
        assert RegistryManager.loaded_bloks['newblok']['Other'] == {
            'registry_names': []
        }
Example #43
0
    def before_worker_thread_shutdown(self, *args, **kwargs):
        """Called before worker thread shutdown

        remove the session instance to clean the Session pool

        """
        registry = RegistryManager.get(Configuration.get('db_name'))
        logger.debug("[before_worker_thread_shutdown] %s: %r %r",
                     id(registry.session), args, kwargs)
        registry.Session.remove()
Example #44
0
    def register(cls, parent, name, cls_, **kwargs):
        """ add new sub registry in the registry

        :param parent: Existing global registry
        :param name: Name of the new registry to add it
        :param cls_: Class Interface to add in registry
        """
        _registryname = parent.__registry_name__ + '.' + name

        if not hasattr(parent, name):
            kwargs['__registry_name__'] = _registryname
            ns = type(name, tuple(), kwargs)
            setattr(parent, name, ns)

        if parent is Declarations:
            return

        RegistryManager.add_entry_in_register(cls.__name__, _registryname,
                                              cls_, **kwargs)
Example #45
0
    def setUpClass(cls):
        """ Initialize the registry.
        """
        super(BlokTestCase, cls).setUpClass()
        additional_setting = cls.additional_setting()
        if cls.registry is None:
            cls.registry = RegistryManager.get(Configuration.get('db_name'),
                                               **additional_setting)

        cls.registry.commit()
Example #46
0
    def after_worker_shutdown(self, *args, **kwargs):
        """Called before worker shutdown

        Close the AnyBlok registry

        """
        registry = RegistryManager.get(Configuration.get('db_name'))
        logger.debug("[after_worker_shutdown] %s: %r %r", id(registry.session),
                     args, kwargs)
        registry.close()
Example #47
0
    def reload(self):
        """ Reload all the imports for this module

        :exception: ImportManagerException
        """
        from anyblok.blok import BlokManager
        from anyblok.registry import RegistryManager
        from anyblok.environment import EnvironmentManager

        b = BlokManager.get(self.blok)
        if not hasattr(b, 'reload_declaration_module'):
            return

        try:
            EnvironmentManager.set('reload', True)
            RegistryManager.init_blok(self.blok)
            b.reload_declaration_module(reload_wraper)
        finally:
            EnvironmentManager.set('reload', False)
Example #48
0
    def register(cls, parent, name, cls_, **kwargs):
        """ add new sub registry in the registry

        :param parent: Existing global registry
        :param name: Name of the new registry to add it
        :param cls_: Class Interface to add in registry
        """
        _registryname = parent.__registry_name__ + '.' + name

        if not hasattr(parent, name):
            kwargs['__registry_name__'] = _registryname
            ns = type(name, tuple(), kwargs)
            setattr(parent, name, ns)

        if parent is Declarations:
            return

        RegistryManager.add_entry_in_register(
            cls.__name__, _registryname, cls_, **kwargs)
Example #49
0
    def reload(self):
        """ Reload all the imports for this module

        :exception: ImportManagerException
        """
        from anyblok.blok import BlokManager
        from anyblok.registry import RegistryManager
        from anyblok.environment import EnvironmentManager

        b = BlokManager.get(self.blok)
        if not hasattr(b, 'reload_declaration_module'):
            return

        try:
            EnvironmentManager.set('reload', True)
            RegistryManager.init_blok(self.blok)
            b.reload_declaration_module(reload_module)
        finally:
            EnvironmentManager.set('reload', False)
Example #50
0
def get_registry_for(
    dbname: str, loadwithoutmigration: bool = True, log_repeat: bool = False
):
    # Methode copied from anyblok_pyramid.common"""
    settings: Dict[str, Any] = {}
    return RegistryManager.get(
        dbname,
        loadwithoutmigration=loadwithoutmigration,
        log_repeat=log_repeat,
        **settings,
    )
Example #51
0
    def register(self, parent, name, cls_, **kwargs):
        """ add new sub registry in the registry

        :param parent: Existing global registry
        :param name: Name of the new registry to add it
        :param cls_: Class Interface to add in registry
        """
        _registryname = parent.__registry_name__ + '.' + name
        if 'tablename' in kwargs:
            tablename = kwargs.pop('tablename')
            if not isinstance(tablename, str):
                tablename = tablename.__tablename__

        elif hasattr(parent, name):
            tablename = getattr(parent, name).__tablename__
        else:
            if parent is Declarations or parent is Declarations.Model:
                tablename = name.lower()
            elif hasattr(parent, '__tablename__'):
                tablename = parent.__tablename__
                tablename += '_' + name.lower()

        if not hasattr(parent, name):
            p = {
                '__tablename__': tablename,
                '__registry_name__': _registryname,
                'use': lambda x: ModelAttribute(_registryname, x),
            }
            ns = type(name, tuple(), p)
            setattr(parent, name, ns)

        if parent is Declarations:
            return

        kwargs['__registry_name__'] = _registryname
        kwargs['__tablename__'] = tablename
        update_factory(kwargs)

        RegistryManager.add_entry_in_register('Model', _registryname, cls_,
                                              **kwargs)
        setattr(cls_, '__anyblok_kwargs__', kwargs)
Example #52
0
    def register(self, parent, name, cls_, **kwargs):
        """ add new sub registry in the registry

        :param parent: Existing global registry
        :param name: Name of the new registry to add it
        :param cls_: Class Interface to add in registry
        """
        _registryname = parent.__registry_name__ + '.' + name
        if 'tablename' in kwargs:
            tablename = kwargs.pop('tablename')
            if not isinstance(tablename, str):
                tablename = tablename.__tablename__

        elif hasattr(parent, name):
            tablename = getattr(parent, name).__tablename__
        else:
            if parent is Declarations or parent is Declarations.Model:
                tablename = name.lower()
            elif hasattr(parent, '__tablename__'):
                tablename = parent.__tablename__
                tablename += '_' + name.lower()

        if not hasattr(parent, name):
            p = {
                '__tablename__': tablename,
                '__registry_name__': _registryname,
                'use': lambda x: ModelAttribute(_registryname, x),
            }
            ns = type(name, tuple(), p)
            setattr(parent, name, ns)

        if parent is Declarations:
            return

        kwargs['__registry_name__'] = _registryname
        kwargs['__tablename__'] = tablename
        update_factory(kwargs)

        RegistryManager.add_entry_in_register(
            'Model', _registryname, cls_, **kwargs)
        setattr(cls_, '__anyblok_kwargs__', kwargs)
Example #53
0
def drop_database(database):
    """ Close the registry instance of the database and drop the database

    :param: database's name
    """
    url = Configuration.get('get_url')(db_name=database)
    if not database_exists(url):
        raise Exception("Database %r does not already exist")

    registry = RegistryManager.get(database)
    registry.close()
    SU_drop_database(url)
Example #54
0
    def test_add_callback(self):

        def callback():
            pass

        RegistryManager.declare_entry('Other', assemble_callback=callback,
                                      initialize_callback=callback)
        hasModel = 'Model' in RegistryManager.declared_entries
        hasMixin = 'Mixin' in RegistryManager.declared_entries
        hasOther = 'Other' in RegistryManager.declared_entries
        self.assertEqual(hasModel, True)
        self.assertEqual(hasMixin, True)
        self.assertEqual(hasOther, True)

        cb = Model.assemble_callback
        hasModelCb = cb == RegistryManager.callback_assemble_entries['Model']
        cb = callback
        hasOtherCb = cb == RegistryManager.callback_assemble_entries['Other']
        self.assertEqual(hasModelCb, True)
        self.assertEqual(hasOtherCb, True)

        cb = Model.initialize_callback
        hasModelCb = cb == RegistryManager.callback_initialize_entries['Model']
        cb = callback
        hasOtherCb = cb == RegistryManager.callback_initialize_entries['Other']
        self.assertEqual(hasModelCb, True)
        self.assertEqual(hasOtherCb, True)

        RegistryManager.init_blok('newblok')
        is_exist = 'newblok' in RegistryManager.loaded_bloks
        self.assertEqual(is_exist, True)
        hasCore = 'Core' in RegistryManager.loaded_bloks['newblok']
        hasModel = 'Model' in RegistryManager.loaded_bloks['newblok']
        hasMixin = 'Mixin' in RegistryManager.loaded_bloks['newblok']
        hasOther = 'Other' in RegistryManager.loaded_bloks['newblok']
        self.assertEqual(hasCore, True)
        self.assertEqual(hasModel, True)
        self.assertEqual(hasMixin, True)
        self.assertEqual(hasOther, True)
Example #55
0
    def getRegistry(cls):
        """Return the registry for the test database.

        This assumes the database is created, and the registry has already
        been initialized::

            registry = self.getRegistry()

        :rtype: registry instance
        """
        additional_setting = cls.additional_setting()
        return RegistryManager.get(Configuration.get('db_name'),
                                   **additional_setting)
Example #56
0
def create_database(database):
    """ Create a new database, initialize it and return an AnyBlok registry

    :param: database's name
    :rtype: AnyBlok registry instance
    """
    url = Configuration.get('get_url')(db_name=database)
    if database_exists(url):
        raise Exception("Database %r already exist")

    db_template_name = Configuration.get('db_template_name', None)
    SU_create_database(url, template=db_template_name)
    registry = RegistryManager.get(database)
    return registry
Example #57
0
 def tearDownClass(cls):
     super(TestRegistryEntry, cls).tearDownClass()
     EnvironmentManager.set('current_blok', None)
     del RegistryManager.loaded_bloks['testEntry']
     RegistryManager.undeclare_entry('Other')
Example #58
0
 def setUpClass(cls):
     super(TestRegistryEntry, cls).setUpClass()
     RegistryManager.declare_entry('Other')
     RegistryManager.init_blok('testEntry')
     EnvironmentManager.set('current_blok', 'testEntry')