コード例 #1
0
def check_simpack(simpack):
    '''Check that the problematic `simpack` raises the correct exception.'''
    _test_settings = simpack._test_settings
    PROBLEM = _test_settings.PROBLEM
    assert PROBLEM
    assert issubclass(PROBLEM, Exception)
           
    with cute_testing.RaiseAssertor(PROBLEM, assert_exact_type=True):
        SimpackGrokker(simpack)
コード例 #2
0
def _check_helpful_warnings_for_old_protocols(pickle_module,
                                              cross_process_persistent,
                                              old_protocol):
    '''
    Test that helpful errors are given when trying to pickle with old protocol.
    '''
    assert old_protocol < 2
    with cute_testing.RaiseAssertor(text=('protocol %s' % old_protocol)):
        pickle_module.dumps(cross_process_persistent, protocol=old_protocol)
コード例 #3
0
def test_helpful_message_when_forgetting_parentheses():
    '''Test user gets a helpful exception when when forgetting parentheses.'''
    def confusedly_forget_parentheses():
        @monkeypatching_tools.monkeypatch_method
        def f():
            pass

    with cute_testing.RaiseAssertor(
            TypeError, 'It seems that you forgot to add parentheses after '
            '`@monkeypatch_method` when decorating the `f` function.'):

        confusedly_forget_parentheses()
コード例 #4
0
def test_helpful_message_when_forgetting_parentheses():
    '''Test user gets a helpful exception when when forgetting parentheses.'''
    def confusedly_forget_parentheses():
        @cache
        def f():
            pass

    with cute_testing.RaiseAssertor(
            TypeError,
            'It seems that you forgot to add parentheses after `@cache` when '
            'decorating the `f` function.'):

        confusedly_forget_parentheses()
コード例 #5
0
def test_defining_exit_and_manage_context():
    '''
    Test context manager class defining both `__exit__` and `manage_context`.
    '''

    with cute_testing.RaiseAssertor(Exception,
                                    'both an `__exit__` method and a'):

        class MyContextManager(ContextManager):
            def manage_context(self):
                yield self

            def __exit__(self, *exc):
                pass
コード例 #6
0
def test_defining_exit_on_top_of_manage_context():
    '''
    Test an `__exit__`-definer inheriting from a `manage_context`-definer.
    '''
    class MyBaseContextManager(ContextManager):
        def manage_context(self):
            yield self

    with cute_testing.RaiseAssertor(
            Exception,
            "defines an `__exit__` method, but not an `__enter__` method"):

        class MyContextManager(MyBaseContextManager):
            def __exit__(self, *exc):
                pass
コード例 #7
0
def test_index():
    '''Test the `OrderedDict.index` method.'''
    ordered_dict = OrderedDict(((1, 'a'), (2, 'b'), (3, 'c')))
    assert ordered_dict.index(1) == 0
    assert ordered_dict.index(3) == 2
    assert ordered_dict.index(2) == 1

    ordered_dict[2] = 'b'

    assert ordered_dict.index(1) == 0
    assert ordered_dict.index(3) == 2
    assert ordered_dict.index(2) == 1

    ordered_dict['meow'] = 'frr'

    assert ordered_dict.index('meow') == 3

    with cute_testing.RaiseAssertor(KeyError):
        ordered_dict.index('Non-existing key')
コード例 #8
0
def test_only_defaultless():
    '''
    Test `ArgumentsProfile` on a function with defaultless arguments only.
    '''
    def func(a, b, c): pass
    
    a1 = ArgumentsProfile(func, 1, 2, 3)
    assert a1.args == (1, 2, 3)
    assert not a1.kwargs
    
    a2 = ArgumentsProfile(func, 1, c=3, b=2)
    a3 = ArgumentsProfile(func, c=3, a=1, b=2)
    a4 = ArgumentsProfile(func, 1, **{'c': 3, 'b': 2})
    a5 = ArgumentsProfile(func, **OrderedDict((('c', 3), ('b', 2), ('a', 1))))
    assert a1 == a2 == a3 == a4 == a5
    
    for arg_prof in [a1, a2, a3, a4, a5]:
        
        ### Testing `.iteritems`: #############################################
        #                                                                     #
        assert dict(arg_prof) == {'a': 1, 'b': 2, 'c': 3}
        assert OrderedDict(arg_prof) == \
            OrderedDict((('a', 1), ('b', 2), ('c', 3)))
        #                                                                     #
        ### Finished testing `.iteritems`. ####################################
        
        ### Testing `.__getitem__`: ###########################################
        #                                                                     #
        assert (arg_prof['a'], arg_prof['b'], arg_prof['c']) == (1, 2, 3)
        with cute_testing.RaiseAssertor(KeyError):
            arg_prof['non_existing_key']
        #                                                                     #
        ### Finished testing `.__getitem__`. ##################################
        
        ### Testing `.get`: ###################################################
        #                                                                     #
        assert arg_prof.get('a') == arg_prof.get('a', 'asdfasdf') == 1
        assert arg_prof.get('non_existing_key', 7) == 7
        assert arg_prof.get('non_existing_key') is None
コード例 #9
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
コード例 #10
0
        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, exception:
        assert not error_catching
コード例 #11
0
def test_many_defaultfuls_and_star_args_and_star_kwargs():
    '''
    Test `ArgumentsProfile` with defaultful arguments, `*args` and `**kwargs`.
    '''
    def func(a, b, c='three', d='four', e='five', f='six', *args, **kwargs):
        pass
    
    func(None, None)
    
    a1 = ArgumentsProfile(func, 'one', 'two', f='boomboomboom', __awesome=True,
                          big=True)
    assert a1.args == ('one', 'two')
    assert a1.kwargs == OrderedDict(
        (('f', 'boomboomboom'), ('big', True), ('__awesome', True))
    )
    
    a2 = ArgumentsProfile(func, 'one', 'two', 'three', 'four', 'five',
                          'bombastic', 'meow_frr', __funky=None, zany=True,
                          _wet=False, blue=True)
    assert a2.args == ('one', 'two', 'three', 'four', 'five', 'bombastic',
                       'meow_frr')
    assert a2.kwargs == OrderedDict(
        (('blue', True), ('zany', True), ('_wet', False), ('__funky', None))
    )
    
    a3 = ArgumentsProfile(func, 'one', 'two', 'three', 'four', 'five',
                          'bombastic', 'meow_frr', zany=True, __funky=None,
                          blue=True, _wet=False, **OrderedDict())
    assert a2 == a3
    
    
    for arg_prof in [a2, a3]:
        # Testing `.iteritems`:
        assert OrderedDict(arg_prof) == OrderedDict(
            (('a', 'one'), ('b', 'two'), ('c', 'three'), ('d', 'four'),
             ('e', 'five'), ('f', 'bombastic'), ('*', ('meow_frr',)),
             ('blue', True), ('zany', True), ('_wet', False),
             ('__funky', None))
        )
        
        ### Testing `.__getitem__`: ###########################################
        #                                                                     #
        assert (arg_prof['a'], arg_prof['b'], arg_prof['c'], arg_prof['d'],
                arg_prof['e'], arg_prof['f'], arg_prof['*'], arg_prof['blue'],
                arg_prof['zany'],  arg_prof['_wet'], arg_prof['__funky']) == \
               ('one', 'two', 'three', 'four', 'five', 'bombastic',
                ('meow_frr',), True, True, False, None)
        
        with cute_testing.RaiseAssertor(KeyError):
            arg_prof['non_existing_key']
        #                                                                     #
        ### Finished testing `.__getitem__`. ##################################
        
        ### Testing `.get`: ###################################################
        #                                                                     #
        assert arg_prof.get('d') == arg_prof.get('d', 7) == 'four'
        assert arg_prof.get('non_existing_key', 7) == 7
        assert arg_prof.get('non_existing_key') is None
        #                                                                     #
        ### Finished testing `.get`. ##########################################
        
        ### Testing `.iterkeys`, `.keys` and `__iter__`: ######################
        #                                                                     #
        assert list(arg_prof.iterkeys()) == list(arg_prof.keys()) == \
            list(arg_prof) == \
            ['a', 'b', 'c', 'd', 'e', 'f', '*', 'blue', 'zany', '_wet',
             '__funky']
        #                                                                     #
        ### Finished testing `.iterkeys`, `.keys` and `__iter__`. #############
        
        ### Testing `.itervalues` and `.values`: ##############################
        #                                                                     #
        assert list(arg_prof.itervalues()) == list(arg_prof.values()) == \
            ['one', 'two', 'three', 'four', 'five', 'bombastic', ('meow_frr',),
             True, True, False, None]
        #                                                                     #
        ### Finished testing `.itervalues` and `.values`. #####################
        
        ### Testing `.iteritems` and `.items`: ################################
        #                                                                     #
        items_1 = list(arg_prof.iteritems())
        items_2 = arg_prof.items()
        assert items_1 == items_2 == zip(arg_prof.keys(), arg_prof.values())
        #                                                                     #
        ### Finished testing `.iteritems` and `.items`. #######################
        
        ### Testing `.__contains__`: ##########################################
        #                                                                     #
        for key in arg_prof:
            assert key in arg_prof
コード例 #12
0
def test_defaultfuls_and_star_kwargs():
    '''Test `ArgumentsProfile` with defaultful arguments and `**kwargs`.'''
    def func(a, b, c=3, d=4, **kwargs): pass
    
    a1 = ArgumentsProfile(func, 1, 2)
    assert a1.args == (1, 2)
    assert not a1.kwargs
    
    # Alphabetic ordering among the `**kwargs`, but `d` is first because it's a
    # non-star:
    a2 = ArgumentsProfile(func, 1, 2, d='bombastic', zany=True, blue=True)
    assert a2.args == (1, 2)
    assert a2.kwargs == OrderedDict(
        (('d', 'bombastic'), ('blue', True), ('zany', True))
    )
    
    a3 = ArgumentsProfile(func, 1, b=2, blue=True, d='bombastic', zany=True)
    a4 = ArgumentsProfile(func, zany=True, a=1, b=2, blue=True, d='bombastic')
    a5 = ArgumentsProfile(func, 1, 2, 3, 'bombastic', zany=True, blue=True)
    assert a2 == a3 == a4 == a5
    
    for arg_prof in [a2, a3, a4, a5]:
        # Testing `.iteritems`:
        assert OrderedDict(arg_prof) == OrderedDict(
            (('a', 1), ('b', 2), ('c', 3), ('d', 'bombastic'), ('blue', True),
             ('zany', True))
        )
        
        ### Testing `.__getitem__`: ###########################################
        #                                                                     #
        assert (arg_prof['a'], arg_prof['b'], arg_prof['c'], arg_prof['d'],
                arg_prof['blue'], arg_prof['zany']) == \
               (1, 2, 3, 'bombastic', True, True)
        
        with cute_testing.RaiseAssertor(KeyError):
            arg_prof['non_existing_key']
        #                                                                     #
        ### Finished testing `.__getitem__`. ##################################
        
        ### Testing `.get`: ###################################################
        #                                                                     #
        assert arg_prof.get('d') == arg_prof.get('d', 7) == 'bombastic'
        assert arg_prof.get('non_existing_key', 7) == 7
        assert arg_prof.get('non_existing_key') is None
        #                                                                     #
        ### Finished testing `.get`. ##########################################
        
        ### Testing `.iterkeys`, `.keys` and `__iter__`: ######################
        #                                                                     #
        assert list(arg_prof.iterkeys()) == list(arg_prof.keys()) == \
            list(arg_prof) == ['a', 'b', 'c', 'd', 'blue', 'zany']
        #                                                                     #
        ### Finished testing `.iterkeys`, `.keys` and `__iter__`. #############
        
        ### Testing `.itervalues` and `.values`: ##############################
        #                                                                     #
        assert list(arg_prof.itervalues()) == list(arg_prof.values()) == \
            [1, 2, 3, 'bombastic', True, True]
        #                                                                     #
        ### Finished testing `.itervalues` and `.values`. #####################
        
        ### Testing `.__contains__`: ##########################################
        #                                                                     #
        for key in arg_prof:
            assert key in arg_prof
        assert 'agaofgnafgadf' not in arg_prof
        assert '**' not in arg_prof