Best Python code snippet using autotest_python
utils.py
Source:utils.py  
1import json2from shutil import copyfile3from result_extractor import *4# TODO re-organize some of these methods in a new file "files manager"5def read_mut_infos_from_file(mutations_file_json=output_mut_infos_json_filename):6	mut_infos = []7	with open(mutations_file_json) as json_file:8		data = json.load(json_file)9		for mut_info_dict in data['mutations']:10			mut_infos.append(from_dict_to_mut_info(mut_info_dict))11	return mut_infos12def save_mutant_and_mut_info(file_mutated, mut_info):13	if not os.path.exists(mutants_dir):14		os.mkdir(mutants_dir)15	cur_mutant_dir = os.path.join(mutants_dir, 'mutant_' + str(mut_info.id))16	if not os.path.exists(cur_mutant_dir):17		os.mkdir(cur_mutant_dir)18	copyfile(file_mutated, os.path.join(cur_mutant_dir, mut_info.source_filename))19	with open(os.path.join(cur_mutant_dir, 'mutant_' + str(mut_info.id) + '.json'), 'w') as mut_info_file:20		json.dump(mut_info.to_dict(), mut_info_file, ensure_ascii=False, indent=4)21def output_dir(execution_tag):22	out_dir = "output"23	if not os.path.exists(out_dir):24		os.mkdir(out_dir)25	out_dir = os.path.join(out_dir, execution_tag)26	if not os.path.exists(out_dir):27		os.mkdir(out_dir)28	return out_dir29def mutant_output_dir(mutant_id, execution_tag):30	out_dir = output_dir(execution_tag)31	out_dir = os.path.join(out_dir, "mutant_{}".format(mutant_id))32	if not os.path.exists(out_dir):33		os.mkdir(out_dir)34	return out_dir35def save_app_output(mutant_id, execution_tag, testsuite_tag, output_text):36	out_dir = mutant_output_dir(mutant_id, execution_tag)37	out_file = os.path.join(out_dir, "app_output_for_{}.txt".format(testsuite_tag))38	with open(out_file, 'w') as f:39		f.write(output_text)40def save_test_suite_output(mutant_id, execution_tag, testsuite_tag, output_text):41	out_dir = mutant_output_dir(mutant_id, execution_tag)42	out_file = os.path.join(out_dir, "test_suite_{}_output.txt".format(testsuite_tag))43	with open(out_file, 'w') as f:44		f.write(output_text)45def copy_surefire_report_html(mutant_id, execution_tag, testsuite_rootdir, testsuite_tag):46	orig_report = os.path.join(testsuite_rootdir, 'target/site', 'surefire-report.html')47	out_dir = mutant_output_dir(mutant_id, execution_tag)48	out_report = os.path.join(out_dir, "test_suite_{}_report.html".format(testsuite_tag))49	copyfile(orig_report, out_report)50def save_mut_info(mut_info, execution_tag):51	out_dir = mutant_output_dir(mut_info.id, execution_tag)52	out_file = os.path.join(out_dir, 'mutant_' + str(mut_info.id) + '.json')53	with open(out_file, 'w') as mut_info_file:54		json.dump(mut_info.to_dict(), mut_info_file, ensure_ascii=False, indent=4)55def get_source_file_path(mut_info):56	if not mut_info.source_root_path:  # this is for support multiple root paths of the source code57		for source_path in source_paths:  # search for the file existing in one of the source paths in the configuration58			file_path = os.path.join(source_path, mut_info.rel_folder_path, mut_info.source_filename)59			if os.path.isfile(file_path):60				mut_info.source_root_path = source_path61				return file_path62		raise FileNotFoundError63	else:64		return os.path.join(mut_info.source_root_path, mut_info.rel_folder_path, mut_info.source_filename)65def backup_source_file(file_path_to_change):  # back up the original source file and return the backed up file path66	backup_file_path = file_path_to_change + backup_ext  # backup file name67	if not os.path.exists(backup_file_path):68		copyfile(file_path_to_change, backup_file_path)  # backup of the original file if not already exists69	return backup_file_path70def copyfile_in_place_as_tmp(file_to_copy):71	tmp_file_path = file_to_copy + '.tmp'  # temporary file name72	copyfile(file_to_copy, tmp_file_path)  # create the temporary copying the original73	return tmp_file_path74def remove_file(file_path):75	try:76		os.remove(file_path)77	except OSError:78		pass79def write_dict_to_file_json(dictionary, output_filename):80	with open(output_filename, 'w', encoding='utf-8') as f:...scv.py
Source:scv.py  
1import json2import os3import shutil4from shutil import copyfile5from time import sleep6import requests7from git import Repo, Git8from gitlab import Gitlab9config = json.load(open('config.json', 'r'))10REPO = None11GIT = Git(config['git']['repopath'])12class GitlabUtil():13    def __init__(self):14        self.AUTH_URL = '{}/oauth/token'.format(config['gitlab']['base_url'])15        self.gl = None16    def __init_client(self):17        response = requests.post(self.AUTH_URL, data={18            'grant_type': 'password',19            'username': config['gitlab']['username'],20            'password': config['gitlab']['password']21        })22        token = response.json()['access_token']23        self.gl = Gitlab(config['gitlab']['base_url'], oauth_token=token)24    def verify_project_exists(self, name):25        if self.gl is None:26            self.__init_client()27        projects = self.gl.projects.list()28        for project in projects:29            project.delete()30        sleep(1)31        self.gl.projects.create({'name': name, 'visibility': 'public'})32class GitUtil:33    def __init__(self, git_url, results_dir=None, tag=None):34        self._repopath = config['git']['repopath']35        self._results_dir = results_dir36        try:37            shutil.rmtree(self._repopath)38        except OSError as e:39            print(e)40        os.mkdir(self._repopath)41        self.REPO = Repo.clone_from(git_url, self._repopath)42        self.GIT = Git(self._repopath)43        if tag:44            self.GIT.checkout(tag)45    @staticmethod46    def purge_repository():47        shutil.rmtree(config['git']['repopath'])48        os.mkdir(config['git']['repopath'])49    def copy_file_into_repo(self, file):50        target = os.path.join(self._repopath, os.path.basename(file))51        copyfile(file, target)52        self.REPO.index.add([os.path.basename(target)])53    def commit_and_push_source_code(self, message):54        self.REPO.index.commit(message)55        self.REPO.remotes.origin.push()56    def tag_repository(self, tag_name):57        tag = self.REPO.create_tag(tag_name)58        self.REPO.remotes.origin.push(tag)59    def create_new_file(self, filename, content):60        target = os.path.join(self._repopath, filename)61        with open(target, 'w') as file:62            file.writelines(content)63        self.REPO.index.add([os.path.basename(target)])64    def copy_repofile_to_results(self, filename, execution_tag):65        shutil.copyfile(os.path.join(self._repopath, filename),66                        os.path.join(self._results_dir, 'pdf', f"{execution_tag}_{filename}"))67    def replace_repofile(self, src, target):68        target = os.path.join(self._repopath, target)69        os.remove(target)70        shutil.copyfile(src, target)71    def checkout(self, branch):...testsuite_manager.py
Source:testsuite_manager.py  
1import subprocess2from utils import *3class TestSuiteManagerSingleton(type):4	_instances = {}5	def __call__(cls, *args, **kwargs):6		if cls not in cls._instances:7			cls._instances[cls] = super(TestSuiteManagerSingleton, cls).__call__(*args, **kwargs)8		return cls._instances[cls]9class TestSuiteManager(metaclass=TestSuiteManagerSingleton):10	_map_testsuite_info = dict()11	def __init__(self):12		for test_suite in test_suites:13			self._map_testsuite_info[test_suite.get('tag')] = test_suite14	def get_test_suite_tags(self):15		return self._map_testsuite_info.keys()16	@staticmethod17	def __run_test_suite(mutation_info, execution_tag, testsuite_rootdir, testsuite_mvn_opts, testsuite_name, testsuite_tag):18		mutant_id = mutation_info.id19		print("[Mutant id: {}] Running test suite '{}' ...".format(mutant_id, testsuite_name))20		clear_surefire_reports(testsuite_rootdir)21		opt_report_title = '-Dsurefire.report.title="Surefire report. Test suite: {}, Mutant id: {}"'.format(testsuite_tag, mutant_id)22		completed_process = subprocess.run(' '.join(['mvn', testsuite_mvn_opts, 'surefire-report:report', opt_report_title, 'surefire:test', '-B']),23				cwd=testsuite_rootdir,24				shell=True,25				encoding='utf-8',26				stderr=subprocess.STDOUT,27				stdout=subprocess.PIPE)28		save_test_suite_output(mutant_id, execution_tag, testsuite_tag, completed_process.stdout)29		# copy_surefire_report_html(mutant_id, execution_tag, testsuite_rootdir, testsuite_tag)30		mut_result = extract_results_from_surefire_reports(testsuite_rootdir, testsuite_tag, testsuite_name)31		mutation_info.add_result(mut_result)32		print("[Mutant id: {}] Test suite '{}' has finished computation".format(mutant_id, testsuite_name))33		# TODO print method for MutationTestsResult34	def run_test_suite(self, testsuite_tag, mutation_info, execution_tag):35		test_suite = self._map_testsuite_info[testsuite_tag]...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!!
