From d9f7e0e818556c6072062755f51f0b397e2b8b7b Mon Sep 17 00:00:00 2001 From: Valentin Lorentz Date: Sat, 8 Dec 2012 21:13:54 +0100 Subject: [PATCH] Add editable() method to registry.Json. --- src/registry.py | 14 ++++++++++++++ test/test_registry.py | 10 ++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/registry.py b/src/registry.py index abd074176..a6ada7b1a 100644 --- a/src/registry.py +++ b/src/registry.py @@ -686,4 +686,18 @@ class Json(String): def __call__(self): return json.loads(super(Json, self).__call__()) + class _Context: + def __init__(self, var): + self._var = var + def __enter__(self): + self._dict = self._var() + return self._dict + def __exit__(self, *args): + self._var.setValue(self._dict) + + def editable(self): + """Return an editable dict usable within a 'with' statement and + committed to the configuration variable at the end.""" + return self._Context(self) + # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: diff --git a/test/test_registry.py b/test/test_registry.py index 9e8bafb85..fb43c5572 100644 --- a/test/test_registry.py +++ b/test/test_registry.py @@ -138,6 +138,16 @@ class ValuesTestCase(SupyTestCase): self.assertEqual(v(), data) self.assertIsNot(v(), data) + with v.editable() as dict_: + dict_['supy'] = 'bot' + del dict_['qux'] + self.assertNotIn('supy', v()) + self.assertIn('qux', v()) + self.assertIn('supy', v()) + self.assertEqual(v()['supy'], 'bot') + self.assertIsNot(v()['supy'], 'bot') + self.assertNotIn('qux', v()) + def testNormalizedString(self): v = registry.NormalizedString("""foo bar baz