From 1dff1cc8ab74389e113933be03380685c17ee303 Mon Sep 17 00:00:00 2001
From: Neda Moeini <neda.moeini@GA0479-NMOEINI.local>
Date: Fri, 4 Aug 2023 14:13:46 +0200
Subject: [PATCH] Support ASN dot notation.

---
 inventory_provider/juniper.py    | 21 +++++++++++++++++++--
 test/test_juniper_data_global.py | 15 +++++++++++++++
 2 files changed, 34 insertions(+), 2 deletions(-)

diff --git a/inventory_provider/juniper.py b/inventory_provider/juniper.py
index 2c3b0b82..0f4bbc0c 100644
--- a/inventory_provider/juniper.py
+++ b/inventory_provider/juniper.py
@@ -243,6 +243,23 @@ def list_interfaces(netconf_config):
                 yield u
 
 
+def asn_to_int(asn_string: str) -> int:
+    """
+    Convert a possibly dotted ASN to an integer.
+
+    Args:
+    asn_string (str): ASN to be converted, can be in dot notation or not.
+
+    Returns:
+    int: ASN in integer format.
+    """
+    if '.' in asn_string:
+        high_order, low_order = map(int, asn_string.split('.'))
+        return (high_order << 16) | low_order
+    else:
+        return int(asn_string)
+
+
 def _system_bgp_peers(system_node):
 
     def _peering_params(neighbor_node):
@@ -251,11 +268,11 @@ def _system_bgp_peers(system_node):
         peer_as = neighbor_node.find('peer-as')
         if peer_as is not None:
             # lxml usage warning: can't just test `if peer_as:`
-            info['remote-asn'] = int(peer_as.text)
+            info['remote-asn'] = asn_to_int(peer_as.text)
         local_as = neighbor_node.find('local-as')
         if local_as is not None:
             asn_value_node = local_as.find('as-number')
-            info['local-asn'] = int(asn_value_node.text)
+            info['local-asn'] = asn_to_int(asn_value_node.text)
         description = neighbor_node.find('description')
         if description is not None:
             # lxml usage warning: can't just test `if description:`
diff --git a/test/test_juniper_data_global.py b/test/test_juniper_data_global.py
index accb5d6f..699e3212 100644
--- a/test/test_juniper_data_global.py
+++ b/test/test_juniper_data_global.py
@@ -5,6 +5,7 @@ import ipaddress
 import pytest
 
 from inventory_provider import juniper
+from inventory_provider.juniper import asn_to_int
 
 NETIFACES_TEST_DATA_STRING = """{
     'lo0': {{AF_INET}: [{'addr': '127.0.0.1', 'netmask': '255.0.0.0', 'peer': '127.0.0.1'}],
@@ -70,3 +71,17 @@ def test_local_v6_interfaces(mocked_netifaces):
     assert len(addresses) == 4
     for a in addresses:
         assert isinstance(a, ipaddress.IPv6Interface)
+
+
+def test_asn_to_int_functionality():
+    """Test that ASN to int conversion works with and without dot notation."""
+
+    # Test with dot notation
+    assert asn_to_int("1.1") == 65537
+    assert asn_to_int("64512.2") == 4227858434
+    assert asn_to_int("0.65535") == 65535
+
+    # Test without dot notation
+    assert asn_to_int("65537") == 65537
+    assert asn_to_int("0") == 0
+    assert asn_to_int("4227858434") == 4227858434
-- 
GitLab