Example #1
0
def test_not_specified2():
    def f():
        """ No types specified in the docstring """
        pass

    with raises(ContractException):
        decorate(f)
Example #2
0
def test_not_specified1():
    """ No docstring specified """
    def f():
        pass

    with raises(ContractException):
        decorate(f)
Example #3
0
    def test_check_docstring_maintained(self):
        def f1(a, b):
            ''' This is good
                :type a: int
                :type b: int
                :rtype: int
            '''
            return a + b
        
        def f2(string):
            pass
        
        f1_dec = decorate(f1)
        self.assertNotEqual(f1.__doc__, f1_dec.__doc__)
        self.assertEqual(f1.__name__, f1_dec.__name__)
        self.assertEqual(f1.__module__, f1_dec.__module__)

        f2_dec = decorate(f2, string='str')
        self.assertNotEqual(f2.__doc__, f2_dec.__doc__)
        self.assertEqual(f2.__name__, f2_dec.__name__)
        self.assertEqual(f2.__module__, f2_dec.__module__)

        f1_dec_p = decorate(f1, modify_docstring=False)
        self.assertEqual(f1_dec_p.__doc__, f1.__doc__)

        f2_dec_p = decorate(f2, modify_docstring=False, string='str')
        self.assertEqual(f2.__doc__, f2_dec_p.__doc__)

        @contract
        def f1b(a, b):
            ''' This is good
                :type a: int
                :type b: int
                :rtype: int
            '''
            return a + b
        
        @contract(string='str')
        def f2b(string):
            pass

        @contract(modify_docstring=False)
        def f1b_p(a, b):
            ''' This is good
                :type a: int
                :type b: int
                :rtype: int
            '''
            return a + b
        
        @contract(modify_docstring=False, string='str')
        def f2b_p(string):
            pass
        
        self.assertNotEqual(f1.__doc__, f1b.__doc__)
        self.assertEqual(f1.__doc__, f1b_p.__doc__)
        self.assertNotEqual(f2.__doc__, f2b.__doc__)
        self.assertEqual(f2.__doc__, f2b_p.__doc__)
Example #4
0
def test_check_docstring_maintained():
    def f1(a, b):
        """ This is good
            :type a: int
            :type b: int
            :rtype: int
        """
        return a + b

    def f2(string):
        pass

    f1_dec = decorate(f1)
    assert f1.__doc__ != f1_dec.__doc__
    assert f1.__name__ == f1_dec.__name__
    assert f1.__module__ == f1_dec.__module__

    f2_dec = decorate(f2, string='str')
    assert f2.__doc__ != f2_dec.__doc__
    assert f2.__name__ == f2_dec.__name__
    assert f2.__module__ == f2_dec.__module__

    f1_dec_p = decorate(f1, modify_docstring=False)
    assert f1_dec_p.__doc__ == f1.__doc__

    f2_dec_p = decorate(f2, modify_docstring=False, string='str')
    assert f2.__doc__ == f2_dec_p.__doc__

    @contract
    def f1b(a, b):
        """ This is good
            :type a: int
            :type b: int
            :rtype: int
        """
        return a + b

    @contract(string='str')
    def f2b(string):
        pass

    @contract(modify_docstring=False)
    def f1b_p(a, b):
        """ This is good
            :type a: int
            :type b: int
            :rtype: int
        """
        return a + b

    @contract(modify_docstring=False, string='str')
    def f2b_p(string):
        pass

    assert f1.__doc__ != f1b.__doc__
    assert f1.__doc__ == f1b_p.__doc__
    assert f2.__doc__ != f2b.__doc__
    assert f2.__doc__ == f2b_p.__doc__
Example #5
0
    def test_check_docstring_maintained(self):
        def f1(a, b):
            ''' This is good
                :type a: int
                :type b: int
                :rtype: int
            '''
            return a + b

        def f2(string):
            pass

        f1_dec = decorate(f1)
        self.assertNotEqual(f1.__doc__, f1_dec.__doc__)
        self.assertEqual(f1.__name__, f1_dec.__name__)
        self.assertEqual(f1.__module__, f1_dec.__module__)

        f2_dec = decorate(f2, string='str')
        self.assertNotEqual(f2.__doc__, f2_dec.__doc__)
        self.assertEqual(f2.__name__, f2_dec.__name__)
        self.assertEqual(f2.__module__, f2_dec.__module__)

        f1_dec_p = decorate(f1, modify_docstring=False)
        self.assertEqual(f1_dec_p.__doc__, f1.__doc__)

        f2_dec_p = decorate(f2, modify_docstring=False, string='str')
        self.assertEqual(f2.__doc__, f2_dec_p.__doc__)

        @contract
        def f1b(a, b):
            ''' This is good
                :type a: int
                :type b: int
                :rtype: int
            '''
            return a + b

        @contract(string='str')
        def f2b(string):
            pass

        @contract(modify_docstring=False)
        def f1b_p(a, b):
            ''' This is good
                :type a: int
                :type b: int
                :rtype: int
            '''
            return a + b

        @contract(modify_docstring=False, string='str')
        def f2b_p(string):
            pass

        self.assertNotEqual(f1.__doc__, f1b.__doc__)
        self.assertEqual(f1.__doc__, f1b_p.__doc__)
        self.assertNotEqual(f2.__doc__, f2b.__doc__)
        self.assertEqual(f2.__doc__, f2b_p.__doc__)
Example #6
0
 def f(a, *b): #@UnusedVariable
     ''' 
         :type a: int
         :type b: tuple(int)
         :rtype: int
     '''
     pass
 
     decorate(f)
Example #7
0
    def f(a, *b):  # @UnusedVariable
        """
            :type a: int
            :type b: tuple(int)
            :rtype: int
        """
        pass

        decorate(f)
Example #8
0
        def f(a, *b):  # @UnusedVariable
            ''' 
                :type a: int
                :type b: tuple(int)
                :rtype: int
            '''
            pass

            decorate(f)
Example #9
0
        def f(a, *b):  # @UnusedVariable
            """
                :type a: int
                :type b: tuple(int)
                :rtype: int
            """
            pass

            decorate(f)
Example #10
0
def test_parse_error1():
    def f(a, b):
        """ Same with optional
            :type a: in
            :type b: int
        """
        pass

    with raises(ContractException):
        decorate(f)
Example #11
0
def test_invalid1():
    def f(a):
        """ Unknown b.
            :type a: int
            :type b: int
        """
        pass

    with raises(ContractException):
        decorate(f)
Example #12
0
def not_supported2():
    """ Cannot do with **args """
    def f(a, **b):
        """
            :type a: int
            :rtype: int
        """
        pass

    with raises(ContractException):
        decorate(f)
Example #13
0
def test_bad_quoting2():
    def f(a, b):
        """
            :type a: ``int``
            :type b: `int``
            :rtype: ``int``
        """
        pass

    with raises(ContractException):
        decorate(f)
Example #14
0
def test_malformed():
    def f():
        """
            Wrong syntax

            :rtype okok
        """
        pass

    with raises(ContractException):
        decorate(f)
Example #15
0
def test_too_many():
    def f():
        """
            Too many rtype clauses.
            :rtype: int
            :rtype: int
        """
        pass

    with raises(ContractException):
        decorate(f)
Example #16
0
def not_supported2():
    """ Support of **args """
    def f(a, **b):
        """
            :type a: int
            :type b: dict(int:int)
            :rtype: int
        """
        pass

    with raises(ContractException):
        decorate(f)
    def test_varargs2(self):
        def f(a, b, *c: """tuple"""

        ):
            assert c == (a, b)
    
        f2 = decorate(f)
        f2(0, 7, 0, 7)
def test_contract_decorate():
    z = 1

    def foo(x):
        pass

    c = decorate(foo, x='$z')
    c(1)
def test_contract_decorate():
    z = 1

    def foo(x):
        pass

    c = decorate(foo, x='$z')
    c(1)
 def test_keywords(self):
     def f(A:int, B:int, **c: dict):
         assert c['a'] == A
         assert c['b'] == B
             
     f2 = decorate(f)
     f(0, 7, a=0, b=7)
     f2(0, 7, a=0, b=7)
 
     self.assertRaises(Exception, f2, 0, 5, 0, 6)
Example #21
0
    def test_check_it_works2c(self):
        ''' Nothing for b '''
        def f1(a, b):  # @UnusedVariable
            return int(a + b)

        f = decorate(f1, a='int', returns='int')

        f(1, 2)
        f(1, 2.0)
        self.assertRaises(ContractNotRespected, f, 1.0, 2)
Example #22
0
 def test_check_it_works2c(self):
     ''' Nothing for b '''
     def f1(a, b): #@UnusedVariable
         return int(a + b)
     
     f = decorate(f1, a='int', returns='int')
     
     f(1, 2)
     f(1, 2.0)
     self.assertRaises(ContractNotRespected, f, 1.0, 2)
    def test_keywords(self):
        def f(A: int, B: int, **c: dict):
            assert c['a'] == A
            assert c['b'] == B

        f2 = decorate(f)
        f(0, 7, a=0, b=7)
        f2(0, 7, a=0, b=7)

        self.assertRaises(Exception, f2, 0, 5, 0, 6)
    def test_kwargs(self):
        def f(a: int, b: int, c: int = 7):  #@UnusedVariable
            if c != b:
                raise Exception()

        f2 = decorate(f)
        f2(0, 7)
        f2(0, 5, 5)
        self.assertRaises(Exception, f2, 0, 5, 4)
        self.assertRaises(Exception, f2, 0, 5)
    def test_kwargs(self):
        def f(a: int, b: int, c: int = 7):  # @UnusedVariable
            if c != b:
                raise Exception()

        f2 = decorate(f)
        f2(0, 7)
        f2(0, 5, 5)
        self.assertRaises(Exception, f2, 0, 5, 4)
        self.assertRaises(Exception, f2, 0, 5)
Example #26
0
def test_keywords():
    def f(A: int, B: int, **c: dict):
        assert c['a'] == A
        assert c['b'] == B

    f2 = decorate(f)
    f(0, 7, a=0, b=7)
    f2(0, 7, a=0, b=7)

    with raises(Exception):
        f2(0, 5, 0, 6)
Example #27
0
    def test_varargs(self):
        def f(a, b, *c):
            ''' Same with optional
                :type a: int
                :type b: int
                :type c: tuple
            '''
            assert c == (a, b)

        f2 = decorate(f)
        f2(0, 7, 0, 7)
Example #28
0
def test_check_it_works2c():
    """ Nothing for b """
    def f1(a, b):  # @UnusedVariable
        return int(a + b)

    f = decorate(f1, a='int', returns='int')

    f(1, 2)
    f(1, 2.0)
    with raises(ContractNotRespected):
        f(1.0, 2)
Example #29
0
def test_varargs():
    def f(a, b, *c):
        """ Same with optional
            :type a: int
            :type b: int
            :type c: tuple
        """
        assert c == (a, b)

    f2 = decorate(f)
    f2(0, 7, 0, 7)
Example #30
0
    def test_varargs(self):
        def f(a, b, *c):
            """ Same with optional
                :type a: int
                :type b: int
                :type c: tuple
            """
            assert c == (a, b)

        f2 = decorate(f)
        f2(0, 7, 0, 7)
Example #31
0
def test_kwargs():
    def f(a: int, b: int, c: int = 7):  #@UnusedVariable
        if c != b:
            raise Exception()

    f2 = decorate(f)
    f2(0, 7)
    f2(0, 5, 5)
    with raises(Exception):
        f2(0, 5, 4)

    with raises(Exception):
        f2(0, 5)
Example #32
0
    def test_kwargs(self):
        def f(a, b, c=7):  # @UnusedVariable
            ''' Same with optional
                :type a: int
                :type b: int
                :type c: int
            '''
            if c != b:
                raise Exception()

        f2 = decorate(f)
        f2(0, 7)
        f2(0, 5, 5)
        self.assertRaises(Exception, f2, 0, 5, 4)
        self.assertRaises(Exception, f2, 0, 5)
Example #33
0
    def test_kwargs(self):
        def f(a, b, c=7):  # @UnusedVariable
            """ Same with optional
                :type a: int
                :type b: int
                :type c: int
            """
            if c != b:
                raise Exception()

        f2 = decorate(f)
        f2(0, 7)
        f2(0, 5, 5)
        self.assertRaises(Exception, f2, 0, 5, 4)
        self.assertRaises(Exception, f2, 0, 5)
Example #34
0
    def test_keywords(self):
        def f(A, B, **c):
            ''' Same with optional
                :type A: int
                :type B: int
                :type c: dict
            '''
            assert c['a'] == A
            assert c['b'] == B

        f2 = decorate(f)
        f(0, 7, a=0, b=7)
        f2(0, 7, a=0, b=7)

        self.assertRaises(Exception, f2, 0, 5, 0, 6)
Example #35
0
    def test_keywords(self):
        def f(A, B, **c):
            """ Same with optional
                :type A: int
                :type B: int
                :type c: dict
            """
            assert c['a'] == A
            assert c['b'] == B

        f2 = decorate(f)
        f(0, 7, a=0, b=7)
        f2(0, 7, a=0, b=7)

        self.assertRaises(Exception, f2, 0, 5, 0, 6)
Example #36
0
def test_keywords():
    def f(A, B, **c):
        """ Same with optional
            :type A: int
            :type B: int
            :type c: dict
        """
        assert c['a'] == A
        assert c['b'] == B

    f2 = decorate(f)
    f(0, 7, a=0, b=7)
    f2(0, 7, a=0, b=7)

    with raises(Exception):
        f2(0, 5, 0, 6)
Example #37
0
def test_kwargs():
    def f(a, b, c=7):  # @UnusedVariable
        """ Same with optional
            :type a: int
            :type b: int
            :type c: int
        """
        if c != b:
            raise Exception()

    f2 = decorate(f)
    f2(0, 7)
    f2(0, 5, 5)
    with raises(Exception):
        f2(0, 5, 4)

    with raises(Exception):
        f2(0, 5)
Example #38
0
def k(f):
    signature = dict(x='array(>=-1,<=+1),shape(x)',
                     returns='array(>=-1,<=+1),shape(x)')
    f2 = decorate(f, **signature)
    kernels.append(f2)
    return f2
Example #39
0
 def setUp(self):
     self.blend = decorate(blend_function)
Example #40
0
 def setUp(self):
     self.blend = decorate(blend_function)
    def test_varargs2(self):
        def f(a, b, *c: "tuple"):
            assert c == (a, b)

        f2 = decorate(f)
        f2(0, 7, 0, 7)
 def test_varargs(self):
     def f(a, b, *c: tuple):
         assert c == (a, b)
 
     f2 = decorate(f)
     f2(0, 7, 0, 7)
Example #43
0
 def wrapper(func, *args, **kwargs):
     """ Decorator """
     # Register exceptions if exception handler object exists
     if all_disabled():
         return func(*args, **kwargs)
     exhobj = putil.exh.get_exh_obj()
     exdata = {}
     if exhobj is not None:
         for param_name, param_contract in contract_args.items():
             # param_name=param_value, as in num='str|float'
             contracts_dicts = list()
             # Create dictionary of custom contracts
             if _get_custom_contract(param_contract):
                 key = _get_custom_contract(param_contract)
                 contracts_dicts += _CUSTOM_CONTRACTS[key].values()
             else: # Add regular PyContracts contracts
                 msg = 'Argument `*[argument_name]*` is not valid'
                 contracts_dicts += [
                     {
                         'num':_get_num_contracts(
                             contracts_dicts, param_name
                         ),
                         'type':RuntimeError,
                         'msg':msg.replace(
                             '*[argument_name]*', param_name
                         )
                     }
                 ]
             func_module = (
                 getattr(func, '__module__')
                 if hasattr(func, '__module__') else
                 'unknown'
             )
             for exdict in contracts_dicts:
                 exname = 'contract:{0}.{1}_{2}'.format(
                     '{0}.{1}'.format(func_module, func.__name__),
                     param_name,
                     exdict['num']
                 )
                 exdata[exname] = exhobj.add_exception(
                     exname=exname,
                     extype=exdict['type'],
                     exmsg=exdict['msg'].replace(
                         '*[argument_name]*',
                         param_name
                     )
                 )
     # Argument validation. PyContracts "entry" is the
     # contracts.contract_decorator, which has some logic to figure out
     # which way the contract was specified. Since this module
     # (pcontracts) supports only the decorator way of specifying the
     # contracts, all the mentioned logic can be bypassed by calling
     # contracts.contracts_decorate, which is renamed to
     # contracts.decorate in the contracts __init__.py file
     try:
         return (
             contracts.decorate(
                 func,
                 False,
                 **contract_args
             )(*args, **kwargs)
         )
     except contracts.ContractSyntaxError:
         raise
     except contracts.ContractNotRespected as eobj:
         # Extract which function parameter triggered exception
         param_dict = _create_argument_value_pairs(
             func, *args, **kwargs
         )
         # re.search returns the string with quotes in it
         param_name = re.search(r"'\w+'", eobj.error).group()[1:-1]
         # Raise exception
         exdict = _get_contract_exception_dict(eobj.error)
         func_module = (
             getattr(func, '__module__')
             if hasattr(func, '__module__') else
             'unknown'
         )
         exname = 'contract:{0}.{1}_{2}'.format(
             '{0}.{1}'.format(func_module, func.__name__),
             param_name,
             exdict['num']
         )
         efield = exdict['field']
         edata = (
             {'field':efield, 'value':param_dict[param_name]}
             if (efield and (efield != 'argument_name')) else
             None
         )
         if exhobj is not None:
             exhobj.raise_exception_if(
                 exname=exname,
                 condition=True,
                 edata=edata,
                 _keys=exdata[exname]
             )
         else:
             # Pick "nice" variable names because the raise line is
             # going to be shown in the exception traceback
             exception_type = exdict['type']
             exception_message = exdict['msg'].replace(
                 '*[{0}]*'.format(exdict['field']),
                 param_name if exdict['field'] == 'argument_name' else
                 '{0}'.format(param_dict[param_name])
             )
             _raise_exception(exception_type(exception_message))
Example #44
0
def k(f):
    signature = dict(x='array(>=-1,<=+1),shape(x)',
                     returns='array(>=-1,<=+1),shape(x)')
    f2 = decorate(f, **signature)
    kernels.append(f2)
    return f2
Example #45
0
def test_malformed():
    def f() -> "":
        pass

    with raises(ContractException):
        decorate(f)