From b4e5c717f5e2c39ded81f0c6f7b0f9f61945befd Mon Sep 17 00:00:00 2001 From: Vratko Polak Date: Tue, 4 Sep 2018 19:19:11 +0200 Subject: [PATCH] Fix various pylint violations + SchedUtils.py: Do not use `len(SEQUENCE)` to determine if a sequence is empty + VatHistory.py: Do not use `len(SEQUENCE)` to determine if a sequence is empty + VppCounters.py: Do not use `len(SEQUENCE)` to determine if a sequence is empty + Memif.py: ++ Do not use `len(SEQUENCE)` to determine if a sequence is empty ++ Either all return statements in a function should return an expression, or none of them should. ++ Update :return: on possible None. + Classify.py: Unnecessary "else" after "return" + ContainerUtils.py: Useless super delegation in method '__init__' + CpuUtils.py: Do not use `len(SEQUENCE)` to determine if a sequence is empty + DropRateSearch.py: Either all return statements in a function should return an expression, or none of them should. + IPv4NodeAddress.py: Do not use `len(SEQUENCE)` to determine if a sequence is empty ++ Also improve docstrings. + IPv4Setup.py: Useless super delegation in method '__init__' + IPv6Setup.py: Do not use `len(SEQUENCE)` to determine if a sequence is empty ++ Also improve docstrings. + IPv6Setup.py: standard import "from ipaddress import IPv6Network" should be placed before "from robot.api import logger" + MacSwap.py: Trailing newlines + NATUtil.py: Do not use `len(SEQUENCE)` to determine if a sequence is empty + NodePath.py: Unnecessary "else" after "return" + Tap.py: Do not use `len(SEQUENCE)` to determine if a sequence is empty + topology.py: Either all return statements in a function should return an expression, or none of them should. + topology.py: Unnecessary "else" after "return" ++ Do not use `len(SEQUENCE)` to determine if a sequence is empty ++ Improve docstrings + DUTSetup.py: Do not use `len(SEQUENCE)` to determine if a sequence is empty ++ Also do not compare int(ret_code) just to access zero-ness. + ssh.py: Do not use `len(SEQUENCE)` to determine if a sequence is empty + InterfaceUtil.py: Unnecessary "else" after "return" Change-Id: Iba4244aa79661ee7df15fed5c7c6dbf04dfa88b2 Signed-off-by: Vratko Polak --- resources/libraries/python/Classify.py | 3 +-- resources/libraries/python/ContainerUtils.py | 8 ++---- resources/libraries/python/CpuUtils.py | 2 +- resources/libraries/python/DUTSetup.py | 37 ++++++++++++++------------- resources/libraries/python/DropRateSearch.py | 14 +++++----- resources/libraries/python/IPv4NodeAddress.py | 23 +++++++++++------ resources/libraries/python/IPv4Setup.py | 8 +++--- resources/libraries/python/IPv6Setup.py | 21 +++++++++------ resources/libraries/python/InterfaceUtil.py | 9 +++---- resources/libraries/python/MacSwap.py | 2 -- resources/libraries/python/Memif.py | 16 +++++++----- resources/libraries/python/NATUtil.py | 8 +++--- resources/libraries/python/NodePath.py | 3 +-- resources/libraries/python/SchedUtils.py | 2 +- resources/libraries/python/Tap.py | 2 +- resources/libraries/python/VatHistory.py | 12 ++++----- resources/libraries/python/VppCounters.py | 9 +++---- resources/libraries/python/ssh.py | 2 +- resources/libraries/python/topology.py | 36 +++++++++++++------------- 19 files changed, 111 insertions(+), 106 deletions(-) diff --git a/resources/libraries/python/Classify.py b/resources/libraries/python/Classify.py index 2510da0b77..a59acad5c7 100644 --- a/resources/libraries/python/Classify.py +++ b/resources/libraries/python/Classify.py @@ -362,8 +362,7 @@ class Classify(object): ) if session_index is not None: return data[0][session_index] - else: - return data[0] + return data[0] @staticmethod def vpp_log_plugin_acl_settings(node): diff --git a/resources/libraries/python/ContainerUtils.py b/resources/libraries/python/ContainerUtils.py index 54bbdbbc04..478a9781a0 100644 --- a/resources/libraries/python/ContainerUtils.py +++ b/resources/libraries/python/ContainerUtils.py @@ -479,9 +479,7 @@ class ContainerEngine(object): class LXC(ContainerEngine): """LXC implementation.""" - def __init__(self): - """Initialize LXC object.""" - super(LXC, self).__init__() + # Implicit constructor is inherited. def acquire(self, force=True): """Acquire a privileged system object where configuration is stored. @@ -672,9 +670,7 @@ class LXC(ContainerEngine): class Docker(ContainerEngine): """Docker implementation.""" - def __init__(self): - """Initialize Docker object.""" - super(Docker, self).__init__() + # Implicit constructor is inherited. def acquire(self, force=True): """Pull an image or a repository from a registry. diff --git a/resources/libraries/python/CpuUtils.py b/resources/libraries/python/CpuUtils.py index 5d8b8a64a3..f4d52f8662 100644 --- a/resources/libraries/python/CpuUtils.py +++ b/resources/libraries/python/CpuUtils.py @@ -82,7 +82,7 @@ class CpuUtils(object): ret, stderr)) node['cpuinfo'] = list() for line in stdout.split("\n"): - if len(line) > 0 and line[0] != "#": + if line and line[0] != "#": node['cpuinfo'].append([CpuUtils.__str2int(x) for x in line.split(",")]) diff --git a/resources/libraries/python/DUTSetup.py b/resources/libraries/python/DUTSetup.py index 632e9ea073..8f9e94d560 100644 --- a/resources/libraries/python/DUTSetup.py +++ b/resources/libraries/python/DUTSetup.py @@ -42,7 +42,7 @@ class DUTSetup(object): 'ActiveEnterTimestamp {name}` | ' 'awk \'{{print $2 $3}}\')"'. format(name=service)) - if int(ret_code) != 0: + if int(ret_code): raise RuntimeError('DUT {host} failed to get logs from unit {name}'. format(host=node['host'], name=service)) @@ -75,7 +75,7 @@ class DUTSetup(object): ret_code, _, _ = \ ssh.exec_command_sudo('service {name} restart'. format(name=service), timeout=120) - if int(ret_code) != 0: + if int(ret_code): raise RuntimeError('DUT {host} failed to start service {name}'. format(host=node['host'], name=service)) @@ -178,7 +178,7 @@ class DUTSetup(object): ssh.exec_command('sudo -Sn bash {0}/{1}/dut_setup.sh'. format(Constants.REMOTE_FW_DIR, Constants.RESOURCES_LIB_SH), timeout=120) - if int(ret_code) != 0: + if int(ret_code): raise RuntimeError('DUT test setup script failed at node {name}'. format(name=node['host'])) @@ -200,14 +200,14 @@ class DUTSetup(object): logger.trace('Try {}: Get VPP PID'.format(i)) ret_code, stdout, stderr = ssh.exec_command('pidof vpp') - if int(ret_code) != 0: + if int(ret_code): raise RuntimeError('Not possible to get PID of VPP process ' 'on node: {0}\n {1}'. format(node['host'], stdout + stderr)) if len(stdout.splitlines()) == 1: return int(stdout) - elif len(stdout.splitlines()) == 0: + elif not stdout.splitlines(): logger.debug("No VPP PID found on node {0}". format(node['host'])) continue @@ -274,7 +274,7 @@ class DUTSetup(object): # Try to read number of VFs from PCI address of QAT device for _ in range(3): ret_code, stdout, _ = ssh.exec_command(cmd) - if int(ret_code) == 0: + if not int(ret_code): try: sriov_numvfs = int(stdout) except ValueError: @@ -328,7 +328,7 @@ class DUTSetup(object): format(numvfs, cryptodev.replace(':', r'\:'), timeout=180) ret_code, _, _ = ssh.exec_command_sudo("sh -c '{0}'".format(cmd)) - if int(ret_code) != 0: + if int(ret_code): raise RuntimeError('Failed to initialize {0} VFs on QAT device ' ' on host {1}'.format(numvfs, node['host'])) @@ -351,7 +351,7 @@ class DUTSetup(object): "sh -c 'echo {0} | tee /sys/bus/pci/devices/{1}/driver/unbind'" .format(pci_addr, pci_addr.replace(':', r'\:')), timeout=180) - if int(ret_code) != 0: + if int(ret_code): raise RuntimeError('Failed to unbind PCI device {0} from driver on ' 'host {1}'.format(pci_addr, node['host'])) @@ -376,7 +376,7 @@ class DUTSetup(object): "sh -c 'echo {0} | tee /sys/bus/pci/drivers/{1}/bind'".format( pci_addr, driver), timeout=180) - if int(ret_code) != 0: + if int(ret_code): raise RuntimeError('Failed to bind PCI device {0} to {1} driver on ' 'host {2}'.format(pci_addr, driver, node['host'])) @@ -410,14 +410,15 @@ class DUTSetup(object): for i in range(3): logger.trace('Try number {0}: Get PCI device driver'.format(i)) + cmd = 'lspci -vmmks {0}'.format(pci_addr) ret_code, stdout, _ = ssh.exec_command(cmd) - if int(ret_code) != 0: + if int(ret_code): raise RuntimeError("'{0}' failed on '{1}'" .format(cmd, node['host'])) for line in stdout.splitlines(): - if len(line) == 0: + if not line: continue name = None value = None @@ -459,7 +460,7 @@ class DUTSetup(object): cmd = 'grep -w {0} /proc/modules'.format(module) ret_code, _, _ = ssh.exec_command(cmd) - if int(ret_code) != 0: + if int(ret_code): if force_load: # Module is not loaded and we want to load it DUTSetup.kernel_module_load(node, module) @@ -513,7 +514,7 @@ class DUTSetup(object): ret_code, _, _ = ssh.exec_command_sudo("modprobe {0}".format(module)) - if int(ret_code) != 0: + if int(ret_code): raise RuntimeError('Failed to load {0} kernel module on host {1}'. format(module, node['host'])) @@ -567,13 +568,13 @@ class DUTSetup(object): cmd = "[[ -f /etc/redhat-release ]]" return_code, _, _ = ssh.exec_command(cmd) - if int(return_code) == 0: + if not int(return_code): # workaroud - uninstall existing vpp installation until # start-testcase script is updated on all virl servers rpm_pkgs_remove = "vpp*" cmd_u = 'yum -y remove "{0}"'.format(rpm_pkgs_remove) r_rcode, _, r_err = ssh.exec_command_sudo(cmd_u, timeout=90) - if int(r_rcode) != 0: + if int(r_rcode): raise RuntimeError('Failed to remove previous VPP' 'installation on host {0}:\n{1}' .format(node['host'], r_err)) @@ -582,7 +583,7 @@ class DUTSetup(object): for pkg in vpp_rpm_pkgs) + "*.rpm" cmd_i = "rpm -ivh {0}".format(rpm_pkgs) ret_code, _, err = ssh.exec_command_sudo(cmd_i, timeout=90) - if int(ret_code) != 0: + if int(ret_code): raise RuntimeError('Failed to install VPP on host {0}:' '\n{1}'.format(node['host'], err)) else: @@ -595,7 +596,7 @@ class DUTSetup(object): deb_pkgs_remove = "vpp*" cmd_u = 'apt-get purge -y "{0}"'.format(deb_pkgs_remove) r_rcode, _, r_err = ssh.exec_command_sudo(cmd_u, timeout=90) - if int(r_rcode) != 0: + if int(r_rcode): raise RuntimeError('Failed to remove previous VPP' 'installation on host {0}:\n{1}' .format(node['host'], r_err)) @@ -603,7 +604,7 @@ class DUTSetup(object): for pkg in vpp_deb_pkgs) + "*.deb" cmd_i = "dpkg -i --force-all {0}".format(deb_pkgs) ret_code, _, err = ssh.exec_command_sudo(cmd_i, timeout=90) - if int(ret_code) != 0: + if int(ret_code): raise RuntimeError('Failed to install VPP on host {0}:' '\n{1}'.format(node['host'], err)) else: diff --git a/resources/libraries/python/DropRateSearch.py b/resources/libraries/python/DropRateSearch.py index 912d2e9f53..9b7c46668d 100644 --- a/resources/libraries/python/DropRateSearch.py +++ b/resources/libraries/python/DropRateSearch.py @@ -403,10 +403,9 @@ class DropRateSearch(object): while True: res = [] for dummy in range(self._max_attempts): - res.append(self.measure_loss(rate, self._frame_size, - self._loss_acceptance, - self._loss_acceptance_type, - traffic_type)) + res.append(self.measure_loss( + rate, self._frame_size, self._loss_acceptance, + self._loss_acceptance_type, traffic_type)) res = self._get_res_based_on_search_type(res) @@ -475,11 +474,10 @@ class DropRateSearch(object): :rtype: tuple :raises Exception: If search failed. """ - if self._search_result == SearchResults.FAILURE: - raise Exception('Search FAILED') - elif self._search_result in [SearchResults.SUCCESS, - SearchResults.SUSPICIOUS]: + if self._search_result in [ + SearchResults.SUCCESS, SearchResults.SUSPICIOUS]: return self._search_result_rate, self.get_latency() + raise Exception('Search FAILED') def binary_search(self, b_min, b_max, traffic_type, skip_max_rate=False, skip_warmup=False): diff --git a/resources/libraries/python/IPv4NodeAddress.py b/resources/libraries/python/IPv4NodeAddress.py index 27d55b7bb6..de96c189e5 100644 --- a/resources/libraries/python/IPv4NodeAddress.py +++ b/resources/libraries/python/IPv4NodeAddress.py @@ -26,26 +26,33 @@ IPV4_NETWORKS = ['192.168.{}.0/24'.format(i) for i in range(1, 100)] class IPv4NetworkGenerator(object): - """IPv4 network generator.""" + """IPv4 network generator. + + TODO: Conform to https://docs.python.org/2/library/stdtypes.html#typeiter + """ + def __init__(self, networks): - """ + """Populate internal list of valid networks. + :param networks: List of strings containing IPv4 subnet - with prefix length. + with prefix length. :type networks: list + :raise RuntimeError: If no IPv4 networks are added. """ - self._networks = list() + self._networks = [] for network in networks: net = IPv4Network(unicode(network)) self._networks.append(net) - if len(self._networks) == 0: - raise Exception('No IPv4 networks') + if not self._networks: + raise RuntimeError("No IPv4 networks") def next_network(self): - """ + """Pop and return network from internal list. + :returns: Next network in form (IPv4Network, subnet). :raises StopIteration: If there are no more elements. """ - if len(self._networks): + if self._networks: return self._networks.pop() else: raise StopIteration() diff --git a/resources/libraries/python/IPv4Setup.py b/resources/libraries/python/IPv4Setup.py index f9b067d0d8..b018bceacf 100644 --- a/resources/libraries/python/IPv4Setup.py +++ b/resources/libraries/python/IPv4Setup.py @@ -118,8 +118,8 @@ class IPv4Node(object): class Tg(IPv4Node): """Traffic generator node""" - def __init__(self, node_info): - super(Tg, self).__init__(node_info) + + # Implicit constructor is inherited. def _execute(self, cmd): """Executes the specified command on TG using SSH. @@ -179,8 +179,8 @@ class Tg(IPv4Node): class Dut(IPv4Node): """Device under test""" - def __init__(self, node_info): - super(Dut, self).__init__(node_info) + + # Implicit contructor is inherited. def get_sw_if_index(self, interface): """Get sw_if_index of specified interface from current node. diff --git a/resources/libraries/python/IPv6Setup.py b/resources/libraries/python/IPv6Setup.py index e0de406a4a..260c08b198 100644 --- a/resources/libraries/python/IPv6Setup.py +++ b/resources/libraries/python/IPv6Setup.py @@ -13,8 +13,8 @@ """Library to set up IPv6 in topology.""" -from robot.api import logger from ipaddress import IPv6Network +from robot.api import logger from resources.libraries.python.ssh import SSH from resources.libraries.python.topology import NodeType, Topology @@ -25,17 +25,22 @@ from resources.libraries.python.VatExecutor import VatTerminal, VatExecutor class IPv6Networks(object): """IPv6 network iterator. - :param networks: List of the available IPv6 networks. - :type networks: list + TODO: Conform to https://docs.python.org/2/library/stdtypes.html#typeiter """ + def __init__(self, networks): - self._networks = list() + """Initialize internal list of valid networks. + + :param networks: List of the available IPv6 networks. + :type networks: list + :raise RuntimeError: If no networks were added. + """ + self._networks = [] for network in networks: net = IPv6Network(unicode(network)) self._networks.append(net) - num = len(self._networks) - if num == 0: - raise Exception('No IPv6 networks') + if not self._networks: + raise RuntimeError('No IPv6 networks') def next_network(self): """Get the next element of the iterator. @@ -44,7 +49,7 @@ class IPv6Networks(object): :rtype: IPv6Network object :raises StopIteration: If there is no more elements. """ - if len(self._networks): + if self._networks: return self._networks.pop() else: raise StopIteration() diff --git a/resources/libraries/python/InterfaceUtil.py b/resources/libraries/python/InterfaceUtil.py index 94cee5ecbc..e43935eb7b 100644 --- a/resources/libraries/python/InterfaceUtil.py +++ b/resources/libraries/python/InterfaceUtil.py @@ -783,11 +783,10 @@ class InterfaceUtil(object): "tap_dump.vat") if name is None: return response[0] - else: - for item in response[0]: - if name == item['dev_name']: - return item - return {} + for item in response[0]: + if name == item['dev_name']: + return item + return {} @staticmethod def create_subinterface(node, interface, sub_id, outer_vlan_id=None, diff --git a/resources/libraries/python/MacSwap.py b/resources/libraries/python/MacSwap.py index 1ec6a5d216..ebcf95eae2 100644 --- a/resources/libraries/python/MacSwap.py +++ b/resources/libraries/python/MacSwap.py @@ -59,5 +59,3 @@ class MacSwap(object): else: raise ValueError('Node {} has not DUT NodeType: "{}"'. format(node['host'], node['type'])) - - diff --git a/resources/libraries/python/Memif.py b/resources/libraries/python/Memif.py index acde3ecc17..76e775fcca 100644 --- a/resources/libraries/python/Memif.py +++ b/resources/libraries/python/Memif.py @@ -145,7 +145,7 @@ class Memif(object): memif_data = memif_data.replace(garbage, '') for line in memif_data.splitlines(): - if line.startswith('Sending') or len(line) == 0: + if not line or line.startswith('Sending'): continue elif line.startswith('memif'): if memif_name: @@ -177,7 +177,7 @@ class Memif(object): :param sw_if_idx: DUT node. :type node: dict :type sw_if_idx: int - :returns: Memif interface name. + :returns: Memif interface name, or None if not found. :rtype: str """ with VatTerminal(node, json_param=False) as vat: @@ -196,7 +196,7 @@ class Memif(object): :param sw_if_idx: DUT node. :type node: dict :type sw_if_idx: int - :returns: Memif interface MAC address. + :returns: Memif interface MAC address, or None if not found. :rtype: str """ with VatTerminal(node, json_param=False) as vat: @@ -205,6 +205,7 @@ class Memif(object): for item in memif_data: if memif_data[item]['sw_if_index'] == str(sw_if_idx): return memif_data[item].get('mac', None) + return None @staticmethod def vpp_get_memif_interface_socket(node, sw_if_idx): @@ -214,7 +215,7 @@ class Memif(object): :param sw_if_idx: DUT node. :type node: dict :type sw_if_idx: int - :returns: Memif interface socket path. + :returns: Memif interface socket path, or None if not found. :rtype: str """ with VatTerminal(node, json_param=False) as vat: @@ -223,6 +224,7 @@ class Memif(object): for item in memif_data: if memif_data[item]['sw_if_index'] == str(sw_if_idx): return memif_data[item].get('socket', None) + return None @staticmethod def vpp_get_memif_interface_id(node, sw_if_idx): @@ -232,7 +234,7 @@ class Memif(object): :param sw_if_idx: DUT node. :type node: dict :type sw_if_idx: int - :returns: Memif interface ID. + :returns: Memif interface ID, or None if not found. :rtype: int """ with VatTerminal(node, json_param=False) as vat: @@ -241,6 +243,7 @@ class Memif(object): for item in memif_data: if memif_data[item]['sw_if_index'] == str(sw_if_idx): return int(memif_data[item].get('id', None)) + return None @staticmethod def vpp_get_memif_interface_role(node, sw_if_idx): @@ -250,7 +253,7 @@ class Memif(object): :param sw_if_idx: DUT node. :type node: dict :type sw_if_idx: int - :returns: Memif interface role. + :returns: Memif interface role, or None if not found. :rtype: int """ with VatTerminal(node, json_param=False) as vat: @@ -259,3 +262,4 @@ class Memif(object): for item in memif_data: if memif_data[item]['sw_if_index'] == str(sw_if_idx): return memif_data[item].get('role', None) + return None diff --git a/resources/libraries/python/NATUtil.py b/resources/libraries/python/NATUtil.py index ab97e05dcc..e08a6daf82 100644 --- a/resources/libraries/python/NATUtil.py +++ b/resources/libraries/python/NATUtil.py @@ -197,9 +197,9 @@ class NATUtil(object): items = line.split(" ") while "" in items: items.remove("") - if len(items) == 0: + if not items: continue - elif len(items) == 4: + if len(items) == 4: # no ports were returned data.append({ "local_address": items[0], @@ -246,9 +246,9 @@ class NATUtil(object): for trash in ("", "vat#"): while trash in items: items.remove(trash) - if len(items) == 0: + if not items: continue - elif len(items) == 3: + if len(items) == 3: data.append({ # items[0] is the table header - "sw_if_index" "sw_if_index": items[1], diff --git a/resources/libraries/python/NodePath.py b/resources/libraries/python/NodePath.py index f41103046f..ec84a8b08b 100644 --- a/resources/libraries/python/NodePath.py +++ b/resources/libraries/python/NodePath.py @@ -151,8 +151,7 @@ class NodePath(object): """ if not self._path_iter: return None, None - else: - return self._path_iter.pop() + return self._path_iter.pop() def first_interface(self): """Return first interface on the path. diff --git a/resources/libraries/python/SchedUtils.py b/resources/libraries/python/SchedUtils.py index ec18b98dac..b4c57217bd 100644 --- a/resources/libraries/python/SchedUtils.py +++ b/resources/libraries/python/SchedUtils.py @@ -45,7 +45,7 @@ class SchedUtils(object): print 'Reading VPP worker thread PID failed.' else: for pid in out.split("\n"): - if len(pid) > 0 and pid[0] != "#": + if pid and pid[0] != '#': SchedUtils.set_proc_scheduling_rr(node, int(pid)) break else: diff --git a/resources/libraries/python/Tap.py b/resources/libraries/python/Tap.py index ffcd00cdaf..6b8ae87c04 100644 --- a/resources/libraries/python/Tap.py +++ b/resources/libraries/python/Tap.py @@ -120,7 +120,7 @@ class Tap(object): :raises RuntimeError: Specified interface was not found. """ tap_if = InterfaceUtil.tap_dump(node, tap_name) - if len(tap_if) == 0: + if not tap_if: raise RuntimeError( 'Tap interface :{} does not exist'.format(tap_name)) diff --git a/resources/libraries/python/VatHistory.py b/resources/libraries/python/VatHistory.py index e273746f9b..ffc1644f1b 100644 --- a/resources/libraries/python/VatHistory.py +++ b/resources/libraries/python/VatHistory.py @@ -71,12 +71,12 @@ class VatHistory(object): :type node: dict """ if node['type'] == NodeType.DUT: - sequence = "\nno VAT command executed"\ - if len(DICT__DUTS_VAT_HISTORY[node['host']]) == 0\ - else "".join("\n{}".format(cmd) - for cmd in DICT__DUTS_VAT_HISTORY[node['host']]) - logger.trace("{0} VAT command history:{1}\n". - format(node['host'], sequence)) + sequence = "\nno VAT command executed" + if DICT__DUTS_VAT_HISTORY[node['host']]: + sequence = "".join(["\n{}".format( + cmd) for cmd in DICT__DUTS_VAT_HISTORY[node['host']]]) + logger.trace( + "{0} VAT command history:{1}\n".format(node['host'], sequence)) @staticmethod def show_vat_history_on_all_duts(nodes): diff --git a/resources/libraries/python/VppCounters.py b/resources/libraries/python/VppCounters.py index 5dc14a9a4e..b2c3b01c60 100644 --- a/resources/libraries/python/VppCounters.py +++ b/resources/libraries/python/VppCounters.py @@ -208,8 +208,7 @@ class VppCounters(object): vat.vat_terminal_exec_cmd('want_stats enable') for _ in range(0, 12): stats_table = vat.vat_terminal_exec_cmd('dump_stats_table') - if_counters = stats_table['interface_counters'] - if len(if_counters) > 0: + if stats_table['interface_counters']: self._stats_table = stats_table return stats_table time.sleep(1) @@ -259,15 +258,15 @@ class VppCounters(object): return 0 if_counters = self._stats_table.get('interface_counters') - if if_counters is None or len(if_counters) == 0: + if not if_counters: logger.trace('No interface counters.') return 0 for counter in if_counters: if counter['vnet_counter_type'] == version: data = counter['data'] return data[if_index] - logger.trace('{i} {v} counter not found.'.format(i=interface, - v=version)) + logger.trace('{i} {v} counter not found.'.format( + i=interface, v=version)) return 0 @staticmethod diff --git a/resources/libraries/python/ssh.py b/resources/libraries/python/ssh.py index 7368c6980a..06cd96010d 100644 --- a/resources/libraries/python/ssh.py +++ b/resources/libraries/python/ssh.py @@ -370,7 +370,7 @@ def exec_cmd(node, cmd, timeout=600, sudo=False): raise TypeError('Node parameter is None') if cmd is None: raise TypeError('Command parameter is None') - if len(cmd) == 0: + if not cmd: raise ValueError('Empty command parameter') ssh = SSH() diff --git a/resources/libraries/python/topology.py b/resources/libraries/python/topology.py index d60bed1b5b..82516beb6b 100644 --- a/resources/libraries/python/topology.py +++ b/resources/libraries/python/topology.py @@ -394,13 +394,13 @@ class Topology(object): :type node: dict :type iface_key: str/int :returns: Return sw_if_index or None if not found. + :rtype: int or None """ try: if isinstance(iface_key, basestring): return node['interfaces'][iface_key].get('vpp_sw_index') # TODO: use only iface_key, do not use integer - else: - return int(iface_key) + return int(iface_key) except (KeyError, ValueError): return None @@ -416,11 +416,10 @@ class Topology(object): :raises TypeError: If provided interface name is not a string. """ try: - if isinstance(iface_name, basestring): - iface_key = Topology.get_interface_by_name(node, iface_name) - return node['interfaces'][iface_key].get('vpp_sw_index') - else: + if not isinstance(iface_name, basestring): raise TypeError("Interface name must be a string.") + iface_key = Topology.get_interface_by_name(node, iface_name) + return node['interfaces'][iface_key].get('vpp_sw_index') except (KeyError, ValueError): return None @@ -565,6 +564,8 @@ class Topology(object): :param iface_keys: Interface keys for lookup. :type node: dict :type iface_keys: strings + :returns: Numa node of most given interfaces or 0. + :rtype: int """ numa_list = [] for if_key in iface_keys: @@ -575,12 +576,11 @@ class Topology(object): numa_cnt_mc = Counter(numa_list).most_common() - if len(numa_cnt_mc) > 0 and numa_cnt_mc[0][0] != -1: + if numa_cnt_mc and numa_cnt_mc[0][0] != -1: return numa_cnt_mc[0][0] - elif len(numa_cnt_mc) > 1 and numa_cnt_mc[0][0] == -1: + if len(numa_cnt_mc) > 1 and numa_cnt_mc[0][0] == -1: return numa_cnt_mc[1][0] - else: - return 0 + return 0 @staticmethod def get_interface_mac(node, iface_key): @@ -650,6 +650,7 @@ class Topology(object): continue if if_val['link'] == link_name: return node_data, if_key + return None @staticmethod def get_interface_pci_addr(node, iface_key): @@ -716,8 +717,8 @@ class Topology(object): :param filter_list: Link filter criteria. :type node: dict :type filter_list: list of strings - :returns: List of strings representing link names occupied by the node. - :rtype: list + :returns: List of link names occupied by the node. + :rtype: None or list of string """ interfaces = node['interfaces'] link_names = [] @@ -732,7 +733,7 @@ class Topology(object): .format(str(interface))) else: link_names.append(interface['link']) - if len(link_names) == 0: + if not link_names: link_names = None return link_names @@ -782,15 +783,14 @@ class Topology(object): :param node2: Connected node. :type node1: dict :type node2: dict - :returns: Name of link connecting the two nodes together. + :returns: Name of a link connecting the two nodes together. :rtype: str :raises RuntimeError: If no links are found. """ connecting_links = self.get_active_connecting_links(node1, node2) - if len(connecting_links) == 0: + if not connecting_links: raise RuntimeError("No links connecting the nodes were found") - else: - return connecting_links[0] + return connecting_links[0] @keyword('Get egress interfaces name on "${node1}" for link with ' '"${node2}"') @@ -806,7 +806,7 @@ class Topology(object): """ interfaces = [] links = self.get_active_connecting_links(node1, node2) - if len(links) == 0: + if not links: raise RuntimeError('No link between nodes') for interface in node1['interfaces'].values(): link = interface.get('link') -- 2.16.6