Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .changelog/5283.changed
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`opentelemetry-sdk`: provide distinct, accurate error messages for instrument name and unit validation
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,13 @@
_logger = getLogger(__name__)


_ERROR_MESSAGE = (
"Expected ASCII string of maximum length 63 characters but got {}"
_NAME_ERROR_MESSAGE = (
"Instrument name must be an ASCII string, start with a letter, "
"contain only letters, digits, '_', '.', '-', '/' and be at most 255 characters; got {!r}"
)

_UNIT_ERROR_MESSAGE = (
"Instrument unit must be an ASCII string of maximum length 63 characters; got {!r}"
)
Comment on lines +48 to 55


Expand Down Expand Up @@ -74,11 +79,11 @@ def __init__(

if result["name"] is None:
# pylint: disable=broad-exception-raised
raise Exception(_ERROR_MESSAGE.format(name))
raise Exception(_NAME_ERROR_MESSAGE.format(name))

if result["unit"] is None:
# pylint: disable=broad-exception-raised
raise Exception(_ERROR_MESSAGE.format(unit))
raise Exception(_UNIT_ERROR_MESSAGE.format(unit))

name = result["name"]
unit = result["unit"]
Expand Down Expand Up @@ -113,11 +118,11 @@ def __init__(

if result["name"] is None:
# pylint: disable=broad-exception-raised
raise Exception(_ERROR_MESSAGE.format(name))
raise Exception(_NAME_ERROR_MESSAGE.format(name))

if result["unit"] is None:
# pylint: disable=broad-exception-raised
raise Exception(_ERROR_MESSAGE.format(unit))
raise Exception(_UNIT_ERROR_MESSAGE.format(unit))

name = result["name"]
unit = result["unit"]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import unittest

from opentelemetry.sdk.metrics._internal.instrument import _Synchronous
from opentelemetry.sdk.util.instrumentation import InstrumentationScope


class TestInstrumentErrorMessage(unittest.TestCase):
def test_invalid_name_error_message(self):
scope = InstrumentationScope("test")
with self.assertRaises(Exception) as cm:
_Synchronous("1invalid", scope, object())
msg = str(cm.exception)
self.assertIn("start with a letter", msg)
self.assertIn("at most 255 characters", msg)

def test_invalid_unit_error_message(self):
scope = InstrumentationScope("test")
# name valid, unit invalid (non-ASCII)
with self.assertRaises(Exception) as cm:
_Synchronous("validname", scope, object(), unit="Ñ")
msg = str(cm.exception)
self.assertIn("maximum length 63", msg)
self.assertIn("ASCII", msg)