Drop Deprecated Backend Globals (hooks,handlers)

This commit is contained in:
BJ Dierkes 2017-02-04 22:33:29 -06:00
parent 47e335a827
commit 45e4ce1b8b
10 changed files with 18 additions and 801 deletions

View File

@ -38,7 +38,8 @@ Refactoring:
Incompatible:
* ``[core]`` Rename ``CementApp`` to ``App``.
* ``[core.foundation]`` Rename ``CementApp`` to ``App``.
* ``[core.controller]`` Drop ``CementBaseController``
* ``[ext.configobj]`` No longer shipped with Cement.
* ``[ext.json_configobj]`` No longer shipped with Cement.
* ``[ext.yaml_configobj]`` No longer shipped with Cement.

View File

@ -604,22 +604,6 @@ class App(meta.MetaMixin):
I.e. ``[MyCustomHandler, SomeOtherHandler]``
"""
use_backend_globals = True
"""
This is a backward compatibility feature. Cement 2.x.x
relies on several global variables hidden in ``cement.core.backend``
used for things like storing hooks and handlers. Future versions of
Cement will no longer use this mechanism, however in order to maintain
backward compatibility this is still the default. By disabling this
feature allows multiple instances of App to be created
from within the same runtime space without clobbering eachothers
hooks/handers/etc.
Be warned that use of third-party extensions might break as they were
built using backend globals, and probably have no idea this feature
has changed or exists.
"""
alternative_module_mapping = {}
"""
EXPERIMENTAL FEATURE: This is an experimental feature added in Cement
@ -1024,15 +1008,8 @@ class App(meta.MetaMixin):
elif '--quiet' in self._meta.argv:
self._suppress_output()
# Forward/Backward compat, see Issue #311
if self._meta.use_backend_globals is True:
backend.__hooks__ = {}
backend.__handlers__ = {}
self.handler = HandlerManager(use_backend_globals=True)
self.hook = HookManager(use_backend_globals=True)
else:
self.handler = HandlerManager(use_backend_globals=False)
self.hook = HookManager(use_backend_globals=False)
self.handler = HandlerManager()
self.hook = HookManager()
# define framework hooks
self.hook.define('pre_setup')

View File

@ -5,7 +5,6 @@ Cement core handler module.
import re
from ..core import exc, meta
from ..core import backend
from ..utils.misc import minimal_logger
LOG = minimal_logger(__name__)
@ -16,15 +15,10 @@ class HandlerManager(object):
Manages the handler system to define, get, resolve, etc handlers with
the Cement Framework.
:param use_backend_globals: Whether to use backend globals (backward
compatibility and deprecated).
"""
def __init__(self, use_backend_globals=False):
if use_backend_globals is True:
self.__handlers__ = backend.__handlers__
else:
self.__handlers__ = {}
def __init__(self):
self.__handlers__ = {}
def get(self, handler_type, handler_label, *args):
"""
@ -381,340 +375,3 @@ class CementBaseHandler(meta.MetaMixin):
dict_obj = dict()
dict_obj[self._meta.config_section] = self._meta.config_defaults
self.app.config.merge(dict_obj, override=False)
def get(handler_type, handler_label, *args):
"""
DEPRECATION WARNING: This function is deprecated as of Cement 2.7.x and
will be removed in future versions of Cement.
Use ``App.handler.get()`` instead.
---
Get a handler object.
Required Arguments:
:param handler_type: The type of handler (i.e. 'output')
:type handler_type: str
:param handler_label: The label of the handler (i.e. 'json')
:type handler_label: str
:param fallback: A fallback value to return if handler_label doesn't
exist.
:returns: An uninstantiated handler object
:raises: cement.core.exc.FrameworkError
Usage:
from cement.core import handler
output = handler.get('output', 'json')
output.render(dict(foo='bar'))
"""
# only log debug for now as this won't be removed until Cement 3.x and
# we don't have access to App.Meta.ignore_deprecation_warnings here
LOG.debug(
'Cement Deprecation Warning: `handler.get()` has been deprecated, '
'and will be removed in future versions of Cement. You should now '
'use `App.handler.get()` instead.'
)
if handler_type not in backend.__handlers__:
raise exc.FrameworkError("handler type '%s' does not exist!" %
handler_type)
if handler_label in backend.__handlers__[handler_type]:
return backend.__handlers__[handler_type][handler_label]
elif len(args) > 0:
return args[0]
else:
raise exc.FrameworkError("handlers['%s']['%s'] does not exist!" %
(handler_type, handler_label))
def list(handler_type):
"""
DEPRECATION WARNING: This function is deprecated as of Cement 2.7.x and
will be removed in future versions of Cement.
Use ``App.handler.list()`` instead.
---
Return a list of handlers for a given type.
:param handler_type: The type of handler (i.e. 'output')
:returns: List of handlers that match `type`.
:rtype: ``list``
:raises: cement.core.exc.FrameworkError
"""
# only log debug for now as this won't be removed until Cement 3.x and
# we don't have access to App.Meta.ignore_deprecation_warnings here
LOG.debug(
'Cement Deprecation Warning: `handler.list()` has been deprecated, '
'and will be removed in future versions of Cement. You should now '
'use `App.handler.list()` instead.'
)
if handler_type not in backend.__handlers__:
raise exc.FrameworkError("handler type '%s' does not exist!" %
handler_type)
res = []
for label in backend.__handlers__[handler_type]:
if label == '__interface__':
continue
res.append(backend.__handlers__[handler_type][label])
return res
def define(interface):
"""
DEPRECATION WARNING: This function is deprecated as of Cement 2.7.x and
will be removed in future versions of Cement.
Use ``App.handler.define()`` instead.
---
Define a handler based on the provided interface. Defines a handler type
based on <interface>.IMeta.label.
:param interface: The interface class that defines the interface to be
implemented by handlers.
:raises: cement.core.exc.InterfaceError
:raises: cement.core.exc.FrameworkError
Usage:
.. code-block:: python
from cement.core import handler
handler.define(IDatabaseHandler)
"""
# only log debug for now as this won't be removed until Cement 3.x and
# we don't have access to App.Meta.ignore_deprecation_warnings here
LOG.debug(
'Cement Deprecation Warning: `handler.define()` has been deprecated, '
'and will be removed in future versions of Cement. You should now '
'use `App.handler.define()` instead.'
)
if not hasattr(interface, 'IMeta'):
raise exc.InterfaceError("Invalid %s, " % interface +
"missing 'IMeta' class.")
if not hasattr(interface.IMeta, 'label'):
raise exc.InterfaceError("Invalid %s, " % interface +
"missing 'IMeta.label' class.")
LOG.debug("defining handler type '%s' (%s)" %
(interface.IMeta.label, interface.__name__))
if interface.IMeta.label in backend.__handlers__:
raise exc.FrameworkError("Handler type '%s' already defined!" %
interface.IMeta.label)
backend.__handlers__[interface.IMeta.label] = {'__interface__': interface}
def defined(handler_type):
"""
DEPRECATION WARNING: This function is deprecated as of Cement 2.7.x and
will be removed in future versions of Cement.
Use ``App.handler.defined()`` instead.
---
Test whether a handler type is defined.
:param handler_type: The name or 'type' of the handler (I.e. 'logging').
:returns: True if the handler type is defined, False otherwise.
:rtype: ``boolean``
"""
# only log debug for now as this won't be removed until Cement 3.x and
# we don't have access to App.Meta.ignore_deprecation_warnings here
LOG.debug(
'Cement Deprecation Warning: `handler.defined()` has been deprecated, '
'and will be removed in future versions of Cement. You should now '
'use `App.handler.defined()` instead.'
)
if handler_type in backend.__handlers__:
return True
else:
return False
def register(handler_obj, force=False):
"""
DEPRECATION WARNING: This function is deprecated as of Cement 2.7.x and
will be removed in future versions of Cement.
Use ``App.handler.register()`` instead.
---
Register a handler object to a handler. If the same object is already
registered then no exception is raised, however if a different object
attempts to be registered to the same name a FrameworkError is
raised.
:param handler_obj: The uninstantiated handler object to register.
:param force: Whether to allow replacement if an existing
handler of the same ``label`` is already registered.
:raises: cement.core.exc.InterfaceError
:raises: cement.core.exc.FrameworkError
Usage:
.. code-block:: python
from cement.core import handler
class MyDatabaseHandler(object):
class Meta:
interface = IDatabase
label = 'mysql'
def connect(self):
...
handler.register(MyDatabaseHandler)
"""
# only log debug for now as this won't be removed until Cement 3.x and
# we don't have access to App.Meta.ignore_deprecation_warnings here
LOG.debug(
'Cement Deprecation Warning: `handler.register()` has been '
'deprecated, and will be removed in future versions of Cement. You '
'should now use `App.handler.register()` instead.'
)
orig_obj = handler_obj
# for checks
obj = orig_obj()
if not hasattr(obj._meta, 'label') or not obj._meta.label:
raise exc.InterfaceError("Invalid handler %s, " % orig_obj +
"missing '_meta.label'.")
if not hasattr(obj._meta, 'interface') or not obj._meta.interface:
raise exc.InterfaceError("Invalid handler %s, " % orig_obj +
"missing '_meta.interface'.")
# translate dashes to underscores
orig_obj.Meta.label = re.sub('-', '_', obj._meta.label)
obj._meta.label = re.sub('-', '_', obj._meta.label)
handler_type = obj._meta.interface.IMeta.label
LOG.debug("registering handler '%s' into handlers['%s']['%s']" %
(orig_obj, handler_type, obj._meta.label))
if handler_type not in backend.__handlers__:
raise exc.FrameworkError("Handler type '%s' doesn't exist." %
handler_type)
if obj._meta.label in backend.__handlers__[handler_type] and \
backend.__handlers__[handler_type][obj._meta.label] != obj:
if force is True:
LOG.debug(
"handlers['%s']['%s'] already exists" %
(handler_type, obj._meta.label) +
", but `force==True`"
)
else:
raise exc.FrameworkError(
"handlers['%s']['%s'] already exists" %
(handler_type, obj._meta.label)
)
interface = backend.__handlers__[handler_type]['__interface__']
if hasattr(interface.IMeta, 'validator'):
interface.IMeta().validator(obj)
else:
LOG.debug("Interface '%s' does not have a validator() function!" %
interface)
backend.__handlers__[handler_type][obj.Meta.label] = orig_obj
def registered(handler_type, handler_label):
"""
DEPRECATION WARNING: This function is deprecated as of Cement 2.7.x and
will be removed in future versions of Cement.
Use ``App.handler.registered()`` instead.
---
Check if a handler is registered.
:param handler_type: The type of handler (interface label)
:param handler_label: The label of the handler
:returns: True if the handler is registered, False otherwise
:rtype: ``boolean``
"""
# only log debug for now as this won't be removed until Cement 3.x and
# we don't have access to App.Meta.ignore_deprecation_warnings here
LOG.debug(
'Cement Deprecation Warning: `handler.registered()` has been '
'deprecated, and will be removed in future versions of Cement. You '
'should now use `App.handler.registered()` instead.'
)
if handler_type in backend.__handlers__ and \
handler_label in backend.__handlers__[handler_type]:
return True
return False
def resolve(handler_type, handler_def, raise_error=True):
"""
DEPRECATION WARNING: This function is deprecated as of Cement 2.7.x and
will be removed in future versions of Cement.
Use ``App.handler.resolve()`` instead.
---
Resolves the actual handler, as it can be either a string identifying
the handler to load from backend.__handlers__, or it can be an
instantiated or non-instantiated handler class.
:param handler_type: The type of handler (aka the interface label)
:param hander_def: The handler as defined in App.Meta.
:type handler_def: str, uninstantiated object, or instantiated object
:param raise_error: Whether or not to raise an exception if unable
to resolve the handler.
:type raise_error: boolean
:returns: The instantiated handler object.
"""
# only log debug for now as this won't be removed until Cement 3.x and
# we don't have access to App.Meta.ignore_deprecation_warnings here
LOG.debug(
'Cement Deprecation Warning: `handler.resove()` has been '
'deprecated, and will be removed in future versions of Cement. You '
'should now use `App.handler.resolve()` instead.'
)
han = None
if type(handler_def) == str:
han = get(handler_type, handler_def)()
elif hasattr(handler_def, '_meta'):
if not registered(handler_type, handler_def._meta.label):
register(handler_def.__class__)
han = handler_def
elif hasattr(handler_def, 'Meta'):
han = handler_def()
if not registered(handler_type, han._meta.label):
register(handler_def)
msg = "Unable to resolve handler '%s' of type '%s'" % \
(handler_def, handler_type)
if han is not None:
return han
elif han is None and raise_error:
raise exc.FrameworkError(msg)
elif han is None:
LOG.debug(msg)
return None

View File

@ -2,7 +2,7 @@
import operator
import types
from ..core import exc, backend
from ..core import exc
from ..utils.misc import minimal_logger
LOG = minimal_logger(__name__)
@ -13,15 +13,10 @@ class HookManager(object):
Manages the hook system to define, get, run, etc hooks within the
the Cement Framework and applications Built on Cement (tm).
:param use_backend_globals: Whether to use backend globals (backward
compatibility and deprecated).
"""
def __init__(self, use_backend_globals=False):
if use_backend_globals is True:
self.__hooks__ = backend.__hooks__
else:
self.__hooks__ = {}
def __init__(self):
self.__hooks__ = {}
def define(self, name):
"""
@ -156,172 +151,3 @@ class HookManager(object):
yield _res
else:
yield res
# the following is only used for backward compat with < 2.7.x!
def define(name):
"""
DEPRECATION WARNING: This function is deprecated as of Cement 2.7.x and
will be removed in future versions of Cement.
Use ``App.hook.define()`` instead.
---
Define a hook namespace that plugins can register hooks in.
:param name: The name of the hook, stored as hooks['name']
:raises: cement.core.exc.FrameworkError
Usage:
.. code-block:: python
from cement.core import hook
hook.define('myhookname_hook')
"""
# only log debug for now as this won't be removed until Cement 3.x and
# we don't have access to App.Meta.ignore_deprecation_warnings here
LOG.debug(
'Cement Deprecation Warning: `hook.define()` has been deprecated, '
'and will be removed in future versions of Cement. You should now '
'use `App.hook.define()` instead.'
)
LOG.debug("defining hook '%s'" % name)
if name in backend.__hooks__:
raise exc.FrameworkError("Hook name '%s' already defined!" % name)
backend.__hooks__[name] = []
def defined(hook_name):
"""
DEPRECATION WARNING: This function is deprecated as of Cement 2.7.x and
will be removed in future versions of Cement.
Use ``App.hook.defined()`` instead.
---
Test whether a hook name is defined.
:param hook_name: The name of the hook.
I.e. ``my_hook_does_awesome_things``.
:returns: True if the hook is defined, False otherwise.
:rtype: ``boolean``
"""
# only log debug for now as this won't be removed until Cement 3.x and
# we don't have access to App.Meta.ignore_deprecation_warnings here
LOG.debug(
'Cement Deprecation Warning: `hook.defined()` has been deprecated, '
'and will be removed in future versions of Cement. You should now '
'use `App.hook.defined()` instead.'
)
if hook_name in backend.__hooks__:
return True
else:
return False
def register(name, func, weight=0):
"""
DEPRECATION WARNING: This function is deprecated as of Cement 2.7.x and
will be removed in future versions of Cement.
Use ``App.hook.register()`` instead.
---
Register a function to a hook. The function will be called, in order of
weight, when the hook is run.
:param name: The name of the hook to register too. I.e. ``pre_setup``,
``post_run``, etc.
:param func: The function to register to the hook. This is an
*un-instantiated*, non-instance method, simple function.
:param weight: The weight in which to order the hook function.
:type weight: ``int``
Usage:
.. code-block:: python
from cement.core import hook
def my_hook(*args, **kwargs):
# do something here
res = 'Something to return'
return res
hook.register('post_setup', my_hook)
"""
# only log debug for now as this won't be removed until Cement 3.x and
# we don't have access to App.Meta.ignore_deprecation_warnings here
LOG.debug(
'Cement Deprecation Warning: `hook.register()` has been deprecated, '
'and will be removed in future versions of Cement. You should now '
'use `App.hook.register()` instead.'
)
if name not in backend.__hooks__:
LOG.debug("hook name '%s' is not defined! ignoring..." % name)
return False
LOG.debug("registering hook '%s' from %s into hooks['%s']" %
(func.__name__, func.__module__, name))
# Hooks are as follows: (weight, name, func)
backend.__hooks__[name].append((int(weight), func.__name__, func))
def run(name, *args, **kwargs):
"""
DEPRECATION WARNING: This function is deprecated as of Cement 2.7.x and
will be removed in future versions of Cement.
Use ``App.hook.run()`` instead.
---
Run all defined hooks in the namespace. Yields the result of each hook
function run.
:param name: The name of the hook function.
:param args: Additional arguments to be passed to the hook functions.
:param kwargs: Additional keyword arguments to be passed to the hook
functions.
:raises: FrameworkError
Usage:
.. code-block:: python
from cement.core import hook
for result in hook.run('hook_name'):
# do something with result from each hook function
...
"""
# only log debug for now as this won't be removed until Cement 3.x and
# we don't have access to App.Meta.ignore_deprecation_warnings here
LOG.debug(
'Cement Deprecation Warning: `hook.run()` has been deprecated, '
'and will be removed in future versions of Cement. You should now '
'use `App.hook.run()` instead.'
)
if name not in backend.__hooks__:
raise exc.FrameworkError("Hook name '%s' is not defined!" % name)
# Will order based on weight (the first item in the tuple)
backend.__hooks__[name].sort(key=operator.itemgetter(0))
for hook in backend.__hooks__[name]:
LOG.debug("running hook '%s' (%s) from %s" %
(name, hook[2], hook[2].__module__))
res = hook[2](*args, **kwargs)
# Check if result is a nested generator - needed to support e.g.
# asyncio
if isinstance(res, types.GeneratorType):
for _res in res:
yield _res
else:
yield res

View File

@ -254,4 +254,4 @@ class HandlebarsOutputHandler(output.TemplateOutputHandler):
def load(app):
handler.register(HandlebarsOutputHandler)
app.handler.register(HandlebarsOutputHandler)

View File

@ -410,7 +410,7 @@ class FoundationTestCase(test.CementCoreTestCase):
def test_define_hooks_meta(self):
app = self.make_app(APP, define_hooks=['my_custom_hook'])
app.setup()
self.ok(hook.defined('my_custom_hook'))
self.ok(app.hook.defined('my_custom_hook'))
@test.raises(HookTestException)
def test_register_hooks_meta(self):
@ -423,7 +423,7 @@ class FoundationTestCase(test.CementCoreTestCase):
app.setup()
for res in hook.run('my_custom_hook'):
for res in app.hook.run('my_custom_hook'):
pass
def test_register_hooks_meta_retry(self):
@ -457,7 +457,6 @@ class FoundationTestCase(test.CementCoreTestCase):
def test_disable_backend_globals(self):
app = self.make_app(APP,
use_backend_globals=False,
define_handlers=[MyTestInterface],
handlers=[MyTestHandler],
define_hooks=['my_hook'],

View File

@ -1,6 +1,6 @@
"""Tests for cement.core.handler."""
from cement.core import exc, backend, handler, output, meta
from cement.core import exc, handler, output, meta
from cement.core import interface
from cement.utils import test
from cement.ext import ext_dummy
@ -117,12 +117,12 @@ class HandlerTestCase(test.CementCoreTestCase):
pass
# register once, verify
handler.register(ext_dummy.DummyOutputHandler)
self.app.handler.register(ext_dummy.DummyOutputHandler)
res = self.app.handler.get('output', 'dummy')
self.eq(res, ext_dummy.DummyOutputHandler)
# register again with force, and verify we get new class back
handler.register(MyDummy, force=True)
self.app.handler.register(MyDummy, force=True)
res = self.app.handler.get('output', 'dummy')
self.eq(res, MyDummy)
@ -131,7 +131,7 @@ class HandlerTestCase(test.CementCoreTestCase):
try:
self.app.handler.register(BogusOutputHandler2)
except exc.InterfaceError:
del backend.__handlers__['output']
del self.app.handler.__handlers__['output']
raise
def test_verify_handler(self):
@ -208,134 +208,3 @@ class HandlerTestCase(test.CementCoreTestCase):
class Meta:
interface = BadInterface
self.app.handler.register(BadHandler)
class DeprecatedHandlerTestCase(test.CementCoreTestCase):
def setUp(self):
super(DeprecatedHandlerTestCase, self).setUp()
self.app = self.make_app()
@test.raises(exc.FrameworkError)
def test_get_invalid_handler(self):
handler.get('output', 'bogus_handler')
@test.raises(exc.InterfaceError)
def test_register_invalid_handler(self):
handler.register(BogusOutputHandler)
@test.raises(exc.InterfaceError)
def test_register_invalid_handler_no_meta(self):
handler.register(BogusHandler3)
@test.raises(exc.InterfaceError)
def test_register_invalid_handler_no_Meta_label(self):
handler.register(BogusHandler4)
@test.raises(exc.FrameworkError)
def test_register_duplicate_handler(self):
from cement.ext import ext_dummy
handler.register(ext_dummy.DummyOutputHandler)
try:
handler.register(DuplicateHandler)
except exc.FrameworkError:
raise
@test.raises(exc.InterfaceError)
def test_register_unproviding_handler(self):
try:
handler.register(BogusOutputHandler2)
except exc.InterfaceError:
del backend.__handlers__['output']
raise
def test_verify_handler(self):
self.app.setup()
self.ok(handler.registered('output', 'dummy'))
self.eq(handler.registered('output', 'bogus_handler'), False)
self.eq(handler.registered('bogus_type', 'bogus_handler'), False)
@test.raises(exc.FrameworkError)
def test_get_bogus_handler(self):
handler.get('log', 'bogus')
@test.raises(exc.FrameworkError)
def test_get_bogus_handler_type(self):
handler.get('bogus', 'bogus')
def test_handler_defined(self):
for handler_type in ['config', 'log', 'argument', 'plugin',
'extension', 'output', 'controller']:
self.eq(handler.defined(handler_type), True)
# and check for bogus one too
self.eq(handler.defined('bogus'), False)
def test_handler_list(self):
self.app.setup()
handler_list = handler.list('config')
res = ConfigParserConfigHandler in handler_list
self.ok(res)
@test.raises(exc.FrameworkError)
def test_handler_list_bogus_type(self):
self.app.setup()
handler.list('bogus')
@test.raises(exc.FrameworkError)
def test_register_invalid_handler_type(self):
self.app.setup()
class BadInterface:
class IMeta:
label = 'bad_interface'
class BadHandler(TestHandler):
class Meta:
interface = BadInterface
handler.register(BadHandler)
@test.raises(exc.InterfaceError)
def test_bogus_interface_no_IMeta(self):
handler.define(BogusInterface1)
@test.raises(exc.InterfaceError)
def test_bogus_interface_no_IMeta_label(self):
handler.define(BogusInterface2)
@test.raises(exc.FrameworkError)
def test_define_duplicate_interface(self):
handler.define(output.IOutput)
handler.define(output.IOutput)
def test_interface_with_no_validator(self):
handler.define(TestInterface)
handler.register(TestHandler)
def test_handler_not_defined(self):
self.eq(handler.defined('bogus'), False)
def test_handler_registered(self):
self.app.setup()
self.eq(handler.registered('output', 'dummy'), True)
def test_handler_get_fallback(self):
self.app.setup()
self.eq(handler.get('log', 'foo', 'bar'), 'bar')
def test_resolve(self):
# just get some coverage
handler.define(TestInterface)
handler.resolve('test', TestHandler())
handler.resolve('test', 'test')
handler.resolve('test', TestHandler)
self.reset_backend()
self.app = self.make_app('test')
handler.define(TestInterface)
handler.resolve('test', TestHandler)
handler.resolve('test', None, raise_error=False)
try:
handler.resolve('test', None)
except Exception as e:
pass

View File

@ -2,7 +2,7 @@
import sys
import signal
from cement.core import exc, backend, hook
from cement.core import exc, hook
from cement.core.foundation import cement_signal_handler
from cement.utils import test
from cement.utils.misc import rando
@ -113,81 +113,3 @@ class HookTestCase(test.CementCoreTestCase):
cement_signal_handler(signal.SIGTERM, frame)
except exc.CaughtSignal as e:
pass
class DeprecatedHookTestCase(test.CementCoreTestCase):
def setUp(self):
super(DeprecatedHookTestCase, self).setUp()
self.app = self.make_app()
hook.define('nosetests_hook')
def test_define(self):
self.ok('nosetests_hook' in backend.__hooks__)
@test.raises(exc.FrameworkError)
def test_define_again(self):
try:
hook.define('nosetests_hook')
except exc.FrameworkError as e:
self.eq(e.msg, "Hook name 'nosetests_hook' already defined!")
raise
def test_hooks_registered(self):
hook.register('nosetests_hook', cement_hook_one, weight=99)
hook.register('nosetests_hook', cement_hook_two, weight=-1)
hook.register('some_bogus_hook', cement_hook_three, weight=-99)
self.eq(len(backend.__hooks__['nosetests_hook']), 2)
def test_run(self):
hook.register('nosetests_hook', cement_hook_one, weight=99)
hook.register('nosetests_hook', cement_hook_two, weight=-1)
hook.register('nosetests_hook', cement_hook_three, weight=-99)
hook.register('nosetests_hook', cement_hook_six, weight=200)
results = []
for res in hook.run('nosetests_hook'):
results.append(res)
self.eq(results[0], 'kapla 3')
self.eq(results[1], 'kapla 2')
self.eq(results[2], 'kapla 1')
self.eq(results[3], 'generator kapla 0')
self.eq(results[4], 'generator kapla 1')
self.eq(results[5], 'generator kapla 2')
@test.raises(exc.FrameworkError)
def test_run_bad_hook(self):
for res in hook.run('some_bogus_hook'):
pass
def test_hook_is_defined(self):
self.ok(hook.defined('nosetests_hook'))
self.eq(hook.defined('some_bogus_hook'), False)
def test_framework_hooks(self):
app = self.make_app(APP, argv=['--quiet'])
hook.register('pre_setup', cement_hook_one)
hook.register('post_setup', cement_hook_one)
hook.register('pre_run', cement_hook_one)
hook.register('post_run', cement_hook_one)
hook.register('pre_argument_parsing', cement_hook_one)
hook.register('post_argument_parsing', cement_hook_one)
hook.register('pre_close', cement_hook_one)
hook.register('post_close', cement_hook_one)
hook.register('signal', cement_hook_one)
hook.register('pre_render', cement_hook_one)
hook.register('pre_render', cement_hook_five)
hook.register('post_render', cement_hook_one)
hook.register('post_render', cement_hook_five)
app.setup()
app.run()
app.render(dict(foo='bar'))
app.close()
# this is where cement_signal_hook is run
try:
frame = sys._getframe(0)
cement_signal_handler(signal.SIGTERM, frame)
except exc.CaughtSignal as e:
pass

View File

@ -1,34 +0,0 @@
"""Tests for cement.ext.ext_alarm."""
import time
import signal
from cement.core.exc import CaughtSignal
from cement.utils import test
class AlarmExtTestCase(test.CementExtTestCase):
def setUp(self):
super(AlarmExtTestCase, self).setUp()
self.app = self.make_app('tests',
extensions=['alarm'],
argv=[]
)
@test.raises(CaughtSignal)
def test_alarm_timeout(self):
global app
app = self.app
with app as app:
try:
app.alarm.set(1, "The Timer Works!")
time.sleep(3)
except CaughtSignal as e:
self.eq(e.signum, signal.SIGALRM)
raise
def test_alarm_no_timeout(self):
with self.app as app:
app.alarm.set(3, "The Timer Works!")
time.sleep(1)
app.alarm.stop()

View File

@ -68,7 +68,7 @@ class LoggingExtTestCase(test.CementExtTestCase):
def test_clear_loggers(self):
self.app.setup()
han = handler.get('log', 'logging')
han = self.app.handler.get('log', 'logging')
Log = han()
Log.clear_loggers(self.app._meta.label)