From 65745010ad55d3893baac48267db2181933ecb96 Mon Sep 17 00:00:00 2001 From: Dave Shawley Date: Sun, 18 Jul 2021 11:23:33 -0400 Subject: [PATCH] Add datetime.timedelta support to `timing`. --- CHANGELOG.rst | 2 ++ sprockets_statsd/statsd.py | 6 +++++- tests/test_processor.py | 8 ++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index caa614c..198b6bd 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -2,6 +2,8 @@ Next release ------------ - Added ``Connector.timer`` method (addresses :issue:`8`) - Implement ``Timer`` abstraction from python-statsd +- ``Connector.timing`` now accepts :class:`datetime.timedelta` instances in addition + to :class:`float` instances :tag:`0.1.0 <0.0.1...0.1.0>` (10-May-2021) ------------------------------------------ diff --git a/sprockets_statsd/statsd.py b/sprockets_statsd/statsd.py index f8bb7ce..73d0393 100644 --- a/sprockets_statsd/statsd.py +++ b/sprockets_statsd/statsd.py @@ -1,4 +1,5 @@ import asyncio +import datetime import logging import socket import time @@ -174,13 +175,16 @@ class AbstractConnector: payload = str(value) self.inject_metric(f'gauges.{path}', payload, 'g') - def timing(self, path: str, seconds: float) -> None: + def timing(self, path: str, + seconds: typing.Union[float, datetime.timedelta]) -> None: """Send a timer metric. :param path: timer to append a value to :param seconds: number of **seconds** to record """ + if isinstance(seconds, datetime.timedelta): + seconds = seconds.total_seconds() self.inject_metric(f'timers.{path}', str(seconds * 1000.0), 'ms') def timer(self, path) -> Timer: diff --git a/tests/test_processor.py b/tests/test_processor.py index eede86f..312dd60 100644 --- a/tests/test_processor.py +++ b/tests/test_processor.py @@ -1,4 +1,5 @@ import asyncio +import datetime import logging import socket import time @@ -337,6 +338,13 @@ class ConnectorTests(ProcessorTestCase): self.assert_metrics_equal(self.statsd_server.metrics[0], 'timers.simple.timer', 12340.0, 'ms') + async def test_sending_timer_using_timedelta(self): + secs = datetime.timedelta(seconds=12, milliseconds=340) + self.connector.timing('simple.timer', secs) + await self.wait_for(self.statsd_server.message_received.acquire()) + self.assert_metrics_equal(self.statsd_server.metrics[0], + 'timers.simple.timer', 12340.0, 'ms') + async def test_timing_context_manager(self): with unittest.mock.patch( 'sprockets_statsd.statsd.time.time') as time_function: