Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle incomparable values in Range #414

Merged
merged 2 commits into from
Nov 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions voluptuous/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,19 @@ def test_range_exlcudes_nan():
assert_raises(MultipleInvalid, s, float('nan'))


def test_range_excludes_none():
s = Schema(Range(min=0, max=10))
assert_raises(MultipleInvalid, s, None)


def test_range_excludes_unordered_object():
class MyObject(object):
pass

s = Schema(Range(min=0, max=10))
assert_raises(MultipleInvalid, s, MyObject())


def test_equal():
s = Schema(Equal(1))
s(1)
Expand Down
41 changes: 24 additions & 17 deletions voluptuous/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -585,23 +585,30 @@ def __init__(self, min=None, max=None, min_included=True,
self.msg = msg

def __call__(self, v):
if self.min_included:
if self.min is not None and not v >= self.min:
raise RangeInvalid(
self.msg or 'value must be at least %s' % self.min)
else:
if self.min is not None and not v > self.min:
raise RangeInvalid(
self.msg or 'value must be higher than %s' % self.min)
if self.max_included:
if self.max is not None and not v <= self.max:
raise RangeInvalid(
self.msg or 'value must be at most %s' % self.max)
else:
if self.max is not None and not v < self.max:
raise RangeInvalid(
self.msg or 'value must be lower than %s' % self.max)
return v
try:
if self.min_included:
if self.min is not None and not v >= self.min:
raise RangeInvalid(
self.msg or 'value must be at least %s' % self.min)
else:
if self.min is not None and not v > self.min:
raise RangeInvalid(
self.msg or 'value must be higher than %s' % self.min)
if self.max_included:
if self.max is not None and not v <= self.max:
raise RangeInvalid(
self.msg or 'value must be at most %s' % self.max)
else:
if self.max is not None and not v < self.max:
raise RangeInvalid(
self.msg or 'value must be lower than %s' % self.max)

return v

# Objects that lack a partial ordering, e.g. None will raise TypeError
except TypeError:
raise RangeInvalid(
self.msg or 'value must have a partial ordering')

def __repr__(self):
return ('Range(min=%r, max=%r, min_included=%r,'
Expand Down