예제 #1
0
def test_as_decorator():
    '''Test `TempWorkingDirectorySetter` used as a decorator.'''
    with temp_file_tools.TemporaryFolder(prefix='temp_test_garlicsim_') \
                                                          as temp_folder:
        old_cwd = os.getcwd()
        @TempWorkingDirectorySetter(temp_folder)
        def f():
            # Note that on Mac OS, the working dir will be phrased differently,
            # so we can't do `assert os.getcwd() == temp_folder`. Instead we'll
            # create a small file and check we can access it:
            
            with open('just_a_file', 'w') as my_file:
                my_file.write('One two three.')
            
            with open('just_a_file', 'r') as my_file:
                assert my_file.read() == 'One two three.'
                
        f()
        
        cute_testing.assert_polite_wrapper(f)
        
        with open(os.path.join(temp_folder, 'just_a_file'), 'r') as my_file:
            assert my_file.read() == 'One two three.'
        
        assert os.getcwd() == old_cwd
        
def test_cached_history_function():
    
    def changes(history_browser):
        '''
        Return how many cells changed between most recent state and its parent.
        '''
        changes.called_flag = True
        try:
            state = history_browser[-1]
            last_state = history_browser[-2]
        except IndexError:
            return None
        board, last_board = state.board, last_state.board
        board_size = len(board._Board__list)
        counter = 0
        for i in range(board_size):
            if board._Board__list[i] != last_board._Board__list[i]:
                counter += 1
        return counter
    
    cached_changes = caching.history_cache(changes)
    
    cute_testing.assert_polite_wrapper(cached_changes, changes,
                                       same_signature=False)
    
    s = life.State.create_messy_root(5, 5)
    
    p = garlicsim.Project(life)
    
    r = p.root_this_state(s)
    
    leaf = p.simulate(r, 10)
    
    path = leaf.make_containing_path()
        
    result_1 = [cached_changes(node) for node in list(path)[0:5]]
        
    assert changes.called_flag is True
    changes.called_flag = False
    
    
    result_2 = [cached_changes(node) for node in list(path)[0:5]]
    
    assert changes.called_flag is False
    
    assert result_1 == result_2
    
    
    result_1 = [cached_changes(node) for node in list(path)]
        
    assert changes.called_flag is True
    changes.called_flag = False
    
    
    result_2 = [cached_changes(node) for node in list(path)]
    
    assert changes.called_flag is False
    
    assert result_1 == result_2
예제 #3
0
def test_cached_history_function():
    
    def changes(history_browser):
        '''
        Return how many cells changed between most recent state and its parent.
        '''
        changes.called_flag = True
        try:
            state = history_browser[-1]
            last_state = history_browser[-2]
        except IndexError:
            return None
        board, last_board = state.board, last_state.board
        board_size = len(board._Board__list)
        counter = 0
        for i in xrange(board_size):
            if board._Board__list[i] != last_board._Board__list[i]:
                counter += 1
        return counter
    
    cached_changes = caching.history_cache(changes)
    
    cute_testing.assert_polite_wrapper(cached_changes, changes,
                                       same_signature=False)
    
    s = life.State.create_messy_root(5, 5)
    
    p = garlicsim.Project(life)
    
    r = p.root_this_state(s)
    
    leaf = p.simulate(r, 10)
    
    path = leaf.make_containing_path()
        
    result_1 = [cached_changes(node) for node in list(path)[0:5]]
        
    assert changes.called_flag is True
    changes.called_flag = False
    
    
    result_2 = [cached_changes(node) for node in list(path)[0:5]]
    
    assert changes.called_flag is False
    
    assert result_1 == result_2
    
    
    result_1 = [cached_changes(node) for node in list(path)]
        
    assert changes.called_flag is True
    changes.called_flag = False
    
    
    result_2 = [cached_changes(node) for node in list(path)]
    
    assert changes.called_flag is False
    
    assert result_1 == result_2
예제 #4
0
def test_polite_wrapper():
    '''
    Test that `profile_ready` decorator produces a polite function wrapper.
    
    e.g. that the name, documentation and signature of the original function
    are used in the wrapper function, and a few other things.
    '''
    cute_testing.assert_polite_wrapper(cute_profile.profile_ready()(func),
                                       func)
예제 #5
0
def test_decorator():
    '''Test using `RaiseAssertor` as a decorator.'''
    @RaiseAssertor(ZeroDivisionError)
    def f():
        1/0
        
    f()
    
    cute_testing.assert_polite_wrapper(f)
def test_polite_wrapper():
    '''
    Test that `profile_ready` decorator produces a polite function wrapper.
    
    e.g. that the name, documentation and signature of the original function
    are used in the wrapper function, and a few other things.
    '''
    cute_testing.assert_polite_wrapper(
        cute_profile.profile_ready()(func),
        func
    )
def test_as_decorator():
    '''Test `TempRecursionLimitSetter` when used as a decorator.'''
    old_recursion_limit = sys.getrecursionlimit()
    @TempRecursionLimitSetter(1234)
    def f():
        assert sys.getrecursionlimit() == 1234
    assert sys.getrecursionlimit() == old_recursion_limit
    f()
    assert sys.getrecursionlimit() == old_recursion_limit
    
    cute_testing.assert_polite_wrapper(f)
def test_as_decorator():
    '''Test `TempValueSetter` used as a decorator.'''
    def a(): pass
    a.x = 1
    
    @TempValueSetter((a, 'x'), 2)
    def f():
        assert a.x == 2
    assert a.x == 1
    f()
    assert a.x == 1
    
    cute_testing.assert_polite_wrapper(f)
예제 #9
0
def test_as_decorator():
    '''Test `TempRecursionLimitSetter` when used as a decorator.'''
    old_recursion_limit = sys.getrecursionlimit()

    @TempRecursionLimitSetter(1234)
    def f():
        assert sys.getrecursionlimit() == 1234

    assert sys.getrecursionlimit() == old_recursion_limit
    f()
    assert sys.getrecursionlimit() == old_recursion_limit

    cute_testing.assert_polite_wrapper(f)
예제 #10
0
def test_as_decorator():
    '''Test `TempValueSetter` used as a decorator.'''
    def a():
        pass

    a.x = 1

    @TempValueSetter((a, 'x'), 2)
    def f():
        assert a.x == 2

    assert a.x == 1
    f()
    assert a.x == 1

    cute_testing.assert_polite_wrapper(f)
예제 #11
0
def test_api():
    """Test the API of cached functions."""
    f = cache()(counting_func)
    g = cache(max_size=3)(counting_func)

    for cached_function in (f, g):

        assert not hasattr(cached_function, "cache")
        cute_testing.assert_polite_wrapper(cached_function, counting_func)

        result_1 = cached_function(1)
        assert cached_function(1) == result_1 == cached_function(1)

        cached_function.cache_clear()

        result_2 = cached_function(1)

        assert cached_function(1) == result_2 == cached_function(1)
        assert result_1 != result_2 == cached_function(1) != result_1

        # Asserting we're not using `dict.clear` or something:
        assert cached_function.cache_clear.__name__ == "cache_clear"
예제 #12
0
def test_api():
    '''Test the API of cached functions.'''
    f = cache()(counting_func)
    g = cache(max_size=3)(counting_func)

    for cached_function in (f, g):

        assert not hasattr(cached_function, 'cache')
        cute_testing.assert_polite_wrapper(cached_function, counting_func)

        result_1 = cached_function(1)
        assert cached_function(1) == result_1 == cached_function(1)

        cached_function.cache_clear()

        result_2 = cached_function(1)

        assert cached_function(1) == result_2 == cached_function(1)
        assert result_1 != result_2 == cached_function(1) != result_1

        # Asserting we're not using `dict.clear` or something:
        assert cached_function.cache_clear.__name__ == 'cache_clear'
예제 #13
0
def check_context_manager_type(context_manager_type, self_returning,
                               error_catching):
    '''
    Run checks on a context manager.
    
    `self_returning` is a flag saying whether the context manager's `__enter__`
    method returns itself. (For the `as` keyword after `with`.)
    
    `error_catching` says whether the context manager catches exceptions it
    gets and updates the `exception_type_caught` global.
    '''

    global flag, exception_type_caught

    assert flag is None
    assert exception_type_caught is None

    ### Testing simple case: ##################################################
    #                                                                         #
    with context_manager_type(7) as return_value:
        assert flag == 7
        if self_returning:
            assert isinstance(return_value, context_manager_type)
        else:  # self_returning is False
            assert return_value is None
    #                                                                         #
    ### Finished testing simple case. #########################################

    assert flag is None
    assert exception_type_caught is None

    ### Testing creating context manager before `with`: #######################
    #                                                                         #
    my_context_manager = context_manager_type(1.1)
    assert isinstance(my_context_manager, context_manager_type)
    with my_context_manager as return_value:
        assert flag == 1.1
        if self_returning:
            assert return_value is my_context_manager
        else:  # self_returning is False
            assert return_value is None
    #                                                                         #
    ### Finished testing creating context manager before `with`. ##############

    assert flag is None
    assert exception_type_caught is None

    ### Testing decorated function: ###########################################
    #                                                                         #
    @context_manager_type('meow')
    def f():
        assert flag == 'meow'

    f()
    assert flag is None
    assert exception_type_caught is None

    #                                                                         #
    ### Finished testing decorated function. ##################################

    ### Testing manually decorated function: ##################################
    #                                                                         #
    def g(a, b=2, **kwargs):
        assert flag == 'meow'

    new_g = context_manager_type('meow')(g)

    with cute_testing.RaiseAssertor(AssertionError):
        g('whatever')

    assert flag is None
    assert exception_type_caught is None

    new_g('whatever')
    assert flag is None
    assert exception_type_caught is None
    cute_testing.assert_polite_wrapper(new_g, g)
    #                                                                         #
    ### Finished testing manually decorated function. #########################

    ### Testing deep nesting: #################################################
    #                                                                         #
    my_context_manager = context_manager_type(123)
    assert flag is None
    with my_context_manager:
        assert flag == 123
        with my_context_manager:
            assert flag == 123
            with my_context_manager:
                assert flag == 123
                with my_context_manager:
                    assert flag == 123
                    with my_context_manager:
                        assert flag == 123
                    assert flag == 123
                assert flag == 123
            assert flag == 123
        assert flag == 123
    assert flag is None

    with context_manager_type(1) as return_value_1:
        assert flag == 1
        with context_manager_type(2) as return_value_2:
            assert flag == 2
            with return_value_1 or context_manager_type(1):
                assert flag == 1
            assert flag == 2
        assert flag == 1
    assert flag is None
    #                                                                         #
    ### Finished testing deep nesting. ########################################

    ###########################################################################
    ###########################################################################
    ### Now while raising exceptions:

    ### Testing simple case: ##################################################
    #                                                                         #
    try:
        with context_manager_type(7) as return_value:
            assert flag == 7
            if self_returning:
                assert isinstance(return_value, context_manager_type)
            else:  # self_returning is False
                assert return_value is None
            raise TypeError('ooga booga')

    except Exception, exception:
        assert not error_catching
        assert type(exception) is TypeError
예제 #14
0
    #                                                                         #
    def g(a, b=2, **kwargs):
        assert flag == 'meow'
        eval('Ooga booga I am a syntax error.')

    with cute_testing.RaiseAssertor(AssertionError):
        g('whatever')

    assert flag is None
    assert exception_type_caught is None

    new_g = context_manager_type('meow')(g)

    assert flag is None
    assert exception_type_caught is None
    cute_testing.assert_polite_wrapper(new_g, g)

    try:
        new_g('whatever')
    except Exception, exception:
        assert not error_catching
        assert exception_type_caught is None
        assert type(exception) is SyntaxError
    else:
        assert error_catching
        assert exception_type_caught is SyntaxError
        exception_type_caught = None
    #                                                                         #
    ### Finished testing manually decorated function. ########################

    ### Testing deep nesting: #################################################
def check_context_manager_type(context_manager_type,
                               self_returning,
                               error_catching):
    '''
    Run checks on a context manager.
    
    `self_returning` is a flag saying whether the context manager's `__enter__`
    method returns itself. (For the `as` keyword after `with`.)
    
    `error_catching` says whether the context manager catches exceptions it
    gets and updates the `exception_type_caught` global.
    '''
    
    global flag, exception_type_caught
    
    assert flag is None
    assert exception_type_caught is None
    
    ### Testing simple case: ##################################################
    #                                                                         #
    with context_manager_type(7) as return_value:
        assert flag == 7
        if self_returning:
            assert isinstance(return_value, context_manager_type)
        else: # self_returning is False
            assert return_value is None
    #                                                                         #
    ### Finished testing simple case. #########################################
        
    assert flag is None
    assert exception_type_caught is None
    
    ### Testing creating context manager before `with`: #######################
    #                                                                         #
    my_context_manager = context_manager_type(1.1)
    assert isinstance(my_context_manager, context_manager_type)
    with my_context_manager as return_value:
        assert flag == 1.1
        if self_returning:
            assert return_value is my_context_manager
        else: # self_returning is False
            assert return_value is None
    #                                                                         #
    ### Finished testing creating context manager before `with`. ##############
    
    assert flag is None
    assert exception_type_caught is None

    ### Testing decorated function: ###########################################
    #                                                                         #
    @context_manager_type('meow')
    def f():
        assert flag == 'meow'
        
    f()
    assert flag is None
    assert exception_type_caught is None
    #                                                                         #
    ### Finished testing decorated function. ##################################
    
    ### Testing manually decorated function: ##################################
    #                                                                         #
    def g(a, b=2, **kwargs):
        assert flag == 'meow'
        
    new_g = context_manager_type('meow')(g)
        
    with cute_testing.RaiseAssertor(AssertionError):
        g('whatever')
        
    assert flag is None
    assert exception_type_caught is None

    new_g('whatever')
    assert flag is None
    assert exception_type_caught is None
    cute_testing.assert_polite_wrapper(new_g, g)
    #                                                                         #
    ### Finished testing manually decorated function. #########################
    
    ### Testing deep nesting: #################################################
    #                                                                         #
    my_context_manager = context_manager_type(123)
    assert flag is None
    with my_context_manager:
        assert flag == 123
        with my_context_manager:
            assert flag == 123
            with my_context_manager:
                assert flag == 123
                with my_context_manager:
                    assert flag == 123
                    with my_context_manager:
                        assert flag == 123
                    assert flag == 123
                assert flag == 123
            assert flag == 123
        assert flag == 123
    assert flag is None
    
    with context_manager_type(1) as return_value_1:
        assert flag == 1
        with context_manager_type(2) as return_value_2:
            assert flag == 2
            with return_value_1 or context_manager_type(1):
                assert flag == 1
            assert flag == 2
        assert flag == 1
    assert flag is None
    #                                                                         #
    ### Finished testing deep nesting. ########################################
    
    
    ###########################################################################
    ###########################################################################
    ### Now while raising exceptions:
        
    ### Testing simple case: ##################################################
    #                                                                         #
    try:    
        with context_manager_type(7) as return_value:
            assert flag == 7
            if self_returning:
                assert isinstance(return_value, context_manager_type)
            else: # self_returning is False
                assert return_value is None
            raise TypeError('ooga booga')
        
    except Exception as exception:
        assert not error_catching
        assert type(exception) is TypeError
        
    else:
        assert error_catching
        assert exception_type_caught is TypeError
        exception_type_caught = None
    #                                                                         #
    ### Finished testing simple case. #########################################
        
    assert flag is None
    
    ### Testing creating context manager before `with`: #######################
    #                                                                         #
    my_context_manager = context_manager_type(1.1)
    assert isinstance(my_context_manager, context_manager_type) 
    try:
        with my_context_manager as return_value:
            assert flag == 1.1
            if self_returning:
                assert return_value is my_context_manager
            else: # self_returning is False
                assert return_value is None
            {}[3]
    
    except Exception as exception:
        assert not error_catching
        assert exception_type_caught is None
        assert type(exception) is KeyError
        
    else:
        assert error_catching
        assert exception_type_caught is KeyError
        exception_type_caught = None
    #                                                                         #
    ### Finished testing creating context manager before `with`. ##############
        
    assert flag is None
    assert exception_type_caught is None

    ### Testing decorated function: ###########################################
    #                                                                         #
    @context_manager_type('meow')
    def f():
        assert flag == 'meow'
        1/0
    
    try:
        f()
    except Exception as exception:
        assert not error_catching
        assert exception_type_caught is None
        assert type(exception) is ZeroDivisionError        
    else:
        assert error_catching
        assert exception_type_caught is ZeroDivisionError
        exception_type_caught = None
    #                                                                         #
    ### Finished testing decorated function. ##################################
        
    assert flag is None
    exception_type_caught = None
    
    ### Testing manually decorated function: ##################################
    #                                                                         #
    def g(a, b=2, **kwargs):
        assert flag == 'meow'
        eval('Ooga booga I am a syntax error.')

    with cute_testing.RaiseAssertor(AssertionError):
        g('whatever')
        
    assert flag is None
    assert exception_type_caught is None
    
    new_g = context_manager_type('meow')(g)
        
    assert flag is None
    assert exception_type_caught is None
    cute_testing.assert_polite_wrapper(new_g, g)
    
    try:
        new_g('whatever')
    except Exception as exception:
        assert not error_catching
        assert exception_type_caught is None
        assert type(exception) is SyntaxError
    else:
        assert error_catching
        assert exception_type_caught is SyntaxError
        exception_type_caught = None
    #                                                                         #
    ### Finished testing manually decorated function. ########################
    
    ### Testing deep nesting: #################################################
    #                                                                         #
    my_context_manager = context_manager_type(123)
    assert flag is None
    try:
        with my_context_manager:
            assert flag == 123
            with my_context_manager:
                assert flag == 123
                with my_context_manager:
                    assert flag == 123
                    with my_context_manager:
                        assert flag == 123
                        with my_context_manager:
                            assert flag == 123
                            raise StopIteration
                        assert flag == 123
                    assert flag == 123
                assert flag == 123
            assert flag == 123
            
    except Exception as exception:
        assert not error_catching
        assert exception_type_caught is None
        assert type(exception) is StopIteration
        
    else:
        assert error_catching
        assert exception_type_caught is StopIteration
        exception_type_caught = None
        
    assert flag is None

    
    try:
        with context_manager_type(1) as return_value_1:
            assert flag == 1
            with context_manager_type(2) as return_value_2:
                assert flag == 2
                with return_value_1 or context_manager_type(1):
                    assert flag == 1
                    raise NotImplementedError
                assert flag == 2
            assert flag == 1
            
    except Exception as exception:
        assert not error_catching
        assert exception_type_caught is None
        assert type(exception) is NotImplementedError
        
    else:
        assert error_catching
        assert exception_type_caught is NotImplementedError
        exception_type_caught = None
        
    assert flag is None
    #                                                                         #
    ### Finished testing deep nesting. ########################################
    
예제 #16
0
    #                                                                         #
    def g(a, b=2, **kwargs):
        assert flag == 'meow'
        eval('Ooga booga I am a syntax error.')

    with cute_testing.RaiseAssertor(AssertionError):
        g('whatever')
        
    assert flag is None
    assert exception_type_caught is None
    
    new_g = context_manager_type('meow')(g)
        
    assert flag is None
    assert exception_type_caught is None
    cute_testing.assert_polite_wrapper(new_g, g)
    
    try:
        new_g('whatever')
    except Exception, exception:
        assert not error_catching
        assert exception_type_caught is None
        assert type(exception) is SyntaxError
    else:
        assert error_catching
        assert exception_type_caught is SyntaxError
        exception_type_caught = None
    #                                                                         #
    ### Finished testing manually decorated function. ########################
    
    ### Testing deep nesting: #################################################