summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLukasz Kawczynski <n@neuroid.pl>2016-06-10 14:31:35 +0100
committerLukasz Kawczynski <n@neuroid.pl>2016-06-10 14:40:21 +0100
commitb7aff3fb63625b992fc36df937ff545ec89155fe (patch)
tree56f94af481fa566fec801477c6bbe4e3b396a001
parent1b4bca7cae660c8f9edd5c9693f9159e69bef320 (diff)
downloadkazoo-b7aff3fb63625b992fc36df937ff545ec89155fe.tar.gz
Counter: expose the previous and changed values.
This commit extends the `Counter` API with the `pre_value` and `post_value` attributes. These attributes are set when a counter is changed. Previously, if the counter was modified concurrently, it was not possible to access the exact value to which the counter was set after a successful increment or decrement.
-rw-r--r--kazoo/recipe/counter.py13
-rw-r--r--kazoo/tests/test_counter.py12
2 files changed, 23 insertions, 2 deletions
diff --git a/kazoo/recipe/counter.py b/kazoo/recipe/counter.py
index 2299742..a2768a3 100644
--- a/kazoo/recipe/counter.py
+++ b/kazoo/recipe/counter.py
@@ -34,10 +34,14 @@ class Counter(object):
counter += 2
counter -= 1
counter.value == 1
+ counter.pre_value == 2
+ counter.post_value == 1
counter = zk.Counter("/float", default=1.0)
counter += 2.0
counter.value == 3.0
+ counter.pre_value == 1.0
+ counter.post_value == 3.0
"""
def __init__(self, client, path, default=0):
@@ -53,6 +57,8 @@ class Counter(object):
self.default = default
self.default_type = type(default)
self._ensured_path = False
+ self.pre_value = None
+ self.post_value = None
def _ensure_node(self):
if not self._ensured_path:
@@ -79,12 +85,15 @@ class Counter(object):
return self
def _inner_change(self, value):
- data, version = self._value()
- data = repr(data + value).encode('ascii')
+ self.pre_value, version = self._value()
+ post_value = self.pre_value + value
+ data = repr(post_value).encode('ascii')
try:
self.client.set(self.path, data, version=version)
except BadVersionError: # pragma: nocover
+ self.post_value = None
raise ForceRetryError()
+ self.post_value = post_value
def __add__(self, value):
"""Add value to counter."""
diff --git a/kazoo/tests/test_counter.py b/kazoo/tests/test_counter.py
index d582a45..50095a2 100644
--- a/kazoo/tests/test_counter.py
+++ b/kazoo/tests/test_counter.py
@@ -33,3 +33,15 @@ class KazooCounterTests(KazooTestCase):
counter = self._makeOne()
self.assertRaises(TypeError, counter.__add__, 2.1)
self.assertRaises(TypeError, counter.__add__, b"a")
+
+ def test_pre_post_values(self):
+ counter = self._makeOne()
+ eq_(counter.value, 0)
+ eq_(counter.pre_value, None)
+ eq_(counter.post_value, None)
+ counter += 2
+ eq_(counter.pre_value, 0)
+ eq_(counter.post_value, 2)
+ counter -= 3
+ eq_(counter.pre_value, 2)
+ eq_(counter.post_value, -1)