Skip to content

Commit

Permalink
Add PositiveIntegerValue to only allow positive integers (#186)
Browse files Browse the repository at this point in the history
  • Loading branch information
MikeWooster authored and blueyed committed Mar 15, 2018
1 parent 3883cc4 commit 1c6fd0f
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
9 changes: 9 additions & 0 deletions configurations/values.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,15 @@ class IntegerValue(CastingMixin, Value):
caster = int


class PositiveIntegerValue(IntegerValue):

def to_python(self, value):
int_value = super(PositiveIntegerValue, self).to_python(value)
if int_value < 0:
raise ValueError(self.message.format(value))
return int_value


class FloatValue(CastingMixin, Value):
caster = float

Expand Down
8 changes: 8 additions & 0 deletions docs/values.rst
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,14 @@ Type values

MYSITE_CACHE_TIMEOUT = values.IntegerValue(3600)

.. class:: PositiveIntegerValue

A :class:`~Value` subclass that handles positive integer values.

::

MYSITE_WORKER_POOL = values.PositiveIntegerValue(8)

This comment has been minimized.

Copy link
@jezdez

jezdez Jul 11, 2018

Member

@blueyed Please add .. versionadded:: 2.1 here so we can track it in the docs.

This comment has been minimized.

Copy link
@blueyed

blueyed Jul 11, 2018

Contributor

@jezdez
Done in b1d92cf.

.. class:: FloatValue

A :class:`~Value` subclass that handles float values.
Expand Down
11 changes: 10 additions & 1 deletion tests/test_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
DatabaseURLValue, EmailURLValue,
CacheURLValue, BackendsValue,
CastingMixin, SearchURLValue,
setup_value)
setup_value, PositiveIntegerValue)


@contextmanager
Expand Down Expand Up @@ -136,6 +136,15 @@ def test_integer_values(self):
with env(DJANGO_TEST='noninteger'):
self.assertRaises(ValueError, value.setup, 'TEST')

def test_positive_integer_values(self):
value = PositiveIntegerValue(1)
with env(DJANGO_TEST='2'):
self.assertEqual(value.setup('TEST'), 2)
with env(DJANGO_TEST='noninteger'):
self.assertRaises(ValueError, value.setup, 'TEST')
with env(DJANGO_TEST='-1'):
self.assertRaises(ValueError, value.setup, 'TEST')

def test_float_values(self):
value = FloatValue(1.0)
with env(DJANGO_TEST='2.0'):
Expand Down

0 comments on commit 1c6fd0f

Please sign in to comment.