Best Python code snippet using tempest_python
pingtester.py
Source:pingtester.py
...23 self.rtt_min = ''24 self.rtt_avg = ''25 self.rtt_max = ''26 self.rtt_mdev = ''27 def ping_host(self, host, count, ping_timeout=1, ping_interval=0.2):28 '''29 This function will run a ping test and return an analysis of the results30 If the ping fails, a False condition is returned with no further31 information. If the ping succeeds, the following dictionary is returned:32 { 'host': self.host,33 'pkts_tx': self.pkts_tx,34 'pkts_rx': self.pkts_rx,35 'pkt_loss': self.pkt_loss,36 'test_time': self.test_time,37 'rtt_min': self.rtt_min,38 'rtt_avg': self.rtt_max,39 'rtt_max': self.rtt_max,40 'rtt_mdev': self.rtt_mdev}41 '''42 self.host = host43 self.file_logger.debug("Pinging host: " + str(host) + " (count=" + str(count) + ")")44 # Execute the ping45 try:46 cmd_string = "{} -4 -q -c {} -W {} -i {} {}".format(PING_CMD, count, ping_timeout, ping_interval, host)47 ping_output = subprocess.check_output(cmd_string, stderr=subprocess.STDOUT, shell=True).decode().splitlines()48 except subprocess.CalledProcessError as exc:49 output = exc.output.decode()50 error = "Hit an error when pinging {} : {}".format(str(host), str(output))51 self.file_logger.error(error)52 #stderr.write(str(error))53 # Things have gone bad - we just return a false status54 return False55 self.file_logger.debug("Ping command output:")56 self.file_logger.debug(ping_output)57 packets_summary_str = ping_output[3]58 # Extract packets transmitted59 pkts_tx_re = re.search(60 r'(\d+) packets transmitted', packets_summary_str)61 if pkts_tx_re is None:62 self.pkts_tx = "NA"63 else:64 self.pkts_tx = pkts_tx_re.group(1)65 # Extract packets received66 pkts_rx_re = re.search(r'(\d+) received', packets_summary_str)67 if pkts_rx_re is None:68 self.pkts_rx = "NA"69 else:70 self.pkts_rx = pkts_rx_re.group(1)71 # Extract packet loss72 pkt_loss_re = re.search(r'(\d+)\% packet loss', packets_summary_str)73 if pkt_loss_re is None:74 self.pkt_loss = "NA"75 else:76 self.pkt_loss = pkt_loss_re.group(1)77 # Extract test time (duration)78 test_time_re = re.search(r'time (\d+)ms', packets_summary_str)79 if test_time_re is None:80 self.test_time = "NA"81 else:82 self.test_time = test_time_re.group(1)83 self.file_logger.debug("Packets transmitted: " + str(self.pkts_tx))84 self.file_logger.debug("Packets received: " + str(self.pkts_rx))85 self.file_logger.debug("Packet loss(%): " + str(self.pkt_loss))86 self.file_logger.debug("Test duration (mS): " + str(self.test_time))87 perf_summary_str = ping_output[4]88 perf_data_re = re.search(r'= ([\d\.]+?)\/([\d\.]+?)\/([\d\.]+?)\/([\d\.]+)',89 perf_summary_str)90 if test_time_re is None:91 self.rtt_min = "NA"92 self.rtt_avg = "NA"93 self.rtt_max = "NA"94 self.rtt_mdev = "NA"95 else:96 self.rtt_min = perf_data_re.group(1)97 self.rtt_avg = perf_data_re.group(2)98 self.rtt_max = perf_data_re.group(3)99 self.rtt_mdev = perf_data_re.group(4)100 self.file_logger.debug("rtt_min : " + str(self.rtt_min))101 self.file_logger.debug("rtt_avg : " + str(self.rtt_avg))102 self.file_logger.debug("rtt_max : " + str(self.rtt_max))103 self.file_logger.debug("rtt_mdev : " + str(self.rtt_mdev))104 self.file_logger.info('ping_host: {}, pkts_tx: {}, pkts_rx: {}, pkt_loss: {}, rtt_avg: {}'.format(105 self.host, self.pkts_tx, self.pkts_rx, self.pkt_loss, self.rtt_avg))106 return {107 'host': self.host,108 'pkts_tx': self.pkts_tx,109 'pkts_rx': self.pkts_rx,110 'pkt_loss': self.pkt_loss,111 'test_time': self.test_time,112 'rtt_min': self.rtt_min,113 'rtt_max': self.rtt_max,114 'rtt_avg': self.rtt_avg,115 'rtt_mdev': self.rtt_mdev}116 def run_tests(self, status_file_obj, config_vars, adapter, check_correct_mode_interface, exporter_obj, watchd):117 self.file_logger.info("Starting ping test...")118 status_file_obj.write_status_file("Ping tests")119 # read in ping hosts (format: 'ping_host1')120 num_ping_targets = int(config_vars['ping_targets_count']) + 1121 ping_hosts = []122 for target_num in range(1, num_ping_targets):123 target_name = 'ping_host{}'.format(target_num)124 ping_host = config_vars[target_name]125 if ping_host:126 ping_hosts.append(ping_host)127 ping_count = config_vars['ping_count']128 129 tests_passed = True130 # initial ping to populate arp cache and avoid arp timeput for first test ping131 for ping_host in ping_hosts:132 if ping_host == '':133 continue134 else:135 # check for def_gw keyword136 if ping_host == 'def_gw':137 ping_host = adapter.get_def_gw()138 # check tests will go over correct interface139 if check_correct_mode_interface(ping_host, config_vars, self.file_logger):140 self.ping_host(ping_host, 1)141 else:142 self.file_logger.error(143 "Unable to ping {} as route to destination not over correct interface...bypassing ping tests".format(ping_host))144 # we will break here if we have an issue as something bad has happened...don't want to run more tests145 config_vars['test_issue'] = True146 tests_passed = False147 break148 # run actual ping tests149 ping_index = 0150 all_tests_fail = True151 for ping_host in ping_hosts:152 # bail if we have had DNS issues153 if config_vars['test_issue'] == True:154 self.file_logger.error("As we had previous issues, bypassing ping tests.")155 break156 ping_index += 1157 if ping_host == '':158 continue159 else:160 # check for def_gw keyword161 if ping_host == 'def_gw':162 ping_host = adapter.get_def_gw()163 ping_result = self.ping_host(ping_host, ping_count)164 results_dict = {}165 # ping results166 if ping_result:167 results_dict['time'] = get_timestamp(config_vars)168 results_dict['ping_index'] = int(ping_index)169 results_dict['ping_host'] = str(ping_result['host'])170 results_dict['pkts_tx'] = int(ping_result['pkts_tx'])171 results_dict['pkts_rx'] = int(ping_result['pkts_rx'])172 results_dict['percent_loss'] = int(ping_result['pkt_loss'])173 results_dict['test_time_ms'] = int(ping_result['test_time'])174 results_dict['rtt_min_ms'] = round(float(ping_result['rtt_min']), 2)175 results_dict['rtt_avg_ms'] = round(float(ping_result['rtt_avg']), 2)176 results_dict['rtt_max_ms'] = round(float(ping_result['rtt_max']), 2)177 results_dict['rtt_mdev_ms'] = round(float(ping_result['rtt_mdev']), 2)...
brillo_PingTest.py
Source:brillo_PingTest.py
1# Copyright 2015 The Chromium OS Authors. All rights reserved.2# Use of this source code is governed by a BSD-style license that can be3# found in the LICENSE file.4import common5from autotest_lib.client.common_lib import error6from autotest_lib.server import test7_DEFAULT_PING_HOST = 'www.google.com'8_DEFAULT_PING_COUNT = 49_DEFAULT_PING_TIMEOUT = 410class brillo_PingTest(test.test):11 """Ping an Internet host."""12 version = 113 def run_once(self, host=None, ping_host=_DEFAULT_PING_HOST,14 ping_count=_DEFAULT_PING_COUNT,15 ping_timeout=_DEFAULT_PING_TIMEOUT):16 """Pings an Internet host with given timeout and count values.17 @param host: A host object representing the DUT.18 @param ping_host: The Internet host to ping.19 @param ping_count: The number of pings to attempt. The test passes if20 we get at least one reply.21 @param ping_timeout: The number of seconds to wait for a reply.22 @raise TestFail: The test failed.23 """24 cmd = 'ping -q -c %s -W %s %s' % (ping_count, ping_timeout, ping_host)25 try:26 host.run(cmd)27 except error.AutoservRunError:28 raise error.TestFail(29 'Failed to ping %s in %d seconds on all %d attempts' %...
ping.py
Source:ping.py
1import os2# modificado para funcionar em diferentes sistemas3def macping():4 print("#" * 60)5 ping_host = input("Digite o IP ou Host a ser verificado: ")6 os.system('ping -c 6 {}'.format(ping_host))7def winping():8 print("#" * 60)9 ping_host = input("Digite o IP ou Host a ser verificado: ")...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!