[Pytest-commit] Issue #682: Check if several functions are called (hpk42/pytest)

Unknown Name issues-reply at bitbucket.org
Sat Feb 14 16:59:51 CET 2015


New issue 682: Check if several functions are called
https://bitbucket.org/hpk42/pytest/issue/682/check-if-several-functions-are-called

Unknown Name:

I wanted to check if several functions were called during the test and I implemented the class bellow. I don't know if you're interested in it. Unfortunately, the code with the tests using this class turned out to be useless. So I don't even know if it is useful.

```python
class StateTesting:
    """A class to test if some functions are called."""
    
    def __init__(self, final_states):
        """
        :param final_states: A list of final states.
        
        :type final_states: list
        """
        
        self.len = len(final_states)
        
        self.final_states = final_states
        self.states = [False] * self.len
        
    
    @staticmethod
    def test(final_states):
        """Create a decorator to test the function.
        
        :param final_states: A list of final states.
        
        :type final_states: list
        
        :return: A decorator.
        :rtype: func
        """
        
        def decorator(func):
            def wrapper(*args, **kwargs):
                obj = StateTesting(final_states)
                
                func(obj, *args, **kwargs)
            
                # Test if the functions have been called
                for i in range(obj.len):
                    assert obj.states[i] == obj.final_states[i]
            
            return wrapper
            
        return decorator
        
    def decorate(self, callback, index):
        """Return a function setting `self.states[index]` to `True` and calling 
        `callback`.
        
        :param callback: A callback to be called.
        :param index: The index to be toggled.
        
        :type callback: callable
        :type index: int
        
        :rtype: func
        """
        
        def func(*args, **kwargs):
            self.states[index] = True
            
            callback(*args, **kwargs)
        
        return func  
```

To be used like that:

```python
def callback1(data):
    pass
    
def callback2(data):
    pass
    
def callback3(data):
    pass


@StateTesting.test([True, False, True])
def test_sth(state_obj):
    process(arg1, arg2, callback=state_obj.decorate(callback1, 0))
    process_not_to_be_supposed_to_call_its_callback(arg3, callback=state_obj.decorate(callback2, 1))
    other_process(arg, callback=state_obj.decorate(callback1, 2))
```

Thanks.




More information about the pytest-commit mailing list