Пример #1
0
def test_module_in_zipped():
    with zip_file_in_sys_path():
        import moduleinzipped

    scan(moduleinzipped)

    assert fixtures.calls == 1
Пример #2
0
def test_package_in_zipped():
    with zip_file_in_sys_path():
        import packageinzipped

    scan(packageinzipped)

    assert fixtures.calls == 1
Пример #3
0
def test_ignore_module_absolute():
    from .fixtures import ignore_module_absolute

    scan(ignore_module_absolute,
         ignore=['importscan.tests.fixtures.ignore_module_absolute.module'])

    assert fixtures.calls == 0
Пример #4
0
def test_package_in_zipped():
    with zip_file_in_sys_path():
        import packageinzipped

    scan(packageinzipped)

    assert fixtures.calls == 1
Пример #5
0
def test_ignore_module_absolute():
    from .fixtures import ignore_module_absolute

    scan(ignore_module_absolute,
         ignore=['importscan.tests.fixtures.ignore_module_absolute.module'])

    assert fixtures.calls == 0
Пример #6
0
def test_scenario():
    importscan.scan(scenario)
    dectate.commit(app.Root, app.Generic, app.Document)

    c = Client(app.Root())

    response = c.get('/document')
    assert response.body == b'Document root'

    response = c.get('/foo')
    assert response.body == b'Generic root'

    response = c.get('/document/a')
    assert response.body == b'Document model a'

    response = c.get('/foo/a')
    assert response.body == b'Generic model a'

    response = c.get('/')
    assert response.json == [
        'http://localhost/foo/a', 'http://localhost/document/b'
    ]

    response = c.get('/foo/a/link')
    assert response.body == b'http://localhost/document/c'

    response = c.get('/document/a/link')
    assert response.body == b'http://localhost/foo/d'
Пример #7
0
def test_module_in_zipped():
    with zip_file_in_sys_path():
        import moduleinzipped

    scan(moduleinzipped)

    assert fixtures.calls == 1
Пример #8
0
def test_attributeerror_not_handle_error():
    from .fixtures import attributeerror_not_handle_error

    # skip import errors but not attribute errors
    def handle_error(name, e):
        if not isinstance(e, ImportError):
            raise e

    with raises(AttributeError):
        scan(attributeerror_not_handle_error, handle_error=handle_error)
Пример #9
0
def test_attributeerror_not_handle_error():
    from .fixtures import attributeerror_not_handle_error

    # skip import errors but not attribute errors
    def handle_error(name, e):
        if not isinstance(e, ImportError):
            raise e

    with raises(AttributeError):
        scan(attributeerror_not_handle_error, handle_error=handle_error)
Пример #10
0
def init_database(registry):
    import importscan
    import reha.sql

    database = reha.sql.Database.from_url(
       url="sqlite:///example.db"
    )
    importscan.scan(reha.sql)
    database.instanciate()
    return database
Пример #11
0
def register_external_implementations_in(*modules):
    warnings.warn(
        message="register_external_implementations_in is deprecated,"
                " please use importscan.scan",
        category=DeprecationWarning,
        stacklevel=2,
    )
    import importscan
    for module in modules:
        importscan.scan(module)
Пример #12
0
def test_importerror_handle_error():
    from .fixtures import importerror_handle_error

    # skip import errors
    def handle_error(name, e):
        if not isinstance(e, ImportError):
            raise e

    scan(importerror_handle_error, handle_error=handle_error)

    assert fixtures.calls == 1
Пример #13
0
def test_importerror_handle_error():
    from .fixtures import importerror_handle_error

    # skip import errors
    def handle_error(name, e):
        if not isinstance(e, ImportError):
            raise e

    scan(importerror_handle_error, handle_error=handle_error)

    assert fixtures.calls == 1
Пример #14
0
def application(request, user_interface, authentication, session_middleware,
                database_with_contents):

    contents = Registry()
    contents.register('user', User)
    contents.register('document', Document)
    contents.register('file', File)

    importscan.scan(uvcreha)
    app = Application(secret=b"secret",
                      database=database_with_contents,
                      authentication=authentication,
                      ui=user_interface,
                      contents=contents)
    yield (app, WebApp(session_middleware(app)))
Пример #15
0
    def call_builder_init(cls, kb_app, sphinx_app: Sphinx):
        """ On builder init event, commit registry and do callbacks """

        # Find and commit docs project plugins
        conf_dir = sphinx_app.confdir
        plugins_dir = sphinx_app.config.kaybee_settings.plugins_dir
        full_plugins_dir = os.path.join(conf_dir, plugins_dir)

        if os.path.exists(full_plugins_dir):
            sys.path.insert(0, conf_dir)
            plugin_package = importlib.import_module(plugins_dir)
            importscan.scan(plugin_package)
        else:
            logger.info(f'## Kaybee: No plugin dir at {plugins_dir}')

        dectate.commit(kb_app)
        for callback in cls.get_callbacks(kb_app, SphinxEvent.BI):
            callback(kb_app, sphinx_app)
Пример #16
0
def scan(package=None, ignore=None, handle_error=None):
    """Scan package for configuration actions (decorators).

    It scans by recursively importing the package and any modules
    in it, including any sub-packages.

    Register any found directives with their app classes.

    :param package: The Python module or package to scan. Optional; if left
      empty case the calling package is scanned.
    :param ignore: A list of packages to ignore. Optional. Defaults to
      ``['.test', '.tests']``. See :func:`importscan.scan` for details.
    :param handle_error: Optional error handling function. See
      :func:`importscan.scan` for details.
    """
    if package is None:
        package = caller_package()
    if ignore is None:
        ignore = ['.test', '.tests']
    importscan.scan(package, ignore, handle_error)
Пример #17
0
def test_rescan():
    importscan.scan(basic)
    dectate.commit(basic.app)
    importscan.scan(basic)

    class Sub(basic.app):
        pass

    @Sub.view(model=basic.Model, name='extra')
    def extra(self, request):
        return "extra"

    dectate.commit(Sub)

    c = Client(Sub())

    response = c.get('/1/extra')
    assert response.body == b'extra'

    response = c.get('/1')
    assert response.body == b'The view for model: 1'
Пример #18
0
def scan(package=None, ignore=None, handle_error=None):
    """Scan package for configuration actions (decorators).

    It scans by recursively importing the package and any modules
    in it, including any sub-packages.

    Register any found directives with their app classes. It also
    makes a list of :class:`App` subclasses that can be commited using
    :func:`autocommit`.

    :param package: The Python module or package to scan. Optional; if left
      empty case the calling package is scanned.
    :param ignore: A list of packages to ignore. Optional. Defaults to
      ``['.test', '.tests']``. See :func:`importscan.scan` for details.
    :param handle_error: Optional error handling function. See
      :func:`importscan.scan` for details.
    """
    if package is None:
        package = caller_package()
    if ignore is None:
        ignore = ['.test', '.tests']
    importscan.scan(package, ignore, handle_error)
Пример #19
0
        def read(self):
            return self.visible_widget.read()

        def fill(self, value):
            return self.visible_widget.fill(value)

    def fill(self, fill_data):
        values = deflatten_dict(fill_data)
        was_change = False
        self.before_fill(values)
        for key, value in values.items():
            widget = self.fields(key)
            if value is None:
                self.logger.debug('Skipping fill of %r because value was None',
                                  key)
                continue
            try:
                if widget.fill(value):
                    was_change = True
            except NotImplementedError:
                continue

        self.after_fill(was_change)
        return was_change


from cfme.services.service_catalogs import ui, ssui  # NOQA last for import cycles
importscan.scan(ui)
importscan.scan(ssui)
Пример #20
0
def test_ignore_subpackage_function():
    from .fixtures import ignore_subpackage_function

    scan(ignore_subpackage_function, ignore=re.compile('sub$').search)

    assert fixtures.calls == 0
Пример #21
0
def test_ignore_module_relative():
    from .fixtures import ignore_module

    scan(ignore_module, ignore=['.module'])

    assert fixtures.calls == 0
Пример #22
0
def test_ignore_module_function():
    from .fixtures import ignore_module_function

    scan(ignore_module_function, ignore=re.compile('module$').search)

    assert fixtures.calls == 0
Пример #23
0
def test_module():
    from .fixtures import module

    scan(module)

    assert fixtures.calls == 1
Пример #24
0
def test_empty_subpackage():
    from .fixtures import empty_subpackage

    scan(empty_subpackage)

    assert fixtures.calls == 1
Пример #25
0
def autoscan(ignore=None):
    """Automatically load Morepath configuration from packages.

    Morepath configuration consists of decorator calls on :class:`App`
    instances, i.e. ``@App.view()`` and ``@App.path()``.

    This function tries to load needed Morepath configuration from all
    packages automatically. This only works if:

     - The package is made available using a ``setup.py`` file.

     - The package or a dependency of the package includes
       ``morepath`` in the ``install_requires`` list of the
       ``setup.py`` file.

     - The ``setup.py`` name is the same as the name of the
       distributed package or module. For example: if the module
       inside the package is named ``myapp`` the package must be named
       ``myapp`` as well (not ``my-app`` or ``MyApp``).

    If the ``setup.py`` name differs from the package name, it's
    possible to specify the module morepath should scan using entry
    points::

        setup(name='some-package',
          ...
          install_requires=[
              'setuptools',
              'morepath'
          ],
          entry_points={
              'morepath': [
                  'scan = somepackage',
              ]
          })

    This function simply recursively imports everything in those packages,
    except for test directories.

    In addition to calling this function you can also import modules
    that use Morepath directives manually, and you can use
    :func:`scan` to automatically import everything in a
    single package.

    Typically called immediately after startup just before the
    application starts serving using WSGI.

    ``autoscan`` always ignores ``.test`` and ``.tests``
    sub-packages -- these are assumed never to contain useful Morepath
    configuration and are not scanned.

    ``autoscan`` can fail with an ``ImportError`` when it tries to
    scan code that imports an optional dependency that is not
    installed. This happens most commonly in test code, which often
    rely on test-only dependencies such as ``pytest`` or ``nose``. If
    those tests are in a ``.test`` or ``.tests`` sub-package they
    are automatically ignored, however.

    If you have a special package with such expected import errors,
    you can exclude them from ``autoscan`` using the ``ignore``
    argument, for instance using ``['special_package']``. You then can
    use :func:`scan` for that package, with a custom
    ``ignore`` argument that excludes the modules that generate import
    errors.

    See also :func:`scan`.

    :param ignore: ignore to ignore some modules
      during scanning. Optional. If ommitted, ignore ``.test`` and
      ``.tests`` packages by default. See :func:`importscan.scan` for
      more details.

    """
    if ignore is None:
        ignore = []
        ignore.extend(['.test', '.tests'])
    for package in morepath_packages():
        importscan.scan(package, ignore)
Пример #26
0
def test_attributeerror():
    from .fixtures import attributeerror

    with raises(AttributeError):
        scan(attributeerror)
Пример #27
0
    """Generic Objects class to context switch between REST and Automate.

    Read/Update/Delete functionality.
    """
    update = sentaku.ContextualMethod()
    delete = sentaku.ContextualMethod()
    add_tag = sentaku.ContextualMethod()
    remove_tag = sentaku.ContextualMethod()
    get_tags = sentaku.ContextualMethod()
    exists = sentaku.ContextualProperty()

    name = attr.ib()
    definition = attr.ib()  # generic object definition
    attributes = attr.ib(default=None)  # e.g. {'address': 'Test Address'}
    associations = attr.ib(default=None)  # e.g. {'services': [myservice1, myservice2]}
    rest_response = attr.ib(default=None, init=False)
    my_service = attr.ib(default=None)   # my_service object with instance assignment


@attr.s
class GenericObjectInstanceCollection(BaseCollection, sentaku.modeling.ElementMixin):

    ENTITY = GenericObjectInstance

    create = sentaku.ContextualMethod()


from . import rest, ui  # NOQA last for import cycles
importscan.scan(rest)
importscan.scan(ui)
Пример #28
0
        # from iqe.test_framework.helpers import find_application
        #
        # return find_application(context)

    @property
    def application(self):
        return self

    @property
    def collections(self):
        from mta.base.modeling import EntityCollections

        return EntityCollections.for_application(self)

    # @contextmanager
    # def copy_using(self, *, user):
    #     """
    #     returns a teporary application with changes applied
    #
    #     :param user: a user credential record to use instead of the  default/original one
    #     """
    #     with _application_construction_allowed():
    #         app = Application(config=self.config, user=user)
    #     yield app
    #     app.web_ui.browser_manager.close()


from mta import base  # noqa

importscan.scan(base)
Пример #29
0
def autoscan(ignore=None):
    """Automatically load Morepath configuration from packages.

    Morepath configuration consists of decorator calls on :class:`App`
    instances, i.e. ``@App.view()`` and ``@App.path()``.

    This function tries to load needed Morepath configuration from all
    packages automatically. This only works if:

     - The package is made available using a ``setup.py`` file.

     - The package or a dependency of the package includes
       ``morepath`` in the ``install_requires`` list of the
       ``setup.py`` file.

     - The ``setup.py`` name is the same as the name of the
       distributed package or module. For example: if the module
       inside the package is named ``myapp`` the package must be named
       ``myapp`` as well (not ``my-app`` or ``MyApp``).

    If the ``setup.py`` name differs from the package name, it's
    possible to specify the module morepath should scan using entry
    points::

        setup(name='some-package',
          ...
          install_requires=[
              'setuptools',
              'morepath'
          ],
          entry_points={
              'morepath': [
                  'scan = somepackage',
              ]
          })

    This function simply recursively imports everything in those packages,
    except for test directories.

    In addition to calling this function you can also import modules
    that use Morepath directives manually, and you can use
    :func:`scan` to automatically import everything in a
    single package.

    Typically called immediately after startup just before the
    application starts serving using WSGI.

    ``autoscan`` always ignores ``.test`` and ``.tests``
    sub-packages -- these are assumed never to contain useful Morepath
    configuration and are not scanned.

    ``autoscan`` can fail with an ``ImportError`` when it tries to
    scan code that imports an optional dependency that is not
    installed. This happens most commonly in test code, which often
    rely on test-only dependencies such as ``pytest`` or ``nose``. If
    those tests are in a ``.test`` or ``.tests`` sub-package they
    are automatically ignored, however.

    If you have a special package with such expected import errors,
    you can exclude them from ``autoscan`` using the ``ignore``
    argument, for instance using ``['special_package']``. You then can
    use :func:`scan` for that package, with a custom
    ``ignore`` argument that excludes the modules that generate import
    errors.

    See also :func:`scan`.

    :param ignore: ignore to ignore some modules
      during scanning. Optional. If ommitted, ignore ``.test`` and
      ``.tests`` packages by default. See :func:`importscan.scan` for
      more details.

    """
    if ignore is None:
        ignore = []
        ignore.extend(['.test', '.tests'])
    for package in morepath_packages():
        importscan.scan(package, ignore)
Пример #30
0
uvcreha.contents.registry.register('file', contents.File)
uvcreha.contents.registry.register('document', contents.Document)
uvcreha.contents.registry.register('preferences', contents.Preferences)


#from database.arango import init_database
from database.sql import init_database


import reha.sql

database = init_database(reha.sql.mappers)


# Load essentials
importscan.scan(uvcreha.browser)
importscan.scan(uvcreha.api)


### Middlewares

# Session
session_environ = "uvcreha.session"

session = uvcreha.plugins.session_middleware(
    pathlib.Path("var/sessions"), secret='secret',
    cookie_name="uvcreha.cookie"
)

session_getter = reiter.auth.components.session_from_environ(
    session_environ
Пример #31
0
@attr.s
class GenericObjectDefinition(BaseEntity, Updateable,
                              sentaku.modeling.ElementMixin):
    """Generic Objects Definition class to context switch between UI and REST.

    Read/Update/Delete functionality.
    """
    update = sentaku.ContextualMethod()
    delete = sentaku.ContextualMethod()
    exists = sentaku.ContextualProperty()

    name = attr.ib()
    description = attr.ib()
    attributes = attr.ib(default=None)  # e.g. {'address': 'string'}
    associations = attr.ib(default=None)  # e.g. {'services': 'Service'}
    methods = attr.ib(default=None)  # e.g. ['method1', 'method2']
    rest_response = attr.ib(default=None, init=False)


@attr.s
class GenericObjectDefinitionCollection(BaseCollection,
                                        sentaku.modeling.ElementMixin):

    ENTITY = GenericObjectDefinition

    create = sentaku.ContextualMethod()


from . import rest  # NOQA last for import cycles
importscan.scan(rest)
Пример #32
0
def test_importerror():
    from .fixtures import importerror

    with raises(ImportError):
        scan(importerror)
Пример #33
0
def test_ignore_subpackage_function():
    from .fixtures import ignore_subpackage_function

    scan(ignore_subpackage_function, ignore=re.compile('sub$').search)

    assert fixtures.calls == 0
Пример #34
0
def test_attributeerror():
    from .fixtures import attributeerror

    with raises(AttributeError):
        scan(attributeerror)
Пример #35
0
def test_importerror():
    from .fixtures import importerror

    with raises(ImportError):
        scan(importerror)
Пример #36
0
def test_empty_subpackage():
    from .fixtures import empty_subpackage

    scan(empty_subpackage)

    assert fixtures.calls == 1
Пример #37
0
def test_subpackage():
    from .fixtures import subpackage

    scan(subpackage)

    assert fixtures.calls == 1
Пример #38
0
def test_scanned_some_error():
    with pytest.raises(ZeroDivisionError):
        importscan.scan(pkg)
Пример #39
0
def test_ignore_module_relative():
    from .fixtures import ignore_module

    scan(ignore_module, ignore=['.module'])

    assert fixtures.calls == 0
Пример #40
0
def test_package():
    from .fixtures import package

    scan(package)

    assert fixtures.calls == 1
Пример #41
0
def scan_onegov():
    import importscan
    import onegov
    importscan.scan(onegov, ignore=['.test', '.tests'])
Пример #42
0
def test_subpackage():
    from .fixtures import subpackage

    scan(subpackage)

    assert fixtures.calls == 1
Пример #43
0
def test_ignore_module_function():
    from .fixtures import ignore_module_function

    scan(ignore_module_function, ignore=re.compile('module$').search)

    assert fixtures.calls == 0
Пример #44
0
def scan_onegov():
    import importscan
    import onegov
    importscan.scan(onegov, ignore=['.test', '.tests'])
Пример #45
0
def test_ignore_subpackage_relative():
    from .fixtures import ignore_subpackage

    scan(ignore_subpackage, ignore=['.sub'])

    assert fixtures.calls == 0
Пример #46
0
def test_ignore_subpackage_relative():
    from .fixtures import ignore_subpackage

    scan(ignore_subpackage, ignore=['.sub'])

    assert fixtures.calls == 0
Пример #47
0
                raise ItemNotFound("Visible widget is not found")

        def read(self):
            return self.visible_widget.read()

        def fill(self, value):
            return self.visible_widget.fill(value)

    def fill(self, fill_data):
        values = deflatten_dict(fill_data)
        was_change = False
        self.before_fill(values)
        for key, value in values.items():
            widget = self.fields(key)
            if value is None:
                self.logger.debug('Skipping fill of %r because value was None', key)
                continue
            try:
                if widget.fill(value):
                    was_change = True
            except NotImplementedError:
                continue

        self.after_fill(was_change)
        return was_change


from . import ui, ssui  # NOQA last for import cycles
importscan.scan(ui)
importscan.scan(ssui)
Пример #48
0
                       JSON dumps settings_dict to pass as raw hash data to rest_api session
        Raises:
            AssertionError: On an http result >=400 (RequestsResponse.ok)
        """
        # Calling the _session patch method because the core patch will wrap settings_dict in a list
        result = self.appliance.rest_api._session.patch(
            url=self._api_settings_url, data=json.dumps(settings_dict))
        assert result.ok


@attr.s
class RegionCollection(BaseCollection, sentaku.modeling.ElementMixin):
    # all = sentaku.ContextualMethod()

    ENTITY = Region

    def all(self):
        self.appliance.rest_api.collections.regions.reload()
        region_collection = self.appliance.rest_api.collections.regions
        regions = [
            self.instantiate(region.region) for region in region_collection
        ]
        return regions


from . import ui, ssui, rest  # NOQA last for import cycles

importscan.scan(ui)
importscan.scan(ssui)
importscan.scan(rest)
Пример #49
0
def test_module():
    from .fixtures import module

    scan(module)

    assert fixtures.calls == 1
Пример #50
0
from __future__ import print_function
import importscan

to_check = 'cfme artifactor fixtures markers utils'

if __name__ == '__main__':
    for name in to_check.split():
        base = __import__(name)

        def handle_error(name, error):
            print(name, error)
        importscan.scan(base, handle_error=handle_error)
Пример #51
0
def test_package():
    from .fixtures import package

    scan(package)

    assert fixtures.calls == 1