summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorLaurent Bachelier <laurent@bachelier.name>2011-12-21 12:27:59 +0100
committerLaurent Bachelier <laurent@bachelier.name>2011-12-21 12:28:17 +0100
commite6dcc8e4e34ae8f2edad47ddc10fc3065788394f (patch)
tree5a6a180808824d5d9e498f168be3fdb7aac77072
parentSafeguards (diff)
downloadffs-e6dcc8e4e34ae8f2edad47ddc10fc3065788394f.tar.xz
Add support for integers
-rw-r--r--ffs.py10
-rw-r--r--test.py14
2 files changed, 24 insertions, 0 deletions
diff --git a/ffs.py b/ffs.py
index 7f57dbe..f420473 100644
--- a/ffs.py
+++ b/ffs.py
@@ -44,8 +44,13 @@ class Dict(MutableMapping):
else:
with open(self._get_path(key), 'rb') as f:
data = f.read()
+ # it's already the class
+ if isinstance(data, cls):
+ return data
+ # lots of classes seem to have this method
if hasattr(cls, 'fromstring'):
return cls.fromstring(data)
+ # works for int, for instance
return cls(data)
def _get_cls(self, key):
@@ -81,10 +86,15 @@ class Dict(MutableMapping):
else:
if not isinstance(value, cls):
raise ValueError("%s is not a %s." % (repr(value), cls.__name__))
+ # lots of classes have this method. usually does not lose information
if hasattr(cls, 'tostring'):
data = value.tostring()
+ # no need for conversion
elif isinstance(value, basestring):
data = value
+ # whitelist of classes with a __str__ that do not lose information
+ elif isinstance(value, (int, long)):
+ data = str(value)
else:
raise ValueError("Unable to convert %s to a string." % repr(value))
with open(self._get_path(key), 'wb') as f:
diff --git a/test.py b/test.py
index 15b3aac..e58da08 100644
--- a/test.py
+++ b/test.py
@@ -101,3 +101,17 @@ class FfsTest(TestCase):
lst1['lulz'] = lst1['lol']
assert 'cat' in lst1['lulz']
assert lst1['lulz']['cat'] == "hello"
+
+ def test_intTypeConv(self):
+ lst1 = Dict(self.root, Router(lulz=int))
+ assert 'lulz' not in lst1
+ lst1['lulz'] = 42
+ assert lst1['lulz'] == 42
+ assert isinstance(lst1['lulz'], int)
+ lst1['lulz'] += 1
+ assert lst1['lulz'] == 43
+ assert isinstance(lst1['lulz'], int)
+
+ lst2 = Dict(self.root, Router(lulz=str))
+ assert lst2['lulz'] == "43"
+ assert isinstance(lst2['lulz'], basestring)