Best Python code snippet using autotest_python
checkMirrors.py
Source:checkMirrors.py  
...43        self.good_mirrors = [[], 0]44        self.bad_mirrors = [[], 0]45        self.error_mirrors = [[], 0]46    47    def get_mirror_list(self):48        """Method that connect on fedoraproject.org, get the mirror list and the repomd.xml.49        """50        temp = self.mirror_list_url % (self.directory, self.version, self.architecture)51        try:52            self.mirrors = [ url53                             for url in urllib2.urlopen(temp).read().split("\n")54                             if url != "" and not "#" in url ]55        except Exception, error:56            print "[ERROR] Failed to get mirror list:", error57            sys.exit(-1)58        temp = self.main_mirror % (self.directory, self.version, self.architecture)59        try:60            print temp + self.xml_filename61            self.repodata = urllib2.urlopen(temp + self.xml_filename).read()62        except Exception, error:63            print "[ERROR] Failed to get XML repodata file:", error64            sys.exit(-1)65        self.number_total_mirrors = len(self.mirrors)66        if self.number_total_mirrors == 0:67            print "[ERROR] Did you specify the right options ?"68            sys.exit(-1)69    70    def check_mirrors(self):71        """Method that verify, for each mirror, if its repomd.xml is equal of that on main.72        """73        print "\nChecking the repositories repodata !\n\nUsing:", self.main_mirror % (self.directory, self.version, self.architecture)            74        for url in self.mirrors:75            print "\rTesting: %d/%d" % (self.good_mirrors[1] , self.number_total_mirrors),76            sys.stdout.flush()77            try:78                if urllib2.urlopen(url + self.xml_filename, timeout=10).read() == self.repodata:79                    self.good_mirrors[0].append(url)80                    self.good_mirrors[1] += 181                else:82                    self.bad_mirrors[0].append(url)83                    self.bad_mirrors[1] += 184            except Exception, error:85                self.error_mirrors[0].append(url + "\n[" + str(error) + "]")86                self.error_mirrors[1] += 187    88    def print_results(self):89        """Method that put the results on STDOUT.90        """91        print """\n92=============== Valid Mirror Results ========================93\tGood\tBad\tError\tTotal\tPerc.Good94\t%4d\t%3d\t%5d\t%5d\t%7.2f%%95=============================================================96[Good Repositories]97%s98[Bad Repositories]99%s100[Errors]101%s102""" % (self.good_mirrors[1],103       self.bad_mirrors[1],104       self.error_mirrors[1],105       self.number_total_mirrors,106       float(self.good_mirrors[1])*100/self.number_total_mirrors,107       "\n".join(self.good_mirrors[0]),108       "\n".join(self.bad_mirrors[0]),109       "\n".join(self.error_mirrors[0]),)110    111    def run(self):112        """Method that execute all method in the right order.113        """114        self.get_mirror_list()115        self.check_mirrors()116        self.print_results()117    118if __name__ == "__main__":119    """Main Function.120    If the programs was called as a script, this will be executed.121    """122    signal(2, SIG_DFL)123    if len(sys.argv) == 4:124        CheckMirrors(sys.argv[1], sys.argv[2], sys.argv[3], ).run()125        sys.exit(0)126    else:127        print "[ERROR] Use: ./mirror_checker.py <directory> <version> <architecture>"128        sys.exit(-1)...mirror_speed.py
Source:mirror_speed.py  
...18    result = subprocess.run(['LC_ALL=C pacman -Si glibc'],19                            capture_output=True, text=True, shell=True).stdout20    version = re.search(r'Version +: ([\d.-]+)', result).group(1)21    return package.format(version)22def get_mirror_list():23    if os.path.exists("mirror_list.txt"):24        with open("mirror_list.txt", "r") as fp:25            mirrors = fp.readlines()26        a = map(lambda x: str.strip(x), mirrors)27        return list(a)28    try:29        resp = requests.get(url=mirrorlist_url,30                            headers=headers, timeout=GET_TIMEOUT).text31        pattern = re.compile(r"#Server = (\S+)/archlinux")32        mirrors = re.findall(pattern, resp)33        with open("mirror_list.txt", "w") as fp:34            for i in mirrors:35                fp.write(i)36                fp.write("\n")37        return mirrors38    except Exception as e:39        print(e)40        exit(-1)41def get_task(mirrors, times):42    package = get_package()43    speed_result = dict()44    for t_n in range(times):45        for mirror in mirrors:46            print("start test: " + mirror)47            speed = test_speed(mirror + package)48            # speed = random.random() * 1049            print("      time: {:.3f}s".format(speed), end="\n\n")50            if t_n == 0:51                speed_result[mirror] = [speed]52            else:53                speed_result[mirror].append(speed)54    return speed_result55def test_speed(url):56    # if "163" in url:57    #     return MAX_TIME58    start = time.time()59    try:60        resp = requests.get(url=url, headers=headers,61                            timeout=GET_TIMEOUT, stream=True)62        if resp.status_code == 200:63            try:64                with eventlet.Timeout(DOWN_TIMEOUT):65                    _ = resp.content66            except eventlet.Timeout:67                return MAX_TIME68        else:69            print('\033[91m' + " " * 6 + str(resp.status_code) + '\033[0m')70            return MAX_TIME71        stop = time.time()72    except Exception as e:73        print(str(e))74        return MAX_TIME75    return stop - start76def analyze_result(result):77    analyzed_result = {}78    for key, value in result.items():79        ave = sum(value) / len(value)80        min_ = min(value)81        max_ = max(value)82        analyzed_result[key] = [min_, max_, ave]83    sorted_result = sorted(analyzed_result.items(), key=lambda x: x[1][2])84    print("        MIRROR                          	 MIN 	 MAX 	 AVE ")85    for key, value in sorted_result:86        print("{:40}\t{:.3f}\t{:.3f}\t{:.3f}".format(87            key, value[0], value[1], value[2]))88    print("\n====================\n")89    for key, _ in sorted_result:90        print("Server = " + key + "/archlinux/$repo/os/$arch")91if __name__ == "__main__":92    mirror_list = get_mirror_list()93    rlt = get_task(mirrors=mirror_list, times=1)...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!!
