summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorLaurent Bachelier <laurent@bachelier.name>2011-06-10 23:17:14 +0200
committerLaurent Bachelier <laurent@bachelier.name>2011-06-10 23:17:14 +0200
commitb69a0a9b978f4a882def881dabdff81a9223a3ab (patch)
tree3bd1a7c72191642397335d53a5a678051c3772fa
parentFix vocabulary (diff)
downloadffs-b69a0a9b978f4a882def881dabdff81a9223a3ab.tar.xz
Support setting dictionaries
-rw-r--r--ffs.py32
-rw-r--r--test.py18
2 files changed, 39 insertions, 11 deletions
diff --git a/ffs.py b/ffs.py
index 96aab9d..21940a9 100644
--- a/ffs.py
+++ b/ffs.py
@@ -55,8 +55,9 @@ class Dict(MutableMapping):
raise KeyError(key)
return cls
- def _is_dict(self, cls):
- return isinstance(cls, Router)
+ def _is_dict(self, cls, allow_std=False):
+ classes = (Router, dict) if allow_std else Router
+ return isinstance(cls, classes)
def _get_path(self, key):
return os.path.join(self.root, key)
@@ -72,16 +73,25 @@ class Dict(MutableMapping):
cls = self.router.route(key)
if cls is None:
raise RouterError(key)
- if not isinstance(value, cls):
- raise ValueError("%s is not a %s." % (repr(value), cls.__name__))
- if hasattr(cls, 'tostring'):
- data = value.tostring()
- elif isinstance(value, basestring):
- data = value
+ if self._is_dict(cls) and self._is_dict(value, True):
+ if key in self:
+ del self[key]
+ os.mkdir(self._get_path(key))
+ if len(value):
+ lst = self[key]
+ for k, v in value.iteritems():
+ lst[k] = v
else:
- raise ValueError("Unable to convert %s to a string." % repr(value))
- with open(self._get_path(key), 'wb') as f:
- f.write(data)
+ if not isinstance(value, cls):
+ raise ValueError("%s is not a %s." % (repr(value), cls.__name__))
+ if hasattr(cls, 'tostring'):
+ data = value.tostring()
+ elif isinstance(value, basestring):
+ data = value
+ else:
+ raise ValueError("Unable to convert %s to a string." % repr(value))
+ with open(self._get_path(key), 'wb') as f:
+ f.write(data)
def keys(self):
return [f for f in os.listdir(self.root) if self.router.route(f)]
diff --git a/test.py b/test.py
index 32c68c9..1d3560e 100644
--- a/test.py
+++ b/test.py
@@ -76,3 +76,21 @@ class FfsTest(TestCase):
assert 'lol' in lst1
del lst1['lol']
assert 'lol' not in lst1
+
+ def test_listSet(self):
+ rtr = Router(lulz=Router(cat=str))
+ lst1 = Dict(self.root, rtr)
+ assert 'lulz' not in lst1
+ lst1['lulz'] = {}
+ assert len(lst1['lulz']) == 0
+ assert isinstance(lst1['lulz'], Dict)
+ lst1['lulz'] = {'cat': "hello"}
+ assert len(lst1['lulz']) == 1
+ assert isinstance(lst1['lulz'], Dict)
+
+ lst1n = Dict(self.root, rtr)
+ assert lst1n['lulz']['cat'] == "hello"
+
+ lst1n['lulz'] = {}
+ assert 'cat' not in lst1['lulz']
+ assert 'cat' not in lst1n['lulz']