diff options
| author | Alec Thomas <alec@swapoff.org> | 2011-08-14 15:52:53 -0700 |
|---|---|---|
| committer | Alec Thomas <alec@swapoff.org> | 2011-08-14 15:52:53 -0700 |
| commit | 5c3ef8b5f838aa8c86507ce937b3f1ec8a38373a (patch) | |
| tree | 726a7b3e3bdd2680910d8f50929feb04b7b577cb | |
| parent | fcc144ab7342bd6bb7c3382d855a3c0772a97e5d (diff) | |
| parent | e71af67202598126cc54a9baaeb42fd632bfaba8 (diff) | |
| download | voluptuous-5c3ef8b5f838aa8c86507ce937b3f1ec8a38373a.tar.gz | |
Merge pull request #2 from kjkuan/master
dict and list as type validators; validation returns the correct type of instance.
| -rw-r--r-- | tests.rst | 29 | ||||
| -rw-r--r-- | voluptuous.py | 16 |
2 files changed, 37 insertions, 8 deletions
@@ -51,3 +51,32 @@ Voluptuous supports validation when extra fields are present in the data:: Traceback (most recent call last): ... Invalid: not a valid value for dictionary key @ data['two'] + + +dict and list should be available as type validators:: + + >>> Schema(dict)({'a': 1, 'b': 2}) + {'a': 1, 'b': 2} + >>> Schema(list)([1,2,3]) + [1, 2, 3] + + +validation should return instances of the right types when the types are +subclasses of dict or list:: + + >>> class Dict(dict): + ... pass + >>> + >>> d = Schema(dict)(Dict(a=1, b=2)) + >>> d + {'a': 1, 'b': 2} + >>> type(d) is Dict + True + >>> class List(list): + ... pass + >>> + >>> l = Schema(list)(List([1,2,3])) + >>> l + [1, 2, 3] + >>> type(l) is List + True diff --git a/voluptuous.py b/voluptuous.py index be450a8..20da1a1 100644 --- a/voluptuous.py +++ b/voluptuous.py @@ -160,15 +160,15 @@ class Schema(object): return self.validate([], self.schema, data) def validate(self, path, schema, data): + if isinstance(schema, dict): + return self.validate_dict(path, schema, data) + elif isinstance(schema, list): + return self.validate_list(path, schema, data) type_ = type(schema) if type_ is type: type_ = schema - if type_ is dict: - return self.validate_dict(path, schema, data) - elif type_ is list: - return self.validate_list(path, schema, data) - elif type_ in (int, long, str, unicode, float, complex, object, - types.NoneType) or callable(schema): + if type_ in (int, long, str, unicode, float, complex, object, + list, dict, types.NoneType) or callable(schema): return self.validate_scalar(path, schema, data) raise SchemaError('unsupported schema data type %r' % type(schema).__name__) @@ -232,7 +232,7 @@ class Schema(object): if not isinstance(data, dict): raise Invalid('expected a dictionary', path) - out = {} + out = type(data)() required_keys = set(key for key in schema if (self.required and not isinstance(key, optional)) @@ -309,7 +309,7 @@ class Schema(object): if not schema: return data - out = [] + out = type(data)() invalid = None index_path = UNDEFINED for i, value in enumerate(data): |
