From 5599e9f73bf701c873c630cbceb981b7c915d69d Mon Sep 17 00:00:00 2001 From: Dan g Date: Fri, 27 Jul 2018 13:51:02 -0400 Subject: [PATCH] Set format strings ass attributes, update tests --- sprockets/mixins/metrics/statsd.py | 15 ++++++--------- tests.py | 17 ++++++----------- 2 files changed, 12 insertions(+), 20 deletions(-) diff --git a/sprockets/mixins/metrics/statsd.py b/sprockets/mixins/metrics/statsd.py index 41d3607..ff187b8 100644 --- a/sprockets/mixins/metrics/statsd.py +++ b/sprockets/mixins/metrics/statsd.py @@ -123,9 +123,11 @@ class StatsDCollector(object): if protocol == 'tcp': self._tcp = True + self._msg_format = '{path}:{value}|{metric_type}\n' self._sock = self._tcp_socket() elif protocol == 'udp': self._tcp = False + self._msg_format = '{path}:{value}|{metric_type}' self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) else: raise ValueError('Invalid protocol: {}'.format(protocol)) @@ -160,9 +162,10 @@ class StatsDCollector(object): :param str metric_type: The metric type """ - msg = '{0}:{1}|{2}'.format( - self._build_path(path, metric_type), value, metric_type) - msg = self._build_udp_or_tcp_message(msg) + msg = self._msg_format.format( + path=self._build_path(path, metric_type), + value=value, + metric_type=metric_type) LOGGER.debug('Sending %s to %s:%s', msg.encode('ascii'), self._host, self._port) @@ -175,12 +178,6 @@ class StatsDCollector(object): except (OSError, socket.error) as error: # pragma: nocover LOGGER.exception('Error sending statsd metric: %s', error) - def _build_udp_or_tcp_message(self, msg): - if self._tcp is False: - return msg - - return msg + "\n" - def _build_path(self, path, metric_type): """Return a normalized path. diff --git a/tests.py b/tests.py index cb2b024..9e5519a 100644 --- a/tests.py +++ b/tests.py @@ -63,12 +63,9 @@ class TCPStatsdMetricCollectionTests(testing.AsyncHTTPTestCase): 'protocol': 'tcp', 'prepend_metric_type': True}) - def test_that_tcp_message_appends_a_newline(self): - orig = 'testing.timers.SimpleHandler.GET.204' - expected = 'testing.timers.SimpleHandler.GET.204\n' - - msg = self.application.statsd._build_udp_or_tcp_message(orig) - self.assertEqual(msg, expected) + def test_tcp_message_format(self): + expected = '{path}:{value}|{metric_type}\n' + self.assertEqual(self.application.statsd._msg_format, expected) def test_that_http_method_call_is_recorded(self): response = self.fetch('/') @@ -178,11 +175,9 @@ class UDPStatsdMetricCollectionTests(testing.AsyncHTTPTestCase): self.statsd.close() super(UDPStatsdMetricCollectionTests, self).tearDown() - def test_that_udp_message_is_unchanged(self): - expected = 'testing.timers.SimpleHandler.GET.204' - - msg = self.application.statsd._build_udp_or_tcp_message(expected) - self.assertEqual(msg, expected) + def test_udp_message_format(self): + expected = '{path}:{value}|{metric_type}' + self.assertEqual(self.application.statsd._msg_format, expected) def test_that_http_method_call_is_recorded(self): response = self.fetch('/')