3
dE                 @   s   d Z ddlZddlZddlZddlZddlZddlmZmZm	Z	m
Z
mZmZmZ ddlmZ G dd deZejdd ZG d	d
 d
e	ZG dd deZdS )zN Trait assert mixin class to simplify test implementation for Trait
Classes.

    N)AnyEventHasStrictTraitsIntListStrProperty)wait_for_conditionc               @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )_AssertTraitChangesContexta   A context manager used to implement the trait change assert methods.

    Notes
    -----
    Checking if the provided xname corresponds to valid traits in the class
    is not implemented yet.

    Parameters
    ----------
    obj : HasTraits
        The HasTraits class instance whose class trait will change.

    xname : str
        The extended trait name of trait changes to listen to.

    count : int, optional
        The expected number of times the event should be fired. When None
        (default value) there is no check for the number of times the
        change event was fired.

    test_case : TestCase
        A unittest TestCase where to raise the failureException if
        necessary.

    Attributes
    ----------
    obj : HasTraits
        The HasTraits class instance whose class trait will change.

    xname : str
        The extended trait name of trait changes to listen to.

    count : int, optional
        The expected number of times the event should be fired. When None
        (default value) there is no check for the number of times the
        change event was fired.

    events : list of tuples
        A list with tuple elements containing the arguments of an
        `on_trait_change` event signature (<object>, <name>, <old>, <new>).

    Raises
    ------
    AssertionError :
          When the desired number of trait changed did not take place or when
          `count = None` and no trait change took place.

    c             C   s*   || _ || _|| _d | _g | _|j| _d S )N)objxnamecounteventeventsfailureException)selfr   r   r   Z	test_case r   ?/tmp/pip-build-7vycvbft/traits/traits/testing/unittest_tools.py__init__X   s    z#_AssertTraitChangesContext.__init__c             C   s    ||||f| _ | jj| j  dS )z Dummy trait listener.
        N)r   r   append)r   r   nameoldnewr   r   r   	_listener`   s    z$_AssertTraitChangesContext._listenerc             C   s   | j j| j| j | S )z" Bind the trait listener.
        )r   on_trait_changer   r   )r   r   r   r   	__enter__f   s    z$_AssertTraitChangesContext.__enter__c             C   s   |dk	rdS | j j| j| jdd | jdk	rft| j| jkrfd}| jt| j| jf}| j|j| n(| jdkr| j rdj| j}| j|dS )z$ Remove the trait listener.
        NFT)removez7Change event for {0} was fired {1} times instead of {2}z%A change event was not fired for: {0})	r   r   r   r   r   lenr   r   format)r   exc_type	exc_valuetbmsgitemsr   r   r   __exit__l   s    
z#_AssertTraitChangesContext.__exit__N)__name__
__module____qualname____doc__r   r   r   r$   r   r   r   r   r
   &   s
   0r
   c             c   sL   | j   z
| V  W d y| jd d d  W n tk
r:   Y nX | j|X d S )N)r   r$   AssertionErrorr   )contextr"   r   r   r   reverse_assertion}   s    
r+   c                   sb   e Zd ZdZeZeZee	Z
eZeeZe Z fddZdd Zdd Zdd	 Zd
d Z  ZS )_TraitsChangeCollectorz5 Class allowing thread-safe recording of events.
    c                sP   d|kr.|j d}d}tj|tdd ||d< t jf | tj | _g | _	d S )Ntraitz:The `trait` keyword is deprecated. please use `trait_name`   )
stacklevel
trait_name)
popwarningswarnDeprecationWarningsuperr   	threadingLock_lockr   )r   Ztraitsvaluemessage)	__class__r   r   r      s    

z_TraitsChangeCollector.__init__c             C   s   | j j| j| j d S )N)r   r   _event_handlerr0   )r   r   r   r   start_collecting   s    z'_TraitsChangeCollector.start_collectingc             C   s   | j j| j| jdd d S )NT)r   )r   r   r<   r0   )r   r   r   r   stop_collecting   s    z&_TraitsChangeCollector.stop_collectingc          	   C   s(   | j  | jj| W d Q R X d| _d S )NT)r8   r   r   event_count_updated)r   r   r   r   r   r<      s    z%_TraitsChangeCollector._event_handlerc          	   C   s   | j  t| jS Q R X dS )zN Traits property getter.

        Thread-safe access to event count.

        N)r8   r   r   )r   r   r   r   _get_event_count   s    z'_TraitsChangeCollector._get_event_count)r%   r&   r'   r(   r   r   r   r0   r   r   event_countr   r?   r   r   r8   r   r=   r>   r<   r@   __classcell__r   r   )r;   r   r,      s   r,   c               @   sv   e Zd ZdZdddZdddZejdd ZejdddZ	dddZ
ejdd Zejdd Zejdd ZdS )UnittestToolszg Mixin class to augment the unittest.TestCase class with useful trait
    related assert methods.

    Nc          
   O   s8   t |||| }|dkr|S | ||| W dQ R X dS )a
   Assert an object trait changes a given number of times.

        Assert that the class trait changes exactly `count` times during
        execution of the provided function.

        This method can also be used in a with statement to assert that
        a class trait has changed during the execution of the code inside
        the with statement (similar to the assertRaises method). Please note
        that in that case the context manager returns itself and the user
        can introspect the information of:

        - The last event fired by accessing the ``event`` attribute of the
          returned object.

        - All the fired events by accessing the ``events`` attribute of
          the return object.

        Note that in the case of chained properties (trait 'foo' depends on
        'bar', which in turn depends on 'baz'), the order in which the
        corresponding trait events appear in the ``events`` attribute is
        not well-defined, and may depend on dictionary ordering.

        **Example**::

            class MyClass(HasTraits):
                number = Float(2.0)

            my_class = MyClass()

            with self.assertTraitChanges(my_class, 'number', count=1):
                my_class.number = 3.0

        Parameters
        ----------
        obj : HasTraits
            The HasTraits class instance whose class trait will change.

        trait : str
            The extended trait name of trait changes to listen to.

        count : int or None, optional
            The expected number of times the event should be fired. When None
            (default value) there is no check for the number of times the
            change event was fired.

        callableObj : callable, optional
            A callable object that will trigger the expected trait change.
            When None (default value) a trigger is expected to be called
            under the context manger returned by this method.

        *args :
            List of positional arguments for ``callableObj``

        **kwargs :
            Dict of keyword value pairs to be passed to the ``callableObj``


        Returns
        -------
        context : context manager or None
            If ``callableObj`` is None, an assertion context manager is
            returned, inside of which a trait-change trigger can be invoked.
            Otherwise, the context is used internally with ``callableObj`` as
            the trigger, in which case None is returned.

        Notes
        -----
        - Checking if the provided ``trait`` corresponds to valid traits in
          the class is not implemented yet.
        - Using the functional version of the assert method requires the
          ``count`` argument to be given even if it is None.

        N)r
   )r   r   r-   r   callableObjargskwargsr*   r   r   r   assertTraitChanges   s
    Lz UnittestTools.assertTraitChangesc          
   O   sN   dj |}t||d| }|dkr*t||S t|| ||| W dQ R X dS )a   Assert an object trait does not change.

        Assert that the class trait does not change during
        execution of the provided function.

        Parameters
        ----------
        obj : HasTraits
            The HasTraits class instance whose class trait will change.

        trait : str
            The extended trait name of trait changes to listen to.

        callableObj : callable, optional
            A callable object that should not trigger a change in the
            passed trait.  When None (default value) a trigger is expected
            to be called under the context manger returned by this method.

        *args :
            List of positional arguments for ``callableObj``

        **kwargs :
            Dict of keyword value pairs to be passed to the ``callableObj``


        Returns
        -------
        context : context manager or None
            If ``callableObj`` is None, an assertion context manager is
            returned, inside of which a trait-change trigger can be invoked.
            Otherwise, the context is used internally with ``callableObj`` as
            the trigger, in which case None is returned.

        z!A change event was fired for: {0}N)r   r
   r+   )r   r   r-   rD   rE   rF   r"   r*   r   r   r   assertTraitDoesNotChange!  s    %

z&UnittestTools.assertTraitDoesNotChangec             c   s   t j n}g }xX|D ]P}x$|D ]}|j|j| j|| qW x$|D ]}|j|j| j|| qDW qW t|V  W dQ R X dS )a!   Assert that traits on multiple objects do or do not change.

        This combines some of the functionality of `assertTraitChanges` and
        `assertTraitDoesNotChange`.

        Parameters
        ----------
        objects : list of HasTraits
            The HasTraits class instances whose traits will change.

        traits_modified : list of str
            The extended trait names of trait expected to change.

        traits_not_modified : list of str
            The extended trait names of traits not expected to change.

        N)
contextlib	ExitStackr   enter_contextrG   rH   tuple)r   objectsZtraits_modifiedZtraits_not_modifiedZ
exit_stackZcmsr   r-   r   r   r   assertMultiTraitChangesM  s    



z%UnittestTools.assertMultiTraitChanges         @c             #   s   t ||d}|j  z^|V  yt fdd|d|d W n6 tk
rn   |j}dj|| ||}| j| Y nX W d|j  X dS )a3   Assert an object trait eventually changes.

        Context manager used to assert that the given trait changes at
        least `count` times within the given timeout, as a result of
        execution of the body of the corresponding with block.

        The trait changes are permitted to occur asynchronously.

        **Example usage**::

            with self.assertTraitChangesAsync(my_object, 'SomeEvent', count=4):
                <do stuff that should cause my_object.SomeEvent to be
                fired at least 4 times within the next 5 seconds>


        Parameters
        ----------
        obj : HasTraits
            The HasTraits class instance whose class trait will change.

        trait : str
            The extended trait name of trait changes to listen to.

        count : int, optional
            The expected number of times the event should be fired.

        timeout : float or None, optional
            The amount of time in seconds to wait for the specified number
            of changes. None can be used to indicate no timeout.

        )r   r0   c                s
   | j  kS )N)rA   )r   )r   r   r   <lambda>  s    z7UnittestTools.assertTraitChangesAsync.<locals>.<lambda>r?   )	conditionr   r-   timeoutz~Expected {0} event on {1} to be fired at least {2} times, but the event was only fired {3} times before timeout ({4} seconds).N)r,   r=   r	   RuntimeErrorrA   r   failr>   )r   r   r-   r   rS   Z	collectorZactual_event_countr"   r   )r   r   assertTraitChangesAsyncm  s     !
z%UnittestTools.assertTraitChangesAsyncc             C   sF   yt ||||d W n, tk
r@   ||}| jdj| Y nX dS )a   Assert that the given condition is eventually true.

        Parameters
        ----------
        obj : HasTraits
            The HasTraits class instance whose traits will change.

        trait : str
            The extended trait name of trait changes to listen to.

        condition : callable
            A function that will be called when the specified trait
            changes.  This should accept ``obj`` and should return a
            Boolean indicating whether the condition is satisfied or not.

        timeout : float or None, optional
            The amount of time in seconds to wait for the condition to
            become true.  None can be used to indicate no timeout.

        )rR   r   r-   rS   z?Timed out waiting for condition. At timeout, condition was {0}.N)r	   rT   rU   r   )r   r   r-   rR   rS   Zcondition_at_timeoutr   r   r   assertEventuallyTrue  s    z"UnittestTools.assertEventuallyTruec          
   c   sX   t jdt tjdjjd}|r*|j  t jdd}t j	dt |V  W dQ R X dS )a   
        Replacement for warnings.catch_warnings.

        This method wraps warnings.catch_warnings, takes care to
        reset the warning registry before entering the with context,
        and ensures that DeprecationWarnings are always emitted.

        The hack to reset the warning registry is no longer needed in
        Python 3.4 and later. See http://bugs.python.org/issue4180 for
        more background.

        .. deprecated:: 6.2
            Use :func:`warnings.catch_warnings` instead.

        zNThe _catch_warnings method is deprecated. Use warnings.catch_warnings instead.   __warningregistry__T)recordalwaysN)
r2   r3   r4   sys	_getframe	f_globalsgetclearcatch_warningssimplefilter)r   registrywr   r   r   _catch_warnings  s    	zUnittestTools._catch_warningsc             c   sB   t jdd}t jdt |V  W dQ R X | jt|ddd dS )z
        Assert that the code inside the with block is deprecated.  Intended
        for testing uses of traits.util.deprecated.deprecated.

        T)rZ   r[   Nr   z2Expected a DeprecationWarning, but none was issued)r"   )r2   ra   rb   r4   ZassertGreaterr   )r   rd   r   r   r   assertDeprecated  s    zUnittestTools.assertDeprecatedc             c   sB   t jdd}t jdt |V  W dQ R X | jt|ddd dS )z
        Assert that the code inside the with block is not deprecated.  Intended
        for testing uses of traits.util.deprecated.deprecated.

        T)rZ   r[   Nr   z;Expected no DeprecationWarning, but at least one was issued)r"   )r2   ra   rb   r4   ZassertEqualr   )r   rd   r   r   r   assertNotDeprecated  s    z!UnittestTools.assertNotDeprecated)NN)N)rO   rP   )rP   )r%   r&   r'   r(   rG   rH   rI   contextmanagerrN   rV   rW   re   rf   rg   r   r   r   r   rC      s   
R
+ ;
#'rC   )r(   rI   r6   r\   r2   ZunittestZ
traits.apir   r   r   r   r   r   r   Ztraits.util.async_trait_waitr	   objectr
   rh   r+   r,   rC   r   r   r   r   <module>   s   $	W>