summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJames Socol <me@jamessocol.com>2014-01-03 01:37:06 -0500
committerJames Socol <me@jamessocol.com>2014-01-03 01:39:01 -0500
commitfafa1619d41c65f89ea0fe0d353bb76bf2dbc83d (patch)
tree384c729b1f9b0f891a2fdaa6efdd241ad3407a24
parent0728fca8c1c9e307c9ab3d187a6a4f462b67024d (diff)
downloadpystatsd-fafa1619d41c65f89ea0fe0d353bb76bf2dbc83d.tar.gz
Guard against empty- or double- sending.
-rw-r--r--statsd/client.py9
-rw-r--r--statsd/tests.py16
2 files changed, 25 insertions, 0 deletions
diff --git a/statsd/client.py b/statsd/client.py
index 0770247..77207a4 100644
--- a/statsd/client.py
+++ b/statsd/client.py
@@ -16,6 +16,8 @@ class Timer(object):
self.stat = stat
self.rate = rate
self.ms = None
+ self._sent = False
+ self._start_time = None
def __call__(self, f):
@wraps(f)
@@ -35,6 +37,8 @@ class Timer(object):
return self
def stop(self, send=True):
+ if self._start_time is None:
+ raise RuntimeError('Timer has not started.')
dt = time.time() - self._start_time
self.ms = int(round(1000 * dt)) # Convert to milliseconds.
if send:
@@ -42,6 +46,11 @@ class Timer(object):
return self
def send(self):
+ if self.ms is None:
+ raise RuntimeError('No data recorded.')
+ if self._sent:
+ raise RuntimeError('Already sent data.')
+ self._sent = True
self.client.timing(self.stat, self.ms, self.rate)
diff --git a/statsd/tests.py b/statsd/tests.py
index 2ffd6b3..4080a9c 100644
--- a/statsd/tests.py
+++ b/statsd/tests.py
@@ -317,6 +317,22 @@ def test_timer_object_rate():
_timer_check(sc, 1, 'foo', 'ms@0.5')
+def test_timer_object_no_send_twice():
+ sc = _client()
+
+ t = sc.timer('foo').start()
+ t.stop()
+
+ with assert_raises(RuntimeError):
+ t.send()
+
+
+def test_timer_object_stop_without_start():
+ sc = _client()
+ with assert_raises(RuntimeError):
+ sc.timer('foo').stop()
+
+
def test_pipeline():
sc = _client()
pipe = sc.pipeline()