From 57e54d9561934b853a44185bbb401207f4503292 Mon Sep 17 00:00:00 2001 From: Qi Luo Date: Thu, 22 Oct 2020 12:58:33 -0700 Subject: [PATCH] Interact with Redis by str instead of bytes, migrate to SonicV2Connector with `decode_responses=True` (#171) * Interact with Redis by str instead of bytes * Implement mockredis decode_responses option --- src/sonic_ax_impl/mibs/__init__.py | 71 +++++++++---------- src/sonic_ax_impl/mibs/ieee802_1ab.py | 46 ++++++------ src/sonic_ax_impl/mibs/ietf/rfc1213.py | 44 ++++++------ src/sonic_ax_impl/mibs/ietf/rfc2737.py | 32 ++++----- src/sonic_ax_impl/mibs/ietf/rfc2863.py | 8 +-- src/sonic_ax_impl/mibs/ietf/rfc3433.py | 6 +- src/sonic_ax_impl/mibs/ietf/rfc4292.py | 8 +-- src/sonic_ax_impl/mibs/ietf/rfc4363.py | 4 +- src/sonic_ax_impl/mibs/vendor/cisco/bgp4.py | 6 +- .../vendor/cisco/ciscoEntityFruControlMIB.py | 17 +++-- .../mibs/vendor/cisco/ciscoPfcExtMIB.py | 10 +-- .../mibs/vendor/cisco/ciscoSwitchQosMIB.py | 16 ++--- tests/mock_tables/dbconnector.py | 37 +++++++--- tests/namespace/test_lldp.py | 4 +- tests/namespace/test_mibs.py | 16 ++--- tests/test_lldp.py | 9 ++- tests/test_mibs.py | 12 ++-- 17 files changed, 182 insertions(+), 164 deletions(-) diff --git a/src/sonic_ax_impl/mibs/__init__.py b/src/sonic_ax_impl/mibs/__init__.py index 8ae59f88719c..9dc0a986bf2f 100644 --- a/src/sonic_ax_impl/mibs/__init__.py +++ b/src/sonic_ax_impl/mibs/__init__.py @@ -5,16 +5,16 @@ from swsssdk import SonicV2Connector from swsssdk import SonicDBConfig from swsssdk import port_util -from swsssdk.port_util import get_index, get_index_from_str +from swsssdk.port_util import get_index_from_str from ax_interface.mib import MIBUpdater from ax_interface.util import oid2tuple from sonic_ax_impl import logger -COUNTERS_PORT_NAME_MAP = b'COUNTERS_PORT_NAME_MAP' -COUNTERS_QUEUE_NAME_MAP = b'COUNTERS_QUEUE_NAME_MAP' -LAG_TABLE = b'LAG_TABLE' -LAG_MEMBER_TABLE = b'LAG_MEMBER_TABLE' -LOC_CHASSIS_TABLE = b'LLDP_LOC_CHASSIS' +COUNTERS_PORT_NAME_MAP = 'COUNTERS_PORT_NAME_MAP' +COUNTERS_QUEUE_NAME_MAP = 'COUNTERS_QUEUE_NAME_MAP' +LAG_TABLE = 'LAG_TABLE' +LAG_MEMBER_TABLE = 'LAG_MEMBER_TABLE' +LOC_CHASSIS_TABLE = 'LLDP_LOC_CHASSIS' APPL_DB = 'APPL_DB' ASIC_DB = 'ASIC_DB' COUNTERS_DB = 'COUNTERS_DB' @@ -78,14 +78,14 @@ def counter_table(sai_id): :param if_name: given sai_id to cast. :return: COUNTERS table key. """ - return b'COUNTERS:oid:0x' + sai_id + return 'COUNTERS:oid:0x' + sai_id def queue_table(sai_id): """ :param sai_id: given sai_id to cast. :return: COUNTERS table key. """ - return b'COUNTERS:' + sai_id + return 'COUNTERS:' + sai_id def queue_key(port_index, queue_index): return str(port_index) + ':' + str(queue_index) @@ -111,7 +111,7 @@ def lldp_entry_table(if_name): :param if_name: given interface to cast. :return: LLDP_ENTRY_TABLE key. """ - return b'LLDP_ENTRY_TABLE:' + if_name + return 'LLDP_ENTRY_TABLE:' + if_name def if_entry_table(if_name): @@ -119,7 +119,7 @@ def if_entry_table(if_name): :param if_name: given interface to cast. :return: PORT_TABLE key. """ - return b'PORT_TABLE:' + if_name + return 'PORT_TABLE:' + if_name def lag_entry_table(lag_name): @@ -127,7 +127,7 @@ def lag_entry_table(lag_name): :param lag_name: given lag to cast. :return: LAG_TABLE key. """ - return b'LAG_TABLE:' + lag_name + return 'LAG_TABLE:' + lag_name def mgmt_if_entry_table(if_name): @@ -136,7 +136,7 @@ def mgmt_if_entry_table(if_name): :return: MGMT_PORT_TABLE key """ - return b'MGMT_PORT|' + if_name + return 'MGMT_PORT|' + if_name def mgmt_if_entry_table_state_db(if_name): @@ -145,7 +145,7 @@ def mgmt_if_entry_table_state_db(if_name): :return: MGMT_PORT_TABLE key """ - return b'MGMT_PORT_TABLE|' + if_name + return 'MGMT_PORT_TABLE|' + if_name def get_sai_id_key(namespace, sai_id): """ @@ -157,7 +157,7 @@ def get_sai_id_key(namespace, sai_id): Return value: namespace:sai id or sai id """ if namespace != '': - return namespace.encode() + b':' + sai_id + return namespace + ':' + sai_id else: return sai_id @@ -166,15 +166,16 @@ def split_sai_id_key(sai_id_key): Input - bytes Return namespace string and sai id in byte string. """ - result = sai_id_key.split(b':') + result = sai_id_key.split(':') if len(result) == 1: return '', sai_id_key else: - return result[0].decode(), result[1] + return result[0], result[1] def config(**kwargs): global redis_kwargs redis_kwargs = {k:v for (k,v) in kwargs.items() if k in ['unix_socket_path', 'host', 'port']} + redis_kwargs['decode_responses'] = True def init_db(): """ @@ -198,21 +199,21 @@ def init_mgmt_interface_tables(db_conn): db_conn.connect(CONFIG_DB) db_conn.connect(STATE_DB) - mgmt_ports_keys = db_conn.keys(CONFIG_DB, mgmt_if_entry_table(b'*')) + mgmt_ports_keys = db_conn.keys(CONFIG_DB, mgmt_if_entry_table('*')) if not mgmt_ports_keys: - logger.debug('No managment ports found in {}'.format(mgmt_if_entry_table(b''))) + logger.debug('No managment ports found in {}'.format(mgmt_if_entry_table(''))) return {}, {} - mgmt_ports = [key.split(mgmt_if_entry_table(b''))[-1] for key in mgmt_ports_keys] - oid_name_map = {get_index(mgmt_name): mgmt_name for mgmt_name in mgmt_ports} + mgmt_ports = [key.split(mgmt_if_entry_table(''))[-1] for key in mgmt_ports_keys] + oid_name_map = {get_index_from_str(mgmt_name): mgmt_name for mgmt_name in mgmt_ports} logger.debug('Managment port map:\n' + pprint.pformat(oid_name_map, indent=2)) if_alias_map = dict() for if_name in oid_name_map.values(): if_entry = db_conn.get_all(CONFIG_DB, mgmt_if_entry_table(if_name), blocking=True) - if_alias_map[if_name] = if_entry.get(b'alias', if_name) + if_alias_map[if_name] = if_entry.get('alias', if_name) logger.debug("Management alias map:\n" + pprint.pformat(if_alias_map, indent=2)) @@ -230,7 +231,7 @@ def init_sync_d_interface_tables(db_conn): # ex: { "Ethernet76" : "1000000000023" } if_name_map_util, if_id_map_util = port_util.get_interface_oid_map(db_conn) for if_name, sai_id in if_name_map_util.items(): - if_name_str = if_name.decode() + if_name_str = if_name if (re.match(port_util.SONIC_ETHERNET_RE_PATTERN, if_name_str) or \ re.match(port_util.SONIC_ETHERNET_BP_RE_PATTERN, if_name_str)): if_name_map[if_name] = sai_id @@ -239,7 +240,6 @@ def init_sync_d_interface_tables(db_conn): # string or in sai id. # sai_id_key = namespace : sai_id for sai_id, if_name in if_id_map_util.items(): - if_name = if_name.decode() if (re.match(port_util.SONIC_ETHERNET_RE_PATTERN, if_name) or \ re.match(port_util.SONIC_ETHERNET_BP_RE_PATTERN, if_name)): if_id_map[get_sai_id_key(db_conn.namespace, sai_id)] = if_name @@ -247,9 +247,9 @@ def init_sync_d_interface_tables(db_conn): logger.debug("Interface name map:\n" + pprint.pformat(if_id_map, indent=2)) # { OID -> if_name (SONiC) } - oid_name_map = {get_index(if_name): if_name for if_name in if_name_map + oid_name_map = {get_index_from_str(if_name): if_name for if_name in if_name_map # only map the interface if it's a style understood to be a SONiC interface. - if get_index(if_name) is not None} + if get_index_from_str(if_name) is not None} logger.debug("OID name map:\n" + pprint.pformat(oid_name_map, indent=2)) @@ -272,7 +272,7 @@ def init_sync_d_interface_tables(db_conn): for if_name in if_name_map: if_entry = db_conn.get_all(APPL_DB, if_entry_table(if_name), blocking=True) - if_alias_map[if_name] = if_entry.get(b'alias', if_name) + if_alias_map[if_name] = if_entry.get('alias', if_name) logger.debug("Chassis name map:\n" + pprint.pformat(if_alias_map, indent=2)) @@ -295,20 +295,20 @@ def init_sync_d_lag_tables(db_conn): db_conn.connect(APPL_DB) - lag_entries = db_conn.keys(APPL_DB, b"LAG_TABLE:*") + lag_entries = db_conn.keys(APPL_DB, "LAG_TABLE:*") if not lag_entries: return lag_name_if_name_map, if_name_lag_name_map, oid_lag_name_map for lag_entry in lag_entries: - lag_name = lag_entry[len(b"LAG_TABLE:"):] - lag_members = db_conn.keys(APPL_DB, b"LAG_MEMBER_TABLE:%s:*" % lag_name) + lag_name = lag_entry[len("LAG_TABLE:"):] + lag_members = db_conn.keys(APPL_DB, "LAG_MEMBER_TABLE:%s:*" % lag_name) # TODO: db_conn.keys() should really return [] instead of None if lag_members is None: lag_members = [] def member_name_str(val, lag_name): - return val[len(b"LAG_MEMBER_TABLE:%s:" % lag_name):] + return val[len("LAG_MEMBER_TABLE:%s:" % lag_name):] lag_member_names = [member_name_str(m, lag_name) for m in lag_members] lag_name_if_name_map[lag_name] = lag_member_names @@ -316,7 +316,7 @@ def member_name_str(val, lag_name): if_name_lag_name_map[lag_member_name] = lag_name for if_name in lag_name_if_name_map.keys(): - idx = get_index(if_name) + idx = get_index_from_str(if_name) if idx: oid_lag_name_map[idx] = if_name @@ -342,7 +342,7 @@ def init_sync_d_queue_tables(db_conn): port_queue_list_map = {} for queue_name, sai_id in queue_name_map.items(): - port_name, queue_index = queue_name.decode().split(':') + port_name, queue_index = queue_name.split(':') queue_index = ''.join(i for i in queue_index if i.isdigit()) port_index = get_index_from_str(port_name) key = queue_key(port_index, queue_index) @@ -464,12 +464,11 @@ def update_data(self): keys = [] for key in keys: - key = key.decode() oid = oid2tuple(key, dot_prefix=False) self.oid_list.append(oid) value = Namespace.dbs_get_all(self.db_conn, SNMP_OVERLAY_DB, key) - if value[b'type'] in [b'COUNTER_32', b'COUNTER_64']: - self.oid_map[oid] = int(value[b'data']) + if value['type'] in ['COUNTER_32', 'COUNTER_64']: + self.oid_map[oid] = int(value['data']) else: raise ValueError("Invalid value type") @@ -486,7 +485,7 @@ def init_namespace_dbs(): db_conn = [] SonicDBConfig.load_sonic_global_db_config() for namespace in SonicDBConfig.get_ns_list(): - db = SonicV2Connector(use_unix_socket_path=True, namespace=namespace) + db = SonicV2Connector(use_unix_socket_path=True, namespace=namespace, decode_responses=True) db_conn.append(db) Namespace.connect_namespace_dbs(db_conn) diff --git a/src/sonic_ax_impl/mibs/ieee802_1ab.py b/src/sonic_ax_impl/mibs/ieee802_1ab.py index bccaa5544a65..a23f216807b3 100644 --- a/src/sonic_ax_impl/mibs/ieee802_1ab.py +++ b/src/sonic_ax_impl/mibs/ieee802_1ab.py @@ -78,7 +78,7 @@ def poll_lldp_entry_updates(pubsub): return ret try: - interface = msg["channel"].split(b":")[-1].decode() + interface = msg["channel"].split(":")[-1] data = msg['data'] except (KeyError, AttributeError) as e: logger.error("Invalid msg when polling for lldp updates: {}\n" @@ -112,8 +112,8 @@ def reinit_data(self): # establish connection to application database. Namespace.connect_all_dbs(self.db_conn, mibs.APPL_DB) self.loc_chassis_data = Namespace.dbs_get_all(self.db_conn, mibs.APPL_DB, mibs.LOC_CHASSIS_TABLE) - self.loc_chassis_data[b'lldp_loc_sys_cap_supported'] = parse_sys_capability(self.loc_chassis_data[b'lldp_loc_sys_cap_supported']) - self.loc_chassis_data[b'lldp_loc_sys_cap_enabled'] = parse_sys_capability(self.loc_chassis_data[b'lldp_loc_sys_cap_enabled']) + self.loc_chassis_data['lldp_loc_sys_cap_supported'] = parse_sys_capability(self.loc_chassis_data['lldp_loc_sys_cap_supported']) + self.loc_chassis_data['lldp_loc_sys_cap_enabled'] = parse_sys_capability(self.loc_chassis_data['lldp_loc_sys_cap_enabled']) def update_data(self): """ Avoid NotImplementedError @@ -123,7 +123,7 @@ def update_data(self): def table_lookup(self, table_name): try: - _table_name = bytes(getattr(table_name, 'name', table_name), 'utf-8') + _table_name = getattr(table_name, 'name', table_name) return self.loc_chassis_data[_table_name] except KeyError as e: logger.warning(" 0 - b'LOC_CHASSIS' missing attribute '{}'.".format(e)) @@ -229,13 +229,13 @@ def _update_per_namespace_data(self, pubsub): if not data: break - if b"set" in data: - self.update_interface_data(interface.encode()) + if "set" in data: + self.update_interface_data(interface) def update_data(self): for i in range(len(self.db_conn)): if not self.pubsub[i]: - pattern = mibs.lldp_entry_table(b'*') + pattern = mibs.lldp_entry_table('*') self.pubsub[i] = mibs.get_redis_pubsub(self.db_conn[i], self.db_conn[i].APPL_DB, pattern) self._update_per_namespace_data(self.pubsub[i]) @@ -270,7 +270,7 @@ def port_table_lookup(self, sub_id, table_name): # no data for this interface return None counters = self.loc_port_data[if_name] - _table_name = bytes(getattr(table_name, 'name', table_name), 'utf-8') + _table_name = getattr(table_name, 'name', table_name) return counters.get(_table_name, '') @@ -302,13 +302,13 @@ def reinit_data(self): # establish connection to application database. self.db_conn.connect(mibs.APPL_DB) - mgmt_ip_bytes = self.db_conn.get(mibs.APPL_DB, mibs.LOC_CHASSIS_TABLE, b'lldp_loc_man_addr') + mgmt_ip_bytes = self.db_conn.get(mibs.APPL_DB, mibs.LOC_CHASSIS_TABLE, 'lldp_loc_man_addr') if not mgmt_ip_bytes: logger.warning("Missing lldp_loc_man_addr from APPL DB") return - self.mgmt_ip_str = mgmt_ip_bytes.decode() + self.mgmt_ip_str = mgmt_ip_bytes logger.debug("Got mgmt ip from db : {}".format(self.mgmt_ip_str)) try: addr_subtype_sub_oid = 4 @@ -435,12 +435,12 @@ def update_data(self): # To avoid repeating the data of same interface index with different remote # time mark, remote time mark is made as 0 in the OID indexing. time_mark = 0 - remote_index = int(lldp_kvs[b'lldp_rem_index']) + remote_index = int(lldp_kvs['lldp_rem_index']) self.if_range.append((time_mark, if_oid, remote_index)) - lldp_kvs[b'lldp_rem_sys_cap_supported'] = parse_sys_capability(lldp_kvs[b'lldp_rem_sys_cap_supported']) - lldp_kvs[b'lldp_rem_sys_cap_enabled'] = parse_sys_capability(lldp_kvs[b'lldp_rem_sys_cap_enabled']) + lldp_kvs['lldp_rem_sys_cap_supported'] = parse_sys_capability(lldp_kvs['lldp_rem_sys_cap_supported']) + lldp_kvs['lldp_rem_sys_cap_enabled'] = parse_sys_capability(lldp_kvs['lldp_rem_sys_cap_enabled']) self.lldp_counters.update({if_name: lldp_kvs}) except (KeyError, AttributeError) as e: logger.warning("Exception when updating lldpRemTable: {}".format(e)) @@ -467,7 +467,7 @@ def lldp_table_lookup(self, sub_id, table_name): # no LLDP data for this interface return None counters = self.lldp_counters[if_name] - _table_name = bytes(getattr(table_name, 'name', table_name), 'utf-8') + _table_name = getattr(table_name, 'name', table_name) try: return counters[_table_name] except KeyError as e: @@ -500,17 +500,17 @@ def __init__(self): def update_rem_if_mgmt(self, if_oid, if_name): lldp_kvs = Namespace.dbs_get_all(self.db_conn, mibs.APPL_DB, mibs.lldp_entry_table(if_name)) - if not lldp_kvs or b'lldp_rem_man_addr' not in lldp_kvs: + if not lldp_kvs or 'lldp_rem_man_addr' not in lldp_kvs: # this interfaces doesn't have remote lldp data, or the peer doesn't advertise his mgmt address return try: - mgmt_ip_str = lldp_kvs[b'lldp_rem_man_addr'].decode() + mgmt_ip_str = lldp_kvs['lldp_rem_man_addr'] mgmt_ip_str = mgmt_ip_str.strip() if len(mgmt_ip_str) == 0: # the peer advertise an emtpy mgmt address return - time_mark = int(lldp_kvs[b'lldp_rem_time_mark']) - remote_index = int(lldp_kvs[b'lldp_rem_index']) + time_mark = int(lldp_kvs['lldp_rem_time_mark']) + remote_index = int(lldp_kvs['lldp_rem_index']) subtype = self.get_subtype(mgmt_ip_str) ip_hex = self.get_ip_hex(mgmt_ip_str, subtype) if subtype == ManAddrConst.man_addr_subtype_ipv4: @@ -546,17 +546,17 @@ def _update_per_namespace_data(self, pubsub): if not data: break - if b"set" in data: - self.update_rem_if_mgmt(if_index, interface.encode()) - elif b"del" in data: + if "set" in data: + self.update_rem_if_mgmt(if_index, interface) + elif "del" in data: # some remote data about that neighbor is gone, del it and try to query again self.if_range = [sub_oid for sub_oid in self.if_range if sub_oid[0] != if_index] - self.update_rem_if_mgmt(if_index, interface.encode()) + self.update_rem_if_mgmt(if_index, interface) def update_data(self): for i in range(len(self.db_conn)): if not self.pubsub[i]: - pattern = mibs.lldp_entry_table(b'*') + pattern = mibs.lldp_entry_table('*') self.pubsub[i] = mibs.get_redis_pubsub(self.db_conn[i], self.db_conn[i].APPL_DB, pattern) self._update_per_namespace_data(self.pubsub[i]) diff --git a/src/sonic_ax_impl/mibs/ietf/rfc1213.py b/src/sonic_ax_impl/mibs/ietf/rfc1213.py index c1b3b1bea172..52c8b82b8fd8 100644 --- a/src/sonic_ax_impl/mibs/ietf/rfc1213.py +++ b/src/sonic_ax_impl/mibs/ietf/rfc1213.py @@ -74,15 +74,15 @@ def _update_from_arptable(self): def _update_from_db(self): for neigh_key in self.neigh_key_list: - neigh_str = neigh_key.decode() + neigh_str = neigh_key db_index = self.neigh_key_list[neigh_key] neigh_info = self.db_conn[db_index].get_all(mibs.APPL_DB, neigh_key, blocking=False) if neigh_info is None: continue - ip_family = neigh_info[b'family'].decode() + ip_family = neigh_info['family'] if ip_family == "IPv4": dev, ip = mibs.get_neigh_info(neigh_str) - mac = neigh_info[b'neigh'].decode() + mac = neigh_info['neigh'] # eth0 interface in a namespace is not management interface # but is a part of docker0 bridge. Ignore this interface. if len(self.db_conn) > 1 and dev == "eth0": @@ -145,12 +145,12 @@ def update_data(self): return for route_entry in route_entries: - routestr = route_entry.decode() + routestr = route_entry ipnstr = routestr[len("ROUTE_TABLE:"):] if ipnstr == "0.0.0.0/0": ipn = ipaddress.ip_network(ipnstr) ent = Namespace.dbs_get_all(self.db_conn, mibs.APPL_DB, routestr, blocking=True) - nexthops = ent[b"nexthop"].decode() + nexthops = ent["nexthop"] for nh in nexthops.split(','): # TODO: if ipn contains IP range, create more sub_id here sub_id = ip2tuple_v4(ipn.network_address) @@ -290,7 +290,7 @@ def _get_counter(self, oid, table_name): :return: the counter for the respective sub_id/table. """ # Enum.name or table_name = 'name_of_the_table' - _table_name = bytes(getattr(table_name, 'name', table_name), 'utf-8') + _table_name = getattr(table_name, 'name', table_name) try: counter_value = self.if_counters[oid][_table_name] @@ -320,7 +320,7 @@ def get_counter(self, sub_id, table_name): elif oid in self.oid_lag_name_map: counter_value = 0 for lag_member in self.lag_name_if_name_map[self.oid_lag_name_map[oid]]: - counter_value += self._get_counter(mibs.get_index(lag_member), table_name) + counter_value += self._get_counter(mibs.get_index_from_str(lag_member), table_name) # truncate to 32-bit counter return counter_value & 0x00000000ffffffff @@ -384,45 +384,45 @@ def _get_status(self, sub_id, key): :return: state value for the respective sub_id/key. """ status_map = { - b"up": 1, - b"down": 2, - b"testing": 3, - b"unknown": 4, - b"dormant": 5, - b"notPresent": 6, - b"lowerLayerDown": 7 + "up": 1, + "down": 2, + "testing": 3, + "unknown": 4, + "dormant": 5, + "notPresent": 6, + "lowerLayerDown": 7 } # Once PORT_TABLE will be moved to CONFIG DB # we will get rid of this if-else # and read oper status from STATE_DB - if self.get_oid(sub_id) in self.mgmt_oid_name_map and key == b"oper_status": + if self.get_oid(sub_id) in self.mgmt_oid_name_map and key == "oper_status": entry = self._get_if_entry_state_db(sub_id) else: entry = self._get_if_entry(sub_id) if not entry: - return status_map.get(b"unknown") + return status_map.get("unknown") # Note: If interface never become up its state won't be reflected in DB entry # If state key is not in DB entry assume interface is down - state = entry.get(key, b"down") + state = entry.get(key, "down") - return status_map.get(state, status_map[b"down"]) + return status_map.get(state, status_map["down"]) def get_admin_status(self, sub_id): """ :param sub_id: The 1-based sub-identifier query. :return: admin state value for the respective sub_id. """ - return self._get_status(sub_id, b"admin_status") + return self._get_status(sub_id, "admin_status") def get_oper_status(self, sub_id): """ :param sub_id: The 1-based sub-identifier query. :return: oper state value for the respective sub_id. """ - return self._get_status(sub_id, b"oper_status") + return self._get_status(sub_id, "oper_status") def get_mtu(self, sub_id): """ @@ -433,7 +433,7 @@ def get_mtu(self, sub_id): if not entry: return - return int(entry.get(b"mtu", 0)) + return int(entry.get("mtu", 0)) def get_speed_bps(self, sub_id): """ @@ -444,7 +444,7 @@ def get_speed_bps(self, sub_id): if not entry: return - speed = int(entry.get(b"speed", 0)) + speed = int(entry.get("speed", 0)) # speed is reported in Mbps in the db return min(self.RFC1213_MAX_SPEED, speed * 1000000) diff --git a/src/sonic_ax_impl/mibs/ietf/rfc2737.py b/src/sonic_ax_impl/mibs/ietf/rfc2737.py index 927ab6797211..9601858a0644 100644 --- a/src/sonic_ax_impl/mibs/ietf/rfc2737.py +++ b/src/sonic_ax_impl/mibs/ietf/rfc2737.py @@ -31,16 +31,16 @@ class PhysicalClass(int, Enum): @unique -class XcvrInfoDB(bytes, Enum): +class XcvrInfoDB(str, Enum): """ Transceiver info keys """ - TYPE = b"type" - HARDWARE_REVISION = b"hardware_rev" - SERIAL_NUMBER = b"serial" - MANUFACTURE_NAME = b"manufacturer" - MODEL_NAME = b"model" + TYPE = "type" + HARDWARE_REVISION = "hardware_rev" + SERIAL_NUMBER = "serial" + MANUFACTURE_NAME = "manufacturer" + MODEL_NAME = "model" # Map used to generate sensor description @@ -71,7 +71,7 @@ def get_transceiver_data(xcvr_info): Empty string if field not in xcvr_info """ - return (xcvr_info.get(xcvr_field.value, b"").decode() + return (xcvr_info.get(xcvr_field.value, "") for xcvr_field in XcvrInfoDB) @@ -159,10 +159,10 @@ def reinit_data(self): chassis_sub_id = (self.CHASSIS_ID, ) self.physical_entities = [chassis_sub_id] - if not device_metadata or not device_metadata.get(b"chassis_serial_number"): + if not device_metadata or not device_metadata.get("chassis_serial_number"): chassis_serial_number = "" else: - chassis_serial_number = device_metadata[b"chassis_serial_number"] + chassis_serial_number = device_metadata["chassis_serial_number"] self.physical_classes_map[chassis_sub_id] = PhysicalClass.CHASSIS self.physical_serial_number_map[chassis_sub_id] = chassis_serial_number @@ -170,7 +170,7 @@ def reinit_data(self): # retrieve the initial list of transceivers that are present in the system transceiver_info = Namespace.dbs_keys(self.statedb, mibs.STATE_DB, self.TRANSCEIVER_KEY_PATTERN) if transceiver_info: - self.transceiver_entries = [entry.decode() \ + self.transceiver_entries = [entry \ for entry in transceiver_info] else: self.transceiver_entries = [] @@ -196,7 +196,7 @@ def _update_per_namespace_data(self, pubsub): if not msg: break - transceiver_entry = msg["channel"].split(b":")[-1].decode() + transceiver_entry = msg["channel"].split(":")[-1] data = msg['data'] # event data # extract interface name @@ -212,9 +212,9 @@ def _update_per_namespace_data(self, pubsub): in STATE_DB, skipping".format(transceiver_entry)) continue - if b"set" in data: + if "set" in data: self._update_transceiver_cache(interface) - elif b"del" in data: + elif "del" in data: # remove deleted transceiver remove_sub_ids = [mibs.get_transceiver_sub_id(ifindex)] @@ -268,7 +268,7 @@ def _update_transceiver_cache(self, interface): self.physical_mfg_name_map[sub_id], \ self.physical_model_name_map[sub_id] = get_transceiver_data(transceiver_info) - ifalias = self.if_alias_map.get(interface.encode(), b"").decode() + ifalias = self.if_alias_map.get(interface, "") # generate a description for this transceiver self.physical_description_map[sub_id] = get_transceiver_description(sfp_type, ifalias) @@ -282,7 +282,7 @@ def _update_transceiver_sensor_cache(self, interface): :param: interface: Interface name associated with transceiver """ - ifalias = self.if_alias_map.get(interface.encode(), b"").decode() + ifalias = self.if_alias_map.get(interface, "") ifindex = port_util.get_index_from_str(interface) # get transceiver sensors from transceiver dom entry in STATE DB @@ -293,7 +293,7 @@ def _update_transceiver_sensor_cache(self, interface): return # go over transceiver sensors - for sensor in map(bytes.decode, transceiver_dom_entry): + for sensor in transceiver_dom_entry: if sensor not in SENSOR_NAME_MAP: continue sensor_sub_id = mibs.get_transceiver_sensor_sub_id(ifindex, sensor) diff --git a/src/sonic_ax_impl/mibs/ietf/rfc2863.py b/src/sonic_ax_impl/mibs/ietf/rfc2863.py index 8ed4515d34cf..931c560f8f85 100644 --- a/src/sonic_ax_impl/mibs/ietf/rfc2863.py +++ b/src/sonic_ax_impl/mibs/ietf/rfc2863.py @@ -151,7 +151,7 @@ def interface_alias(self, sub_id): if not entry: return - return entry.get(b"description", "") + return entry.get("description", "") def get_counter32(self, sub_id, table_name): oid = self.get_oid(sub_id) @@ -183,12 +183,12 @@ def _get_counter(self, oid, table_name, mask): if oid in self.oid_lag_name_map: counter_value = 0 for lag_member in self.lag_name_if_name_map[self.oid_lag_name_map[oid]]: - counter_value += self._get_counter(mibs.get_index(lag_member), table_name, mask) + counter_value += self._get_counter(mibs.get_index_from_str(lag_member), table_name, mask) return counter_value & mask # Enum.name or table_name = 'name_of_the_table' - _table_name = bytes(getattr(table_name, 'name', table_name), 'utf-8') + _table_name = getattr(table_name, 'name', table_name) try: counter_value = self.if_counters[oid][_table_name] # truncate to 32-bit counter (database implements 64-bit counters) @@ -233,7 +233,7 @@ def get_high_speed(self, sub_id): if not entry: return - return int(entry.get(b"speed", 40000)) + return int(entry.get("speed", 40000)) class InterfaceMIBObjects(metaclass=MIBMeta, prefix='.1.3.6.1.2.1.31.1'): diff --git a/src/sonic_ax_impl/mibs/ietf/rfc3433.py b/src/sonic_ax_impl/mibs/ietf/rfc3433.py index 4e97b2babe5a..3cdc6ed5f633 100644 --- a/src/sonic_ax_impl/mibs/ietf/rfc3433.py +++ b/src/sonic_ax_impl/mibs/ietf/rfc3433.py @@ -280,7 +280,7 @@ def reinit_data(self): transceiver_dom_encoded = Namespace.dbs_keys(self.statedb, mibs.STATE_DB, self.TRANSCEIVER_DOM_KEY_PATTERN) if transceiver_dom_encoded: - self.transceiver_dom = [entry.decode() for entry in transceiver_dom_encoded] + self.transceiver_dom = [entry for entry in transceiver_dom_encoded] def update_data(self): """ @@ -311,11 +311,11 @@ def update_data(self): if not transceiver_dom_entry_data: continue - for sensor_key in map(bytes.decode, transceiver_dom_entry_data): + for sensor_key in transceiver_dom_entry_data: if sensor_key not in TRANSCEIVER_SENSOR_MAP: continue - raw_sensor_value = transceiver_dom_entry_data.get(sensor_key.encode()).decode() + raw_sensor_value = transceiver_dom_entry_data.get(sensor_key) sensor = get_transceiver_sensor(sensor_key) sub_id = mibs.get_transceiver_sensor_sub_id(ifindex, sensor_key) diff --git a/src/sonic_ax_impl/mibs/ietf/rfc4292.py b/src/sonic_ax_impl/mibs/ietf/rfc4292.py index c004338bb61f..a103360b1938 100644 --- a/src/sonic_ax_impl/mibs/ietf/rfc4292.py +++ b/src/sonic_ax_impl/mibs/ietf/rfc4292.py @@ -28,7 +28,7 @@ def reinit_data(self): ## Collect only ipv4 lo interfaces for loopback in loopbacks: - lostr = loopback.decode() + lostr = loopback loipmask = lostr[len("INTF_TABLE:lo:"):] loip = loipmask.split('/')[0] ipa = ipaddress.ip_address(loip) @@ -54,13 +54,13 @@ def update_data(self): return for route_entry in route_entries: - routestr = route_entry.decode() + routestr = route_entry ipnstr = routestr[len("ROUTE_TABLE:"):] if ipnstr == "0.0.0.0/0": ipn = ipaddress.ip_network(ipnstr) ent = Namespace.dbs_get_all(self.db_conn, mibs.APPL_DB, routestr, blocking=True) - nexthops = ent[b"nexthop"].decode() - ifnames = ent[b"ifname"].decode() + nexthops = ent["nexthop"] + ifnames = ent["ifname"] for nh, ifn in zip(nexthops.split(','), ifnames.split(',')): ## Ignore non front panel interfaces ## TODO: non front panel interfaces should not be in APPL_DB at very beginning diff --git a/src/sonic_ax_impl/mibs/ietf/rfc4363.py b/src/sonic_ax_impl/mibs/ietf/rfc4363.py index 1e321fc6dd0d..51d5e4f8c1bb 100644 --- a/src/sonic_ax_impl/mibs/ietf/rfc4363.py +++ b/src/sonic_ax_impl/mibs/ietf/rfc4363.py @@ -57,7 +57,7 @@ def update_data(self): return for s in fdb_strings: - fdb_str = s.decode() + fdb_str = s try: fdb = json.loads(fdb_str.split(":", maxsplit=2)[-1]) except ValueError as e: # includes simplejson.decoder.JSONDecodeError @@ -66,7 +66,7 @@ def update_data(self): ent = Namespace.dbs_get_all(self.db_conn, mibs.ASIC_DB, s, blocking=True) # Example output: oid:0x3a000000000608 - bridge_port_id = ent[b"SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID"][6:] + bridge_port_id = ent["SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID"][6:] if bridge_port_id not in self.if_bpid_map: continue port_id = self.if_bpid_map[bridge_port_id] diff --git a/src/sonic_ax_impl/mibs/vendor/cisco/bgp4.py b/src/sonic_ax_impl/mibs/vendor/cisco/bgp4.py index 33c1806ba162..c8475d56044f 100644 --- a/src/sonic_ax_impl/mibs/vendor/cisco/bgp4.py +++ b/src/sonic_ax_impl/mibs/vendor/cisco/bgp4.py @@ -35,11 +35,11 @@ def update_data(self): self.session_status_list = [] for neigh_key, db_index in self.neigh_state_map.items(): - neigh_str = neigh_key.decode() + neigh_str = neigh_key neigh_str = neigh_str.split('|')[1] neigh_info = self.db_conn[db_index].get_all(mibs.STATE_DB, neigh_key, blocking=False) if neigh_info is not None: - state = neigh_info[b'state'].decode() + state = neigh_info['state'] ip = ipaddress.ip_address(neigh_str) if type(ip) is ipaddress.IPv4Address: oid_head = (1, 4) @@ -52,7 +52,7 @@ def update_data(self): elif state in STATE_CODE: status = STATE_CODE[state] else: - continue + continue oid = oid_head + oid_ip self.session_status_list.append(oid) diff --git a/src/sonic_ax_impl/mibs/vendor/cisco/ciscoEntityFruControlMIB.py b/src/sonic_ax_impl/mibs/vendor/cisco/ciscoEntityFruControlMIB.py index d7d15c802c2d..1871bd34cb27 100644 --- a/src/sonic_ax_impl/mibs/vendor/cisco/ciscoEntityFruControlMIB.py +++ b/src/sonic_ax_impl/mibs/vendor/cisco/ciscoEntityFruControlMIB.py @@ -1,7 +1,6 @@ from enum import Enum, unique from sonic_ax_impl import mibs from ax_interface import MIBMeta, ValueType, SubtreeMIBEntry -from swsssdk import SonicV2Connector CHASSIS_INFO_KEY_TEMPLATE = 'chassis {}' PSU_INFO_KEY_TEMPLATE = 'PSU {}' @@ -10,21 +9,21 @@ PSU_STATUS_OK = 'true' @unique -class CHASSISInfoDB(bytes, Enum): +class CHASSISInfoDB(str, Enum): """ CHASSIS info keys """ - PSU_NUM = b"psu_num" + PSU_NUM = "psu_num" @unique -class PSUInfoDB(bytes, Enum): +class PSUInfoDB(str, Enum): """ PSU info keys """ - PRESENCE = b"presence" - STATUS = b"status" + PRESENCE = "presence" + STATUS = "status" def get_chassis_data(chassis_info): """ @@ -33,7 +32,7 @@ def get_chassis_data(chassis_info): Empty string if field not in chassis_info """ - return tuple(chassis_info.get(chassis_field.value, b"").decode() for chassis_field in CHASSISInfoDB) + return tuple(chassis_info.get(chassis_field.value, "") for chassis_field in CHASSISInfoDB) def get_psu_data(psu_info): """ @@ -42,7 +41,7 @@ def get_psu_data(psu_info): Empty string if field not in psu_info """ - return tuple(psu_info.get(psu_field.value, b"").decode() for psu_field in PSUInfoDB) + return tuple(psu_info.get(psu_field.value, "") for psu_field in PSUInfoDB) class PowerStatusHandler: """ @@ -52,7 +51,7 @@ def __init__(self): """ init the handler """ - self.statedb = SonicV2Connector() + self.statedb = mibs.init_db() self.statedb.connect(self.statedb.STATE_DB) def _get_num_psus(self): diff --git a/src/sonic_ax_impl/mibs/vendor/cisco/ciscoPfcExtMIB.py b/src/sonic_ax_impl/mibs/vendor/cisco/ciscoPfcExtMIB.py index fdb0b7766e89..ca2516cd500f 100644 --- a/src/sonic_ax_impl/mibs/vendor/cisco/ciscoPfcExtMIB.py +++ b/src/sonic_ax_impl/mibs/vendor/cisco/ciscoPfcExtMIB.py @@ -91,7 +91,7 @@ def _get_counter(self, oid, counter_name): """ # Enum.name or counter_name = 'name_of_the_table' - _counter_name = bytes(getattr(counter_name, 'name', counter_name), 'utf-8') + _counter_name = getattr(counter_name, 'name', counter_name) try: counter_value = self.if_counters[oid][_counter_name] @@ -117,7 +117,7 @@ def cpfc_if_requests(self, sub_id): if oid in self.oid_lag_name_map: counter_value = 0 for lag_member in self.lag_name_if_name_map[self.oid_lag_name_map[oid]]: - counter_value += self._get_counter(mibs.get_index(lag_member), counter_name) + counter_value += self._get_counter(mibs.get_index_from_str(lag_member), counter_name) return counter_value else: @@ -139,7 +139,7 @@ def cpfc_if_indications(self, sub_id): if oid in self.oid_lag_name_map: counter_value = 0 for lag_member in self.lag_name_if_name_map[self.oid_lag_name_map[oid]]: - counter_value += self._get_counter(mibs.get_index(lag_member), counter_name) + counter_value += self._get_counter(mibs.get_index_from_str(lag_member), counter_name) return counter_value else: @@ -211,7 +211,7 @@ def requests_per_priority(self, sub_id): if port_oid in self.oid_lag_name_map: counter_value = 0 for lag_member in self.lag_name_if_name_map[self.oid_lag_name_map[port_oid]]: - counter_value += self._get_counter(mibs.get_index(lag_member), counter_name) + counter_value += self._get_counter(mibs.get_index_from_str(lag_member), counter_name) return counter_value else: @@ -241,7 +241,7 @@ def indications_per_priority(self, sub_id): if port_oid in self.oid_lag_name_map: counter_value = 0 for lag_member in self.lag_name_if_name_map[self.oid_lag_name_map[port_oid]]: - counter_value += self._get_counter(mibs.get_index(lag_member), counter_name) + counter_value += self._get_counter(mibs.get_index_from_str(lag_member), counter_name) return counter_value else: diff --git a/src/sonic_ax_impl/mibs/vendor/cisco/ciscoSwitchQosMIB.py b/src/sonic_ax_impl/mibs/vendor/cisco/ciscoSwitchQosMIB.py index e113b02057d7..8b34a50d261d 100644 --- a/src/sonic_ax_impl/mibs/vendor/cisco/ciscoSwitchQosMIB.py +++ b/src/sonic_ax_impl/mibs/vendor/cisco/ciscoSwitchQosMIB.py @@ -10,21 +10,21 @@ # Maps SNMP queue stat counters to SAI counters and type CounterMap = { # Unicast send packets - (b'SAI_QUEUE_STAT_PACKETS', b'SAI_QUEUE_TYPE_UNICAST'): 1, + ('SAI_QUEUE_STAT_PACKETS', 'SAI_QUEUE_TYPE_UNICAST'): 1, # Unicast send bytes - (b'SAI_QUEUE_STAT_BYTES', b'SAI_QUEUE_TYPE_UNICAST'): 2, + ('SAI_QUEUE_STAT_BYTES', 'SAI_QUEUE_TYPE_UNICAST'): 2, # Multicast send packets - (b'SAI_QUEUE_STAT_PACKETS',b'SAI_QUEUE_TYPE_MULTICAST'): 3, + ('SAI_QUEUE_STAT_PACKETS','SAI_QUEUE_TYPE_MULTICAST'): 3, # Multicast send bytes - (b'SAI_QUEUE_STAT_BYTES',b'SAI_QUEUE_TYPE_MULTICAST'): 4, + ('SAI_QUEUE_STAT_BYTES','SAI_QUEUE_TYPE_MULTICAST'): 4, # Unicast dropped packets - (b'SAI_QUEUE_STAT_DROPPED_PACKETS',b'SAI_QUEUE_TYPE_UNICAST'): 5, + ('SAI_QUEUE_STAT_DROPPED_PACKETS','SAI_QUEUE_TYPE_UNICAST'): 5, # Unicast dropped bytes - (b'SAI_QUEUE_STAT_DROPPED_BYTES',b'SAI_QUEUE_TYPE_UNICAST'): 6, + ('SAI_QUEUE_STAT_DROPPED_BYTES','SAI_QUEUE_TYPE_UNICAST'): 6, # Multicast dropped packets - (b'SAI_QUEUE_STAT_DROPPED_PACKETS',b'SAI_QUEUE_TYPE_MULTICAST'): 7, + ('SAI_QUEUE_STAT_DROPPED_PACKETS','SAI_QUEUE_TYPE_MULTICAST'): 7, # Multicast dropped bytes - (b'SAI_QUEUE_STAT_DROPPED_BYTES', b'SAI_QUEUE_TYPE_MULTICAST'): 8 + ('SAI_QUEUE_STAT_DROPPED_BYTES', 'SAI_QUEUE_TYPE_MULTICAST'): 8 } diff --git a/tests/mock_tables/dbconnector.py b/tests/mock_tables/dbconnector.py index b9433ed059ad..324feb42c8b4 100644 --- a/tests/mock_tables/dbconnector.py +++ b/tests/mock_tables/dbconnector.py @@ -1,6 +1,7 @@ # MONKEY PATCH!!! import json import os +import sys import mockredis from swsssdk.interface import redis, DBInterface @@ -8,6 +9,12 @@ from swsssdk import SonicDBConfig +if sys.version_info >= (3, 0): + long = int + xrange = range + basestring = str + from functools import reduce + def clean_up_config(): # Set SonicDBConfig variables to initial state # so that it can be loaded with single or multiple @@ -52,6 +59,7 @@ def connect_SonicV2Connector(self, db_name, retry_on=True): self.dbintf.redis_kwargs['namespace'] = self.namespace # Mock DB filename for unit-test self.dbintf.redis_kwargs['db_name'] = db_name + self.dbintf.redis_kwargs['decode_responses'] = True _old_connect_SonicV2Connector(self, db_name, retry_on) @@ -76,7 +84,6 @@ def __call__(self, *args, **kwargs): INPUT_DIR = os.path.dirname(os.path.abspath(__file__)) - class SwssSyncClient(mockredis.MockRedis): def __init__(self, *args, **kwargs): super(SwssSyncClient, self).__init__(strict=True, *args, **kwargs) @@ -84,6 +91,7 @@ def __init__(self, *args, **kwargs): # to identify the file path to load the db json files. namespace = kwargs.pop('namespace') db_name = kwargs.pop('db_name') + self.decode_responses = kwargs.pop('decode_responses') == True fname = db_name.lower() + ".json" self.pubsub = MockPubSub() @@ -98,6 +106,23 @@ def __init__(self, *args, **kwargs): for k, v in table.items(): self.hset(h, k, v) + # Patch mockredis/mockredis/client.py + # The offical implementation assume decode_responses=False + # Here we detect the option first and only encode when decode_responses=False + def _encode(self, value): + "Return a bytestring representation of the value. Taken from redis-py connection.py" + if isinstance(value, bytes): + return value + elif isinstance(value, (int, long)): + value = str(value).encode('utf-8') + elif isinstance(value, float): + value = repr(value).encode('utf-8') + elif not isinstance(value, basestring): + value = str(value).encode('utf-8') + elif not self.decode_responses: + value = value.encode('utf-8', 'strict') + return value + # Patch mockredis/mockredis/client.py # The official implementation will filter out keys with a slash '/' # ref: https://github.com/locationlabs/mockredis/blob/master/mockredis/client.py @@ -106,20 +131,12 @@ def keys(self, pattern='*'): import fnmatch import re - # making sure the pattern is unicode/str. - try: - pattern = pattern.decode('utf-8') - # This throws an AttributeError in python 3, or an - # UnicodeEncodeError in python 2 - except (AttributeError, UnicodeEncodeError): - pass - # Make regex out of glob styled pattern. regex = fnmatch.translate(pattern) regex = re.compile(regex) # Find every key that matches the pattern - return [key for key in self.redis.keys() if regex.match(key.decode('utf-8'))] + return [key for key in self.redis.keys() if regex.match(key)] DBInterface._subscribe_keyspace_notification = _subscribe_keyspace_notification diff --git a/tests/namespace/test_lldp.py b/tests/namespace/test_lldp.py index ccdc1c35d563..96e940fa703d 100644 --- a/tests/namespace/test_lldp.py +++ b/tests/namespace/test_lldp.py @@ -133,13 +133,13 @@ def test_subtype_lldp_rem_man_addr_table(self): def test_local_port_identification(self): mib_entry = self.lut[(1, 0, 8802, 1, 1, 2, 1, 3, 7, 1, 3)] ret = mib_entry(sub_id=(1,)) - self.assertEquals(ret, b'etp1') + self.assertEquals(ret, 'etp1') print(ret) def test_mgmt_local_port_identification(self): mib_entry = self.lut[(1, 0, 8802, 1, 1, 2, 1, 3, 7, 1, 3)] ret = mib_entry(sub_id=(10001,)) - self.assertEquals(ret, b'mgmt1') + self.assertEquals(ret, 'mgmt1') print(ret) def test_getnextpdu_local_port_identification(self): diff --git a/tests/namespace/test_mibs.py b/tests/namespace/test_mibs.py index d34ddaa83575..3e76485cd32f 100644 --- a/tests/namespace/test_mibs.py +++ b/tests/namespace/test_mibs.py @@ -23,16 +23,16 @@ def test_init_namespace_sync_d_lag_tables(self): if_name_lag_name_map, \ oid_lag_name_map = Namespace.get_sync_d_from_all_namespace(mibs.init_sync_d_lag_tables, dbs) #PortChannel in asic0 Namespace - self.assertTrue(b"PortChannel01" in lag_name_if_name_map) - self.assertTrue(b"Ethernet-BP0" in lag_name_if_name_map[b"PortChannel01"]) - self.assertTrue(b"Ethernet-BP4" in lag_name_if_name_map[b"PortChannel01"]) + self.assertTrue("PortChannel01" in lag_name_if_name_map) + self.assertTrue("Ethernet-BP0" in lag_name_if_name_map["PortChannel01"]) + self.assertTrue("Ethernet-BP4" in lag_name_if_name_map["PortChannel01"]) #PortChannel in asic2 Namespace - self.assertTrue(b"PortChannel03" in lag_name_if_name_map) - self.assertTrue(b"Ethernet-BP16" in lag_name_if_name_map[b"PortChannel03"]) - self.assertTrue(b"Ethernet-BP20" in lag_name_if_name_map[b"PortChannel03"]) + self.assertTrue("PortChannel03" in lag_name_if_name_map) + self.assertTrue("Ethernet-BP16" in lag_name_if_name_map["PortChannel03"]) + self.assertTrue("Ethernet-BP20" in lag_name_if_name_map["PortChannel03"]) - self.assertTrue(b"PortChannel_Temp" in lag_name_if_name_map) - self.assertTrue(lag_name_if_name_map[b"PortChannel_Temp"] == []) + self.assertTrue("PortChannel_Temp" in lag_name_if_name_map) + self.assertTrue(lag_name_if_name_map["PortChannel_Temp"] == []) @classmethod def tearDownClass(cls): diff --git a/tests/test_lldp.py b/tests/test_lldp.py index b73bf1616974..a9ee5f2feee1 100644 --- a/tests/test_lldp.py +++ b/tests/test_lldp.py @@ -1,11 +1,14 @@ import os import sys +# noinspection PyUnresolvedReferences +import tests.mock_tables.dbconnector +from tests.mock_tables.dbconnector import SonicV2Connector + modules_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(modules_path, 'src')) from unittest import TestCase -import tests.mock_tables.dbconnector from ax_interface import ValueType from ax_interface.pdu_implementations import GetPDU, GetNextPDU @@ -112,13 +115,13 @@ def test_subtype_lldp_rem_man_addr_table(self): def test_local_port_identification(self): mib_entry = self.lut[(1, 0, 8802, 1, 1, 2, 1, 3, 7, 1, 3)] ret = mib_entry(sub_id=(1,)) - self.assertEquals(ret, b'etp1') + self.assertEquals(ret, 'etp1') print(ret) def test_mgmt_local_port_identification(self): mib_entry = self.lut[(1, 0, 8802, 1, 1, 2, 1, 3, 7, 1, 3)] ret = mib_entry(sub_id=(10001,)) - self.assertEquals(ret, b'mgmt1') + self.assertEquals(ret, 'mgmt1') print(ret) def test_getnextpdu_local_port_identification(self): diff --git a/tests/test_mibs.py b/tests/test_mibs.py index 5fdeb2030922..6fb461760c04 100644 --- a/tests/test_mibs.py +++ b/tests/test_mibs.py @@ -23,10 +23,10 @@ def test_init_sync_d_lag_tables(self): if_name_lag_name_map, \ oid_lag_name_map = Namespace.get_sync_d_from_all_namespace(mibs.init_sync_d_lag_tables, db_conn) - self.assertTrue(b"PortChannel04" in lag_name_if_name_map) - self.assertTrue(lag_name_if_name_map[b"PortChannel04"] == [b"Ethernet124"]) - self.assertTrue(b"Ethernet124" in if_name_lag_name_map) - self.assertTrue(if_name_lag_name_map[b"Ethernet124"] == b"PortChannel04") + self.assertTrue("PortChannel04" in lag_name_if_name_map) + self.assertTrue(lag_name_if_name_map["PortChannel04"] == ["Ethernet124"]) + self.assertTrue("Ethernet124" in if_name_lag_name_map) + self.assertTrue(if_name_lag_name_map["Ethernet124"] == "PortChannel04") - self.assertTrue(b"PortChannel_Temp" in lag_name_if_name_map) - self.assertTrue(lag_name_if_name_map[b"PortChannel_Temp"] == []) + self.assertTrue("PortChannel_Temp" in lag_name_if_name_map) + self.assertTrue(lag_name_if_name_map["PortChannel_Temp"] == [])