Best Python code snippet using robotframework
random_tests.py
Source:random_tests.py  
1#!/usr/bin/python32import random, string3import requests4import threading5import argparse, subprocess, os6import inspect7PROXY = "http://dh2020pc05:8026/"8filename = inspect.getframeinfo(inspect.currentframe()).filename9CWD     = os.path.dirname(os.path.abspath(filename))10class testThread(threading.Thread):11	def __init__(self, thread_id, read_tests, write_tests):12		threading.Thread.__init__(self)13		self.thread_id = thread_id14		self.read_tests = read_tests15		self.write_tests = write_tests16	17	def run(self):18		GETResponse = send_GET_Request(self.read_tests)19		# for i in range (10):20		# 	subprocess.run(["./stopNode"], cwd=f"{CWD}/../scripts")21		# 	getres = send_GET_Request(self.read_tests)22		# 	print(f"{i},{getres}")23		# print("read response from thread" + str(self.thread_id) + ": " + str(GETResponse))24		PUTResponse = send_PUT_Request(self.write_tests)25		# print("write response from thread" + str(self.thread_id) + ": " + str(PUTResponse))26def get_random_string(length):27	letters = string.ascii_lowercase28	result_str = ''.join(random.choice(letters) for i in range(length))29	return result_str30# def send_GET_Request(num_tests):31# 	response = {"success": 0, "fail": 0}32# 	tic = None33# 	for i in range(num_tests):34# 		try:35# 			request = requests.get(PROXY + get_random_string(8))36# 			if request.status_code == 404:37# 				# if i % 60 == 0:38# 				# 	print("1")39# 				if not tic is None:40# 					print("timer ended")41# 					toc = time.perf_counter()42# 					print(f"{toc-tic:0.6f}")43# 					break44# 				response["success"] += 145# 			else:46# 				response["fail"] += 147# 		except:48# 			if tic is None:49# 				print("timer started")50# 				tic = time.perf_counter()51# 				num_tests = num_tests - 252# 	return response53def send_GET_Request(num_tests):54	response = {"success": 0, "fail": 0}55	tic = None56	for i in range(num_tests):57		try:58			request = requests.get(PROXY + get_random_string(8))59			if request.status_code == 404:60				if not tic is None:61					toc = time.perf_counter()62					print(f"{toc-tic:0.6f}")63					break64				response["success"] += 165			else:66				response["fail"] += 167		except:68			if tic is None:69				tic = time.perf_counter()70				num_tests = num_tests - 271	return response72def send_PUT_Request(num_tests):73	response = {"success": 0, "fail": 0}74	for i in range(num_tests):75		longResource = "http://" + get_random_string(20)76		shortResource = get_random_string(8)77		try:78			request = requests.put(PROXY + "?short=" + shortResource + "&long=" + longResource)79			if request.status_code == 200:80				response["success"] += 181			else:82				response["fail"] += 183		except:84			print("Error sending request")85	return response86def test(num_threads, total_read_tests, total_write_tests):87	threads = []88	read_tests_per_thread = total_read_tests // num_threads89	write_tests_per_thread = total_write_tests // num_threads90	for thread_id in range(num_threads):91		threads.append(testThread(thread_id, read_tests_per_thread, write_tests_per_thread))92	for t in threads:93		t.start()94	for t in threads:95		t.join()96if __name__=='__main__':97	import time98	import sys99	100	if len(sys.argv) != 6:101		print("Usage: python3 random_tests.py [proxy_host] [hostname] [number_of_threads] [number_of_read_tests] [number_of_write_tests]")102		sys.exit(1)103	104	proxy_host = sys.argv[1]105	PROXY = "http://" + proxy_host + ":8026/"106	hostname = sys.argv[2]107	num_threads = int(sys.argv[3])108	read_tests = int(sys.argv[4])109	write_tests = int(sys.argv[5])110	tic = time.perf_counter()111	test(num_threads, read_tests, write_tests)112	toc = time.perf_counter()113	# print(f"{hostname:s} {num_threads:d} {read_tests:d} {write_tests:d} {toc-tic:0.6f}")...regex-match-tests.py
Source:regex-match-tests.py  
...13import datetime14import os.path as path15def print_tests(tests):16    print('\n'.join([test_tostr(t) for t in tests]))17def read_tests(f):18    basename, _ = path.splitext(path.basename(f))19    tests = []20    for lineno, line in enumerate(open(f), 1):21        fields = filter(None, map(str.strip, line.split('\t')))22        if not (4 <= len(fields) <= 5) \23           or 'E' not in fields[0] or fields[0][0] == '#':24            continue25        opts, pat, text, sgroups = fields[0:4]26        groups = []  # groups as integer ranges27        if sgroups == 'NOMATCH':28            groups = [None]29        elif ',' in sgroups:30            noparen = map(lambda s: s.strip('()'), sgroups.split(')('))31            for g in noparen:32                s, e = map(str.strip, g.split(','))33                if s == '?' and e == '?':34                    groups.append(None)35                else:36                    groups.append((int(s), int(e)))37        else:38            # This skips tests that should result in an error.39            # There aren't many, so I think we can just capture those40            # manually. Possibly fix this in future.41            continue42        if pat == 'SAME':43            pat = tests[-1][1]44        if '$' in opts:45            pat = pat.decode('string_escape')46            text = text.decode('string_escape')47        if 'i' in opts:48            pat = '(?i)%s' % pat49        name = '%s_%d' % (basename, lineno)50        tests.append((name, pat, text, groups))51    return tests52def test_tostr(t):53    lineno, pat, text, groups = t54    options = map(group_tostr, groups)55    return 'mat!(match_%s, r"%s", r"%s", %s);' \56           % (lineno, pat, '' if text == "NULL" else text, ', '.join(options))57def group_tostr(g):58    if g is None:59        return 'None'60    else:61        return 'Some((%d, %d))' % (g[0], g[1])62if __name__ == '__main__':63    parser = argparse.ArgumentParser(64        description='Generate match tests from an AT&T POSIX test file.')65    aa = parser.add_argument66    aa('files', nargs='+',67       help='A list of dat AT&T POSIX test files. See src/testdata')68    args = parser.parse_args()69    tests = []70    for f in args.files:71        tests += read_tests(f)72    tpl = '''// Copyright 2014 The Rust Project Developers. See the COPYRIGHT73// file at the top-level directory of this distribution and at74// http://rust-lang.org/COPYRIGHT.75//76// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or77// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license78// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your79// option. This file may not be copied, modified, or distributed80// except according to those terms.81// DO NOT EDIT. Automatically generated by 'scripts/regex-match-tests.py'82// on {date}.83'''84    print(tpl.format(date=str(datetime.datetime.now())))85    for f in args.files:86        print('// Tests from %s' % path.basename(f))87        print_tests(read_tests(f))...rem.py
Source:rem.py  
...16    return f"FROM: {self.supercomp}: N={self.n} {self.op}\ttime={self.time}s NTR={self.ntr} nproc={self.nproc}"17def get_test_times(basename):18  md = re.match(rf'test_\d+_(\d+)', basename)19  return int(md[1])20def read_tests(test_no, supercomp="bluegene"):21  tests_all = []22  for basename in filter(lambda fn: re.match(rf'test_{test_no}_(\d+)', fn), os.listdir('.')):23    test_times = get_test_times(basename)24    tests = []25    for fn in os.listdir(basename):26      f = path.join(basename, fn)27      with open(f, 'r') as file:28        content = file.read()29        matches = re.findall(r"([a-zA-Z]+)\s+time=\s*([\d.]+)s\s+NTR=(\d+)\s+nproc=(\d+)\s+N=(\d+)", content)30        if len(matches) < 4:31          print(f"{f}: Error!\n")32        for m in matches:33          tests.append(Experiment(34            int(m[4]),35            m[0], 36            float(m[1]), 37            int(m[2]), 38            int(m[3]), 39            supercomp,40            None,41            test_times,42          ))43    tests_all = tests_all + tests44  return tests_all45n_p = None46def cond_fix_n_p(e):47  global n_p48  return e.n // e.nproc == n_p and e.op == "solver"49def series_corr_to_n(n):50  def foo(e):51    return e.n == n52  return foo53tests_1 = read_tests(1)54series = rm.divide(tests_1, 'test_no', 'n', 'op')55for ks, s_k in rm.iter_series(series):56  e_start = min(s_k, key=lambda e: e.nproc)57  for e in s_k:58    e.speedup = e_start.time / e.time59with open("exp2.csv", 'w') as f:60  t = rm.table(tests_1, 'nproc', 'op', 'speedup', series_corr_to_n(10**5))61  rm.print_table(t)62  f.write(rm.print_table(t, csv=True))63  f.write("\n")64  t = rm.table(tests_1, 'nproc', 'op', 'speedup', series_corr_to_n(10**6))65  rm.print_table(t)66  f.write(rm.print_table(t, csv=True))67  f.write("\n")68  t = rm.table(tests_1, 'nproc', 'op', 'speedup', series_corr_to_n(10**7))69  rm.print_table(t)70  f.write(rm.print_table(t, csv=True))71  f.write("\n")72test_2 = read_tests(2)73newer = list(filter(lambda e: e.test_no >= 0, test_2))74with open("exp3.csv", 'w') as f:75  n_p = 819276  t = rm.table(newer, 'nproc', 'n', 'time', cond_fix_n_p)77  rm.print_table(t)78  f.write(rm.print_table(t, csv=True))79  n_p = 8192*2**380  t = rm.table(newer, 'nproc', 'n', 'time', cond_fix_n_p)81  rm.print_table(t)82  f.write(rm.print_table(t, csv=True))83  n_p = 8192*2**684  t = rm.table(newer, 'nproc', 'n', 'time', cond_fix_n_p)85  rm.print_table(t)86  f.write(rm.print_table(t, csv=True))87test_3 = read_tests(3)88nproc_1 = list(filter(lambda e: e.nproc == 1, test_3))89series = rm.divide(nproc_1, 'test_no', 'op')90for ks, s_k in rm.iter_series(series):91  e_start = min(s_k, key=lambda e: e.ntr)92  for e in s_k:93    e.speedup = e_start.time / e.time94with open("exp1.csv", 'w') as f:95  t = rm.table(nproc_1, 'ntr', 'op', 'speedup')96  rm.print_table(t)...fowler-to-toml
Source:fowler-to-toml  
1#!/usr/bin/env python2from __future__ import absolute_import, division, print_function3import argparse4import os.path as path5def read_tests(f):6    basename, _ = path.splitext(path.basename(f))7    tests = []8    prev_pattern = None9    for lineno, line in enumerate(open(f), 1):10        fields = list(filter(None, map(str.strip, line.split('\t'))))11        if not (4 <= len(fields) <= 5) \12           or 'E' not in fields[0] or fields[0][0] == '#':13            continue14        terse_opts, pat, text, sgroups = fields[0:4]15        groups = []  # groups as integer ranges16        if sgroups == 'NOMATCH':17            groups = []18        elif ',' in sgroups:19            noparen = map(lambda s: s.strip('()'), sgroups.split(')('))20            for g in noparen:21                s, e = map(str.strip, g.split(','))22                groups.append([int(s), int(e)])23                break24        else:25            # This skips tests that should result in an error.26            # There aren't many, so I think we can just capture those27            # manually. Possibly fix this in future.28            continue29        opts = []30        if text == "NULL":31            text = ""32        if pat == 'SAME':33            pat = prev_pattern34        if '$' in terse_opts:35            pat = pat.encode('utf-8').decode('unicode_escape')36            text = text.encode('utf-8').decode('unicode_escape')37            text = text.encode('unicode_escape').decode('utf-8')38            opts.append('escaped')39        else:40            opts.append('escaped')41            text = text.encode('unicode_escape').decode('utf-8')42        if 'i' in terse_opts:43            opts.append('case-insensitive')44        pat = pat.encode('unicode_escape').decode('utf-8')45        pat = pat.replace('\\\\', '\\')46        tests.append({47            'name': '"%s%d"' % (basename, lineno),48            'options': repr(opts),49            'pattern': "'''%s'''" % pat,50            'input': "'''%s'''" % text,51            'matches': str(groups),52        })53        prev_pattern = pat54    return tests55if __name__ == '__main__':56    parser = argparse.ArgumentParser(57        description='Generate match tests from an AT&T POSIX test file.')58    aa = parser.add_argument59    aa('datfile', help='A dat AT&T POSIX test file.')60    args = parser.parse_args()61    tests = read_tests(args.datfile)62    for t in tests:63        print('[[tests]]')64        for k, v in t.items():65            print('%s = %s' % (k, v))...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!!
