/usr/lib/python2.7/dist-packages/gnutls/validators.py is in python-gnutls 3.0.0-0ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | """GNUTLS data validators"""
__all__ = ['function_args', 'method_args', 'none', 'ignore', 'list_of', 'one_of']
# Helper functions (internal use)
#
def isclass(obj):
return hasattr(obj, '__bases__') or isinstance(obj, type)
# Internal validator classes
#
class Validator(object):
_registered = []
def __init__(self, typ):
self.type = typ
def check(self, value):
return False
@staticmethod
def can_validate(typ):
return False
@classmethod
def register(cls, validator):
cls._registered.append(validator)
@classmethod
def get(cls, typ):
for validator in cls._registered:
if validator.can_validate(typ):
return validator(typ)
else:
return None
@staticmethod
def join_names(names):
if type(names) in (tuple, list):
if len(names) <= 2:
return ' or '.join(names)
else:
return ' or '.join((', '.join(names[:-1]), names[-1]))
else:
return names
def _type_names(self):
if isinstance(self.type, tuple):
return self.join_names([t.__name__.replace('NoneType', 'None') for t in self.type])
else:
return self.type.__name__.replace('NoneType', 'None')
@property
def name(self):
name = self._type_names()
if name.startswith('None'):
prefix = ''
elif name[0] in ('a', 'e', 'i', 'o', 'u'):
prefix = 'an '
else:
prefix = 'a '
return prefix + name
class IgnoringValidator(Validator):
def __init__(self, typ):
self.type = none
def check(self, value):
return True
@staticmethod
def can_validate(obj):
return obj is ignore
class TypeValidator(Validator):
def check(self, value):
return isinstance(value, self.type)
@staticmethod
def can_validate(obj):
return isclass(obj)
class MultiTypeValidator(TypeValidator):
@staticmethod
def can_validate(obj):
return isinstance(obj, tuple) and not filter(lambda x: not isclass(x), obj)
class OneOfValidator(Validator):
def __init__(self, typ):
self.type = typ.type
def check(self, value):
return value in self.type
@staticmethod
def can_validate(obj):
return isinstance(obj, one_of)
@property
def name(self):
return 'one of %s' % self.join_names(["`%r'" % e for e in self.type])
class ListOfValidator(Validator):
def __init__(self, typ):
self.type = typ.type
def check(self, value):
return isinstance(value, (tuple, list)) and not filter(lambda x: not isinstance(x, self.type), value)
@staticmethod
def can_validate(obj):
return isinstance(obj, list_of)
@property
def name(self):
return 'a list of %s' % self._type_names()
class ComplexValidator(Validator):
def __init__(self, typ):
self.type = [Validator.get(x) for x in typ]
def check(self, value):
return bool(sum(t.check(value) for t in self.type))
@staticmethod
def can_validate(obj):
return isinstance(obj, tuple) and not filter(lambda x: Validator.get(x) is None, obj)
@property
def name(self):
return self.join_names([x.name for x in self.type])
Validator.register(IgnoringValidator)
Validator.register(TypeValidator)
Validator.register(MultiTypeValidator)
Validator.register(OneOfValidator)
Validator.register(ListOfValidator)
Validator.register(ComplexValidator)
# Extra types to be used with argument validating decorators
#
none = type(None)
class one_of(object):
def __init__(self, *args):
if len(args) < 2:
raise ValueError("one_of must have at least 2 arguments")
self.type = args
class list_of(object):
def __init__(self, *args):
if filter(lambda x: not isclass(x), args):
raise TypeError("list_of arguments must be types")
if len(args) == 1:
self.type = args[0]
else:
self.type = args
ignore = type('ignore', (), {})()
# Helpers for writing well behaved decorators
#
def decorator(func):
"""A syntactic marker with no other effect than improving readability."""
return func
def preserve_signature(func):
"""Preserve the original function signature and attributes in decorator wrappers."""
from inspect import getargspec, formatargspec
from gnutls.constants import GNUTLSConstant
constants = [c for c in (getargspec(func)[3] or []) if isinstance(c, GNUTLSConstant)]
signature = formatargspec(*getargspec(func))[1:-1]
parameters = formatargspec(*getargspec(func), **{'formatvalue': lambda value: ""})[1:-1]
def fix_signature(wrapper):
if constants:
## import the required GNUTLSConstants used as function default arguments
code = "from gnutls.constants import %s\n" % ', '.join(c.name for c in constants)
exec code in locals(), locals()
code = "def %s(%s): return wrapper(%s)\nnew_wrapper = %s\n" % (func.__name__, signature, parameters, func.__name__)
exec code in locals(), locals()
new_wrapper.__name__ = func.__name__
new_wrapper.__doc__ = func.__doc__
new_wrapper.__module__ = func.__module__
new_wrapper.__dict__.update(func.__dict__)
return new_wrapper
return fix_signature
# Argument validating decorators
#
def _callable_args(*args, **kwargs):
"""Internal function used by argument checking decorators"""
start = kwargs.get('_start', 0)
validators = []
for i, arg in enumerate(args):
validator = Validator.get(arg)
if validator is None:
raise TypeError("unsupported type `%r' at position %d for argument checking decorator" % (arg, i+1))
validators.append(validator)
def check_args_decorator(func):
@preserve_signature(func)
def check_args(*func_args):
pos = start
for validator in validators:
if not validator.check(func_args[pos]):
raise TypeError("argument %d must be %s" % (pos+1-start, validator.name))
pos += 1
return func(*func_args)
return check_args
return check_args_decorator
@decorator
def method_args(*args):
"""Check class or instance method arguments"""
return _callable_args(*args, **{'_start': 1})
@decorator
def function_args(*args):
"""Check functions or staticmethod arguments"""
return _callable_args(*args)
|