schema_builder.py 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190
  1. import collections
  2. import inspect
  3. import re
  4. from functools import wraps
  5. import sys
  6. from contextlib import contextmanager
  7. import itertools
  8. try:
  9. import error as er
  10. except ImportError:
  11. from . import error as er
  12. if sys.version_info >= (3,):
  13. long = int
  14. unicode = str
  15. basestring = str
  16. ifilter = filter
  17. def iteritems(d):
  18. return d.items()
  19. else:
  20. from itertools import ifilter
  21. def iteritems(d):
  22. return d.iteritems()
  23. """Schema validation for Python data structures.
  24. Given eg. a nested data structure like this:
  25. {
  26. 'exclude': ['Users', 'Uptime'],
  27. 'include': [],
  28. 'set': {
  29. 'snmp_community': 'public',
  30. 'snmp_timeout': 15,
  31. 'snmp_version': '2c',
  32. },
  33. 'targets': {
  34. 'localhost': {
  35. 'exclude': ['Uptime'],
  36. 'features': {
  37. 'Uptime': {
  38. 'retries': 3,
  39. },
  40. 'Users': {
  41. 'snmp_community': 'monkey',
  42. 'snmp_port': 15,
  43. },
  44. },
  45. 'include': ['Users'],
  46. 'set': {
  47. 'snmp_community': 'monkeys',
  48. },
  49. },
  50. },
  51. }
  52. A schema like this:
  53. >>> settings = {
  54. ... 'snmp_community': str,
  55. ... 'retries': int,
  56. ... 'snmp_version': All(Coerce(str), Any('3', '2c', '1')),
  57. ... }
  58. >>> features = ['Ping', 'Uptime', 'Http']
  59. >>> schema = Schema({
  60. ... 'exclude': features,
  61. ... 'include': features,
  62. ... 'set': settings,
  63. ... 'targets': {
  64. ... 'exclude': features,
  65. ... 'include': features,
  66. ... 'features': {
  67. ... str: settings,
  68. ... },
  69. ... },
  70. ... })
  71. Validate like so:
  72. >>> schema({
  73. ... 'set': {
  74. ... 'snmp_community': 'public',
  75. ... 'snmp_version': '2c',
  76. ... },
  77. ... 'targets': {
  78. ... 'exclude': ['Ping'],
  79. ... 'features': {
  80. ... 'Uptime': {'retries': 3},
  81. ... 'Users': {'snmp_community': 'monkey'},
  82. ... },
  83. ... },
  84. ... }) == {
  85. ... 'set': {'snmp_version': '2c', 'snmp_community': 'public'},
  86. ... 'targets': {
  87. ... 'exclude': ['Ping'],
  88. ... 'features': {'Uptime': {'retries': 3},
  89. ... 'Users': {'snmp_community': 'monkey'}}}}
  90. True
  91. """
  92. # options for extra keys
  93. PREVENT_EXTRA = 0 # any extra key not in schema will raise an error
  94. ALLOW_EXTRA = 1 # extra keys not in schema will be included in output
  95. REMOVE_EXTRA = 2 # extra keys not in schema will be excluded from output
  96. def _isnamedtuple(obj):
  97. return isinstance(obj, tuple) and hasattr(obj, '_fields')
  98. primitive_types = (str, unicode, bool, int, float)
  99. class Undefined(object):
  100. def __nonzero__(self):
  101. return False
  102. def __repr__(self):
  103. return '...'
  104. UNDEFINED = Undefined()
  105. def default_factory(value):
  106. if value is UNDEFINED or callable(value):
  107. return value
  108. return lambda: value
  109. @contextmanager
  110. def raises(exc, msg=None, regex=None):
  111. try:
  112. yield
  113. except exc as e:
  114. if msg is not None:
  115. assert str(e) == msg, '%r != %r' % (str(e), msg)
  116. if regex is not None:
  117. assert re.search(regex, str(e)), '%r does not match %r' % (str(e), regex)
  118. def Extra(_):
  119. """Allow keys in the data that are not present in the schema."""
  120. raise er.SchemaError('"Extra" should never be called')
  121. # As extra() is never called there's no way to catch references to the
  122. # deprecated object, so we just leave an alias here instead.
  123. extra = Extra
  124. class Schema(object):
  125. """A validation schema.
  126. The schema is a Python tree-like structure where nodes are pattern
  127. matched against corresponding trees of values.
  128. Nodes can be values, in which case a direct comparison is used, types,
  129. in which case an isinstance() check is performed, or callables, which will
  130. validate and optionally convert the value.
  131. We can equate schemas also.
  132. For Example:
  133. >>> v = Schema({Required('a'): unicode})
  134. >>> v1 = Schema({Required('a'): unicode})
  135. >>> v2 = Schema({Required('b'): unicode})
  136. >>> assert v == v1
  137. >>> assert v != v2
  138. """
  139. _extra_to_name = {
  140. REMOVE_EXTRA: 'REMOVE_EXTRA',
  141. ALLOW_EXTRA: 'ALLOW_EXTRA',
  142. PREVENT_EXTRA: 'PREVENT_EXTRA',
  143. }
  144. def __init__(self, schema, required=False, extra=PREVENT_EXTRA):
  145. """Create a new Schema.
  146. :param schema: Validation schema. See :module:`voluptuous` for details.
  147. :param required: Keys defined in the schema must be in the data.
  148. :param extra: Specify how extra keys in the data are treated:
  149. - :const:`~voluptuous.PREVENT_EXTRA`: to disallow any undefined
  150. extra keys (raise ``Invalid``).
  151. - :const:`~voluptuous.ALLOW_EXTRA`: to include undefined extra
  152. keys in the output.
  153. - :const:`~voluptuous.REMOVE_EXTRA`: to exclude undefined extra keys
  154. from the output.
  155. - Any value other than the above defaults to
  156. :const:`~voluptuous.PREVENT_EXTRA`
  157. """
  158. self.schema = schema
  159. self.required = required
  160. self.extra = int(extra) # ensure the value is an integer
  161. self._compiled = self._compile(schema)
  162. def __eq__(self, other):
  163. if str(other) == str(self.schema):
  164. # Because repr is combination mixture of object and schema
  165. return True
  166. return False
  167. def __str__(self):
  168. return str(self.schema)
  169. def __repr__(self):
  170. return "<Schema(%s, extra=%s, required=%s) object at 0x%x>" % (
  171. self.schema, self._extra_to_name.get(self.extra, '??'),
  172. self.required, id(self))
  173. def __call__(self, data):
  174. """Validate data against this schema."""
  175. try:
  176. return self._compiled([], data)
  177. except er.MultipleInvalid:
  178. raise
  179. except er.Invalid as e:
  180. raise er.MultipleInvalid([e])
  181. # return self.validate([], self.schema, data)
  182. def _compile(self, schema):
  183. if schema is Extra:
  184. return lambda _, v: v
  185. if isinstance(schema, Object):
  186. return self._compile_object(schema)
  187. if isinstance(schema, collections.Mapping) and len(schema):
  188. return self._compile_dict(schema)
  189. elif isinstance(schema, list) and len(schema):
  190. return self._compile_list(schema)
  191. elif isinstance(schema, tuple):
  192. return self._compile_tuple(schema)
  193. type_ = type(schema)
  194. if type_ is type:
  195. type_ = schema
  196. if type_ in (bool, bytes, int, long, str, unicode, float, complex, object,
  197. list, dict, type(None)) or callable(schema):
  198. return _compile_scalar(schema)
  199. raise er.SchemaError('unsupported schema data type %r' %
  200. type(schema).__name__)
  201. def _compile_mapping(self, schema, invalid_msg=None):
  202. """Create validator for given mapping."""
  203. invalid_msg = invalid_msg or 'mapping value'
  204. # Keys that may be required
  205. all_required_keys = set(key for key in schema
  206. if key is not Extra and
  207. ((self.required and not isinstance(key, (Optional, Remove))) or
  208. isinstance(key, Required)))
  209. # Keys that may have defaults
  210. all_default_keys = set(key for key in schema
  211. if isinstance(key, Required) or
  212. isinstance(key, Optional))
  213. _compiled_schema = {}
  214. for skey, svalue in iteritems(schema):
  215. new_key = self._compile(skey)
  216. new_value = self._compile(svalue)
  217. _compiled_schema[skey] = (new_key, new_value)
  218. candidates = list(_iterate_mapping_candidates(_compiled_schema))
  219. # After we have the list of candidates in the correct order, we want to apply some optimization so that each
  220. # key in the data being validated will be matched against the relevant schema keys only.
  221. # No point in matching against different keys
  222. additional_candidates = []
  223. candidates_by_key = {}
  224. for skey, (ckey, cvalue) in candidates:
  225. if type(skey) in primitive_types:
  226. candidates_by_key.setdefault(skey, []).append((skey, (ckey, cvalue)))
  227. elif isinstance(skey, Marker) and type(skey.schema) in primitive_types:
  228. candidates_by_key.setdefault(skey.schema, []).append((skey, (ckey, cvalue)))
  229. else:
  230. # These are wildcards such as 'int', 'str', 'Remove' and others which should be applied to all keys
  231. additional_candidates.append((skey, (ckey, cvalue)))
  232. def validate_mapping(path, iterable, out):
  233. required_keys = all_required_keys.copy()
  234. # keeps track of all default keys that haven't been filled
  235. default_keys = all_default_keys.copy()
  236. error = None
  237. errors = []
  238. for key, value in iterable:
  239. key_path = path + [key]
  240. remove_key = False
  241. # Optimization. Validate against the matching key first, then fallback to the rest
  242. relevant_candidates = itertools.chain(candidates_by_key.get(key, []), additional_candidates)
  243. # compare each given key/value against all compiled key/values
  244. # schema key, (compiled key, compiled value)
  245. for skey, (ckey, cvalue) in relevant_candidates:
  246. try:
  247. new_key = ckey(key_path, key)
  248. except er.Invalid as e:
  249. if len(e.path) > len(key_path):
  250. raise
  251. if not error or len(e.path) > len(error.path):
  252. error = e
  253. continue
  254. # Backtracking is not performed once a key is selected, so if
  255. # the value is invalid we immediately throw an exception.
  256. exception_errors = []
  257. # check if the key is marked for removal
  258. is_remove = new_key is Remove
  259. try:
  260. cval = cvalue(key_path, value)
  261. # include if it's not marked for removal
  262. if not is_remove:
  263. out[new_key] = cval
  264. else:
  265. remove_key = True
  266. continue
  267. except er.MultipleInvalid as e:
  268. exception_errors.extend(e.errors)
  269. except er.Invalid as e:
  270. exception_errors.append(e)
  271. if exception_errors:
  272. if is_remove or remove_key:
  273. continue
  274. for err in exception_errors:
  275. if len(err.path) <= len(key_path):
  276. err.error_type = invalid_msg
  277. errors.append(err)
  278. # If there is a validation error for a required
  279. # key, this means that the key was provided.
  280. # Discard the required key so it does not
  281. # create an additional, noisy exception.
  282. required_keys.discard(skey)
  283. break
  284. # Key and value okay, mark any Required() fields as found.
  285. required_keys.discard(skey)
  286. # No need for a default if it was filled
  287. default_keys.discard(skey)
  288. break
  289. else:
  290. if remove_key:
  291. # remove key
  292. continue
  293. elif self.extra == ALLOW_EXTRA:
  294. out[key] = value
  295. elif self.extra != REMOVE_EXTRA:
  296. errors.append(er.Invalid('extra keys not allowed', key_path))
  297. # else REMOVE_EXTRA: ignore the key so it's removed from output
  298. # set defaults for any that can have defaults
  299. for key in default_keys:
  300. if not isinstance(key.default, Undefined): # if the user provides a default with the node
  301. out[key.schema] = key.default()
  302. if key in required_keys:
  303. required_keys.discard(key)
  304. # for any required keys left that weren't found and don't have defaults:
  305. for key in required_keys:
  306. msg = key.msg if hasattr(key, 'msg') and key.msg else 'required key not provided'
  307. errors.append(er.RequiredFieldInvalid(msg, path + [key]))
  308. if errors:
  309. raise er.MultipleInvalid(errors)
  310. return out
  311. return validate_mapping
  312. def _compile_object(self, schema):
  313. """Validate an object.
  314. Has the same behavior as dictionary validator but work with object
  315. attributes.
  316. For example:
  317. >>> class Structure(object):
  318. ... def __init__(self, one=None, three=None):
  319. ... self.one = one
  320. ... self.three = three
  321. ...
  322. >>> validate = Schema(Object({'one': 'two', 'three': 'four'}, cls=Structure))
  323. >>> with raises(er.MultipleInvalid, "not a valid value for object value @ data['one']"):
  324. ... validate(Structure(one='three'))
  325. """
  326. base_validate = self._compile_mapping(
  327. schema, invalid_msg='object value')
  328. def validate_object(path, data):
  329. if schema.cls is not UNDEFINED and not isinstance(data, schema.cls):
  330. raise er.ObjectInvalid('expected a {0!r}'.format(schema.cls), path)
  331. iterable = _iterate_object(data)
  332. iterable = ifilter(lambda item: item[1] is not None, iterable)
  333. out = base_validate(path, iterable, {})
  334. return type(data)(**out)
  335. return validate_object
  336. def _compile_dict(self, schema):
  337. """Validate a dictionary.
  338. A dictionary schema can contain a set of values, or at most one
  339. validator function/type.
  340. A dictionary schema will only validate a dictionary:
  341. >>> validate = Schema({'prop': str})
  342. >>> with raises(er.MultipleInvalid, 'expected a dictionary'):
  343. ... validate([])
  344. An invalid dictionary value:
  345. >>> validate = Schema({'one': 'two', 'three': 'four'})
  346. >>> with raises(er.MultipleInvalid, "not a valid value for dictionary value @ data['one']"):
  347. ... validate({'one': 'three'})
  348. An invalid key:
  349. >>> with raises(er.MultipleInvalid, "extra keys not allowed @ data['two']"):
  350. ... validate({'two': 'three'})
  351. Validation function, in this case the "int" type:
  352. >>> validate = Schema({'one': 'two', 'three': 'four', int: str})
  353. Valid integer input:
  354. >>> validate({10: 'twenty'})
  355. {10: 'twenty'}
  356. An empty dictionary is matched as value:
  357. >>> validate = Schema({})
  358. >>> with raises(er.MultipleInvalid, 'not a valid value'):
  359. ... validate([])
  360. By default, a "type" in the schema (in this case "int") will be used
  361. purely to validate that the corresponding value is of that type. It
  362. will not Coerce the value:
  363. >>> validate = Schema({'one': 'two', 'three': 'four', int: str})
  364. >>> with raises(er.MultipleInvalid, "extra keys not allowed @ data['10']"):
  365. ... validate({'10': 'twenty'})
  366. Wrap them in the Coerce() function to achieve this:
  367. >>> from voluptuous import Coerce
  368. >>> validate = Schema({'one': 'two', 'three': 'four',
  369. ... Coerce(int): str})
  370. >>> validate({'10': 'twenty'})
  371. {10: 'twenty'}
  372. Custom message for required key
  373. >>> validate = Schema({Required('one', 'required'): 'two'})
  374. >>> with raises(er.MultipleInvalid, "required @ data['one']"):
  375. ... validate({})
  376. (This is to avoid unexpected surprises.)
  377. Multiple errors for nested field in a dict:
  378. >>> validate = Schema({
  379. ... 'adict': {
  380. ... 'strfield': str,
  381. ... 'intfield': int
  382. ... }
  383. ... })
  384. >>> try:
  385. ... validate({
  386. ... 'adict': {
  387. ... 'strfield': 123,
  388. ... 'intfield': 'one'
  389. ... }
  390. ... })
  391. ... except er.MultipleInvalid as e:
  392. ... print(sorted(str(i) for i in e.errors)) # doctest: +NORMALIZE_WHITESPACE
  393. ["expected int for dictionary value @ data['adict']['intfield']",
  394. "expected str for dictionary value @ data['adict']['strfield']"]
  395. """
  396. base_validate = self._compile_mapping(
  397. schema, invalid_msg='dictionary value')
  398. groups_of_exclusion = {}
  399. groups_of_inclusion = {}
  400. for node in schema:
  401. if isinstance(node, Exclusive):
  402. g = groups_of_exclusion.setdefault(node.group_of_exclusion, [])
  403. g.append(node)
  404. elif isinstance(node, Inclusive):
  405. g = groups_of_inclusion.setdefault(node.group_of_inclusion, [])
  406. g.append(node)
  407. def validate_dict(path, data):
  408. if not isinstance(data, dict):
  409. raise er.DictInvalid('expected a dictionary', path)
  410. errors = []
  411. for label, group in groups_of_exclusion.items():
  412. exists = False
  413. for exclusive in group:
  414. if exclusive.schema in data:
  415. if exists:
  416. msg = exclusive.msg if hasattr(exclusive, 'msg') and exclusive.msg else \
  417. "two or more values in the same group of exclusion '%s'" % label
  418. next_path = path + [VirtualPathComponent(label)]
  419. errors.append(er.ExclusiveInvalid(msg, next_path))
  420. break
  421. exists = True
  422. if errors:
  423. raise er.MultipleInvalid(errors)
  424. for label, group in groups_of_inclusion.items():
  425. included = [node.schema in data for node in group]
  426. if any(included) and not all(included):
  427. msg = "some but not all values in the same group of inclusion '%s'" % label
  428. for g in group:
  429. if hasattr(g, 'msg') and g.msg:
  430. msg = g.msg
  431. break
  432. next_path = path + [VirtualPathComponent(label)]
  433. errors.append(er.InclusiveInvalid(msg, next_path))
  434. break
  435. if errors:
  436. raise er.MultipleInvalid(errors)
  437. out = data.__class__()
  438. return base_validate(path, iteritems(data), out)
  439. return validate_dict
  440. def _compile_sequence(self, schema, seq_type):
  441. """Validate a sequence type.
  442. This is a sequence of valid values or validators tried in order.
  443. >>> validator = Schema(['one', 'two', int])
  444. >>> validator(['one'])
  445. ['one']
  446. >>> with raises(er.MultipleInvalid, 'expected int @ data[0]'):
  447. ... validator([3.5])
  448. >>> validator([1])
  449. [1]
  450. """
  451. _compiled = [self._compile(s) for s in schema]
  452. seq_type_name = seq_type.__name__
  453. def validate_sequence(path, data):
  454. if not isinstance(data, seq_type):
  455. raise er.SequenceTypeInvalid('expected a %s' % seq_type_name, path)
  456. # Empty seq schema, allow any data.
  457. if not schema:
  458. return data
  459. out = []
  460. invalid = None
  461. errors = []
  462. index_path = UNDEFINED
  463. for i, value in enumerate(data):
  464. index_path = path + [i]
  465. invalid = None
  466. for validate in _compiled:
  467. try:
  468. cval = validate(index_path, value)
  469. if cval is not Remove: # do not include Remove values
  470. out.append(cval)
  471. break
  472. except er.Invalid as e:
  473. if len(e.path) > len(index_path):
  474. raise
  475. invalid = e
  476. else:
  477. errors.append(invalid)
  478. if errors:
  479. raise er.MultipleInvalid(errors)
  480. if _isnamedtuple(data):
  481. return type(data)(*out)
  482. else:
  483. return type(data)(out)
  484. return validate_sequence
  485. def _compile_tuple(self, schema):
  486. """Validate a tuple.
  487. A tuple is a sequence of valid values or validators tried in order.
  488. >>> validator = Schema(('one', 'two', int))
  489. >>> validator(('one',))
  490. ('one',)
  491. >>> with raises(er.MultipleInvalid, 'expected int @ data[0]'):
  492. ... validator((3.5,))
  493. >>> validator((1,))
  494. (1,)
  495. """
  496. return self._compile_sequence(schema, tuple)
  497. def _compile_list(self, schema):
  498. """Validate a list.
  499. A list is a sequence of valid values or validators tried in order.
  500. >>> validator = Schema(['one', 'two', int])
  501. >>> validator(['one'])
  502. ['one']
  503. >>> with raises(er.MultipleInvalid, 'expected int @ data[0]'):
  504. ... validator([3.5])
  505. >>> validator([1])
  506. [1]
  507. """
  508. return self._compile_sequence(schema, list)
  509. def extend(self, schema, required=None, extra=None):
  510. """Create a new `Schema` by merging this and the provided `schema`.
  511. Neither this `Schema` nor the provided `schema` are modified. The
  512. resulting `Schema` inherits the `required` and `extra` parameters of
  513. this, unless overridden.
  514. Both schemas must be dictionary-based.
  515. :param schema: dictionary to extend this `Schema` with
  516. :param required: if set, overrides `required` of this `Schema`
  517. :param extra: if set, overrides `extra` of this `Schema`
  518. """
  519. assert type(self.schema) == dict and type(schema) == dict, 'Both schemas must be dictionary-based'
  520. result = self.schema.copy()
  521. # returns the key that may have been passed as arugment to Marker constructor
  522. def key_literal(key):
  523. return (key.schema if isinstance(key, Marker) else key)
  524. # build a map that takes the key literals to the needed objects
  525. # literal -> Required|Optional|literal
  526. result_key_map = dict((key_literal(key), key) for key in result)
  527. # for each item in the extension schema, replace duplicates
  528. # or add new keys
  529. for key, value in iteritems(schema):
  530. # if the key is already in the dictionary, we need to replace it
  531. # transform key to literal before checking presence
  532. if key_literal(key) in result_key_map:
  533. result_key = result_key_map[key_literal(key)]
  534. result_value = result[result_key]
  535. # if both are dictionaries, we need to extend recursively
  536. # create the new extended sub schema, then remove the old key and add the new one
  537. if type(result_value) == dict and type(value) == dict:
  538. new_value = Schema(result_value).extend(value).schema
  539. del result[result_key]
  540. result[key] = new_value
  541. # one or the other or both are not sub-schemas, simple replacement is fine
  542. # remove old key and add new one
  543. else:
  544. del result[result_key]
  545. result[key] = value
  546. # key is new and can simply be added
  547. else:
  548. result[key] = value
  549. # recompile and send old object
  550. result_required = (required if required is not None else self.required)
  551. result_extra = (extra if extra is not None else self.extra)
  552. return Schema(result, required=result_required, extra=result_extra)
  553. def _compile_scalar(schema):
  554. """A scalar value.
  555. The schema can either be a value or a type.
  556. >>> _compile_scalar(int)([], 1)
  557. 1
  558. >>> with raises(er.Invalid, 'expected float'):
  559. ... _compile_scalar(float)([], '1')
  560. Callables have
  561. >>> _compile_scalar(lambda v: float(v))([], '1')
  562. 1.0
  563. As a convenience, ValueError's are trapped:
  564. >>> with raises(er.Invalid, 'not a valid value'):
  565. ... _compile_scalar(lambda v: float(v))([], 'a')
  566. """
  567. if isinstance(schema, type):
  568. def validate_instance(path, data):
  569. if isinstance(data, schema):
  570. return data
  571. else:
  572. msg = 'expected %s' % schema.__name__
  573. raise er.TypeInvalid(msg, path)
  574. return validate_instance
  575. if callable(schema):
  576. def validate_callable(path, data):
  577. try:
  578. return schema(data)
  579. except ValueError as e:
  580. raise er.ValueInvalid('not a valid value', path)
  581. except er.Invalid as e:
  582. e.prepend(path)
  583. raise
  584. return validate_callable
  585. def validate_value(path, data):
  586. if data != schema:
  587. raise er.ScalarInvalid('not a valid value', path)
  588. return data
  589. return validate_value
  590. def _compile_itemsort():
  591. '''return sort function of mappings'''
  592. def is_extra(key_):
  593. return key_ is Extra
  594. def is_remove(key_):
  595. return isinstance(key_, Remove)
  596. def is_marker(key_):
  597. return isinstance(key_, Marker)
  598. def is_type(key_):
  599. return inspect.isclass(key_)
  600. def is_callable(key_):
  601. return callable(key_)
  602. # priority list for map sorting (in order of checking)
  603. # We want Extra to match last, because it's a catch-all. On the other hand,
  604. # Remove markers should match first (since invalid values will not
  605. # raise an Error, instead the validator will check if other schemas match
  606. # the same value).
  607. priority = [(1, is_remove), # Remove highest priority after values
  608. (2, is_marker), # then other Markers
  609. (4, is_type), # types/classes lowest before Extra
  610. (3, is_callable), # callables after markers
  611. (5, is_extra)] # Extra lowest priority
  612. def item_priority(item_):
  613. key_ = item_[0]
  614. for i, check_ in priority:
  615. if check_(key_):
  616. return i
  617. # values have hightest priorities
  618. return 0
  619. return item_priority
  620. _sort_item = _compile_itemsort()
  621. def _iterate_mapping_candidates(schema):
  622. """Iterate over schema in a meaningful order."""
  623. # Without this, Extra might appear first in the iterator, and fail to
  624. # validate a key even though it's a Required that has its own validation,
  625. # generating a false positive.
  626. return sorted(iteritems(schema), key=_sort_item)
  627. def _iterate_object(obj):
  628. """Return iterator over object attributes. Respect objects with
  629. defined __slots__.
  630. """
  631. d = {}
  632. try:
  633. d = vars(obj)
  634. except TypeError:
  635. # maybe we have named tuple here?
  636. if hasattr(obj, '_asdict'):
  637. d = obj._asdict()
  638. for item in iteritems(d):
  639. yield item
  640. try:
  641. slots = obj.__slots__
  642. except AttributeError:
  643. pass
  644. else:
  645. for key in slots:
  646. if key != '__dict__':
  647. yield (key, getattr(obj, key))
  648. raise StopIteration()
  649. class Msg(object):
  650. """Report a user-friendly message if a schema fails to validate.
  651. >>> validate = Schema(
  652. ... Msg(['one', 'two', int],
  653. ... 'should be one of "one", "two" or an integer'))
  654. >>> with raises(er.MultipleInvalid, 'should be one of "one", "two" or an integer'):
  655. ... validate(['three'])
  656. Messages are only applied to invalid direct descendants of the schema:
  657. >>> validate = Schema(Msg([['one', 'two', int]], 'not okay!'))
  658. >>> with raises(er.MultipleInvalid, 'expected int @ data[0][0]'):
  659. ... validate([['three']])
  660. The type which is thrown can be overridden but needs to be a subclass of Invalid
  661. >>> with raises(er.SchemaError, 'Msg can only use subclases of Invalid as custom class'):
  662. ... validate = Schema(Msg([int], 'should be int', cls=KeyError))
  663. If you do use a subclass of Invalid, that error will be thrown (wrapped in a MultipleInvalid)
  664. >>> validate = Schema(Msg([['one', 'two', int]], 'not okay!', cls=er.RangeInvalid))
  665. >>> try:
  666. ... validate(['three'])
  667. ... except er.MultipleInvalid as e:
  668. ... assert isinstance(e.errors[0], er.RangeInvalid)
  669. """
  670. def __init__(self, schema, msg, cls=None):
  671. if cls and not issubclass(cls, er.Invalid):
  672. raise er.SchemaError("Msg can only use subclases of"
  673. " Invalid as custom class")
  674. self._schema = schema
  675. self.schema = Schema(schema)
  676. self.msg = msg
  677. self.cls = cls
  678. def __call__(self, v):
  679. try:
  680. return self.schema(v)
  681. except er.Invalid as e:
  682. if len(e.path) > 1:
  683. raise e
  684. else:
  685. raise (self.cls or er.Invalid)(self.msg)
  686. def __repr__(self):
  687. return 'Msg(%s, %s, cls=%s)' % (self._schema, self.msg, self.cls)
  688. class Object(dict):
  689. """Indicate that we should work with attributes, not keys."""
  690. def __init__(self, schema, cls=UNDEFINED):
  691. self.cls = cls
  692. super(Object, self).__init__(schema)
  693. class VirtualPathComponent(str):
  694. def __str__(self):
  695. return '<' + self + '>'
  696. def __repr__(self):
  697. return self.__str__()
  698. # Markers.py
  699. class Marker(object):
  700. """Mark nodes for special treatment."""
  701. def __init__(self, schema_, msg=None):
  702. self.schema = schema_
  703. self._schema = Schema(schema_)
  704. self.msg = msg
  705. def __call__(self, v):
  706. try:
  707. return self._schema(v)
  708. except er.Invalid as e:
  709. if not self.msg or len(e.path) > 1:
  710. raise
  711. raise er.Invalid(self.msg)
  712. def __str__(self):
  713. return str(self.schema)
  714. def __repr__(self):
  715. return repr(self.schema)
  716. def __lt__(self, other):
  717. return self.schema < other.schema
  718. def __hash__(self):
  719. return hash(self.schema)
  720. def __eq__(self, other):
  721. return self.schema == other
  722. def __ne__(self, other):
  723. return not(self.schema == other)
  724. class Optional(Marker):
  725. """Mark a node in the schema as optional, and optionally provide a default
  726. >>> schema = Schema({Optional('key'): str})
  727. >>> schema({})
  728. {}
  729. >>> schema = Schema({Optional('key', default='value'): str})
  730. >>> schema({})
  731. {'key': 'value'}
  732. >>> schema = Schema({Optional('key', default=list): list})
  733. >>> schema({})
  734. {'key': []}
  735. If 'required' flag is set for an entire schema, optional keys aren't required
  736. >>> schema = Schema({
  737. ... Optional('key'): str,
  738. ... 'key2': str
  739. ... }, required=True)
  740. >>> schema({'key2':'value'})
  741. {'key2': 'value'}
  742. """
  743. def __init__(self, schema, msg=None, default=UNDEFINED):
  744. super(Optional, self).__init__(schema, msg=msg)
  745. self.default = default_factory(default)
  746. class Exclusive(Optional):
  747. """Mark a node in the schema as exclusive.
  748. Exclusive keys inherited from Optional:
  749. >>> schema = Schema({Exclusive('alpha', 'angles'): int, Exclusive('beta', 'angles'): int})
  750. >>> schema({'alpha': 30})
  751. {'alpha': 30}
  752. Keys inside a same group of exclusion cannot be together, it only makes sense for dictionaries:
  753. >>> with raises(er.MultipleInvalid, "two or more values in the same group of exclusion 'angles' @ data[<angles>]"):
  754. ... schema({'alpha': 30, 'beta': 45})
  755. For example, API can provides multiple types of authentication, but only one works in the same time:
  756. >>> msg = 'Please, use only one type of authentication at the same time.'
  757. >>> schema = Schema({
  758. ... Exclusive('classic', 'auth', msg=msg):{
  759. ... Required('email'): basestring,
  760. ... Required('password'): basestring
  761. ... },
  762. ... Exclusive('internal', 'auth', msg=msg):{
  763. ... Required('secret_key'): basestring
  764. ... },
  765. ... Exclusive('social', 'auth', msg=msg):{
  766. ... Required('social_network'): basestring,
  767. ... Required('token'): basestring
  768. ... }
  769. ... })
  770. >>> with raises(er.MultipleInvalid, "Please, use only one type of authentication at the same time. @ data[<auth>]"):
  771. ... schema({'classic': {'email': 'foo@example.com', 'password': 'bar'},
  772. ... 'social': {'social_network': 'barfoo', 'token': 'tEMp'}})
  773. """
  774. def __init__(self, schema, group_of_exclusion, msg=None):
  775. super(Exclusive, self).__init__(schema, msg=msg)
  776. self.group_of_exclusion = group_of_exclusion
  777. class Inclusive(Optional):
  778. """ Mark a node in the schema as inclusive.
  779. Inclusive keys inherited from Optional:
  780. >>> schema = Schema({
  781. ... Inclusive('filename', 'file'): str,
  782. ... Inclusive('mimetype', 'file'): str
  783. ... })
  784. >>> data = {'filename': 'dog.jpg', 'mimetype': 'image/jpeg'}
  785. >>> data == schema(data)
  786. True
  787. Keys inside a same group of inclusive must exist together, it only makes sense for dictionaries:
  788. >>> with raises(er.MultipleInvalid, "some but not all values in the same group of inclusion 'file' @ data[<file>]"):
  789. ... schema({'filename': 'dog.jpg'})
  790. If none of the keys in the group are present, it is accepted:
  791. >>> schema({})
  792. {}
  793. For example, API can return 'height' and 'width' together, but not separately.
  794. >>> msg = "Height and width must exist together"
  795. >>> schema = Schema({
  796. ... Inclusive('height', 'size', msg=msg): int,
  797. ... Inclusive('width', 'size', msg=msg): int
  798. ... })
  799. >>> with raises(er.MultipleInvalid, msg + " @ data[<size>]"):
  800. ... schema({'height': 100})
  801. >>> with raises(er.MultipleInvalid, msg + " @ data[<size>]"):
  802. ... schema({'width': 100})
  803. >>> data = {'height': 100, 'width': 100}
  804. >>> data == schema(data)
  805. True
  806. """
  807. def __init__(self, schema, group_of_inclusion, msg=None):
  808. super(Inclusive, self).__init__(schema, msg=msg)
  809. self.group_of_inclusion = group_of_inclusion
  810. class Required(Marker):
  811. """Mark a node in the schema as being required, and optionally provide a default value.
  812. >>> schema = Schema({Required('key'): str})
  813. >>> with raises(er.MultipleInvalid, "required key not provided @ data['key']"):
  814. ... schema({})
  815. >>> schema = Schema({Required('key', default='value'): str})
  816. >>> schema({})
  817. {'key': 'value'}
  818. >>> schema = Schema({Required('key', default=list): list})
  819. >>> schema({})
  820. {'key': []}
  821. """
  822. def __init__(self, schema, msg=None, default=UNDEFINED):
  823. super(Required, self).__init__(schema, msg=msg)
  824. self.default = default_factory(default)
  825. class Remove(Marker):
  826. """Mark a node in the schema to be removed and excluded from the validated
  827. output. Keys that fail validation will not raise ``Invalid``. Instead, these
  828. keys will be treated as extras.
  829. >>> schema = Schema({str: int, Remove(int): str})
  830. >>> with raises(er.MultipleInvalid, "extra keys not allowed @ data[1]"):
  831. ... schema({'keep': 1, 1: 1.0})
  832. >>> schema({1: 'red', 'red': 1, 2: 'green'})
  833. {'red': 1}
  834. >>> schema = Schema([int, Remove(float), Extra])
  835. >>> schema([1, 2, 3, 4.0, 5, 6.0, '7'])
  836. [1, 2, 3, 5, '7']
  837. """
  838. def __call__(self, v):
  839. super(Remove, self).__call__(v)
  840. return self.__class__
  841. def __repr__(self):
  842. return "Remove(%r)" % (self.schema,)
  843. def __hash__(self):
  844. return object.__hash__(self)
  845. def message(default=None, cls=None):
  846. """Convenience decorator to allow functions to provide a message.
  847. Set a default message:
  848. >>> @message('not an integer')
  849. ... def isint(v):
  850. ... return int(v)
  851. >>> validate = Schema(isint())
  852. >>> with raises(er.MultipleInvalid, 'not an integer'):
  853. ... validate('a')
  854. The message can be overridden on a per validator basis:
  855. >>> validate = Schema(isint('bad'))
  856. >>> with raises(er.MultipleInvalid, 'bad'):
  857. ... validate('a')
  858. The class thrown too:
  859. >>> class IntegerInvalid(er.Invalid): pass
  860. >>> validate = Schema(isint('bad', clsoverride=IntegerInvalid))
  861. >>> try:
  862. ... validate('a')
  863. ... except er.MultipleInvalid as e:
  864. ... assert isinstance(e.errors[0], IntegerInvalid)
  865. """
  866. if cls and not issubclass(cls, er.Invalid):
  867. raise er.SchemaError("message can only use subclases of Invalid as custom class")
  868. def decorator(f):
  869. @wraps(f)
  870. def check(msg=None, clsoverride=None):
  871. @wraps(f)
  872. def wrapper(*args, **kwargs):
  873. try:
  874. return f(*args, **kwargs)
  875. except ValueError:
  876. raise (clsoverride or cls or er.ValueInvalid)(msg or default or 'invalid value')
  877. return wrapper
  878. return check
  879. return decorator
  880. def _args_to_dict(func, args):
  881. """Returns argument names as values as key-value pairs."""
  882. if sys.version_info >= (3, 0):
  883. arg_count = func.__code__.co_argcount
  884. arg_names = func.__code__.co_varnames[:arg_count]
  885. else:
  886. arg_count = func.func_code.co_argcount
  887. arg_names = func.func_code.co_varnames[:arg_count]
  888. arg_value_list = list(args)
  889. arguments = dict((arg_name, arg_value_list[i])
  890. for i, arg_name in enumerate(arg_names)
  891. if i < len(arg_value_list))
  892. return arguments
  893. def _merge_args_with_kwargs(args_dict, kwargs_dict):
  894. """Merge args with kwargs."""
  895. ret = args_dict.copy()
  896. ret.update(kwargs_dict)
  897. return ret
  898. def validate(*a, **kw):
  899. """Decorator for validating arguments of a function against a given schema.
  900. Set restrictions for arguments:
  901. >>> @validate(arg1=int, arg2=int)
  902. ... def foo(arg1, arg2):
  903. ... return arg1 * arg2
  904. Set restriction for returned value:
  905. >>> @validate(arg=int, __return__=int)
  906. ... def bar(arg1):
  907. ... return arg1 * 2
  908. """
  909. RETURNS_KEY = '__return__'
  910. def validate_schema_decorator(func):
  911. returns_defined = False
  912. returns = None
  913. schema_args_dict = _args_to_dict(func, a)
  914. schema_arguments = _merge_args_with_kwargs(schema_args_dict, kw)
  915. if RETURNS_KEY in schema_arguments:
  916. returns_defined = True
  917. returns = schema_arguments[RETURNS_KEY]
  918. del schema_arguments[RETURNS_KEY]
  919. input_schema = Schema(schema_arguments) if len(schema_arguments) != 0 else lambda x: x
  920. output_schema = Schema(returns) if returns_defined else lambda x: x
  921. @wraps(func)
  922. def func_wrapper(*args, **kwargs):
  923. args_dict = _args_to_dict(func, args)
  924. arguments = _merge_args_with_kwargs(args_dict, kwargs)
  925. validated_arguments = input_schema(arguments)
  926. output = func(**validated_arguments)
  927. return output_schema(output)
  928. return func_wrapper
  929. return validate_schema_decorator