diff --git a/tests/test_store.py b/tests/test_store.py new file mode 100644 index 0000000..70225d0 --- /dev/null +++ b/tests/test_store.py @@ -0,0 +1,47 @@ +import unittest + +import util.store + +class config(unittest.TestCase): + def setUp(self): + self.store = util.store.Store() + + self.unusedKey = "someRandomUnusedKey" + self.someKey = "someRandomKey" + self.someOtherKey = "anotherRandomKey" + self.someValue = "someRandomValue" + self.someOtherValue = "anotherRandomValue" + + def tearDown(self): + pass + + def test_get_of_unset_key(self): + self.assertEqual(None, self.store.get(self.unusedKey), 'default value expected to be None') + self.assertEqual(self.someValue, self.store.get(self.unusedKey, self.someValue), 'wrong user-provided default value returned') + + def test_get_of_set_key(self): + self.assertNotEqual(self.someValue, None) + + self.store.set(self.someKey, self.someValue) + self.assertEqual(self.someValue, self.store.get(self.someKey), 'unexpected value for existing key') + + def test_overwrite_set(self): + self.assertNotEqual(self.someValue, None) + self.assertNotEqual(self.someOtherValue, self.someValue) + + self.store.set(self.someKey, self.someValue) + self.store.set(self.someKey, self.someOtherValue) + self.assertEqual(self.someOtherValue, self.store.get(self.someKey), 'unexpected value for existing key') + + def test_unused_keys(self): + self.assertNotEqual(self.someKey, self.someOtherKey) + + self.store.set(self.someKey, self.someValue) + self.store.set(self.someOtherKey, self.someOtherValue) + + self.assertEqual(sorted(self.store.unused_keys()), sorted([self.someKey, self.someOtherKey])) + + self.store.get(self.someKey) + self.assertEqual(self.store.unused_keys(), [self.someOtherKey]) + +# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 diff --git a/util/__init__.py b/util/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/util/store.py b/util/store.py new file mode 100644 index 0000000..81c8452 --- /dev/null +++ b/util/store.py @@ -0,0 +1,26 @@ +"""Store interface + +Allows arbitrary classes to offer a simple get/set +store interface by deriving from the Store class in +this module +""" + +class Store(object): + """Interface for storing and retrieving simple values""" + def __init__(self): + self._data = {} + + def set(self, key, value): + """Set 'key' to 'value', overwriting 'key' if it exists already""" + self._data[key] = { 'value': value, 'used': False } + + def unused_keys(self): + return [ key for key, value in self._data.items() if value['used'] == False ] + + def get(self, key, default=None): + """Return the current value of 'key', or 'default' if 'key' is not set""" + if key in self._data: + self._data[key]['used'] = True + return self._data.get(key, { 'value': default })['value'] + +# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4