Best Python code snippet using locust
build_report.py
Source:build_report.py
...18 return parser.parse_args()19def save_json_report(report, output_dir, file_name):20 with open(os.path.abspath(os.path.join(output_dir, file_name)), "w", encoding='utf8') as file:21 json.dump(report, file, indent=4, sort_keys=True) 22def save_html_report(report, output_dir, file_name):23 with open(os.path.abspath(os.path.join(output_dir, file_name)), 'w', encoding='utf8') as file:24 file.write(report)25def prepare_results_dir(output_dir):26 if os.path.exists(os.path.join(output_dir, 'resources')):27 rmtree(os.path.join(output_dir, 'resources'), True)28 try:29 copytree(os.path.join('report', 'resources'),30 os.path.join(output_dir, 'resources'))31 logger.info('Report resources were copied successfully')32 except Exception as err:33 logger.error('Fail during copying report resources: {}'.format(str(err)))34def get_displayable_platform_name(platform_name):35 return platform_name.replace('_', ' '). replace('-', ' (') + ')'36def build_summary_report(test_results):37 summary_report = {}38 summary_report['results'] = {}39 summary_report['summary'] = {40 'Tests': 0,41 'Time': 042 }43 summary_report['summary']['statuses'] = {44 'Passed': 0,45 'Failed': 0,46 'Error': 0,47 'Skipped': 048 }49 xml_reports = glob(os.path.join(test_results, XML_REPORT_PATTERN))50 for xml_report_path in xml_reports:51 with open(xml_report_path, 'r') as file:52 xml_report = file.read()53 platform_name = os.path.split(xml_report_path)[1].replace('Test-', '').split('.')[0]54 summary_report['results'][platform_name] = xmltodict.parse(xml_report)55 for testcase in summary_report['results'][platform_name]['testsuites']['testsuite']['testcase']:56 if 'error' in testcase:57 testcase['status'] = 'error'58 elif 'failure' in testcase:59 testcase['status'] = 'failure'60 elif testcase['@result'] == 'suppressed':61 testcase['status'] = 'skipped'62 else:63 testcase['status'] = 'passed'64 # make platform name more readable65 displayable_platform_name = get_displayable_platform_name(platform_name)66 summary_report['results'][platform_name]['name'] = displayable_platform_name67 summary_report['summary']['statuses']['Passed'] += int(summary_report['results'][platform_name]['testsuites']['@tests']) \68 - int(summary_report['results'][platform_name]['testsuites']['@failures']) - int(summary_report['results'][platform_name]['testsuites']['@errors']) \69 - int(summary_report['results'][platform_name]['testsuites']['@disabled'])70 summary_report['summary']['statuses']['Failed'] += int(summary_report['results'][platform_name]['testsuites']['@failures'])71 summary_report['summary']['statuses']['Error'] += int(summary_report['results'][platform_name]['testsuites']['@errors'])72 summary_report['summary']['statuses']['Skipped'] += int(summary_report['results'][platform_name]['testsuites']['@disabled'])73 summary_report['summary']['Tests'] += int(summary_report['results'][platform_name]['testsuites']['@tests'])74 summary_report['summary']['Time'] += float(summary_report['results'][platform_name]['testsuites']['@time'])75 return summary_report76def build_detailed_reports(env, summary_report, output_dir):77 detailed_summary_template = env.get_template('detailed_summary_template.html')78 for platform in summary_report['results']:79 detailed_summary_html = detailed_summary_template.render(title='Results of RIF performance tests ({})'.format(summary_report['results'][platform]['name']),80 report=summary_report['results'][platform]['testsuites']['testsuite'], platform_name=platform)81 save_html_report(detailed_summary_html, output_dir, DETAILED_REPORT_HTML.format(platform))82def build_testcase_reports(env, test_results, output_dir):83 testcase_template = env.get_template('testcase_template.html')84 logs = glob(os.path.join(test_results, CSV_FILE_PATTERN))85 for log in logs:86 platform_name = os.path.split(log)[1].replace('Test-', '').replace('.csv', '')87 platform_dir = os.path.join(output_dir, platform_name)88 if not os.path.exists(platform_dir):89 os.makedirs(platform_dir)90 with open(log) as file:91 lines = file.readlines()92 csv_lines = []93 for line in lines:94 # delete new line symbol and ; at the end95 line = line[0:-2]96 # replace spaces after column name or value97 line = re.sub(r'\s*;', ';', line)98 line = re.sub(r'\s*$', '', line)99 # if it isn't title with testcase name before next csv100 if len(line.split(';')) != 1:101 csv_lines.append(line)102 else:103 # check that it isn't first testcase104 if len(csv_lines) != 0:105 # check that current testcase has some csv data106 if len(csv_lines) != 1:107 generate_testcase_reports(csv_lines, testcase_template, platform_dir, testcase_name, platform_name)108 csv_lines.clear()109 testcase_name = line.replace(';', '')110 generate_testcase_reports(csv_lines, testcase_template, platform_dir, testcase_name, platform_name)111def generate_testcase_reports(csv_lines, testcase_template, platform_dir, testcase_name, platform_name):112 csv_reader = csv.DictReader(csv_lines, delimiter=';')113 converted_csv = [ row for row in csv_reader ]114 testcase_html = testcase_template.render(115 title='{testcase} testcase details ({platform})'.format(testcase=testcase_name, platform=get_displayable_platform_name(platform_name)), 116 data=converted_csv117 )118 save_json_report(converted_csv, platform_dir, TESTCASE_REPORT_JSON.format(testcase_name))119 save_html_report(testcase_html, platform_dir, TESTCASE_REPORT_HTML.format(testcase_name))120def main():121 args = parse_args()122 prepare_results_dir(args.output_dir)123 env = jinja2.Environment(124 loader=jinja2.PackageLoader('build_report', 'report/templates'),125 autoescape=True126 )127 summary_report = build_summary_report(args.test_results)128 save_json_report(summary_report, args.output_dir, SUMMARY_REPORT_JSON)129 summary_template = env.get_template('summary_template.html')130 summary_html = summary_template.render(title='Results of RIF performance tests',131 report=summary_report)132 save_html_report(summary_html, args.output_dir, SUMMARY_REPORT_HTML)133 build_detailed_reports(env, summary_report, args.output_dir)134 build_testcase_reports(env, args.test_results, args.output_dir)135if __name__ == '__main__':...
abstract_screening.py
Source:abstract_screening.py
...54 template = load_template(report_name)55 html = template.render(56 concordances=zip(abstracts.document_id.tolist(), abstracts.phrase.tolist())57 )58 save_html_report(directory, html, report_name)59def _extract_contexts(abstracts, text, left, right):60 text = text.upper()61 regex = r"\b" + text + r"\b"62 left_context_regex = r"(?P<left_context>(?:\w+\W+){1," + str(left) + "})"63 right_context_regex = r"(?P<right_context>(?:\W+\w+){1," + str(right) + "})"64 contexts = abstracts["phrase"].str.extract(65 left_context_regex + regex + right_context_regex66 )67 contexts["left_context"] = contexts["left_context"].fillna("")68 contexts["right_context"] = contexts["right_context"].fillna("")69 left_max_len = max(contexts["left_context"].str.len())70 contexts["left_context"] = contexts["left_context"].str.rjust(left_max_len)71 contexts = contexts.assign(72 text=contexts.left_context + text + contexts.right_context...
prefect_example.py
Source:prefect_example.py
...55def save_report(result):56 client = MongoClient("mongodb://localhost:27018/")57 client.get_database("prediction_service").get_collection("report").insert_one(result[0])58@task59def save_html_report(result):60 result[1].save("evidently_report_example.html")61@flow62def batch_analyze():63 upload_target("target.csv")64 ref_data = load_reference_data("./evidently_service/datasets/green_tripdata_2021-01.parquet")65 data = fetch_data()66 result = run_evidently(ref_data, data)67 save_report(result)68 save_html_report(result)...
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!!