diff --git a/ezsnmp/helpers.py b/ezsnmp/helpers.py index 0c32d617..2f749082 100644 --- a/ezsnmp/helpers.py +++ b/ezsnmp/helpers.py @@ -3,6 +3,8 @@ import re # This regular expression is used to extract the index from an OID +# We attempt to extract the index from an OID (e.g. sysDescr.0 +# or .iso.org.dod.internet.mgmt.mib-2.system.sysContact.0) OID_INDEX_RE = re.compile( r"""( \.?\d+(?:\.\d+)* # numeric OID @@ -16,6 +18,10 @@ re.VERBOSE, ) +# This regular expression takes something like 'SNMPv2::mib-2.17.7.1.4.3.1.2.300' +# and splits it into 'SNMPv2::mib-2' and '17.7.1.4.3.1.2.300' +OID_INDEX_RE2 = re.compile(r"^([^\.]+::[^\.]+)\.(.*)$") + def normalize_oid(oid, oid_index=None): """ @@ -27,10 +33,17 @@ def normalize_oid(oid, oid_index=None): # Determine the OID index from the OID if not specified if oid_index is None and oid is not None: - # We attempt to extract the index from an OID (e.g. sysDescr.0 - # or .iso.org.dod.internet.mgmt.mib-2.system.sysContact.0) - match = OID_INDEX_RE.match(oid) - if match: - oid, oid_index = match.group(1, 2) + first_match = OID_INDEX_RE.match(oid) + second_match = OID_INDEX_RE2.match(oid) + + if second_match: + oid, oid_index = second_match.group(1, 2) + + elif first_match: + oid, oid_index = first_match.group(1, 2) + + elif oid == ".": + oid = "." + oid_index = "" return oid, oid_index diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 070fd1b3..9ba15edd 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -3,12 +3,42 @@ from ezsnmp.helpers import normalize_oid +def test_normalize_oid_just_iso(): + oid, oid_index = normalize_oid("oid") + assert oid == "oid" + assert oid_index == "" + + +def test_normalize_oid_just_period(): + oid, oid_index = normalize_oid(".") + assert oid == "." + assert oid_index == "" + + def test_normalize_oid_regular(): oid, oid_index = normalize_oid("sysContact.0") assert oid == "sysContact" assert oid_index == "0" +def test_normalize_oid_regular_2(): + oid, oid_index = normalize_oid("SNMPv2::mib-2.17.7.1.4.3.1.2.300") + assert oid == "SNMPv2::mib-2" + assert oid_index == "17.7.1.4.3.1.2.300" + + +def test_normalize_oid_regular_3(): + oid, oid_index = normalize_oid("nsCacheTimeout.1.3.6.1.2.1.2") + assert oid == "nsCacheTimeout" + assert oid_index == "1.3.6.1.2.1.2" + + +def test_normalize_oid_regular_4(): + oid, oid_index = normalize_oid("iso.3.6.1.2.1.31.1.1.1.1.5035") + assert oid == "iso" + assert oid_index == "3.6.1.2.1.31.1.1.1.1.5035" + + def test_normalize_oid_numeric(): oid, oid_index = normalize_oid(".1.3.6.1.2.1.1.1.0") assert oid == ".1.3.6.1.2.1.1.1.0"