Best Python code snippet using green
junithelper.py
Source:junithelper.py
1#!/usr/bin/env python32import os, sys3import pathlib4import argparse5"""6Python module helping combine JUnit xml test results, merge them and print to a unified xml7It can also help to print html result8"""9try:10 import junitparser11except ImportError :12 print("junitparser package is required to execute this script. Try to install it :")13 print("python -m -pip install junitparser")14def _percentage_to_hex_color(passed_percentage):# percentage passed15 #light red very red16 color_vector = ['ffff00', 'ffbf00', 'ff8000', 'ff9999', 'ff6666', 'ff0000']17 if passed_percentage >99.9:18 return '#00ff2b'# Green. absolutely everything passed19 percentage_int = int(passed_percentage)20 failed_color_index = int((100-percentage_int)/20)21 color_str = '#{}'.format(color_vector[failed_color_index])22 return color_str23def _append_testname_postfix(junit_xml, test_name_postfix):24 for child in junit_xml:25 if type(child) is junitparser.TestSuite:26 _append_testname_postfix(child, test_name_postfix)27 if type(child) is junitparser.TestCase:28 child.name += test_name_postfix29 child.classname += test_name_postfix30## Test reported by mocha has 'testsuites' tag which junitparser in python don't like it. Change testsuites to testsuite make it work31def _fix_testsuites_if_exist(xml_file):32 has_testsuites=False33 xml_content=''34 with open(xml_file) as f:35 xml_content = f.read()36 if 'testsuites' in xml_content:37 has_testsuites=True38 xml_content=xml_content.replace('testsuites', 'testsuite')39 if has_testsuites:40 with open(xml_file, "w") as f:41 f.write(xml_content)42def get_consolidated_junitxml(result_dir_path, test_name_postfix=''):43 xml_file_list = sorted(result_dir_path.glob('*test*.xml'))44 #print('\n'.join(xml_file_list))45 junit_xml = junitparser.JUnitXml()46 for xml_file in xml_file_list:47 _fix_testsuites_if_exist(xml_file)# Mocha junit reporter has testsuites which is incompatible with junitparser48 test_results = junitparser.JUnitXml.fromfile(xml_file)49 is_test_suites = False ## case where in the xml file is a test_suites (multiple test_suite)50 for suite in test_results.testsuites():51 junit_xml.add_testsuite(suite)52 is_test_suites=True53 if not is_test_suites:54 junit_xml.add_testsuite(test_results)55 if test_name_postfix is not None:56 _append_testname_postfix(junit_xml, test_name_postfix)57 return junit_xml58def _get_html_table(xml_junit):59 max_nb_col = 460 html_table_str = '<table cellpadding="10">\n'61 col_id=062 for test_suite in xml_junit:63 if col_id < 1:64 html_table_str += ' <tr>\n'65 test_suite_name = test_suite.name66 test_suite_time = test_suite.time67 nb_test_cases = len(test_suite)68 test_suite_failures = test_suite.failures69 test_suite_errors = test_suite.errors70 total_failed = test_suite_failures + test_suite_errors71 total_passed = nb_test_cases-total_failed72 passing_percentage = 100 if nb_test_cases == 0 else 100*((total_passed)/(nb_test_cases))73 test_suite_color_str = _percentage_to_hex_color(passing_percentage)74 html_table_str += ' <td {}>\n'.format('style="background-color:{}"'.format(test_suite_color_str))75 html_table_str += ' <b>'+ test_suite_name + '</b><br>\n'76 html_table_str += ' time : ' + str(test_suite_time) + 's<br>\n'77 html_table_str += ' passed : ' + str(total_passed) + '<br>\n'78 html_table_str += ' failed : ' + str(test_suite_failures) + '<br>\n'79 html_table_str += ' error : ' + str(test_suite_errors) + '<br>\n'80 html_table_str += ' TOTAL : ' + str(nb_test_cases) + '<br>\n'81 html_table_str += ' </td>\n'82 col_id=col_id+183 if col_id > 3:84 col_id=085 html_table_str += ' </tr>\n'86 html_table_str += '</table>\n'87 return html_table_str88def get_consolidated_html(xml_release, xml_debug):89 html_test_str =''90 if len(xml_release) > 0:91 html_test_str+= '<b>Test results on Release</b>:<br>{}<br>\n'.format(_get_html_table(xml_release))92 else:93 html_test_str+= '<font color="red"><b>Test results on Release</b>: MISSING</font><br><br>\n'94 if len(xml_debug) > 0:95 html_test_str+= '<b>Test results on Debug</b>:<br>{}<br>\n'.format(_get_html_table(xml_debug))96 else:97 html_test_str+= '<font color="red"><b>Test results on Debug: MISSING</b></font><br><br>\n'...
cucumber_json_to_junit.py
Source:cucumber_json_to_junit.py
1#!/usr/bin/env python32'''3Utility to convert from Cucumber JSON output to JUnit XML output4'''5import sys6import json7def main():8 '''9 Main function10 '''11 if len(sys.argv) < 2 or not sys.argv[1].endswith(".json"):12 print("No JSON file path received. Usage:")13 print("\tpython cucumber-json-to-junit.py source-report.json target-report.xml")14 sys.exit()15 if len(sys.argv) < 3 or not sys.argv[2].endswith(".xml"):16 print("No XML file path received. Usage:")17 print("\tpython cucumber-json-to-junit.py source-report.json target-report.xml")18 sys.exit()19 with open(sys.argv[1], "r") as json_file:20 print("Opening file " + sys.argv[1] + " in read-only")21 json_data = json.load(json_file)22 test_cases = ""23 header = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"24 test_suite_time = 0.025 failure_count = 026 scenario_count = 027 for feature in json_data:28 feature_name = sanitize(feature["name"])29 scenarios = feature["elements"]30 feature_time = 0.031 for scenario in scenarios:32 scenario_count += 133 scenario_name = sanitize(scenario["name"])34 steps_blob = "<![CDATA["35 err_blob = ""36 scenario_status = "passed"37 scenario_time = 0.038 if scenario["type"] != "background":39 for tag in scenario["tags"]:40 steps_blob += tag["name"] + " "41 steps_blob += "\n"42 for step in scenario["steps"]:43 description = sanitize(step["name"])44 results = step["result"]45 status = sanitize(results["status"])46 keyword = sanitize(step["keyword"])47 if status != "skipped":48 scenario_time += float(results["duration"]) / 100000000049 num_dots = 83 - len(keyword) - len(description) - len(status)50 if num_dots <= 0:51 num_dots = 152 steps_blob += keyword + description53 for i in range(num_dots):54 steps_blob += "."55 steps_blob += status + "\n"56 if status == "failed":57 err_blob = sanitize(results["error_message"])58 scenario_status = "failed"59 failure_count += 160 feature_time += scenario_time61 steps_blob += "]]>"62 test_case = "<testcase "63 test_case += "classname=\"" + feature_name + "\" "64 test_case += "name=\"" + scenario_name + "\" "65 test_case += "time=\"" + str(scenario_time) + "\">"66 if scenario_status == "passed":67 test_case += "<system-out>" + steps_blob + "</system-out>\n"68 else:69 test_case += "<failure message=\"" + err_blob + "\">"70 test_case += steps_blob + "</failure>\n"71 test_case += "</testcase>\n"72 test_cases += test_case73 test_suite_time += feature_time74 test_suite = "<testsuite "75 test_suite += "failures=\"" + str(failure_count) + "\" "76 test_suite += "name=\"Cucumber JSON to JUnit\" "77 test_suite += "skipped=\"0\" "78 test_suite += "tests=\"" + str(scenario_count) + "\" "79 test_suite += "time=\"" + str(test_suite_time) + "\">\n"80 for test_case in test_cases:81 test_suite += test_case82 test_suite += "</testsuite>"83 with open(sys.argv[2], "w") as junit_file:84 print("Writing to file " + sys.argv[2] + "...")85 junit_file.write(header)86 junit_file.write(test_suite)87 print("Done.")88def sanitize(input):89 input = input.replace("&","&").replace("\"",""")90 input = input.replace("<","<").replace(">",">")91 return input92if __name__ == "__main__":93 # execute only if run as a script...
webvtoJunit.py
Source:webvtoJunit.py
1#!/usr/bin/env python32'''3Utility to convert from webv output to JUnit format4'''5import sys6import json7def get_test_case_details(json_data):8 test_cases = ""9 test_suite_time = 0.0 10 test_case_count = 011 failure_count = 012 for test_case_json in json_data:13 test_case_name = str(test_case_json["tag"]) + ": " + str(test_case_json["verb"]) + ": " + encode_special_characters(str(test_case_json["path"]) )14 test_case_count += 115 test_case_status = "passed"16 test_case_time = 0.017 failed = test_case_json["failed"]18 19 if bool(failed) == True:20 err_blob = encode_special_characters(test_case_json["errors"])21 err_blob += "\nServer:" + encode_special_characters(test_case_json["server"])22 err_blob += "\nPath:" + encode_special_characters(test_case_json["path"])23 test_case_status = "failed"24 failure_count += 125 test_case_time += float(test_case_json["duration"]) / 100026 test_case = "<testcase "27 test_case += "classname=\"" + test_case_name + "\" "28 test_case += "name=\"" + test_case_name + "\" "29 test_case += "time=\"" + str(test_case_time) + "\">"30 if test_case_status == "passed":31 test_case += "<system-out>" 32 test_case += "</system-out>\n"33 else:34 test_case += "<failure message=\"" + err_blob + "\">"35 test_case += "</failure>\n"36 test_case += "</testcase>\n"37 test_cases += test_case38 test_suite_time += test_case_time39 return (test_cases, test_case_count, failure_count, test_suite_time)40def get_test_suite(test_cases_xml, test_case_count, failure_count, test_suite_time):41 test_suite = "<testsuite "42 test_suite += "failures=\"" + str(failure_count) + "\" "43 test_suite += "name=\"Webv to JUnit\" "44 test_suite += "skipped=\"0\" "45 test_suite += "tests=\"" + str(test_case_count) + "\" "46 test_suite += "time=\"" + str(test_suite_time) + "\">\n"47 for test_case in test_cases_xml:48 test_suite += test_case49 test_suite += "</testsuite>"50 return test_suite51def encode_special_characters(input_string):52 output_string = str(input_string).replace("&","&")53 output_string = output_string.replace("\"",""")54 output_string = output_string.replace("<","<")55 output_string = output_string.replace(">",">")56 return output_string57def main():58 '''59 Main func60 '''61 if len(sys.argv) < 2 or not sys.argv[1].endswith(".json"):62 print("JSON file path not found or incorrect:")63 sys.exit()64 if len(sys.argv) < 3 or not sys.argv[2].endswith(".xml"):65 print("XML file path incorrect")66 sys.exit()67 with open(sys.argv[1], "r") as json_file:68 print("Opening file " + sys.argv[1] + " in read-only mode")69 json_data = json.load(json_file)70 header = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"71 # Get the XML, and aggregate details for test cases72 (test_cases, test_case_count, failure_count, test_case_total_time) = get_test_case_details(json_data)73 # Get the XML for test suite with embedded test cases74 test_suite = get_test_suite(test_cases, test_case_count, failure_count, test_case_total_time)75 76 with open(sys.argv[2], "w") as junit_file:77 print("Writing to file " + sys.argv[2] + "...")78 junit_file.write(header)79 junit_file.write(test_suite)80 print("webv report written in JUnit format...")81if __name__ == "__main__":...
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!!