Add a float type.

This commit is contained in:
Chris McDonough
2010-03-14 00:57:25 +00:00
parent 38506e574c
commit fa45df514b
5 changed files with 62 additions and 4 deletions

View File

@@ -370,6 +370,26 @@ class Integer(object):
Int = Integer
class Float(object):
""" A type representing a float.
The substructures of the :class:`cereal.Structure` that wraps this
type are ignored.
"""
def deserialize(self, struct, value):
try:
return float(value)
except Exception:
raise Invalid(struct, '%r is not a number' % value)
def serialize(self, struct, value):
try:
return str(float(value))
except Exception:
raise Invalid(struct, '%r is not a number' % value)
Int = Integer
class Boolean(object):
""" A type representing a boolean object.

View File

@@ -565,6 +565,39 @@ class TestInteger(unittest.TestCase):
result = typ.serialize(struct, val)
self.assertEqual(result, '1')
class TestFloat(unittest.TestCase):
def _makeOne(self):
from cereal import Float
return Float()
def test_deserialize_fails(self):
val = 'P'
struct = DummyStructure(None)
typ = self._makeOne()
e = invalid_exc(typ.deserialize, struct, val)
self.failUnless(e.msg)
def test_deserialize_ok(self):
val = '1.0'
struct = DummyStructure(None)
typ = self._makeOne()
result = typ.deserialize(struct, val)
self.assertEqual(result, 1.0)
def test_serialize_fails(self):
val = 'P'
struct = DummyStructure(None)
typ = self._makeOne()
e = invalid_exc(typ.serialize, struct, val)
self.failUnless(e.msg)
def test_serialize_ok(self):
val = 1.0
struct = DummyStructure(None)
typ = self._makeOne()
result = typ.serialize(struct, val)
self.assertEqual(result, '1.0')
class TestBoolean(unittest.TestCase):
def _makeOne(self):
from cereal import Boolean

View File

@@ -37,6 +37,8 @@ Types
.. autoclass:: Int
.. autoclass:: Float
.. autoclass:: Boolean
.. autoclass:: Bool

View File

@@ -29,7 +29,9 @@ objects, including:
- An integer.
- A boolean value.
- A float.
- A boolean.
- An importable Python object (to a dotted Python object path).

View File

@@ -25,16 +25,17 @@ requires = []
setup(name='cereal',
version='0.0',
description='A schema-based serialization and deserialization library',
description=('A simple schema-based serialization and deserialization '
'library'),
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Intended Audience :: Developers",
"Programming Language :: Python",
],
keywords='serialize deserialize validate schema',
keywords='serialize deserialize validate schema validation',
author="Agendaless Consulting",
author_email="repoze-dev@lists.repoze.org",
url="http://www.repoze.org",
url="http://docs.repoze.org/cereal",
license="BSD-derived (http://www.repoze.org/LICENSE.txt)",
packages=find_packages(),
include_package_data=True,