Fix Urllib instrumentation - Add status code to span if not None (#1430)

This commit is contained in:
Shalev Roda
2022-11-05 16:29:47 +02:00
committed by GitHub
parent af972a07a9
commit f994e14636
3 changed files with 36 additions and 1 deletions

View File

@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## Unreleased ## Unreleased
### Fixed
- Fix bug in Urllib instrumentation - add status code to span attributes only if the status code is not None.
([#1430](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1430))
## Version 1.14.0/0.35b0 (2022-11-03) ## Version 1.14.0/0.35b0 (2022-11-03)
### Deprecated ### Deprecated

View File

@ -206,7 +206,7 @@ def _instrument(
code_ = result.getcode() code_ = result.getcode()
labels[SpanAttributes.HTTP_STATUS_CODE] = str(code_) labels[SpanAttributes.HTTP_STATUS_CODE] = str(code_)
if span.is_recording(): if span.is_recording() and code_ is not None:
span.set_attribute(SpanAttributes.HTTP_STATUS_CODE, code_) span.set_attribute(SpanAttributes.HTTP_STATUS_CODE, code_)
span.set_status(Status(http_status_to_status_code(code_))) span.set_status(Status(http_status_to_status_code(code_)))

View File

@ -16,6 +16,7 @@ import abc
import socket import socket
import urllib import urllib
from unittest import mock from unittest import mock
from unittest.mock import patch
from urllib import request from urllib import request
from urllib.error import HTTPError from urllib.error import HTTPError
from urllib.request import OpenerDirector from urllib.request import OpenerDirector
@ -150,6 +151,35 @@ class RequestsIntegrationTestBase(abc.ABC):
trace.StatusCode.ERROR, trace.StatusCode.ERROR,
) )
@staticmethod
def mock_get_code(*args, **kwargs):
return None
@patch("http.client.HTTPResponse.getcode", new=mock_get_code)
def test_response_code_none(self):
result = self.perform_request(self.URL)
self.assertEqual(result.read(), b"Hello!")
span = self.assert_span()
self.assertIs(span.kind, trace.SpanKind.CLIENT)
self.assertEqual(span.name, "HTTP GET")
self.assertEqual(
span.attributes,
{
SpanAttributes.HTTP_METHOD: "GET",
SpanAttributes.HTTP_URL: self.URL,
},
)
self.assertIs(span.status.status_code, trace.StatusCode.UNSET)
self.assertEqualSpanInstrumentationInfo(
span, opentelemetry.instrumentation.urllib
)
def test_uninstrument(self): def test_uninstrument(self):
URLLibInstrumentor().uninstrument() URLLibInstrumentor().uninstrument()
result = self.perform_request(self.URL) result = self.perform_request(self.URL)