← Back to team overview

checkbox-dev team mailing list archive

Re: [Merge] lp:~zkrynicki/checkbox/use-morris into lp:checkbox

 

Hey

I'm re-sending the merge request to the mailing list. I was wondering
if this would also send something to the mailing list automatically,
since I've subscribed it to merge requests, but that apparently is not
working very well.

Please read the (probably hidden if you're using gmail) text below and
comment. If you keep the mp+number@c.l.n in the CC list.

Thanks (rest below)

On Fri, Feb 6, 2015 at 6:15 PM, Zygmunt Krynicki
<zygmunt.krynicki@xxxxxxxxxxxxx> wrote:
> Zygmunt Krynicki has proposed merging lp:~zkrynicki/checkbox/use-morris into lp:checkbox.
>
> Requested reviews:
>   Checkbox Developers (checkbox-dev)
>
> For more details, see:
> https://code.launchpad.net/~zkrynicki/checkbox/use-morris/+merge/248938
>
> Hey
>
> This branch adds the upstream morris package [1], [2], [3] as a new vendor module. It also removes the old signal module and updates all of the uses of plainbox.impl.signal to use plainbox.vendor.morris instead.
>
> I gave it some testing with checkbox-gui (the heaviest user of signals) and obviously with unit tests. I'm mainly looking for general feedback on the idea as I'd like to upstream more parts of plainbox that are generic and could be useful in other python-based applications.
>
> 768cc78 plainbox:vendor: vendorize morris 1.2
> f111915 plainbox:pod: spell Signal.define(..., signal_name=)
> 5391eda plainbox:signal: expose morris through plainbox.impl.signal
> c08bb46 plainbox:session: use SignalTestCase instead of SignalInterceptorMixIn
> cb16913 plainbox,checkbox-ng: use morris directly
> 186647a plainbox:signal: remove the singal module
>
> [1]: https://github.com/zyga/morris
> [2]: https://pypi.python.org/pypi/morris/1.2
> [3]: http://morris.readthedocs.org/en/latest/
> --
> You are the owner of lp:~zkrynicki/checkbox/use-morris.
>
> === modified file 'checkbox-ng/checkbox_ng/dbus_ex/service.py'
> --- checkbox-ng/checkbox_ng/dbus_ex/service.py  2015-01-07 14:52:42 +0000
> +++ checkbox-ng/checkbox_ng/dbus_ex/service.py  2015-02-06 17:15:13 +0000
> @@ -27,7 +27,7 @@
>  import threading
>  import weakref
>
> -from plainbox.impl.signal import Signal
> +from plainbox.vendor import morris
>  import _dbus_bindings
>  import dbus
>  import dbus.exceptions
> @@ -620,7 +620,7 @@
>          """
>          return self.__class__._dbus_class_table[self._dct_key]
>
> -    @Signal.define
> +    @morris.signal
>      def _on_managed_objects_changed(self, old_objs, new_objs):
>          logger.debug("%r._on_managed_objects_changed(%r, %r)",
>                       self, old_objs, new_objs)
>
> === modified file 'checkbox-ng/checkbox_ng/service.py'
> --- checkbox-ng/checkbox_ng/service.py  2015-02-03 14:45:25 +0000
> +++ checkbox-ng/checkbox_ng/service.py  2015-02-06 17:15:13 +0000
> @@ -40,8 +40,8 @@
>  from plainbox.impl.result import MemoryJobResult
>  from plainbox.impl.secure.qualifiers import select_jobs
>  from plainbox.impl.session import JobState
> -from plainbox.impl.signal import remove_signals_listeners
>  from plainbox.vendor import extcmd
> +from plainbox.vendor.morris import remove_signals_listeners
>
>  from checkbox_ng import dbus_ex as dbus
>  from checkbox_ng.dbus_ex import OBJECT_MANAGER_IFACE
>
> === removed file 'plainbox/docs/ref/plainbox.impl.signal.rst'
> --- plainbox/docs/ref/plainbox.impl.signal.rst  2013-11-08 15:26:50 +0000
> +++ plainbox/docs/ref/plainbox.impl.signal.rst  1970-01-01 00:00:00 +0000
> @@ -1,5 +0,0 @@
> -.. currentmodule:: plainbox.impl.signal
> -
> -.. automodule:: plainbox.impl.signal
> -    :members:
> -    :undoc-members:
>
> === modified file 'plainbox/plainbox/impl/ctrl.py'
> --- plainbox/plainbox/impl/ctrl.py      2015-02-06 12:45:23 +0000
> +++ plainbox/plainbox/impl/ctrl.py      2015-02-06 17:15:13 +0000
> @@ -71,10 +71,10 @@
>  from plainbox.impl.secure.rfc822 import gen_rfc822_records
>  from plainbox.impl.session.jobs import InhibitionCause
>  from plainbox.impl.session.jobs import JobReadinessInhibitor
> -from plainbox.impl.signal import Signal
>  from plainbox.impl.unit.job import JobDefinition
>  from plainbox.impl.unit.template import TemplateUnit
>  from plainbox.impl.validation import ValidationError
> +from plainbox.vendor.morris import signal
>  from plainbox.vendor import extcmd
>
>  __all__ = [
> @@ -557,7 +557,7 @@
>                  for filename in filenames)
>          return leftovers
>
> -    @Signal.define
> +    @signal
>      def on_leftover_files(self, job, config, cwd_dir, leftovers):
>          """
>          Handle any files left over by the execution of a job definition.
>
> === modified file 'plainbox/plainbox/impl/pod.py'
> --- plainbox/plainbox/impl/pod.py       2015-01-29 01:55:49 +0000
> +++ plainbox/plainbox/impl/pod.py       2015-02-06 17:15:13 +0000
> @@ -60,7 +60,7 @@
>  from logging import getLogger
>
>  from plainbox.i18n import gettext as _
> -from plainbox.impl.signal import Signal
> +from plainbox.vendor.morris import signal
>
>  __all__ = ['POD', 'Field', 'MANDATORY', 'UNSET', 'read_only_assign_filter',
>             'type_convert_assign_filter', 'type_check_assign_filter',
> @@ -238,9 +238,9 @@
>              return
>          assert self.signal_name is not None
>          if not hasattr(cls, self.signal_name):
> -            signal_def = Signal.define(
> +            signal_def = signal(
>                  self.on_changed,
> -                '{}.{}'.format(cls.__name__, self.signal_name))
> +                signal_name='{}.{}'.format(cls.__name__, self.signal_name))
>              setattr(cls, self.signal_name, signal_def)
>
>      def __get__(self, instance: object, owner: type) -> "Any":
>
> === modified file 'plainbox/plainbox/impl/result.py'
> --- plainbox/plainbox/impl/result.py    2015-01-26 15:38:31 +0000
> +++ plainbox/plainbox/impl/result.py    2015-02-06 17:15:13 +0000
> @@ -36,7 +36,7 @@
>  from plainbox.abc import IJobResult
>  from plainbox.i18n import gettext as _
>  from plainbox.i18n import pgettext as C_
> -from plainbox.impl.signal import Signal
> +from plainbox.vendor.morris import signal
>
>  logger = logging.getLogger("plainbox.result")
>
> @@ -257,7 +257,7 @@
>                  "{}:{!r}".format(key, self._data[key])
>                  for key in sorted(self._data.keys())]))
>
> -    @Signal.define
> +    @signal
>      def on_outcome_changed(self, old, new):
>          """
>          Signal sent when ``outcome`` property value is changed
> @@ -347,7 +347,7 @@
>          else:
>              self.comments = self.comments + '\n' + comments
>
> -    @Signal.define
> +    @signal
>      def on_comments_changed(self, old, new):
>          """
>          Signal sent when ``comments`` property value is changed
>
> === modified file 'plainbox/plainbox/impl/runner.py'
> --- plainbox/plainbox/impl/runner.py    2015-01-29 23:47:22 +0000
> +++ plainbox/plainbox/impl/runner.py    2015-02-06 17:15:13 +0000
> @@ -44,7 +44,7 @@
>  from plainbox.impl.result import IOLogRecord
>  from plainbox.impl.result import IOLogRecordWriter
>  from plainbox.impl.result import MemoryJobResult
> -from plainbox.impl.signal import Signal
> +from plainbox.vendor.morris import signal
>
>
>  logger = logging.getLogger("plainbox.runner")
> @@ -89,7 +89,7 @@
>          record = IOLogRecord(delay.total_seconds(), stream_name, line)
>          self.on_new_record(record)
>
> -    @Signal.define
> +    @signal
>      def on_new_record(self, record):
>          """
>          Internal signal method of :class:`IOLogRecordGenerator`
> @@ -926,7 +926,7 @@
>              ctrl.__class__.__name__, score, job.id)
>          return ctrl
>
> -    @Signal.define
> +    @signal
>      def on_leftover_files(self, job, config, cwd_dir, leftovers):
>          """
>          Handle any files left over by the execution of a job definition.
>
> === modified file 'plainbox/plainbox/impl/session/manager.py'
> --- plainbox/plainbox/impl/session/manager.py   2014-11-19 21:43:05 +0000
> +++ plainbox/plainbox/impl/session/manager.py   2015-02-06 17:15:13 +0000
> @@ -42,7 +42,7 @@
>  from plainbox.impl.session.storage import SessionStorage
>  from plainbox.impl.session.storage import SessionStorageRepository
>  from plainbox.impl.session.suspend import SessionSuspendHelper
> -from plainbox.impl.signal import Signal
> +from plainbox.vendor.morris import signal
>
>  logger = logging.getLogger("plainbox.session.manager")
>
> @@ -419,7 +419,7 @@
>          self._device_context_list.remove(context)
>          self.on_device_context_removed(context)
>
> -    @Signal.define
> +    @signal
>      def on_device_context_added(self, context):
>          """
>          Signal fired when a session device context object is added
> @@ -428,7 +428,7 @@
>              _("Device context %s added to session manager %s"),
>              context, self)
>
> -    @Signal.define
> +    @signal
>      def on_device_context_removed(self, context):
>          """
>          Signal fired when a session device context object is removed
>
> === modified file 'plainbox/plainbox/impl/session/state.py'
> --- plainbox/plainbox/impl/session/state.py     2014-10-13 16:13:28 +0000
> +++ plainbox/plainbox/impl/session/state.py     2015-02-06 17:15:13 +0000
> @@ -30,8 +30,8 @@
>  from plainbox.impl.depmgr import DependencySolver
>  from plainbox.impl.session.jobs import JobState
>  from plainbox.impl.session.jobs import UndesiredJobReadinessInhibitor
> -from plainbox.impl.signal import Signal
>  from plainbox.impl.unit.job import JobDefinition
> +from plainbox.vendor.morris import signal
>
>
>  logger = logging.getLogger("plainbox.session.state")
> @@ -402,7 +402,7 @@
>              ctrl.__class__.__name__, score, job.id)
>          return ctrl
>
> -    @Signal.define
> +    @signal
>      def on_provider_added(self, provider):
>          """
>          Signal sent whenever a provider is added to the context.
> @@ -412,14 +412,14 @@
>          # on the accuracy of provider_list
>          self._invalidate_execution_ctrl_list()
>
> -    @Signal.define
> +    @signal
>      def on_unit_added(self, unit):
>          """
>          Signal sent whenever a unit is added to the context.
>          """
>          logger.debug(_("Unit %s added to context %s"), unit, self)
>
> -    @Signal.define
> +    @signal
>      def on_unit_removed(self, unit):
>          """
>          Signal sent whenever a unit is removed from the context.
> @@ -567,7 +567,7 @@
>      :ivar dict metadata: instance of :class:`SessionMetaData`
>      """
>
> -    @Signal.define
> +    @signal
>      def on_job_state_map_changed(self):
>          """
>          Signal fired after job_state_map is changed in any way.
> @@ -582,7 +582,7 @@
>          and can be easily looked at by the application.
>          """
>
> -    @Signal.define
> +    @signal
>      def on_job_result_changed(self, job, result):
>          """
>          Signal fired after a job get changed (set)
> @@ -593,7 +593,7 @@
>          """
>          logger.info(_("Job %s result changed to %r"), job, result)
>
> -    @Signal.define
> +    @signal
>      def on_job_added(self, job):
>          """
>          Signal sent whenever a job is added to the session.
> @@ -601,7 +601,7 @@
>          This signal is fired **after** :meth:`on_job_state_map_changed()`
>          """
>
> -    @Signal.define
> +    @signal
>      def on_job_removed(self, job):
>          """
>          Signal sent whenever a job is removed from the session.
> @@ -609,13 +609,13 @@
>          This signal is fired **after** :meth:`on_job_state_map_changed()`
>          """
>
> -    @Signal.define
> +    @signal
>      def on_unit_added(self, unit):
>          """
>          Signal sent whenever a unit is added to the session.
>          """
>
> -    @Signal.define
> +    @signal
>      def on_unit_removed(self, unit):
>          """
>          Signal sent whenever a unit is removed from the session.
>
> === modified file 'plainbox/plainbox/impl/session/test_manager.py'
> --- plainbox/plainbox/impl/session/test_manager.py      2014-11-19 21:43:05 +0000
> +++ plainbox/plainbox/impl/session/test_manager.py      2015-02-06 17:15:13 +0000
> @@ -33,11 +33,11 @@
>  from plainbox.impl.session import SessionStorage
>  from plainbox.impl.session.state import SessionDeviceContext
>  from plainbox.impl.session.suspend import SessionSuspendHelper
> -from plainbox.impl.signal import SignalInterceptorMixIn
>  from plainbox.vendor import mock
> -
> -
> -class SessionManagerTests(TestCase, SignalInterceptorMixIn):
> +from plainbox.vendor.morris import SignalTestCase
> +
> +
> +class SessionManagerTests(SignalTestCase):
>
>      def setUp(self):
>          self.storage = mock.Mock(name="storage", spec=SessionStorage)
>
> === modified file 'plainbox/plainbox/impl/session/test_state.py'
> --- plainbox/plainbox/impl/session/test_state.py        2015-02-03 14:45:25 +0000
> +++ plainbox/plainbox/impl/session/test_state.py        2015-02-06 17:15:13 +0000
> @@ -40,11 +40,11 @@
>  from plainbox.impl.session import UndesiredJobReadinessInhibitor
>  from plainbox.impl.session.state import SessionDeviceContext
>  from plainbox.impl.session.state import SessionMetaData
> -from plainbox.impl.signal import SignalInterceptorMixIn
>  from plainbox.impl.testing_utils import make_job
>  from plainbox.impl.unit.job import JobDefinition
>  from plainbox.impl.unit.unit import Unit
>  from plainbox.vendor import mock
> +from plainbox.vendor.morris import SignalTestCase
>
>
>  class SessionStateSmokeTests(TestCase):
> @@ -697,7 +697,7 @@
>              metadata.app_id, 'com.canonical.certification.plainbox')
>
>
> -class SessionDeviceContextTests(TestCase, SignalInterceptorMixIn):
> +class SessionDeviceContextTests(SignalTestCase):
>
>      def setUp(self):
>          self.ctx = SessionDeviceContext()
>
> === removed file 'plainbox/plainbox/impl/signal.py'
> --- plainbox/plainbox/impl/signal.py    2015-01-16 19:58:50 +0000
> +++ plainbox/plainbox/impl/signal.py    1970-01-01 00:00:00 +0000
> @@ -1,260 +0,0 @@
> -# Copyright 2012 Canonical Ltd.
> -# Written by:
> -#   Zygmunt Krynicki <zygmunt.krynicki@xxxxxxxxxxxxx>
> -#
> -# This program is free software: you can redistribute it and/or modify
> -# it under the terms of the GNU General Public License version 3,
> -# as published by the Free Software Foundation.
> -#
> -# This program is distributed in the hope that it will be useful,
> -# but WITHOUT ANY WARRANTY; without even the implied warranty of
> -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> -# GNU General Public License for more details.
> -#
> -# You should have received a copy of the GNU General Public License
> -# along with this program.  If not, see <http://www.gnu.org/licenses/>.
> -
> -"""
> -:mod:`plainbox.impl.signal` -- signal system
> -============================================
> -"""
> -from collections import defaultdict
> -import inspect
> -import logging
> -
> -from plainbox.i18n import gettext as _
> -
> -logger = logging.getLogger("plainbox.signal")
> -
> -__all__ = ['Signal']
> -
> -
> -class Signal:
> -    """
> -    Basic signal that supports arbitrary listeners.
> -
> -    While this class can be used directly it is best used with the helper
> -    decorator Signal.define on a member function. The function body is ignored,
> -    apart from the documentation.
> -
> -    The function name then becomes a unique (per encapsulating class instance)
> -    object (an instance of this Signal class) that is created on demand.
> -
> -    In practice you just have a documentation and use
> -    `object.signal_name.connect()` and `object.signal_name(*args, **kwargs)` to
> -    fire it.
> -    """
> -
> -    def __init__(self, signal_name):
> -        """
> -        Construct a signal with the given name
> -        """
> -        self._listeners = []
> -        self._signal_name = signal_name
> -
> -    def __repr__(self):
> -        return "<Signal name:{!r}>".format(self._signal_name)
> -
> -    def connect(self, listener):
> -        """
> -        Connect a new listener to this signal
> -
> -        That listener will be called whenever fire() is invoked on the signal
> -        """
> -        self._listeners.append(listener)
> -        # TRANSLATORS: this is a indicative statement
> -        logger.debug(_("connect %r to %r"), str(listener), self._signal_name)
> -        # Track listeners in the instances only
> -        if inspect.ismethod(listener):
> -            listener_object = listener.__self__
> -            # Ensure that the instance has __listeners__ property
> -            if not hasattr(listener_object, "__listeners__"):
> -                listener_object.__listeners__ = defaultdict(list)
> -            # Append the signals a listener is connected to
> -            listener_object.__listeners__[listener].append(self)
> -
> -    def disconnect(self, listener):
> -        """
> -        Disconnect an existing listener from this signal
> -        """
> -        self._listeners.remove(listener)
> -        logger.debug(
> -            # TRANSLATORS: this is a indicative statement
> -            _("disconnect %r from %r"), str(listener), self._signal_name)
> -        if inspect.ismethod(listener):
> -            listener_object = listener.__self__
> -            if hasattr(listener_object, "__listeners__"):
> -                listener_object.__listeners__[listener].remove(self)
> -                # Remove the listener from the list if any signals connected
> -                if (len(listener_object.__listeners__[listener])) == 0:
> -                    del listener_object.__listeners__[listener]
> -
> -    def fire(self, args, kwargs):
> -        """
> -        Fire this signal with the specified arguments and keyword arguments.
> -
> -        Typically this is used by using __call__() on this object which is more
> -        natural as it does all the argument packing/unpacking transparently.
> -        """
> -        for listener in self._listeners:
> -            listener(*args, **kwargs)
> -
> -    def __call__(self, *args, **kwargs):
> -        """
> -        Call fire() with all arguments forwarded transparently
> -        """
> -        self.fire(args, kwargs)
> -
> -    @classmethod
> -    def define(cls, first_responder, signal_name=None):
> -        """
> -        Helper decorator to define a signal descriptor in a class
> -
> -        The decorated function is never called but is used to get
> -        documentation.
> -        """
> -        return _SignalDescriptor(first_responder, signal_name)
> -
> -
> -class _SignalDescriptor:
> -    """
> -    Descriptor for convenient signal access.
> -
> -    Typically this class is used indirectly, when accessed from Signal.define
> -    method decorator. It is used to do all the magic required when accessing
> -    signal name on a class or instance.
> -    """
> -
> -    def __init__(self, first_responder, signal_name=None):
> -        if signal_name is None:
> -            if hasattr(first_responder, '__qualname__'):
> -                signal_name = first_responder.__qualname__
> -            else:
> -                signal_name = first_responder.__name__
> -        self.signal_name = signal_name
> -        self.first_responder = first_responder
> -        self.__doc__ = first_responder.__doc__
> -
> -    def __repr__(self):
> -        return "<SignalDecorator for signal:{!r}>".format(self.signal_name)
> -
> -    def __get__(self, instance, owner):
> -        if instance is None:
> -            return self
> -        # Ensure that the instance has __signals__ property
> -        if not hasattr(instance, "__signals__"):
> -            instance.__signals__ = {}
> -        # Ensure that the instance signal is defined
> -        if self.signal_name not in instance.__signals__:
> -            # Or create it if needed
> -            signal = Signal(self.signal_name)
> -            # Connect the first responder function
> -            signal.connect(lambda *args, **kwargs: self.first_responder(
> -                instance, *args, **kwargs))
> -            # Ensure we don't recreate signals
> -            instance.__signals__[self.signal_name] = signal
> -        return instance.__signals__[self.signal_name]
> -
> -    def __set__(self, instance, value):
> -        raise AttributeError("You cannot overwrite signals")
> -
> -    def __delete__(self, instance):
> -        raise AttributeError("You cannot delete signals")
> -
> -
> -def remove_signals_listeners(instance):
> -    """
> -    utility function that disconnects all listeners from all signals on an
> -    object
> -    """
> -    if hasattr(instance, "__listeners__"):
> -        for listener in list(instance.__listeners__):
> -            for signal in instance.__listeners__[listener]:
> -                signal.disconnect(listener)
> -
> -
> -class SignalInterceptorMixIn:
> -    """
> -    A mix-in class for :class:`unittest.TestCase` that simplifies testing
> -    uses of the plainbox signal system
> -    """
> -
> -    def _extend_state(self):
> -        if not hasattr(self, '_events_seen'):
> -            self._events_seen = []
> -
> -    def watchSignal(self, signal):
> -        """
> -        Setup provisions to watch a specified signal
> -
> -        :param signal:
> -            The signal (from :mod:`plainbox.impl.signal`) to watch.
> -        """
> -        self._extend_state()
> -
> -        def signal_handler(*args, **kwargs):
> -            self._events_seen.append((signal, args, kwargs))
> -        signal.connect(signal_handler)
> -        if hasattr(self, 'addCleanup'):
> -            self.addCleanup(signal.disconnect, signal_handler)
> -
> -    def assertSignalFired(self, signal, *args, **kwargs):
> -        """
> -        Assert that a signal was fired with appropriate arguments.
> -
> -        :param signal:
> -            The signal (from :mod:`plainbox.impl.signal`) that should have been
> -            fired. Typically this is ``SomeClass.on_some_signal`` reference
> -        :param args:
> -            List of positional arguments passed to the signal handler
> -        :param kwargs:
> -            List of keyword arguments passed to the signal handler
> -        :returns:
> -            A 3-tuple (signal, args, kwargs) that describes that event
> -        """
> -        event = (signal, args, kwargs)
> -        self.assertIn(event, self._events_seen)
> -        return event
> -
> -    def assertSignalNotFired(self, signal, *args, **kwargs):
> -        """
> -        Assert that a signal was fired with appropriate arguments.
> -
> -        :param signal:
> -            The signal (from :mod:`plainbox.impl.signal`) that should have been
> -            fired. Typically this is ``SomeClass.on_some_signal`` reference
> -        :param args:
> -            List of positional arguments passed to the signal handler
> -        :param kwargs:
> -            List of keyword arguments passed to the signal handler
> -        """
> -        event = (signal, args, kwargs)
> -        self.assertNotIn(event, self._events_seen)
> -
> -    def assertSignalOrdering(self, *expected_events):
> -        """
> -        Assert that a signals were fired in a specific sequence.
> -
> -        :param expected_events:
> -            A (varadic) list of events describing the signals that were fired
> -            Each element is a 3-tuple (signal, args, kwargs) that describes
> -            the event.
> -
> -        .. note::
> -            If you are using :meth:`assertSignalFired()` then the return value
> -            of that method is a single event that can be passed to this method
> -        """
> -        expected_order = [self._events_seen.index(event)
> -                          for event in expected_events]
> -        actual_order = sorted(expected_order)
> -        self.assertEqual(
> -            expected_order, actual_order,
> -            "\nExpected order of fired signals:\n{}\n"
> -            "Actual order observed:\n{}".format(
> -                "\n".join(
> -                    "\t{}: {}".format(i, event)
> -                    for i, event in enumerate(expected_events, 1)),
> -                "\n".join(
> -                    "\t{}: {}".format(i, event)
> -                    for i, event in enumerate(
> -                        (self._events_seen[idx] for idx in actual_order), 1))))
>
> === removed file 'plainbox/plainbox/impl/test_signal.py'
> --- plainbox/plainbox/impl/test_signal.py       2013-11-27 20:40:19 +0000
> +++ plainbox/plainbox/impl/test_signal.py       1970-01-01 00:00:00 +0000
> @@ -1,79 +0,0 @@
> -# This file is part of Checkbox.
> -#
> -# Copyright 2013 Canonical Ltd.
> -# Written by:
> -#   Zygmunt Krynicki <zygmunt.krynicki@xxxxxxxxxxxxx>
> -#
> -# Checkbox is free software: you can redistribute it and/or modify
> -# it under the terms of the GNU General Public License version 3,
> -# as published by the Free Software Foundation.
> -
> -#
> -# Checkbox is distributed in the hope that it will be useful,
> -# but WITHOUT ANY WARRANTY; without even the implied warranty of
> -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> -# GNU General Public License for more details.
> -#
> -# You should have received a copy of the GNU General Public License
> -# along with Checkbox.  If not, see <http://www.gnu.org/licenses/>.
> -
> -"""
> -plainbox.impl.test_signal
> -=========================
> -
> -Test definitions for plainbox.impl.signal module
> -"""
> -
> -from unittest import TestCase
> -
> -from plainbox.impl.signal import Signal, remove_signals_listeners
> -
> -
> -class SignalTests(TestCase):
> -
> -    def setUp(self):
> -
> -        class C:
> -
> -            @Signal.define
> -            def on_foo(self):
> -                self.first_responder_called = True
> -
> -            @Signal.define
> -            def on_bar(self):
> -                self.first_responder_called = True
> -
> -        self.c = C()
> -
> -    def test_smoke(self):
> -        self.c.on_foo.connect(lambda: setattr(self, 'signal_called', True))
> -        self.c.on_foo()
> -        self.assertEqual(self.c.first_responder_called, True)
> -        self.assertEqual(self.signal_called, True)
> -
> -    def test_remove_signals_listeners(self):
> -        c = self.c
> -
> -        class R:
> -
> -            def __init__(self):
> -                c.on_foo.connect(self._foo)
> -                c.on_bar.connect(self._bar)
> -                c.on_bar.connect(self._baz)
> -
> -            def _foo(self):
> -                pass
> -
> -            def _bar(self):
> -                pass
> -
> -            def _baz(self):
> -                pass
> -
> -        a = R()
> -        b = R()
> -        self.assertEqual(len(a.__listeners__), 3)
> -        self.assertEqual(len(b.__listeners__), 3)
> -        remove_signals_listeners(a)
> -        self.assertEqual(len(a.__listeners__), 0)
> -        self.assertEqual(len(b.__listeners__), 3)
>
> === added directory 'plainbox/plainbox/vendor/morris'
> === added file 'plainbox/plainbox/vendor/morris/__init__.py'
> --- plainbox/plainbox/vendor/morris/__init__.py 1970-01-01 00:00:00 +0000
> +++ plainbox/plainbox/vendor/morris/__init__.py 2015-02-06 17:15:13 +0000
> @@ -0,0 +1,873 @@
> +# Copyright 2012-2015 Canonical Ltd.
> +# Written by:
> +#   Zygmunt Krynicki <zygmunt.krynicki@xxxxxxxxxxxxx>
> +#
> +# This file is part of Morris.
> +#
> +# Morris is free software: you can redistribute it and/or modify
> +# it under the terms of the GNU Lesser General Public License as published by
> +# the Free Software Foundation, either version 3 of the License.
> +#
> +# Morris is distributed in the hope that it will be useful,
> +# but WITHOUT ANY WARRANTY; without even the implied warranty of
> +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> +# GNU Lesser General Public License for more details.
> +#
> +# You should have received a copy of the GNU Lesser General Public License
> +# along with Morris.  If not, see <http://www.gnu.org/licenses/>.
> +"""
> +:mod:`plainbox.vendor.morris` --  announcement (signal/event) system for Python
> +===============================================================
> +
> +The plainbox.vendor.morris module defines two main classes :class:`signal` and
> +:class:`SignalTestCase`.
> +
> +Defining Signals
> +----------------
> +
> +.. note::
> +    Since version 1.1 ``Signal.define`` and ``signal`` are identical
> +
> +You can import the ``signal`` class and use idiomatic code like::
> +
> +    >>> from plainbox.vendor.morris import signal
> +
> +    >>> # NOTE: classic python 2.x classes are not supported
> +    >>> class Klass(object):
> +    ...     @signal
> +    ...     def on_foo(self):
> +    ...         pass
> +
> +    >>> @signal
> +    ... def on_bar():
> +    ...     pass
> +
> +Connecting signal listeners
> +---------------------------
> +
> +Connecting signals is equally easy, just call :meth:`signal.connect()`
> +
> +    >>> def handler():
> +    ...     print("handling signal")
> +
> +    >>> obj = Klass()
> +    >>> obj.on_foo.connect(handler)
> +    >>> on_bar.connect(handler)
> +
> +Firing signals
> +--------------
> +
> +To fire a signal simply *call* the signal object::
> +
> +    >>> obj.on_foo()
> +    handling signal
> +    >>> on_bar()
> +    handling signal
> +
> +Typically you will want to pass some additional arguments. Both positional
> +and keyword arguments are supported::
> +
> +    >>> @signal
> +    ... def on_bar_with_args(arg1, arg2):
> +    ...     print("fired!")
> +
> +    >>> on_bar_with_args('foo', arg2='bar')
> +    fired!
> +
> +If you are working in a tight loop it is slightly faster to construct the list
> +of positional arguments and the dictionary of keyword arguments and call the
> +:meth:`Signal.fire()` method directly::
> +
> +    >>> args = ('foo',)
> +    >>> kwargs = {'arg2': 'bar'}
> +    >>> for i in range(3):
> +    ...     on_bar_with_args.fire(args, kwargs)
> +    fired!
> +    fired!
> +    fired!
> +
> +Passing additional meta-data to the signal listener
> +---------------------------------------------------
> +
> +In some cases you may wish to use a generic signal handler that would benefit
> +from knowing which signal has triggered it. To do that first make sure that
> +your handler has a ``signal`` argument and then call ``sig.connect(handler,
> +pass_signal=True)``:
> +
> +    >>> def generic_handler(*args, **kwargs):
> +    ...     signal = kwargs.pop('signal')
> +    ...     print("Handling signal {}: {} {}".format(signal, args, kwargs))
> +
> +Let's define two signals now:
> +
> +    >>> @signal
> +    ... def login(user, password):
> +    ...     pass
> +    >>> @signal
> +    ... def logout(user):
> +    ...     pass
> +
> +And connect both to the same handler:
> +
> +    >>> login.connect(generic_handler, pass_signal=True)
> +    >>> logout.connect(generic_handler, pass_signal=True)
> +
> +Now we can fire either one and see our handler work:
> +
> +    >>> login(str('user'), password=str('pass'))
> +    Handling signal <signal name:'login'>: ('user',) {'password': 'pass'}
> +    >>> logout(str('user'))
> +    Handling signal <signal name:'logout'>: ('user',) {}
> +
> +.. note::
> +    The example uses ``str(...)`` to have identical output on Python
> +    2.7 and 3.x but ``str()`` it is otherwise useless.
> +
> +This also works with classes:
> +
> +    >>> class App(object):
> +    ...     def __repr__(self):
> +    ...         return "app"
> +    ...     @signal
> +    ...     def login(self, user, password):
> +    ...         pass
> +    ...     @signal
> +    ...     def logout(self, user):
> +    ...         pass
> +    >>> app = App()
> +    >>> app.login.connect(generic_handler, pass_signal=True)
> +    >>> app.logout.connect(generic_handler, pass_signal=True)
> +
> +We can now fire the signals, just as before:
> +
> +    >>> app.login(str('user'), password=str('pass'))
> +    ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
> +    Handling signal <signal name:'...login' (specific to app)>:
> +        ('user',) {'password': 'pass'}
> +    >>> app.logout(str('user'))  # doctest: +ELLIPSIS
> +    Handling signal <signal name:'...logout' (specific to app)>: ('user',) {}
> +
> +Disconnecting signals
> +---------------------
> +
> +To disconnect a signal handler call :meth:`signal.disconnect()` with the same
> +listener object that was used in ``connect()``:
> +
> +    >>> obj.on_foo.disconnect(handler)
> +    >>> on_bar.disconnect(handler)
> +
> +Threading considerations
> +------------------------
> +
> +Morris doesn't do anything related to threads. Threading is diverse enough that
> +for now it was better to just let uses handle it. There are two things that
> +are worth mentioning though:
> +
> +1) :meth:`signal.connect()` and :meth:`signal.disconnect()` should be safe to
> +   call concurrently with :meth:`signal.fire()` since fire() operates on
> +   a *copy* of the list of listeners
> +
> +2) Event handlers are called from the thread calling :meth:`signal.fire()`,
> +   not from the thread that was used to connect to the signal handler. If you
> +   need special provisions for working with signals in a specific thread
> +   consider calling a thread-library-specific function that calls a callable
> +   in a specific thread context.
> +
> +Support for writing unit tests
> +------------------------------
> +
> +Morris ships with support for writing tests for signals. You can use
> +:class:`SignalTestCase`'s support methods such as
> +:meth:`~signalTestCase.watchSignal()`,
> +:meth:`~SignalTestCase.assertSignalFired()`,
> +:meth:`~SignalTestCase.assertSignalNotFired()` and
> +:meth:`~SignalTestCase.assertSignalOrdering()` to simplify your tests.
> +
> +Here's a simple example using all of the above:
> +
> +    >>> class App(object):
> +    ...     @signal
> +    ...     def on_login(self, user):
> +    ...         pass
> +    ...     @signal
> +    ...     def on_logout(self, user):
> +    ...         pass
> +    ...     def login(self, user):
> +    ...         self.on_login(user)
> +    ...     def logout(self, user):
> +    ...         self.on_logout(user)
> +
> +    >>> class AppTests(SignalTestCase):
> +    ...     def setUp(self):
> +    ...         self.app = App()
> +    ...         self.watchSignal(self.app.on_login)
> +    ...         self.watchSignal(self.app.on_logout)
> +    ...     def test_login(self):
> +    ...         # Log the user in, then out
> +    ...         self.app.login("user")
> +    ...         self.app.logout("user")
> +    ...         # Ensure that both login and logout signals were sent
> +    ...         event1 = self.assertSignalFired(self.app.on_login, 'user')
> +    ...         event2 = self.assertSignalFired(self.app.on_logout, 'user')
> +    ...         # Ensure that signals were fired in the right order
> +    ...         self.assertSignalOrdering(event1, event2)
> +    ...         # Ensure that we didn't login as admin
> +    ...         self.assertSignalNotFired(self.app.on_login, 'admin')
> +
> +    >>> import sys
> +    >>> suite = unittest.TestLoader().loadTestsFromTestCase(AppTests)
> +    >>> runner = unittest.TextTestRunner(stream=sys.stdout, verbosity=2)
> +    >>> runner.run(suite)  # doctest: +ELLIPSIS
> +    test_login (plainbox.vendor.morris.AppTests) ... ok
> +    <BLANKLINE>
> +    ----------------------------------------------------------------------
> +    Ran 1 test in ...s
> +    <BLANKLINE>
> +    OK
> +    <unittest.runner.TextTestResult run=1 errors=0 failures=0>
> +
> +Implementation notes
> +--------------------
> +
> +At some point in time one may need to peek under the cover and understand where
> +the list of signal listeners is being stored and how signals interact with
> +classes. First of all, the :class:`signal` class can be used as a Python
> +descriptor. Descriptors are objects that have methods such as ``__get__``,
> +``__set__`` or ``__delete__``.
> +
> +You have most certainly used descriptors before, in fact the well-known
> +``@property`` decorator is nothing more than a class with methods such as
> +listed above.
> +
> +When used as a descriptor, a signal object will **create new signal objects
> +each time it is being accessed on an instance of some class**. The instance of
> +some class will be injected with a ``__signals__`` dictionary that contains
> +signals that have been accessed.
> +
> +Consider this example::
> +
> +    >>> class Foo(object):
> +    ...     @signal
> +    ...     def ping(self):
> +    ...         pass
> +
> +Here ``Foo.ping`` is one instance of :class:`signal`. When that instance
> +is being accessed on a class it simply returns itself.
> +
> +    >>> Foo.ping  # doctest: +ELLIPSIS
> +    <signal name:'...ping'>
> +
> +.. note::
> +    While this looks similar to decorating a function it is functioning in a
> +    totally different way. Signals decorating plain functions (outside of a
> +    class definition body) are not using their descriptor nature.
> +
> +Now, let's instantiate ``Foo`` and see what's inside::
> +
> +    >>> foo = Foo()
> +    >>> foo.__dict__
> +    {}
> +
> +Nothing is inside, but there will be once we access ``foo.ping``. Morris will
> +create a new :class:`signal` object associated with both the ``foo`` instance
> +and the ``foo.ping`` method. It will look for ``foo.__signals__`` and not
> +having found any will create one from an empty dictionary. Lastly morris will
> +add the newly created signal object to the dictionary. This way each time we
> +access ``foo.ping`` (on the particular ``foo`` object) we'll get exactly the
> +same signal object in return.
> +
> +    >>> foo.ping  # doctest: +ELLIPSIS
> +    <signal name:'...ping' (specific to <...Foo object at ...>)>
> +    >>> foo.__dict__  # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
> +    {'__signals__':
> +     {'...ping': <signal name:'...ping'
> +      (specific to <...Foo object at ...>)>}}
> +
> +This all happens transparently the first time that code such as
> +``foo.ping.connect(...)`` is executed. When you connect a signal morris simply
> +needs a place to store the list of listeners and that is in a signal object
> +itself. We can now register a simple listener.
> +
> +    >>> def handler():
> +    ...     pass
> +    >>> foo.ping.connect(handler)
> +
> +Handlers are stored in the :meth:`signal.listeners` attribute. They are stored
> +as a list of :class:`listenerinfo` tuples. Note that the first responder (the
> +decorated function itself) is also present, here it is wrapped in the special
> +(specific to morris) :class:`boundmethod` class.
> +
> +    >>> foo.ping.listeners  # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
> +    [listenerinfo(listener=<...boundmethod object at ...>, pass_signal=False),
> +     listenerinfo(listener=<function handler at ...>, pass_signal=False)]
> +
> +Now, let's compare this to using signals as a function decorator:
> +
> +    >>> @signal
> +    ... def standalone():
> +    ...     pass
> +
> +The ``standalone()`` function is now *replaced* by the correspondingly-named
> +signal object:
> +
> +    >>> standalone
> +    <signal name:'standalone'>
> +
> +The original function is connected as the first responder though:
> +
> +    >>> standalone.listeners  # doctest: +ELLIPSIS
> +    [listenerinfo(listener=<function ...standalone at ...>, pass_signal=False)]
> +
> +Since there are no extra objects, there is no ``__dict__`` and no
> +``__signals__`` either.
> +
> +
> +Using @signal on class with __slots__
> +-------------------------------------
> +
> +Since (having read the previous section) you already know that signal
> +descriptors access the ``__signals__`` attribute on objects of classes they
> +belong to, to use signals on a class that uses ``__slots__`` you need to
> +reserve the ``__signals__`` slot up-front.
> +
> +    >>> class Slotted(object):
> +    ...     __slots__ = ('__signals__')
> +    ...     @signal
> +    ...     def ping(self):
> +    ...         pass
> +    >>> Slotted.ping  # doctest: +ELLIPSIS
> +    <signal name:'...ping'>
> +    >>> slotted = Slotted()
> +    >>> slotted.ping  # doctest: +ELLIPSIS
> +    <signal name:'...ping' (specific to <...Slotted object at ...>)>
> +    >>> slotted.__signals__  # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
> +    {'...ping': <signal name:'...ping'
> +     (specific to <...Slotted object at ...>)>}
> +
> +Creating signals explicitly
> +---------------------------
> +
> +In all of the examples above we've been using signal as a decorator for
> +existing methods or functions. This is fine for the vast majority of code but
> +in some cases it may be beneficial to create signal objects explicitly. This
> +may be of use in meta-programming, for example.
> +
> +The :class:`signal` class may be instantiated in the two following ways:
> + - with the signal name (and no listeners)
> + - with the first responder function (which becomes the first listener)
> +
> +The second mode also has a special special case where the first responder.
> +Let's examine than now. First, the plain signal object:
> +
> +    >>> signal(str("my-signal"))
> +    <signal name:'my-signal'>
> +
> +This is a normal signal object, we can call it to fire the signal, we can use
> +the :meth:`signal.connect()` method to add listeners, etc. If you want to
> +create standalone signals, this is the best way to do it.
> +
> +Now let's examine the case where we pass a signal handler instead of the name:
> +
> +    >>> def my_signal2_handler():
> +    ...     pass
> +    >>> signal(my_signal2_handler)
> +    <signal name:'my_signal2_handler'>
> +
> +Here the name of the signal is derived from the name of the handler function.
> +We can customize the name, if desired, by passing the signal_name argument
> +(preferably as a keyword argument to differentiate it from the ``pass_signal``
> +argument):
> +
> +    >>> signal(my_signal2_handler, signal_name='my-signal-2')
> +    <signal name:'my-signal-2'>
> +
> +Both examples that pass a handler are identical to what happens when decorating
> +a regular function. There is nothing special about this mode either.
> +
> +The last, and somewhat special, mode is where the handler is an instance of
> +:class:`boundmethod` (which is implemented inside morris). In the Python 2.x
> +world, python had bound methods but they were removed. We still benefit from
> +them, a little, hence they are back.
> +
> +    >>> class C(object):
> +    ...     def handler(self):
> +    ...         pass
> +    >>> signal(boundmethod(C(), C.handler))  # doctest: +ELLIPSIS
> +    <signal name:'...handler' (specific to <...C object at ...>)>
> +
> +.. note::
> +    It is possible to remove boundmethod and rely  ``func.__self__`` but this
> +    was not done, yet. Contributions are welcome!
> +
> +To summarize this section, some simple rules:
> +
> +- each signal object has a list of listeners
> +- signal objects act as descriptors and create per-instance signal objects
> +- signal object created this way are stored in per-instance ``__signals__``
> +  attribute
> +"""
> +from __future__ import print_function, absolute_import, unicode_literals
> +
> +import collections
> +import inspect
> +import logging
> +import unittest
> +
> +__author__ = 'Zygmunt Krynicki'
> +__email__ = 'zygmunt.krynicki@xxxxxxxxxxxxx'
> +__version__ = '1.2'
> +__all__ = ['signal', 'SignalTestCase']
> +
> +_logger = logging.getLogger("plainbox.vendor.morris")
> +
> +
> +listenerinfo = collections.namedtuple('listenerinfo', 'listener pass_signal')
> +
> +
> +class signal(object):
> +    """
> +    Basic signal that supports arbitrary listeners.
> +
> +    While this class can be used directly it is best used with the helper
> +    decorator Signal.define on a function or method. See the documentation
> +    for the :mod:`plainbox.vendor.morris` module for details.
> +
> +    :attr _name:
> +        Name of the signal, typically accessed via :meth:`name`.
> +    :attr _listeners:
> +        List of signal listeners. Each item is a tuple ``(listener,
> +        pass_signal)`` that encodes how to call the listener.
> +    """
> +    try:
> +        _str_bases = (str, unicode)
> +    except NameError:
> +        _str_bases = (str,)
> +
> +    def __init__(self, name_or_first_responder, pass_signal=False,
> +                 signal_name=None):
> +        """
> +        Construct a signal with the given name
> +
> +        :param name_or_first_responder:
> +            Either the name of the signal to construct or a callable which
> +            will be the first responder. In the latter case the callable is
> +            used to obtain the name of the signal.
> +        :param pass_signal:
> +            An optional flag that instructs morris to pass the signal object
> +            itself to the first responder (as the ``signal`` argument). This is
> +            only used in the case where ``name_or_first_responder`` is a
> +            callable.
> +        :param signal_name:
> +            Optional name of the signal. This is meaningful only when the first
> +            argument ``name_or_first_responder`` is a callable.  When that
> +            happens this argument is used and no guessing based on __qualname__
> +            or __name__ is being used.
> +        """
> +        if isinstance(name_or_first_responder, self._str_bases):
> +            first_responder = None
> +            name = name_or_first_responder
> +        else:
> +            first_responder = name_or_first_responder
> +            name = signal_name or _get_fn_name(first_responder)
> +        self._name = name
> +        self._first_responder = first_responder
> +        self._listeners = []
> +        if first_responder is not None:
> +            self._listeners.append(listenerinfo(first_responder, pass_signal))
> +
> +    def __repr__(self):
> +        """
> +        A representation of the signal.
> +
> +        There are two possible representations:
> +            - a signal object created via a signal descriptor on an object
> +            - a signal object acting as a descriptor or function decorator
> +        """
> +        if (len(self._listeners) > 0
> +                and isinstance(self.listeners[0].listener, boundmethod)):
> +            return "<signal name:{!r} (specific to {!r})>".format(
> +                str(self._name), self._listeners[0].listener.instance)
> +        else:
> +            return "<signal name:{!r}>".format(str(self._name))
> +
> +    def __get__(self, instance, owner):
> +        """
> +        Descriptor __get__ method
> +
> +        This method is called when a signal-decorated method is being accessed
> +        via an object or a class. It is never called for decorated functions.
> +
> +        :param instance:
> +            Instance of the object the descriptor is being used on.
> +            This is None when the descriptor is accessed on a class.
> +        :param owner:
> +            The class that the descriptor is defined on.
> +        :returns:
> +            If ``instance`` is None we return ourselves, this is what
> +            descriptors typically do. If ``instance`` is not None we return a
> +            unique :class:`Signal` instance that is specific to that object and
> +            signal. This is implemented by storing the signal inside the
> +            object's __signals__ attribute.
> +        """
> +        if instance is None:
> +            return self
> +        # Ensure that the instance has __signals__ property
> +        if not hasattr(instance, "__signals__"):
> +            instance.__signals__ = {}
> +        # Ensure that the instance signal is defined
> +        if self._name not in instance.__signals__:
> +            # Or create it if needed
> +            signal = Signal(self._name)
> +            # Connect the first responder function via the trampoline so that
> +            # the instance's self object is also passed explicitly
> +            signal.connect(boundmethod(instance, self._first_responder))
> +            # Ensure we don't recreate signals
> +            instance.__signals__[self._name] = signal
> +        return instance.__signals__[self._name]
> +
> +    def __set__(self, instance, value):
> +        raise AttributeError("You cannot overwrite signals")
> +
> +    def __delete__(self, instance):
> +        raise AttributeError("You cannot delete signals")
> +
> +    @property
> +    def name(self):
> +        """
> +        Name of the signal
> +
> +        For signals constructed manually (i.e. by calling :class:`Signal()`)
> +        the name is arbitrary. For signals constructed using either
> +        :meth:`Signal.define()` or :class:`signal` the name is obtained
> +        from the decorated function.
> +
> +        On python 3.3+ the qualified name is used (see :pep:`3155`), on earlier
> +        versions the plain name is used (without the class name). The name is
> +        identical regardless of how the signal is being accessed:
> +
> +            >>> class C(object):
> +            ...     @signal
> +            ...     def on_meth(self):
> +            ...         pass
> +
> +        As a descriptor on a class:
> +
> +            >>> C.on_meth.name  # doctest: +ELLIPSIS
> +            '...on_meth'
> +
> +        As a descriptor on an object:
> +
> +            >>> C().on_meth.name  # doctest: +ELLIPSIS
> +            '...on_meth'
> +
> +        As a decorated function:
> +
> +            >>> @signal
> +            ... def on_func():
> +            ...     pass
> +            >>> on_func.name
> +            'on_func'
> +        """
> +        return self._name
> +
> +    # For backwards compatibility with Plainbox-based code
> +    signal_name = name
> +
> +    @property
> +    def listeners(self):
> +        """
> +        List of :class:`listenerinfo` objects associated with this signal
> +
> +        The list of listeners is considered part of an implementation detail
> +        but is exposed for convenience. This is always the real list. Keep
> +        this in mind while connecting and disconnecting listeners. During
> +        the time :meth:`fire()` is called the list of listeners can be changed
> +        but won't take effect until after ``fire()`` returns.
> +        """
> +        return self._listeners
> +
> +    @property
> +    def first_responder(self):
> +        """
> +        The first responder function.
> +
> +        This is the function that the ``signal`` may have been instantiated
> +        with. It is only relevant if the signal itself is used as a
> +        *descriptor* in a class (where it decorates a method).
> +
> +        For example, contrast the access of the signal on the class and on a
> +        class instance:
> +
> +            >>> class C(object):
> +            ...     @signal
> +            ...     def on_foo(self):
> +            ...         pass
> +
> +        Class access gives uses the descriptor protocol to expose the
> +        actual signal object.
> +
> +            >>> C.on_foo  # doctest: +ELLIPSIS
> +            <signal name:'...on_foo'>
> +
> +        Here we can use the ``first_responder`` property to see the actual
> +        function.
> +
> +            >>> C.on_foo.first_responder  # doctest: +ELLIPSIS
> +            <function ...on_foo at ...>
> +
> +        Object access is different as now the signal instance is specific to
> +        the object:
> +
> +            >>> C().on_foo  # doctest: +ELLIPSIS
> +            <signal name:'...on_foo' (specific to <plainbox.vendor.morris.C object at ...)>
> +
> +        And now the first responder is gone (it is now buried inside the
> +        :meth:`listeners` list):
> +
> +            >>> C().on_foo.first_responder
> +        """
> +        return self._first_responder
> +
> +    def connect(self, listener, pass_signal=False):
> +        """
> +        Connect a new listener to this signal
> +
> +        :param listener:
> +            The listener (callable) to add
> +        :param pass_signal:
> +            An optional argument that controls if the signal object is
> +            explicitly passed to this listener when it is being fired.
> +            If enabled, a ``signal=`` keyword argument is passed to the
> +            listener function.
> +        :returns:
> +            None
> +
> +        The listener will be called whenever :meth:`fire()` or
> +        :meth:`__call__()` are called.  The listener is appended to the list of
> +        listeners. Duplicates are not checked and if a listener is added twice
> +        it gets called twice.
> +        """
> +        info = listenerinfo(listener, pass_signal)
> +        self._listeners.append(info)
> +        _logger.debug("connect %r to %r", str(listener), self._name)
> +        # Track listeners in the instances only
> +        if inspect.ismethod(listener):
> +            listener_object = listener.__self__
> +            # Ensure that the instance has __listeners__ property
> +            if not hasattr(listener_object, "__listeners__"):
> +                listener_object.__listeners__ = collections.defaultdict(list)
> +            # Append the signals a listener is connected to
> +            listener_object.__listeners__[listener].append(self)
> +
> +    def disconnect(self, listener, pass_signal=False):
> +        """
> +        Disconnect an existing listener from this signal
> +
> +        :param listener:
> +            The listener (callable) to remove
> +        :param pass_signal:
> +            An optional argument that controls if the signal object is
> +            explicitly passed to this listener when it is being fired.
> +            If enabled, a ``signal=`` keyword argument is passed to the
> +            listener function.
> +
> +            Here, this argument simply aids in disconnecting the right
> +            listener. Make sure to pass the same value as was passed to
> +            :meth:`connect()`
> +        :raises ValueError:
> +            If the listener (with the same value of pass_signal) is not present
> +        :returns:
> +            None
> +        """
> +        info = listenerinfo(listener, pass_signal)
> +        self._listeners.remove(info)
> +        _logger.debug(
> +            "disconnect %r from %r", str(listener), self._name)
> +        if inspect.ismethod(listener):
> +            listener_object = listener.__self__
> +            if hasattr(listener_object, "__listeners__"):
> +                listener_object.__listeners__[listener].remove(self)
> +                # Remove the listener from the list if any signals connected
> +                if (len(listener_object.__listeners__[listener])) == 0:
> +                    del listener_object.__listeners__[listener]
> +
> +    def fire(self, args, kwargs):
> +        """
> +        Fire this signal with the specified arguments and keyword arguments.
> +
> +        Typically this is used by using :meth:`__call__()` on this object which
> +        is more natural as it does all the argument packing/unpacking
> +        transparently.
> +        """
> +        for info in self._listeners[:]:
> +            if info.pass_signal:
> +                info.listener(*args, signal=self, **kwargs)
> +            else:
> +                info.listener(*args, **kwargs)
> +
> +    def __call__(self, *args, **kwargs):
> +        """
> +        Call fire() with all arguments forwarded transparently
> +
> +        This is provided for convenience so that a signal can be fired just
> +        by a simple method or function call and so that signals can be passed
> +        to other APIs that don't understand the :meth:`fire()` method.
> +        """
> +        self.fire(args, kwargs)
> +
> +# In the past this used to be a helper method for defining signals.
> +# Now the same functionality is available through the signal class.
> +signal.define = signal
> +
> +
> +# In the past this used to be the actual signal class that knows about
> +# listeners. Now that is all merged into the one ``signal`` class.
> +Signal = signal
> +
> +
> +# In the past this used to be the signal descriptor class that knows about
> +# the first responder and knows how to create :class:`Signal` objects. Now
> +# that is all merged into the one ``signal`` class.
> +signaldescriptor = signal
> +
> +
> +def _get_fn_name(fn):
> +    if hasattr(fn, '__qualname__'):
> +        return fn.__qualname__
> +    else:
> +        return fn.__name__
> +
> +
> +class boundmethod(object):
> +    """
> +    A helper class that allows us to emulate a bound method
> +
> +    This class emulates a bond method by storing an object ``instance``,
> +    function ``func`` and calling ``instance``.``func``() whenever the
> +    boundmethod object itself is called.
> +    """
> +
> +    def __init__(self, instance, func):
> +        self.instance = instance
> +        self.func = func
> +        if hasattr(func, '__qualname__'):
> +            self.__qualname__ = self.func.__qualname__
> +        self.__name__ = self.func.__name__
> +
> +    def __call__(self, *args, **kwargs):
> +        return self.func(self.instance, *args, **kwargs)
> +
> +
> +class SignalInterceptorMixIn:
> +    """
> +    A mix-in class for TestCase-like classes that adds extra methods for
> +    working with and testing signals. This class may be of use if the base
> +    TestCase class is not the standard ``unittest.TestCase`` class but the user
> +    still wants to take advantage of the extra methods provided here.
> +    """
> +
> +    def _extend_state(self):
> +        if not hasattr(self, '_events_seen'):
> +            self._events_seen = []
> +
> +    def watchSignal(self, signal):
> +        """
> +        Setup provisions to watch a specified signal
> +
> +        :param signal:
> +            The :class:`Signal` to watch for.
> +
> +        After calling this method you can use :meth:`assertSignalFired()`
> +        and :meth:`assertSignalNotFired()` with the same signal.
> +        """
> +        self._extend_state()
> +
> +        def signal_handler(*args, **kwargs):
> +            self._events_seen.append((signal, args, kwargs))
> +        signal.connect(signal_handler)
> +        if hasattr(self, 'addCleanup'):
> +            self.addCleanup(signal.disconnect, signal_handler)
> +
> +    def assertSignalFired(self, signal, *args, **kwargs):
> +        """
> +        Assert that a signal was fired with appropriate arguments.
> +
> +        :param signal:
> +            The :class:`Signal` that should have been fired.
> +            Typically this is ``SomeClass.on_some_signal`` reference
> +        :param args:
> +            List of positional arguments passed to the signal handler
> +        :param kwargs:
> +            List of keyword arguments passed to the signal handler
> +        :returns:
> +            A 3-tuple (signal, args, kwargs) that describes that event
> +        """
> +        event = (signal, args, kwargs)
> +        self.assertIn(
> +            event, self._events_seen,
> +            "\nSignal unexpectedly not fired: {}\n".format(event))
> +        return event
> +
> +    def assertSignalNotFired(self, signal, *args, **kwargs):
> +        """
> +        Assert that a signal was fired with appropriate arguments.
> +
> +        :param signal:
> +            The :class:`Signal` that should not have been fired.
> +            Typically this is ``SomeClass.on_some_signal`` reference
> +        :param args:
> +            List of positional arguments passed to the signal handler
> +        :param kwargs:
> +            List of keyword arguments passed to the signal handler
> +        """
> +        event = (signal, args, kwargs)
> +        self.assertNotIn(
> +            event, self._events_seen,
> +            "\nSignal unexpectedly fired: {}\n".format(event))
> +
> +    def assertSignalOrdering(self, *expected_events):
> +        """
> +        Assert that a signals were fired in a specific sequence.
> +
> +        :param expected_events:
> +            A (varadic) list of events describing the signals that were fired
> +            Each element is a 3-tuple (signal, args, kwargs) that describes
> +            the event.
> +
> +        .. note::
> +            If you are using :meth:`assertSignalFired()` then the return value
> +            of that method is a single event that can be passed to this method
> +        """
> +        expected_order = [self._events_seen.index(event)
> +                          for event in expected_events]
> +        actual_order = sorted(expected_order)
> +        self.assertEqual(
> +            expected_order, actual_order,
> +            "\nExpected order of fired signals:\n{}\n"
> +            "Actual order observed:\n{}".format(
> +                "\n".join(
> +                    "\t{}: {}".format(i, event)
> +                    for i, event in enumerate(expected_events, 1)),
> +                "\n".join(
> +                    "\t{}: {}".format(i, event)
> +                    for i, event in enumerate(
> +                        (self._events_seen[idx] for idx in actual_order), 1))))
> +
> +
> +class SignalTestCase(unittest.TestCase, SignalInterceptorMixIn):
> +    """
> +    A :class:`unittest.TestCase` subclass that simplifies testing uses of
> +    the Morris signals. It provides three assertion methods and one utility
> +    helper method for observing signal events.
> +    """
> +
> +
> +def remove_signals_listeners(instance):
> +    """
> +    utility function that disconnects all listeners from all signals on an
> +    object
> +    """
> +    if hasattr(instance, "__listeners__"):
> +        for listener in list(instance.__listeners__):
> +            for signal in instance.__listeners__[listener]:
> +                signal.disconnect(listener)
>
> === added file 'plainbox/plainbox/vendor/morris/test_morris.py'
> --- plainbox/plainbox/vendor/morris/test_morris.py      1970-01-01 00:00:00 +0000
> +++ plainbox/plainbox/vendor/morris/test_morris.py      2015-02-06 17:15:13 +0000
> @@ -0,0 +1,369 @@
> +# Copyright 2012-2015 Canonical Ltd.
> +# Written by:
> +#   Zygmunt Krynicki <zygmunt.krynicki@xxxxxxxxxxxxx>
> +#
> +# This file is part of Morris.
> +#
> +# Morris is free software: you can redistribute it and/or modify
> +# it under the terms of the GNU Lesser General Public License as published by
> +# the Free Software Foundation, either version 3 of the License
> +#
> +# Morris is distributed in the hope that it will be useful,
> +# but WITHOUT ANY WARRANTY; without even the implied warranty of
> +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> +# GNU Lesser General Public License for more details.
> +#
> +# You should have received a copy of the GNU Lesser General Public License
> +# along with Morris.  If not, see <http://www.gnu.org/licenses/>.
> +"""
> +morris.tests
> +============
> +Test definitions for Morris
> +"""
> +from __future__ import print_function, absolute_import, unicode_literals
> +
> +from unittest import TestCase
> +from doctest import DocTestSuite
> +
> +from plainbox.vendor.morris import Signal
> +from plainbox.vendor.morris import SignalTestCase
> +from plainbox.vendor.morris import boundmethod
> +from plainbox.vendor.morris import remove_signals_listeners
> +from plainbox.vendor.morris import signal
> +from plainbox.vendor.morris import signaldescriptor
> +
> +
> +def load_tests(loader, tests, ignore):
> +    from plainbox.vendor import morris
> +    tests.addTests(DocTestSuite(morris))
> +    return tests
> +
> +
> +class FakeSignalTestCase(SignalTestCase):
> +    """
> +    A subclass of :class:`morris.SignalTestCase` that defines :meth:`runTest()`
> +    """
> +
> +    def runTest(self):
> +        """
> +        An empty test method
> +        """
> +
> +
> +class SignalTestCaseTest(TestCase):
> +    """
> +    Test definitions for the :class:`morris.SignalTestCase` class.
> +    """
> +
> +    def setUp(self):
> +        self.signal = Signal('signal')
> +        self.case = FakeSignalTestCase()
> +
> +    def test_watchSignal(self):
> +        """
> +        Ensure that calling watchSignal() actually connects a signal listener
> +        """
> +        self.assertEqual(len(self.signal.listeners), 0)
> +        self.case.watchSignal(self.signal)
> +        self.assertEqual(len(self.signal.listeners), 1)
> +
> +    def test_assertSignalFired(self):
> +        """
> +        Ensure that assertSignalFired works correctly
> +        """
> +        self.case.watchSignal(self.signal)
> +        self.signal.fire((), {})
> +        sig = self.case.assertSignalFired(self.signal)
> +        self.assertEqual(sig,  (self.signal, (), {}))
> +
> +    def test_assertSignalNotFired(self):
> +        """
> +        Ensure that assertSignalNotFired works correctly
> +        """
> +        self.case.watchSignal(self.signal)
> +        self.case.assertSignalNotFired(self.signal)
> +
> +    def test_assertSignalOrdering(self):
> +        """
> +        Ensure that assertSignalOrdering works correctly
> +        """
> +        self.case.watchSignal(self.signal)
> +        self.signal('first')
> +        self.signal('second')
> +        self.signal('third')
> +        first = self.case.assertSignalFired(self.signal, 'first')
> +        second = self.case.assertSignalFired(self.signal, 'second')
> +        third = self.case.assertSignalFired(self.signal, 'third')
> +        self.case.assertSignalOrdering(first, second, third)
> +
> +
> +class C1(object):
> +    """
> +    Helper class with two signals defined using :meth:`Signal.define`
> +    """
> +
> +    def on_foo(self, *args, **kwargs):
> +        """
> +        A signal accepting (ignoring) arbitrary arguments
> +        """
> +
> +    on_foo_func = on_foo
> +    on_foo = Signal.define(on_foo)
> +
> +    @Signal.define
> +    def on_bar(self):
> +        """
> +        A signal accepting no arguments
> +        """
> +
> +
> +class C2(object):
> +    """
> +    Helper class with two signals defined using :class:`morris.signal`
> +    """
> +
> +    def on_foo(self, *args, **kwargs):
> +        """
> +        A signal accepting (ignoring) arbitrary arguments
> +        """
> +
> +    on_foo_func = on_foo
> +    on_foo = signal(on_foo)
> +
> +    @signal
> +    def on_bar(self):
> +        """
> +        A signal accepting no arguments
> +        """
> +
> +
> +class NS(object):
> +    """
> +    Helper namespace-like class
> +    """
> +
> +
> +def get_foo_bar():
> +    """
> +    Helper function that returns two functions, on_foo() and on_bar(), similar
> +    to what :class:`C1` and :class:`C2` define internally.
> +    """
> +    def on_foo(*args, **kwargs):
> +        """
> +        A signal accepting (ignoring) arbitrary arguments
> +        """
> +    def on_bar():
> +        """
> +        A signal accepting no arguments
> +        """
> +    return on_foo, on_bar
> +
> +
> +def M1():
> +    """
> +    Helper function that returns a module-like thing with two signals defined
> +    using :meth:`Signal.define`
> +    """
> +    on_foo, on_bar = get_foo_bar()
> +    ns = NS()
> +    ns.on_foo_func = on_foo
> +    ns.on_foo = Signal.define(on_foo)
> +    ns.on_bar = Signal.define(on_bar)
> +    return ns
> +
> +
> +def M2():
> +    """
> +    Helper function that returns a module-like thing with two signals defined
> +    using :class:`signal`
> +    """
> +    on_foo, on_bar = get_foo_bar()
> +    ns = NS()
> +    ns.on_foo_func = on_foo
> +    ns.on_foo = signal(on_foo)
> +    ns.on_bar = signal(on_bar)
> +    return ns
> +
> +
> +class R(object):
> +    """
> +    Helper class that collaborates with either :class:`C1` or :class:`C2`
> +    """
> +
> +    def __init__(self, c):
> +        c.on_foo.connect(self._foo)
> +        c.on_bar.connect(self._bar)
> +        c.on_bar.connect(self._baz)
> +
> +    def _foo(self):
> +        pass
> +
> +    def _bar(self):
> +        pass
> +
> +    def _baz(self):
> +        pass
> +
> +
> +class SignalTestsBase(object):
> +    """
> +    Set of base test definitions for :class:`morris.Signal` class.
> +    """
> +
> +    def setUp(self):
> +        self.c = self.get_c()
> +
> +    def test_sanity(self):
> +        """
> +        Ensure that :meth:`get_c()` is not faulty
> +        """
> +        self.assertIsInstance(self.c.on_foo, Signal)
> +        self.assertNotIsInstance(self.c.on_foo_func, Signal)
> +        self.assertNotIsInstance(self.c.on_foo_func, signaldescriptor)
> +        self.assertEqual(len(self.c.on_foo.listeners), 1)
> +        self.assertIsInstance(self.c.on_bar, Signal)
> +        self.assertEqual(len(self.c.on_bar.listeners), 1)
> +
> +    def get_c(self):
> +        raise NotImplementedError
> +
> +    def test_connect(self):
> +        """
> +        Ensure that connecting signals works
> +        """
> +        def handler():
> +            pass
> +        self.c.on_foo.connect(handler)
> +        self.assertIn(
> +            handler, (info.listener for info in self.c.on_foo.listeners))
> +
> +    def test_disconnect(self):
> +        """
> +        Ensure that disconnecting signals works
> +        """
> +        def handler():
> +            pass
> +        self.c.on_foo.connect(handler)
> +        self.c.on_foo.disconnect(handler)
> +        self.assertNotIn(
> +            handler, (info.listener for info in self.c.on_foo.listeners))
> +
> +    def test_calling_signal_fires_them(self):
> +        """
> +        Ensure that calling signals fires them
> +        """
> +        self.watchSignal(self.c.on_foo)
> +        self.c.on_foo()
> +        self.assertSignalFired(self.c.on_foo)
> +
> +    def test_calling_signals_passes_positional_arguments(self):
> +        """
> +        Ensure that calling the signal object with positional arguments works
> +        """
> +        self.watchSignal(self.c.on_foo)
> +        self.c.on_foo(1, 2, 3)
> +        self.assertSignalFired(self.c.on_foo, 1, 2, 3)
> +
> +    def test_calling_signals_passes_keyword_arguments(self):
> +        """
> +        Ensure that calling the signal object with keyword arguments works
> +        """
> +        self.watchSignal(self.c.on_foo)
> +        self.c.on_foo(one=1, two=2, three=3)
> +        self.assertSignalFired(self.c.on_foo, one=1, two=2, three=3)
> +
> +    def test_remove_signals_listeners(self):
> +        """
> +        Ensure that calling :func:`remove_signal_listeners()` works
> +        """
> +        a = R(self.c)
> +        b = R(self.c)
> +        self.assertEqual(len(a.__listeners__), 3)
> +        self.assertEqual(len(b.__listeners__), 3)
> +        remove_signals_listeners(a)
> +        self.assertEqual(len(a.__listeners__), 0)
> +        self.assertEqual(len(b.__listeners__), 3)
> +
> +
> +class SignalsOnMethods(object):
> +    """
> +    Mix-in for C1 and C2-based tests
> +    """
> +
> +    def test_first_responder(self):
> +        """
> +        Ensure that using the decorator syntax connects the decorated object
> +        as the first responder
> +        """
> +        self.assertEqual(len(self.c.on_foo.listeners), 1)
> +        # NOTE: this is a bit hairy. The ``signal`` decorator is always called
> +        # on the bare function object (so on the ``on_foo`` function, before
> +        # it becomes a method.
> +        #
> +        # To test that we need to extract the bare function (using the __func__
> +        # property) from the (real) boundmethod that we see as
> +        # self.c.on_foo_func.
> +        #
> +        # Then on top of that, the first responder is treated specially
> +        # by ``signal.__get__()`` so that it creates a fake boundmethod
> +        # (implemented in morris, not by python built-in) that stores the
> +        # signal and the instance manually.
> +        first_info = self.c.on_foo.listeners[0]
> +        first_listener = first_info.listener
> +        self.assertIsInstance(first_listener, boundmethod)
> +        self.assertEqual(first_listener.instance, self.c)
> +        self.assertEqual(first_listener.func, self.c.on_foo_func.__func__)
> +        self.assertEqual(first_info.pass_signal, False)
> +
> +
> +class SignalsOnFunctions(object):
> +    """
> +    Mix-in for M1 and M2-based tests
> +    """
> +
> +    def test_first_responder(self):
> +        """
> +        Ensure that using the decorator syntax connects the decorated object as
> +        the first responder
> +        """
> +        self.assertEqual(len(self.c.on_foo.listeners), 1)
> +        first_info = self.c.on_foo.listeners[0]
> +        first_listener = first_info.listener
> +        self.assertEqual(first_listener, self.c.on_foo_func)
> +        self.assertEqual(first_info.pass_signal, False)
> +
> +
> +class SignalTestsC1(SignalTestsBase, SignalsOnMethods, SignalTestCase):
> +    """
> +    Test definitions for :class:`morris.Signal` class that use :class:`C1`
> +    """
> +
> +    def get_c(self):
> +        return C1()
> +
> +
> +class SignalTestsC2(SignalTestsBase, SignalsOnMethods, SignalTestCase):
> +    """
> +    Test definitions for :class:`morris.Signal` class that use :class:`C2`
> +    """
> +
> +    def get_c(self):
> +        return C2()
> +
> +
> +class SignalTestsM1(SignalTestsBase, SignalsOnFunctions, SignalTestCase):
> +    """
> +    Test definitions for :class:`morris.Signal` class that use :func:`M1`
> +    """
> +
> +    def get_c(self):
> +        return M1()
> +
> +
> +class SignalTestsM2(SignalTestsBase, SignalsOnFunctions, SignalTestCase):
> +    """
> +    Test definitions for :class:`morris.Signal` class that use :func:`M2`
> +    """
> +
> +    def get_c(self):
> +        return M2()
>
>
> ...
>
> [Message clipped]