You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1292 lines
42 KiB

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