Skip to content

Commit

Permalink
Better old-style class support
Browse files Browse the repository at this point in the history
  • Loading branch information
ngaya-ll committed Apr 14, 2017
1 parent 2a690a8 commit a404944
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
4 changes: 2 additions & 2 deletions voluptuous/schema_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ def _compile(self, schema):
elif isinstance(schema, tuple):
return self._compile_tuple(schema)
type_ = type(schema)
if type_ is type:
if inspect.isclass(schema):
type_ = schema
if type_ in (bool, bytes, int, long, str, unicode, float, complex, object,
list, dict, type(None)) or callable(schema):
Expand Down Expand Up @@ -700,7 +700,7 @@ def _compile_scalar(schema):
>>> with raises(er.Invalid, 'not a valid value'):
... _compile_scalar(lambda v: float(v))([], 'a')
"""
if isinstance(schema, type):
if inspect.isclass(schema):
def validate_instance(path, data):
if isinstance(data, schema):
return data
Expand Down
35 changes: 34 additions & 1 deletion voluptuous/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from voluptuous import (
Schema, Required, Optional, Extra, Invalid, In, Remove, Literal,
Url, MultipleInvalid, LiteralInvalid, NotIn, Match, Email,
Url, MultipleInvalid, LiteralInvalid, TypeInvalid, NotIn, Match, Email,
Replace, Range, Coerce, All, Any, Length, FqdnUrl, ALLOW_EXTRA, PREVENT_EXTRA,
validate, ExactSequence, Equal, Unordered, Number, Maybe, Datetime, Date,
Contains, Marker)
Expand Down Expand Up @@ -153,6 +153,39 @@ def test_literal():
assert False, "Did not raise Invalid"


def test_class():
class C1(object):
pass

schema = Schema(C1)
schema(C1())

try:
schema(None)
except MultipleInvalid as e:
assert_equal(str(e), "expected C1")
assert_equal(len(e.errors), 1)
assert_equal(type(e.errors[0]), TypeInvalid)
else:
assert False, "Did not raise Invalid"

# In Python 2, this will be an old-style class (classobj instance)
class C2:
pass

schema = Schema(C2)
schema(C2())

try:
schema(None)
except MultipleInvalid as e:
assert_equal(str(e), "expected C2")
assert_equal(len(e.errors), 1)
assert_equal(type(e.errors[0]), TypeInvalid)
else:
assert False, "Did not raise Invalid"


def test_email_validation():
""" test with valid email """
schema = Schema({"email": Email()})
Expand Down

0 comments on commit a404944

Please sign in to comment.