def Shuffle(self, force_seed_value=None): """ randomize the dict keys entries saving and printing the seed value for recovery :param force_seed_value: if given will use the seed value to randomize list :type force_seed_value:int :return: True on success :rtype: """ res = True max_random_size = 10000000 SEED = 0 funcname = GetFunctionName(self.Shuffle) if not list(self.keys()): err = funcname + "dict is empty" print(err) res = False else: self._orig_dict = OrderedDict(self) # save original dictionary self.random_seed_value = force_seed_value if force_seed_value is None: # generate random seed value since it was not self.random_seed_value = random.randrange(max_random_size) random.seed(self.random_seed_value) if self.logger: self.logger.debug( funcname + " Seed Value: {}".format(self.random_seed_value)) keys = list(self.keys()) random.shuffle(keys) new_dict = RandomOrderedDict(self.logger) for index, value in enumerate(self.values()): self[keys[index]] = value return res
def verifyReceivedTrafficIsAsExpected(self, tx_port, rx_port): """ verifies that the whole transmitted traffic was received and that no packet loss occurred nor errors :param tx_port: the transmitting port :param rx_port: the receiving port :return: """ funcname = GetFunctionName(self.verifyReceivedTrafficIsAsExpected) dbg = funcname + "Verify received traffic on port is as expected" self.logger.debug(dbg) status = self._verifyTrafficOnPort(tx_port, rx_port) if status: if 'ECMP_unicast_traffic_distribution_remaining_paths' in self._testClassref.testName: if rx_port.id == 2: dbg = funcname + f"Passed! packet not went through Ecmp nexthop {rx_port.DutDevPort.name}" self.logger.debug(dbg) else: dbg = funcname + f"Passed! packet been received for Ecmp nexthop {rx_port.DutDevPort.name}" self.logger.debug(dbg) elif 'ECMP_link_down_nexthops' in self._testClassref.testName: dbg = funcname + f"Passed! packet not went through Ecmp nexthop {rx_port.DutDevPort.name}" self.logger.debug(dbg) else: dbg = funcname + f"Passed! packet been received for Ecmp nexthop {rx_port.DutDevPort.name}" self.logger.debug(dbg) else: dbg = funcname + f"Failed! Ecmp nexthop {rx_port.DutDevPort.name} didn't receive any packets" self.FailTheTest(dbg)
def reseting_dev_and_verifying_new_ver(self): funcname = GetFunctionName(self.reseting_dev_and_verifying_new_ver) self._uboot_channel_host.WaitForPatternAndSendCommand( ExpectedPrompt=self._uboot_prompt.uboot_prompt, command="reset", timeOutSeconds=60) self._uboot_channel_host.WaitForPatternAndSendCommand( ExpectedPrompt=self._uboot_prompt.loaded_prompt, command="root", timeOutSeconds=600) self._uboot_channel_host.WaitForPatternAndSendCommand( ExpectedPrompt=self._uboot_prompt.dev_prompt, command="modinfo prestera_sw", timeOutSeconds=60) self._uboot_channel_host.WaitForPatternAndSendCommand( ExpectedPrompt=self._uboot_prompt.dev_prompt, command="", timeOutSeconds=60) self._uboot_class_ref.login() if self._uboot_class_ref.host_kernel_version(): self._uboot_class_ref._testclassref.TestData.DutInfo.Host_kernel_version = self._uboot_class_ref.host_kernel_version( ) if self._uboot_class_ref.uboot_version(): self._uboot_class_ref._testclassref.TestData.DutInfo.UBOOT_Version = self._uboot_class_ref.uboot_version( ) if self._uboot_class_ref.software_version(): self._uboot_class_ref._testclassref.TestData.DutInfo.Software_Version = self._uboot_class_ref.software_version( )
def _detect_context(self): funcname = GetFunctionName(self._detect_context) if self.channel is not None: if self._promptlist_re is not None: # try to detect context ret_prompts = self.channel.SendCommandAndGetFoundPatterns(self.channel.newlineChar, self._promptlist_re, False) if not not ret_prompts: # found something if len(ret_prompts) > 1: msg = funcname + " there are more than 1 found prompts that matches to input contexts\n" msg += "found prompts patterns: {\n}".join(ret_prompts) msg += "\nChoosing First Match" GlobalLogger.logger.debug(msg) for matched_prompt in ret_prompts: if self._prompt2Context.get(matched_prompt,None): self.context = self._prompt2Context[matched_prompt] elif len(ret_prompts) == 1: if self._prompt2Context.get(ret_prompts[0],None): self.context = self._prompt2Context[ret_prompts[0]] else: err = funcname+": the found context prompt '{}' has no associated context in {} dictionary"\ .format(ret_prompts[0],self.__class__.__name__) raise TestCrashedException(err) return self.context else: return None else: err = funcname + "can't detect context since prompt2Context dictionary is not initilized" raise TestCrashedException(err) else: err = funcname + "can't detect context since communication channel to Dut is not initilized" raise TestCrashedException(err) pass
def addIPv4ProtocolInterface(self, port, srcIP, gateway, macAddress, mask=24): funcname = GetFunctionName(self.addIPv4ProtocolInterface) self.logger.debug( funcname + f"Setting up IPv4 protocol interface on port {getTGRep(port.TGPort)}" ) tgPort = port.TGPort tgPort.protocol_managment.enable_ARP = True portIntKey = tgPort.protocol_managment.protocol_interfaces.add_interface( ) portInt = tgPort.protocol_managment.protocol_interfaces.interfaces[ portIntKey] portInt.enable = True portInt.mac_addr = macAddress portInt.description = str(port) portInt.ipv4.mask = mask portInt.ipv4.address = srcIP portInt.ipv4.gateway = gateway tgPort.protocol_managment.protocol_interfaces.auto_arp = True return portIntKey
def configureLLDPInterval(self, interval): funcname = GetFunctionName(self.configureLLDPInterval) ret = LLDP_config.setLLDPTxInterval(interval) if ret: self.FailTheTest( f"{funcname} {ret} unable to set tx-interval {interval}") self.Add_Cleanup_Function_To_Stack(LLDP_config.setLLDPTxInterval, 30)
def setupStream(self, tgDutLinks, srcMac='AA:AA:AA:AA:AA:00', dstMac='ff:ff:ff:ff:ff:ff'): """ :param tgDutLinks: BastTest.TGDutLinks dict :param srcMac: the source mac address :param dstMac: the destination mac address """ funcname = GetFunctionName(self.setupStream) for txPort, txDits in self._txInterfaces.items(): TGTxPort = tgDutLinks[int(txPort)].TGPort # type: Port self.logger.debug(funcname + 'Setting up stream on: ' + getTGRep(TGTxPort)) for vlanTested in txDits['packet_vids']: TGTxPort.add_stream(f'testPacketVID#{vlanTested}') stream = TGTxPort.streams[f'testPacketVID#{vlanTested}'] stream.packet.mac.da.value = dstMac stream.packet.l2_proto = TGEnums.L2_PROTO.RAW stream.packet.mac.sa.value = srcMac stream.control.packets_per_burst = self.numOfPackets stream.control.mode = TGEnums.STREAM_TRANSMIT_MODE.STOP_AFTER_THIS_STREAM if \ vlanTested is txDits['packet_vids'][-1] else TGEnums.STREAM_TRANSMIT_MODE.ADVANCE_TO_NEXT_STREAM srcMac = srcMac[:-1] + txPort
def checkAddrNotInFDB(self, tx_port, index=0, vlan=0): funcname = GetFunctionName(self.checkAddrNotInFDB) ret = self._bridge.getPortEntries(tx_port.DutDevPort.name) entry = f"{self._testClassref.TestCaseData['macs'][str(tx_port.id)]} extern_learn" if 'relearning' in self._testClassref.testName or 'remove_restore' in self._testClassref.testName: entry = f"{self._testClassref.TestCaseData['macs'][str(tx_port.id)]} vlan {vlan}" if entry in ret: self.FailTheTest( f"{funcname} {entry} Entry was found in Mac table for port {tx_port.DutDevPort.name}" ) elif 'robustness_macs' in self._testClassref.testName: mac = '00:00:00:00' start_index = self._testClassref.TestCaseData["mac_table"][ "start_index"] for number in range(start_index, start_index + index): hex_num = hex(number)[2:].rjust(4, '0') entry = "{}:{}{}:{}{}".format(mac, *hex_num) if entry in ret: self.FailTheTest( f"{funcname} {entry} Entry was found in Mac table for port {tx_port.DutDevPort.name}" ) elif entry in ret: self.FailTheTest( f"{funcname} {entry} Entry was found in Mac table for port {tx_port.DutDevPort.name}" )
def configureEntityUp(self, dev): funcname = GetFunctionName(self.configureEntityUp) ret = dev.setState('up') if ret: self.FailTheTest( f"{funcname} {ret} Could not config entity {dev.switchdevInterface.name} up" )
def verifyReceivedTrafficIsAsExpected(self, tx_port, rx_port): """ verifies that the whole transmitted traffic was received and that no packet loss occurred nor errors :param tx_port: the transmitting port :param rx_port: the receiving port :return: """ funcname = GetFunctionName(self.verifyReceivedTrafficIsAsExpected) dbg = funcname + "Verify received traffic on ports is as expected" self.logger.debug(dbg) status = self._verifyTrafficOnPorts(tx_port, rx_port) if status: if 'backward_forwarding' in self._testClassref.testName: dbg = funcname + "Passed! No backward forwarding has occured" self.logger.debug(dbg) elif 'addr_rate' in self._testClassref.testName: dbg = funcname + "Passed! No flooding to third port has occured all addr have been learned" self.logger.debug(dbg) else: dbg = funcname + "Passed! No packet loss has occured" self.logger.debug(dbg) elif 'backward_forwarding' in self._testClassref.testName: dbg = funcname + "Failed! backward forwarding has occured" self.FailTheTest(dbg) elif 'addr_rate' in self._testClassref.testName: dbg = funcname + "Failed! flooding to third port has occured" self.FailTheTest(dbg) else: dbg = funcname + "Failed! a bad formatted stream might have been received or a packet loss might occured" self.FailTheTest(dbg)
def checkAddrInFDB(self, tx_port, index=0, vlan=0): funcname = GetFunctionName(self.checkAddrInFDB) ret = self._bridge.getPortEntries(tx_port.DutDevPort.name) entry = f'{self._testClassref.TestCaseData["macs"][str(tx_port.id)]} extern_learn' if 'illegal' in self._testClassref.testName: entry = self._testClassref.TestCaseData["illegal_macs"][str(index)] if f'{entry} extern_learn' in ret: self.FailTheTest( f"{funcname} {entry} Illegal Entry was found in Mac table for port {tx_port.DutDevPort.name}!" ) elif 'relearning' in self._testClassref.testName or 'remove_restore' in self._testClassref.testName: if tx_port.DutDevPort.name == self._port_list_SwitchDevDutInterface[ 2].name: index = 1 #self._port_list_SwitchDevDutInterface[0].name entry = '{} vlan {}'.format( self._testClassref.TestCaseData["macs"][str(index)], vlan) if entry not in ret: self.FailTheTest( f"{funcname} {entry} Entry wasn't found in Mac table for port {tx_port.DutDevPort.name}" ) elif 'robustness_macs' in self._testClassref.testName: mac = '00:00:00:00' start_index = self._testClassref.TestCaseData["mac_table"][ "start_index"] for number in range(start_index, start_index + index): hex_num = hex(number)[2:].rjust(4, '0') entry = "{}:{}{}:{}{} extern_learn".format(mac, *hex_num) if entry not in ret: self.FailTheTest( f"{funcname} {entry} Entry wasn't found in Mac table for port {tx_port.DutDevPort.name}" ) elif entry not in ret: self.FailTheTest( f"{funcname} {entry} Entry wasn't found in Mac table for port {tx_port.DutDevPort.name}" )
def initBridge(self): """ creates bridge entity :return: """ funcname = GetFunctionName(self.initBridge) self._bridge = BridgeConfig(SwitchDevDutInterface("br0")) if 'route_between_vlans' in self._testClassref.testName: self._bridge1 = BridgeConfig(SwitchDevDutInterface("br1")) #init ports for i in range(1, len(list(self._testClassref.TGDutLinks.values())) + 1): self._port_list.append( L1PortConfig( SwitchDevDutPort( self._testClassref.TGDutLinks[i].DutDevPort.name))) self._port_list_SwitchDevDutInterface.extend( [x.switchdevInterface for x in self._port_list]) ret = self._bridge.createL2Entity() if 'route_between_vlans' in self._testClassref.testName: self._bridge1 = BridgeConfig(SwitchDevDutInterface("br1")) ret = self._bridge1.createL2Entity() if ret: self.FailTheTest( f"{funcname} {ret} Could not initiate bridge {self._bridge.switchdevInterface.name}" ) self.Add_Cleanup_Function_To_Stack(self._bridge.deleteEntity) if 'route_between_vlans' in self._testClassref.testName: self.Add_Cleanup_Function_To_Stack(self._bridge1.deleteEntity)
def configureAging(self, age=30000): """ sets aging :return: """ funcname = GetFunctionName(self.configureAging) self._bridge.aging_time = str(age)
def configureBridgeEntityUp(self): funcname = GetFunctionName(self.configureBridgeEntityDown) ret = self._bridge.setState('up') if ret: self.FailTheTest( f"{funcname} {ret} Could not config bridge entity up {self._bridge.switchdevInterface.name}" )
def verifyReceivedTrafficIsAsExpected(self, tx_port, stressMode=False, sleepTime=0): """ verifies that the whole transmitted traffic was received and that no packet loss occurred nor errors :param tx_port: the transmitting port :param rx_port: the receiving port :return: """ funcname = GetFunctionName(self.verifyReceivedTrafficIsAsExpected) dbg = funcname + "Verify received traffic on port is as expected" self.logger.debug(dbg) status = self._verifyTrafficOnPort(tx_port, stressMode, sleepTime) if status: dbg = funcname + "Passed! lldp trasmitted packet have been recieved" self.logger.debug(dbg) elif 'LLDP_trasmitted' in self._testClassref.testName: dbg = funcname + "Failed! lldp trasmitted packet has not been recieved" self.FailTheTest(dbg) elif 'LLDP_tx_hold' in self._testClassref.testName: dbg = funcname + "Failed! lldp trasmitted packet has not been recieved might be a problem with tx-hold" self.FailTheTest(dbg) elif 'LLDP_transmitted_mandatory_tlvs' in self._testClassref.testName: dbg = funcname + "Failed! lldp trasmitted packet has not been recieved with correct tlvs values" self.FailTheTest(dbg) elif 'LLDP_bridge_interface' in self._testClassref.testName: dbg = funcname + "Failed! lldp trasmitted packet from slaved interface has not been recieved" self.FailTheTest(dbg) elif 'LLDP_en_dis_diff_ports' in self._testClassref.testName or 'LLDP_stress' in self._testClassref.testName: dbg = funcname + f"Failed! lldp packet haven't been received\dropped for {tx_port.DutDevPort.name} port" self.FailTheTest(dbg)
def setBridgeSTP(self, mode): funcname = GetFunctionName(self.setBridgeSTP) ret = self._bridge.setBridgeSTP(self._bridge.switchdevInterface.name, mode) if ret: self.FailTheTest( f"{funcname} {ret} Unable to set Bridge STP {mode}")
def configurePortUp(self, port): funcname = GetFunctionName(self.configurePortUp) ret = LLDP_config.setPortlink(port, 'up') if ret: self.FailTheTest( f"{funcname} {ret} unable to set {port.switchdevInterface.name} up" )
def GetStackTraceOnException(exeception_obj): """ :param exeception_obj: exception object that was caught :type exeception_obj: Exception :return: returns string of exception information and stack trace :rtype: str """ funcname = GetFunctionName(GetStackTraceOnException) exp_info = "" if not isinstance(exeception_obj,BaseException): err = funcname + "Warning: exeception_obj is not inherited from BaseException" print(err) try: exp_info = "type {}, message {}".format(type(exeception_obj),exeception_obj) exc_type, exc_value, exc_traceback = sys.exc_info() err = "\nFull Exception Call Stack\n" traceblist = traceback.format_exception(exc_type, exc_value, exc_traceback) for tb in traceblist: err += tb exp_info += err return exp_info except Exception as e: err = funcname + "caught exception: {}".format(str(e)) print(err) finally: return exp_info
def reboot(self, poll_dut_loaded=True, max_attempts=3, timeout_seconds=120, software_reset=True): """ reboots the Dut by PDU if reboot mode is Hardware or by software reset if reboot mode is software :param poll_dut_loaded: if True polls the Dut by ping or by :param max_attempts: maximum attempts to try to reboot dut before giving up :param software_reset True if reset by is done by software, False otherwise :type poll_dut_loaded: bool :return: True if succeeded or false otherwise """ funcname = GetFunctionName(self.reboot) try: reboot_func = self._software_reboot if software_reset else self._reboot_with_PDU for i in range(1, max_attempts + 1): if reboot_func(poll_dut_loaded, timeout_seconds=timeout_seconds): if poll_dut_loaded: if self.login(): return True else: wrn = funcname + "attempt #{} faild to connect to dut after reboot,retrying again for " \ "up to {} more times".format(i, max_attempts + 1 - i) self.logger.warning(wrn) else: return True except Exception as e: err = funcname + " failed to reboot Dut:{}".format(GetStackTraceOnException(e)) self.logger.error(err) return False
def _create_temp_logger(self): """ generates a logfile path in cases where loggers is not initilized :return: True if succeeded to generate log or False Otherwise :rtype: bool """ def getlogpath(filename): currentDir = os.getcwd() GrasResultsBasePath = os.path.join(currentDir, "Results", filename) + os.sep currentDate = strftime("%d-%m-%Y") path = GrasResultsBasePath return path ret = True filename = GetMainFileName() funcname = GetFunctionName(self._create_temp_logger) # fl = filename.split("/") # if "filer" in filename.lower(): # fl = filename.split("\\") # # extract file name from path # filename = fl[-1].split(".")[0] log_path = getlogpath(filename) try: self.logger = GetLogger(filename, log_path, filename, append_source_name=False, logger_type=LogType.HTML_LOGGER) except Exception as e: err = funcname + " failed to create a logger, got error {}\n".format(str(e)) self.logger = None if not self.logger: ret = False return ret
def calculateExpectedTraffic(self, tgDutLinks): """ Verifies that the whole transmitted traffic was received and no packet loss occurred nor errors :param tgDutLinks: BastTest.TGDutLinks dict """ funcname = GetFunctionName(self.calculateExpectedTraffic) self.logger.debug(funcname + 'Verify received traffic on ports is as expected') rxPortsExpectedCounters = { v: 0 for v in set(chain(*self._rxInterfaces.values())) } acceptablePrecentLoss = 0.045 for txNum, txDits in self._txInterfaces.items(): for vlanTested in txDits['vlan_tested']: try: for rxPort in self._rxInterfaces[str(vlanTested)]: rxDutPort = tgDutLinks[int(rxPort)].DutDevPort rxPvid = Bridge1QConfig.getPVID(rxDutPort) isTagged = Bridge1QConfig.isTagged( rxDutPort, vlanTested) if rxPvid and rxPvid == vlanTested and isTagged and 'X' in txDits[ 'packet_vids']: rxPortsExpectedCounters[rxPort] += (txDits['vlan_tested'][vlanTested] - 1) \ * self.numOfPackets + \ self.numOfPackets * (1 - acceptablePrecentLoss) else: rxPortsExpectedCounters[rxPort] += txDits[ 'vlan_tested'][vlanTested] * self.numOfPackets except KeyError: continue return rxPortsExpectedCounters
def _get_uboot_version(self): """ reads the uboot version from the command 'strings /dev/mtd0 | grep U-Boot' on Dut and saves these params to self class :return: UBOOT_Version str :rtype: str """ funcname = GetFunctionName(self._get_uboot_version) cmd = "strings /dev/mtd0 | grep U-Boot" self._dut_active_channel.GetBuffer() if not self._dut_active_channel.SendCommandAndWaitForPattern( cmd, ExpectedPrompt=self._dut_active_channel.shellPrompt, timeOutSeconds=30): err = funcname + " failed to detect expected prompt after sending {} command, terminal buffer:\n{}".format( cmd, self._dut_active_channel.lastBufferTillPrompt) GlobalLogger.logger.error(err) return else: response = self._dut_active_channel.lastBufferTillPrompt from PyInfraCommon.GlobalFunctions.CLI import clean_dut_cli_buffer response = clean_dut_cli_buffer( response, [cmd, self._dut_active_channel.shellPrompt]) try: self.UBOOT_Version = re.findall(r"ver=(U-Boot\s+.*\d)\s\(", response)[0] except Exception as e: print(e) return self.UBOOT_Version
def _parse_dmesg(self): funcname = GetFunctionName(self._parse_dmesg) GlobalLogger.logger.debug(funcname) try: match_kw = {} caller_full_folder_path = inspect.stack()[1][1] path = "{}{}Tests{}{}".format( os.path.dirname( os.path.dirname( os.path.dirname( os.path.dirname(caller_full_folder_path)))), os.sep, os.sep, "dmesg_kw.json") with open(path) as json_file: match_kw = json.load(json_file) # for item in match_kw: # match_kw[item]["regex"] = str(match_kw[item]["regex"]).replace("\\\\", "\\") log_lines = "" buff = GlobalGetterSetter()._getter._("cat /var/log/messages") if buff: log_lines = buff.split("\n") self._process_log_line(log_lines, match_kw) self._report_log_lines(match_kw) return True except Exception as e: print(e) GlobalLogger.logger.debug( "Error - _parse_dmesg had exception:\n{}".format(str(e)))
def reboot(self, poll_dut_loaded=True, max_attempts=3, timeout_seconds=120, software_reset=False, isLoad=False): funcname = GetFunctionName(self.reboot) if isLoad: return super(SwitchDevDutManager, self).reboot(poll_dut_loaded, max_attempts, timeout_seconds, software_reset) crashBeforeLogin = self.Host_kernel_version is None and self.Host_version is None and self.UBOOT_Version is None if crashBeforeLogin: software_reset = False res = super(SwitchDevDutManager, self).reboot(poll_dut_loaded, max_attempts, timeout_seconds, software_reset) if crashBeforeLogin and res: # If we crashed before login the following timeout is required in order to finish CPSS init # In the regular scenario this is handled by test self.logger.info( f'{funcname}Waiting 30s after power cycle to give CPSS time for init' ) sleep(30) return res
def transmitTraffic(self, tgManager, txPorts, rxPorts=None, continues: bool = False, packetGroups=False, delayTime=0, transmitDuration: int = 0): """ Start traffic on tx ports :param rxPorts: the RX ports :param txPorts: the TX ports :param delayTime: The delay time before transmitting traffic (used for slow ports) :param packetGroups: True if packet group receiving mode is used; False if not. :param tgManager: the the TGManager of the test :type: tgManager: BaseTest._TGManager :param continues: if the stream control mode is continues :param transmitDuration: the transmission duration in seconds if traffic is continues (continues == True) """ funcname = GetFunctionName(self.transmitTraffic) st = "" txTgPorts = list(map(lambda x: x.TGPort, txPorts)) if rxPorts: # just some log print which prints for indx, row in cartesianProduct('Tx Port', 'Rx Port', txTgPorts, rxPorts).iterrows(): if row['Tx Port'] != row['Rx Port'].TGPort: st += f"{getTGRep(row['Tx Port'])} ----------> {getTGRep(row['Rx Port'].TGPort)}\n" self.waitUpTgPorts(rxPorts) if packetGroups: # configure packet groups mode if packetGroups == True for interface in rxPorts: interface.TGPort.receive_mode.capture = False interface.TGPort.receive_mode.wide_packet_group = True interface.TGPort.receive_mode.automatic_signature.enabled = True interface.TGPort.apply() else: # if rxPorts is None, print sending from TG port ----> DUT port for port in txPorts: st += f"{getTGRep(port.TGPort)} ----------> {port.DutDevPort.name}\n" if delayTime: self.logger.debug(f'wait {delayTime} seconds...') time.sleep(delayTime) self.logger.debug(f'{funcname}Transmitting traffic:\n{st}') tgManager.chassis.start_traffic(txTgPorts, blocking=not continues, wait_up=True, start_packet_groups=packetGroups) if continues and transmitDuration: self.logger.debug( f'{funcname}Transmitting traffic for {transmitDuration} time...' ) time.sleep(transmitDuration) tgManager.chassis.stop_traffic()
def getLLDPPortStats(self, port, isPortDown=False): funcname = GetFunctionName(self.getLLDPPortStats) sleep(30) ret = LLDP_config.getPortStats(port) total_tx_trasmitted = ret.split('\n')[4] lldp_tx_pckts = re.sub('\D', '', total_tx_trasmitted) if 'LLDP_tx_disabled' in self._testClassref.testName: if int(lldp_tx_pckts) > 1: self.FailTheTest( f"{funcname} {total_tx_trasmitted} port {port.switchdevInterface.name} trasmitting lldp packets but tx disabled!" ) elif 'LLDP_tx_port_down_up' in self._testClassref.testName: if not isPortDown and int(lldp_tx_pckts) <= 1: self.FailTheTest( f"{funcname} {total_tx_trasmitted} port {port.switchdevInterface.name} not trasmitting lldp packets but port is up!" ) elif isPortDown and int(lldp_tx_pckts) > 1: self.FailTheTest( f"{funcname} {total_tx_trasmitted} port {port.switchdevInterface.name} trasmitting lldp packets but port is down!" ) elif 'LLDP_tx_interval' in self._testClassref.testName: sleep(30) ret = LLDP_config.getPortStats(port) total_tx_trasmitted = ret.split('\n')[4] lldp_tx_pckts = re.sub('\D', '', total_tx_trasmitted) if int(lldp_tx_pckts) <= 10: self.FailTheTest( f"{funcname} {total_tx_trasmitted} port {port.switchdevInterface.name} trasmitting lldp packets not accordint to tx-interval!" )
def fw_aldrin2_load_ver_cmds(self): funcname = GetFunctionName(self.fw_aldrin2_load_ver_cmds) self._uboot_channel_fw.WaitForPatternAndSendCommand( ExpectedPrompt=self._uboot_prompt.uboot_prompt, command="usb start", timeOutSeconds=60) self._uboot_channel_fw.WaitForPatternAndSendCommand( ExpectedPrompt=self._uboot_prompt.uboot_prompt, command="set ethact asx0", timeOutSeconds=60) self._uboot_channel_fw.WaitForPatternAndSendCommand( ExpectedPrompt=self._uboot_prompt.uboot_prompt, command="set ethprime asx0", timeOutSeconds=60) self._uboot_channel_fw.WaitForPatternAndSendCommand( ExpectedPrompt=self._uboot_prompt.uboot_prompt, command="set fw_loader_size 0x1700000", timeOutSeconds=60) self._uboot_channel_fw.WaitForPatternAndSendCommand( ExpectedPrompt=self._uboot_prompt.uboot_prompt, command= "tftpboot 0x2000000 switchdev/shared/mrvl_val/tn4810m-loader/zImage.armada-385-dni-amzgo", timeOutSeconds=60) self._uboot_channel_fw.WaitForPatternAndSendCommand( ExpectedPrompt=self._uboot_prompt.uboot_prompt, command="nand erase 0xa00000 $fw_loader_size", timeOutSeconds=300) self._uboot_channel_fw.WaitForPatternAndSendCommand( ExpectedPrompt=self._uboot_prompt.uboot_prompt, command="nand write 0x2000000 0xa00000 $filesize", timeOutSeconds=60) self._uboot_channel_fw.WaitForPatternAndSendCommand( ExpectedPrompt=self._uboot_prompt.uboot_prompt, command="saveenv", timeOutSeconds=60)
def setupFilter(self, tx_port, ttl=120, tlv_type="IEEE 802.1"): funcname = GetFunctionName(self.setupFilter) TGTxPort = tx_port.TGPort #type: Port mac_src_addr = self.getPortMac( tx_port.DutDevPort.name ) #self._testClassref.TestCaseData["LLDP_port_tlvs"]["enp3s4"]["mac"] termDA = TGTxPort.filter_properties.create_match_term( self._testClassref.TestCaseData["macs"]["multicast_lldp"], 0) termSA = TGTxPort.filter_properties.create_match_term(mac_src_addr, 6) ttl_to_hex = hex(ttl)[2:].rjust(4, "0") ttl_to_hex = f'{ttl_to_hex[:2]} {ttl_to_hex[2:]}' TTL_term = TGTxPort.filter_properties.create_match_term(ttl_to_hex, 34) if 'LLDP_transmitted_mandatory_tlvs' in self._testClassref.testName: if tlv_type == "IEEE 802.1": oui = "00 80 C2" else: oui = "00 12 0F" OUI_term = TGTxPort.filter_properties.create_match_term(oui, 211) TGTxPort.filter_properties.filters[3].enabled = False myFilter = TGTxPort.filter_properties.capture_filter myFilter.enabled = True myFilter.add_condition(termDA) myFilter.add_condition(termSA) myFilter.add_condition(TTL_term) if 'LLDP_transmitted_mandatory_tlvs' in self._testClassref.testName: myFilter.add_condition(OUI_term) TGTxPort.apply_filters()
def add_daemon_worker(self, command, name, stderr, stdout, **kwargs): """ ada a daemon worker - Note for cross-compatibility with windows and linux this must run in cli mode, hence target must be a program file name to run with optional args note that the args are cli args that would be parsed by target arg parser :param command:full path of the program name to run :type command:str :param name:name of the process :type name:str :param args:optional command line args to pass to target function file :type args: :param kwargs: :type kwargs: :return: :rtype: """ if not all( os.path.isdir(os.path.dirname(p)) for p in [stderr, stdout]): err = GetFunctionName( self.add_daemon_worke ) + "one of the dirs in path of stderr and or stdout dont exist, cant continue" raise Exception(err) pinfo = self.ProcessInfo(name=name, ipc_type=self.ProcessInfo.PIPE_IPC) w = ProcessWorker(target=command, name=name, ipc=pinfo.pipe_ends[1], ipc_type=self.ProcessInfo.PIPE_IPC, orphaned=True, stdout=stdout, stderr=stderr, **kwargs) self.daemon_workers_info_pairs.append([pinfo, w])
def reboot_and_stop_dev_in_marvell_prompt(self, isLoad=False, isM0=False): funcname = GetFunctionName(self.reboot_and_stop_dev_in_marvell_prompt) self._uboot_class_ref.reboot(poll_dut_loaded=False, software_reset=False, isLoad=isLoad) self.uboot_fw_login() if not isM0: self.uboot_host_login()