Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Counter: expose the previous and changed values. #397

Merged
merged 1 commit into from
May 31, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions kazoo/recipe/counter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -53,6 +57,8 @@ def __init__(self, client, path, default=0):
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:
Expand All @@ -79,12 +85,15 @@ def _change(self, value):
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."""
Expand Down
12 changes: 12 additions & 0 deletions kazoo/tests/test_counter.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,15 @@ def test_errors(self):
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)