Skip to content

Commit

Permalink
Add a strict mode to Integer
Browse files Browse the repository at this point in the history
This would disallow float's from being accepted and truncated
  • Loading branch information
digitalresistor committed Feb 1, 2019
1 parent 1c3bd63 commit 08c95b8
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
12 changes: 12 additions & 0 deletions colander/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1432,6 +1432,18 @@ class Integer(Number):

num = int

def __init__(self, strict=False):
if strict:

def _strict_int(val):
if not float(val).is_integer():
raise ValueError("Value is not an Integer")
return int(val)

self.num = _strict_int

super(Integer, self).__init__()


Int = Integer

Expand Down
32 changes: 30 additions & 2 deletions colander/tests/test_colander.py
Original file line number Diff line number Diff line change
Expand Up @@ -1730,10 +1730,10 @@ def test_serialize_encoding_with_non_string_type(self):


class TestInteger(unittest.TestCase):
def _makeOne(self):
def _makeOne(self, strict=False):
from colander import Integer

return Integer()
return Integer(strict=strict)

def test_alias(self):
from colander import Int
Expand Down Expand Up @@ -1802,6 +1802,34 @@ def test_serialize_zero(self):
result = typ.serialize(node, val)
self.assertEqual(result, '0')

def test_serialize_strict_float(self):
val = 1.2
node = DummySchemaNode(None)
typ = self._makeOne(strict=True)
e = invalid_exc(typ.serialize, node, val)
self.assertTrue(e.msg)

def test_serialize_strict_int(self):
val = 1
node = DummySchemaNode(None)
typ = self._makeOne(strict=True)
result = typ.serialize(node, val)
self.assertEqual(result, '1')

def test_deserialize_strict(self):
val = '58'
node = DummySchemaNode(None)
typ = self._makeOne(strict=True)
result = typ.deserialize(node, val)
self.assertEqual(result, 58)

def test_serialize_truncates(self):
val = 1.4
node = DummySchemaNode(None)
typ = self._makeOne(strict=False)
result = typ.serialize(node, val)
self.assertEqual(result, '1')


class TestFloat(unittest.TestCase):
def _makeOne(self):
Expand Down

0 comments on commit 08c95b8

Please sign in to comment.