Skip to content

Commit f994e14

Browse files
authored
Fix Urllib instrumentation - Add status code to span if not None (#1430)
1 parent af972a0 commit f994e14

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## Unreleased
99

10+
### Fixed
11+
12+
- Fix bug in Urllib instrumentation - add status code to span attributes only if the status code is not None.
13+
([#1430](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1430))
14+
1015
## Version 1.14.0/0.35b0 (2022-11-03)
1116

1217
### Deprecated

instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@ def _instrumented_open_call(
206206
code_ = result.getcode()
207207
labels[SpanAttributes.HTTP_STATUS_CODE] = str(code_)
208208

209-
if span.is_recording():
209+
if span.is_recording() and code_ is not None:
210210
span.set_attribute(SpanAttributes.HTTP_STATUS_CODE, code_)
211211
span.set_status(Status(http_status_to_status_code(code_)))
212212

instrumentation/opentelemetry-instrumentation-urllib/tests/test_urllib_integration.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import socket
1717
import urllib
1818
from unittest import mock
19+
from unittest.mock import patch
1920
from urllib import request
2021
from urllib.error import HTTPError
2122
from urllib.request import OpenerDirector
@@ -150,6 +151,35 @@ def test_not_foundbasic(self):
150151
trace.StatusCode.ERROR,
151152
)
152153

154+
@staticmethod
155+
def mock_get_code(*args, **kwargs):
156+
return None
157+
158+
@patch("http.client.HTTPResponse.getcode", new=mock_get_code)
159+
def test_response_code_none(self):
160+
161+
result = self.perform_request(self.URL)
162+
163+
self.assertEqual(result.read(), b"Hello!")
164+
span = self.assert_span()
165+
166+
self.assertIs(span.kind, trace.SpanKind.CLIENT)
167+
self.assertEqual(span.name, "HTTP GET")
168+
169+
self.assertEqual(
170+
span.attributes,
171+
{
172+
SpanAttributes.HTTP_METHOD: "GET",
173+
SpanAttributes.HTTP_URL: self.URL,
174+
},
175+
)
176+
177+
self.assertIs(span.status.status_code, trace.StatusCode.UNSET)
178+
179+
self.assertEqualSpanInstrumentationInfo(
180+
span, opentelemetry.instrumentation.urllib
181+
)
182+
153183
def test_uninstrument(self):
154184
URLLibInstrumentor().uninstrument()
155185
result = self.perform_request(self.URL)

0 commit comments

Comments
 (0)