From b739f3523496b7372d39f4ad0812e4bcdb4035ba Mon Sep 17 00:00:00 2001 From: Ben Plotnick Date: Mon, 29 May 2017 17:15:30 -0700 Subject: [PATCH] handle socket exception in create_endpoint --- py_zipkin/thrift/__init__.py | 5 ++++- tests/thrift/thrift_test.py | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/py_zipkin/thrift/__init__.py b/py_zipkin/thrift/__init__.py index f3d5e30..b07b666 100644 --- a/py_zipkin/thrift/__init__.py +++ b/py_zipkin/thrift/__init__.py @@ -61,7 +61,10 @@ def create_endpoint(port=0, service_name='unknown', host=None): :returns: zipkin Endpoint object """ if host is None: - host = socket.gethostbyname(socket.gethostname()) + try: + host = socket.gethostbyname(socket.gethostname()) + except socket.gaierror: + host = '127.0.0.1' # Convert ip address to network byte order ipv4 = struct.unpack('!i', socket.inet_aton(host))[0] # Zipkin passes unsigned values in signed types because Thrift has no diff --git a/tests/thrift/thrift_test.py b/tests/thrift/thrift_test.py index dad453e..953352d 100644 --- a/tests/thrift/thrift_test.py +++ b/tests/thrift/thrift_test.py @@ -1,5 +1,6 @@ import mock import pytest +import socket from py_zipkin import thrift @@ -117,6 +118,20 @@ def test_copy_endpoint_with_new_service_name(gethostbyname): assert endpoint.ipv4 == 0 +@mock.patch('socket.gethostbyname', autospec=True) +def test_create_endpoint_defaults_localhost(gethostbyname): + gethostbyname.side_effect = socket.gaierror + + endpoint = thrift.create_endpoint( + port=8080, + service_name='foo', + ) + assert endpoint.service_name == 'foo' + assert endpoint.port == 8080 + # An IP address of 127.0.0.1 unpacks to 2130706433 + assert endpoint.ipv4 == 2130706433 + + def test_create_annotation(): ann = thrift.create_annotation('foo', 'bar', 'baz') assert ('foo', 'bar', 'baz') == (ann.timestamp, ann.value, ann.host)