Best Python code snippet using robotframework
verify_network_via_no_proxy.py
Source:verify_network_via_no_proxy.py
1import os2import subprocess3import time4import requests5from Common import common_function6from Common.log import log7from Test_Suite.verify_network_via_http_proxy import ProxyTest8910class NoProxyTest(ProxyTest):11 def __init__(self, protocol_name='noproxy', bypass_setting=False):12 super().__init__(protocol_name, bypass_setting)1314 def set_no_proxy(self, fill_all_protocol, bypass_text, case_name, report_file):15 log.info('set bypass: {}'.format(bypass_text))16 steps = {17 'step_name': 'set {} {}'.format(self.protocol, bypass_text),18 'result': 'Fail',19 'expect': 'icon can be recognised',20 'actual': '',21 'note': ''}22 proxy_list = ['http', 'ftp', 'https']23 t = self.dns.open_dns()24 if not t:25 log.info('Failed to recognise DNS icon')26 steps['actual'] = 'Failed to recognise DNS icon'27 common_function.update_cases_result(report_file, case_name, steps)28 self.dns.close_dns()29 return30 if fill_all_protocol:31 for i in proxy_list:32 proxy_text = self.get_proxy_server('proxy3').replace(self.protocol, 'http')33 t2 = self.dns.set_value(i, proxy_text)34 if not t2:35 log.info('Failed to recognise {} icon'.format(i))36 steps['actual'] = 'Failed to recognise {} icon'.format(i)37 common_function.update_cases_result(report_file, case_name, steps)38 self.dns.close_dns()39 return40 t3 = self.dns.set_value(self.protocol, bypass_text)41 time.sleep(5)42 if not t3:43 log.info('Failed to recognise noproxy icon')44 steps['actual'] = 'Failed to recognise noproxy icon'45 common_function.update_cases_result(report_file, case_name, steps)46 self.dns.close_dns()47 return48 t4 = self.dns.close_dns()49 if not t4:50 log.info('Failed to recognise apply icon')51 steps['actual'] = 'Failed to recognise apply icon'52 common_function.update_cases_result(report_file, case_name, steps)53 return54 log.info('proxy set successfully')55 steps['actual'] = 'proxy set successfully'56 steps['result'] = 'Pass'57 common_function.update_cases_result(report_file, case_name, steps)58 return True5960 def website_test(self, url, flag, case_name, report_file):61 if flag:62 expect = 20063 msg = "verify {} can be accessed".format(url)64 else:65 expect = 'Error'66 msg = "verify {} can not be accessed".format(url)67 steps = {68 'step_name': "test {}".format(url),69 'result': '',70 'expect': 'status code should be {}'.format(expect),71 'actual': '',72 'note': ''}73 log.info(msg)74 log.info('current ip: {}'.format(common_function.get_ip()))75 log.info('get status code from {}'.format(url))76 data = self.get_website_response()77 actual = 'status code is {}'.format(data)78 log.info(actual)79 if data == expect:80 s = 'Pass'81 rs = True82 else:83 s = 'Fail'84 rs = False85 log.info('test {}'.format(s))86 steps['result'] = s87 steps['actual'] = actual88 common_function.update_cases_result(report_file, case_name, steps)89 return rs9091 @staticmethod92 def website_test222(bypass_text, accessed_list, not_accessed_list, case_name, report_file):93 log.info('wait 10s')94 time.sleep(10)95 rs = False96 steps = {97 'step_name': "test no proxy: ".format(bypass_text),98 'result': '',99 'expect': 'status code should be 200',100 'actual': '',101 'note': ''}102 for j in accessed_list:103 log.info("verify {} can be accessed".format(j))104 log.info('get data from {}'.format(j))105 try:106 data = requests.get(j, timeout=5).status_code107 except Exception:108 data = 'Error'109 log.info('status code is: {}'.format(data))110111 if data == 200:112 s = 'Pass'113 rs = True114 else:115 s = 'Fail'116 rs = False117 log.info('test {}'.format(s))118 steps['result'] = s119 common_function.update_cases_result(report_file, case_name, steps)120 for i in not_accessed_list:121 log.info("verify {} can not be accessed".format(i))122 log.info('get data from {}'.format(i))123 try:124 data = requests.get(i, timeout=5).status_code125 except Exception:126 data = 'Error'127 log.info('status code is: {}'.format(data))128 steps = {129 'step_name': "verify {} can not be accessed".format(i),130 'result': '',131 'expect': 'status code should be Error',132 'actual': data,133 'note': ''}134 if data == 'Error':135 s = 'Pass'136 rs = True137 else:138 s = 'Fail'139 rs = False140 log.info('test {}'.format(s))141 steps['result'] = s142 common_function.update_cases_result(report_file, case_name, steps)143 return rs144145 def set_proxy_bypass(self, proxy_text, case_name, report_file):146 steps = {147 'step_name': "set {}: {}".format(self.protocol, proxy_text),148 'result': 'Fail',149 'expect': 'icon can be recognised',150 'actual': '',151 'note': ''}152 t = self.dns.open_dns()153 if not t:154 steps['actual'] = 'Failed to recognise DNS icon'155 common_function.update_cases_result(report_file, case_name, steps)156 return157 t2 = self.dns.set_value(self.protocol, proxy_text)158 if not t2:159 steps['actual'] = 'Failed to recognise {} icon'.format(self.protocol)160 common_function.update_cases_result(report_file, case_name, steps)161 return162 t4 = self.dns.close_dns()163 if not t4:164 steps['actual'] = 'Failed to recognise apply icon'165 common_function.update_cases_result(report_file, case_name, steps)166 return167 self.reboot()168169 def reset_env_last(self):170 log.info('restore env default after the last step')171 # common_function.import_profile()172 self.dns.open_dns()173 for i in ['http', 'ftp', 'https']:174 self.dns.clear_text(i)175 self.dns.clear_text(self.protocol)176 self.dns.close_dns()177 subprocess.run('reboot')178 time.sleep(10)179180181def set_bypass_baidu(**kwargs):182 case_name = kwargs.get("case_name")183 report_file = kwargs.get("report_file")184 no_proxy_test = kwargs.get('obj')185 bypass_text = 'http://www.baidu.com'186 if no_proxy_test.set_no_proxy(True, bypass_text, case_name, report_file):187 no_proxy_test.reboot()188 else:189 no_proxy_test.reset_env_halfway()190 return False191192193def test_bypass_baidu(**kwargs):194 case_name = kwargs.get("case_name")195 report_file = kwargs.get("report_file")196 no_proxy_test = kwargs.get('obj')197 a = ['http://www.google.com']198 n = ['http://www.baidu.com']199 for url in a:200 if not no_proxy_test.website_test(url, True, case_name, report_file):201 no_proxy_test.reset_env_halfway()202 return False203 for url in n:204 if not no_proxy_test.website_test(url, False, case_name, report_file):205 no_proxy_test.reset_env_halfway()206 return False207 return True208209210def set_bypass_baidu_google(**kwargs):211 case_name = kwargs.get("case_name")212 report_file = kwargs.get("report_file")213 no_proxy_test = kwargs.get('obj')214 bypass_text = 'http://www.baidu.com,http://www.google.com'215 if no_proxy_test.set_no_proxy(False, bypass_text, case_name, report_file):216 no_proxy_test.reboot()217 else:218 no_proxy_test.reset_env_halfway()219 return False220221222def test_bypass_baidu_google(**kwargs):223 case_name = kwargs.get("case_name")224 report_file = kwargs.get("report_file")225 no_proxy_test = kwargs.get('obj')226 a = ['http://www.youtube.com']227 n = ['http://www.baidu.com', 'http://www.google.com']228 for url in a:229 if not no_proxy_test.website_test(url, True, case_name, report_file):230 no_proxy_test.reset_env_halfway()231 return False232 for url in n:233 if not no_proxy_test.website_test(url, False, case_name, report_file):234 no_proxy_test.reset_env_halfway()235 return False236 return True237238239def set_bypass_contain_baidu(**kwargs):240 case_name = kwargs.get("case_name")241 report_file = kwargs.get("report_file")242 no_proxy_test = kwargs.get('obj')243 bypass_text = '.baidu.com'244 if no_proxy_test.set_no_proxy(False, bypass_text, case_name, report_file):245 no_proxy_test.reboot()246 else:247 no_proxy_test.reset_env_halfway()248 return False249250251def test_bypass_contain_baidu(**kwargs):252 case_name = kwargs.get("case_name")253 report_file = kwargs.get("report_file")254 no_proxy_test = kwargs.get('obj')255 a = ['http://www.youtube.com']256 n = ['http://www.baidu.com', 'http://map.baidu.com']257 for url in a:258 if not no_proxy_test.website_test(url, True, case_name, report_file):259 no_proxy_test.reset_env_halfway()260 return False261 for url in n:262 if not no_proxy_test.website_test(url, False, case_name, report_file):263 no_proxy_test.reset_env_halfway()264 return False265 no_proxy_test.reset_env_last()266 return True267268269def finish(**kwargs):270 log.info('pave the way for the finish')271272273def start(case_name, kwargs):274 steps_list = (275 "set_bypass_baidu",276 "test_bypass_baidu",277 "set_bypass_baidu_google",278 "test_bypass_baidu_google",279 "set_bypass_contain_baidu",280 "test_bypass_contain_baidu",281 "finish"282 )283 no_proxy_test = NoProxyTest()284 result_file = common_function.get_current_dir(r'Test_Report', '{}.yaml'.format(common_function.check_ip_yaml()))285 common_function.new_cases_result(result_file, case_name)286 # no_proxy_test.tp.switch_mode()287 common_function.case_steps_run_control(steps_list, __name__, case_name=case_name, log=log,
...
oonireport.py
Source:oonireport.py
1from __future__ import print_function2import os3import sys4import json5import yaml6from twisted.python import usage7from twisted.internet import defer, task, reactor8from ooni.constants import CANONICAL_BOUNCER_ONION9from ooni.reporter import OONIBReporter, OONIBReportLog10from ooni.utils import log11from ooni.settings import config12from ooni.backend_client import BouncerClient, CollectorClient13from ooni import __version__14@defer.inlineCallbacks15def lookup_collector_client(report_header, bouncer):16 oonib_client = BouncerClient(bouncer)17 net_tests = [{18 'test-helpers': [],19 'input-hashes': [],20 'name': report_header['test_name'],21 'version': report_header['test_version'],22 }]23 result = yield oonib_client.lookupTestCollector(24 net_tests25 )26 collector_client = CollectorClient(27 address=result['net-tests'][0]['collector']28 )29 defer.returnValue(collector_client)30class NoIDFound(Exception):31 pass32def report_path_to_id(report_file):33 measurement_dir = os.path.dirname(report_file)34 measurement_id = os.path.basename(measurement_dir)35 if os.path.dirname(measurement_dir) != config.measurements_directory:36 raise NoIDFound37 return measurement_id38@defer.inlineCallbacks39def upload(report_file, collector=None, bouncer=None, measurement_id=None):40 oonib_report_log = OONIBReportLog()41 collector_client = None42 if collector:43 collector_client = CollectorClient(address=collector)44 try:45 # Try to guess the measurement_id from the file path46 measurement_id = report_path_to_id(report_file)47 except NoIDFound:48 pass49 log.msg("Attempting to upload %s" % report_file)50 if report_file.endswith(".njson"):51 report = NJSONReportLoader(report_file)52 else:53 log.warn("Uploading of YAML formatted reports will be dropped in "54 "future versions")55 report = YAMLReportLoader(report_file)56 if bouncer and collector_client is None:57 collector_client = yield lookup_collector_client(report.header,58 bouncer)59 if collector_client is None:60 if measurement_id:61 report_log = yield oonib_report_log.get_report_log(measurement_id)62 collector_settings = report_log['collector']63 print(collector_settings)64 if collector_settings is None or len(collector_settings) == 0:65 log.warn("Skipping uploading of %s since this measurement "66 "was run by specifying no collector." %67 report_file)68 defer.returnValue(None)69 elif isinstance(collector_settings, dict):70 collector_client = CollectorClient(settings=collector_settings)71 elif isinstance(collector_settings, str):72 collector_client = CollectorClient(address=collector_settings)73 else:74 log.msg("Looking up collector with canonical bouncer." % report_file)75 collector_client = yield lookup_collector_client(report.header,76 CANONICAL_BOUNCER_ONION)77 oonib_reporter = OONIBReporter(report.header, collector_client)78 log.msg("Creating report for %s with %s" % (report_file,79 collector_client.settings))80 report_id = yield oonib_reporter.createReport()81 report.header['report_id'] = report_id82 if measurement_id:83 log.debug("Marking it as created")84 yield oonib_report_log.created(measurement_id,85 collector_client.settings)86 log.msg("Writing report entries")87 for entry in report:88 yield oonib_reporter.writeReportEntry(entry)89 log.msg("Written entry")90 log.msg("Closing report")91 yield oonib_reporter.finish()92 if measurement_id:93 log.debug("Closing log")94 yield oonib_report_log.closed(measurement_id)95@defer.inlineCallbacks96def upload_all(collector=None, bouncer=None, upload_incomplete=False):97 oonib_report_log = OONIBReportLog()98 reports_to_upload = yield oonib_report_log.get_to_upload()99 for report_file, value in reports_to_upload:100 try:101 yield upload(report_file, collector, bouncer,102 value['measurement_id'])103 except Exception as exc:104 log.exception(exc)105 if upload_incomplete:106 reports_to_upload = yield oonib_report_log.get_incomplete()107 for report_file, value in reports_to_upload:108 try:109 yield upload(report_file, collector, bouncer,110 value['measurement_id'])111 except Exception as exc:112 log.exception(exc)113def print_report(report_file, value):114 print("* %s" % report_file)115 print(" %s" % value['last_update'])116@defer.inlineCallbacks117def status():118 oonib_report_log = OONIBReportLog()119 reports_to_upload = yield oonib_report_log.get_to_upload()120 print("Reports to be uploaded")121 print("----------------------")122 for report_file, value in reports_to_upload:123 print_report(report_file, value)124 reports_in_progress = yield oonib_report_log.get_in_progress()125 print("Reports in progress")126 print("-------------------")127 for report_file, value in reports_in_progress:128 print_report(report_file, value)129 reports_incomplete = yield oonib_report_log.get_incomplete()130 print("Incomplete reports")131 print("------------------")132 for report_file, value in reports_incomplete:133 print_report(report_file, value)134class ReportLoader(object):135 _header_keys = (136 'probe_asn',137 'probe_cc',138 'probe_ip',139 'probe_city',140 'test_start_time',141 'test_name',142 'test_version',143 'options',144 'input_hashes',145 'software_name',146 'software_version',147 'data_format_version',148 'report_id',149 'test_helpers',150 'annotations',151 'id'152 )153 def __iter__(self):154 return self155 def close(self):156 self._fp.close()157class YAMLReportLoader(ReportLoader):158 def __init__(self, report_filename):159 self._fp = open(report_filename)160 self._yfp = yaml.safe_load_all(self._fp)161 self.header = self._yfp.next()162 def next(self):163 try:164 return self._yfp.next()165 except StopIteration:166 self.close()167 raise StopIteration168class NJSONReportLoader(ReportLoader):169 def __init__(self, report_filename):170 self._fp = open(report_filename)171 self.header = self._peek_header()172 def _peek_header(self):173 header = {}174 first_entry = json.loads(next(self._fp))175 for key in self._header_keys:176 header[key] = first_entry.get(key, None)177 self._fp.seek(0)178 return header179 def next(self):180 try:181 entry = json.loads(next(self._fp))182 for key in self._header_keys:183 entry.pop(key, None)184 test_keys = entry.pop('test_keys')185 entry.update(test_keys)186 return entry187 except StopIteration:188 self.close()189 raise StopIteration190class Options(usage.Options):191 synopsis = """%s [options] upload | status192""" % (os.path.basename(sys.argv[0]),)193 optFlags = [194 ["default-collector", "d", "Upload the reports to the default "195 "collector that is looked up with the "196 "canonical bouncer."]197 ]198 optParameters = [199 ["configfile", "f", None,200 "Specify the configuration file to use."],201 ["collector", "c", None,202 "Specify the collector to upload the result to."],203 ["bouncer", "b", None,204 "Specify the bouncer to query for a collector."]205 ]206 def opt_version(self):207 print("oonireport version: %s" % __version__)208 sys.exit(0)209 def parseArgs(self, *args):210 if len(args) == 0:211 raise usage.UsageError(212 "Must specify at least one command"213 )214 return215 self['command'] = args[0]216 if self['command'] not in ("upload", "status"):217 raise usage.UsageError(218 "Must specify either command upload or status"219 )220 if self['command'] == "upload":221 try:222 self['report_file'] = args[1]223 except IndexError:224 self['report_file'] = None225def tor_check():226 if not config.tor.socks_port:227 log.err("Currently oonireport requires that you start Tor yourself "228 "and set the socks_port inside of ooniprobe.conf")229 sys.exit(1)230def oonireport(_reactor=reactor, _args=sys.argv[1:]):231 options = Options()232 try:233 options.parseOptions(_args)234 except Exception as exc:235 print("Error: %s" % exc)236 print(options)237 sys.exit(2)238 config.global_options = dict(options)239 config.set_paths()240 config.read_config_file()241 if options['default-collector']:242 options['bouncer'] = CANONICAL_BOUNCER_ONION243 if options['command'] == "upload" and options['report_file']:244 log.start()245 tor_check()246 return upload(options['report_file'],247 options['collector'],248 options['bouncer'])249 elif options['command'] == "upload":250 log.start()251 tor_check()252 return upload_all(options['collector'],253 options['bouncer'])254 elif options['command'] == "status":255 return status()256 else:257 print(options)258def run():259 task.react(oonireport)260if __name__ == "__main__":...
acm_analysis.py
Source:acm_analysis.py
1#2# This script perform a mca on clinical data3# except medication variable and control patients (for now)4# use the acm_clinical.R script.5# Create .tex reports6#7### REFORMAT INPUT FILES ###8"""9-> Convert stupid tsv files into clean csv files10-> Create a file with only the "Clinical" variables 11 (and no medication variable)12"""13index_to_keep = []14medication_index = []15data = open("data/clinical_i2b2trans_1.txt", "r")16output = open("data/clinical_i2b2trans_1.csv", "w")17output_clinical = open("data/clinical_data_phase_1.csv", "w")18cmpt = 019for line in data:20 line = line.split("\n")21 line = line[0]22 line_in_array = line.split("\t")23 if(cmpt == 0):24 index = 025 header_in_string = ""26 clinical_header_in_string = ""27 for element in line_in_array:28 header_in_string += str(element)+","29 element_in_array = element.split("\\")30 if("Clinical" in element_in_array or "Autoantibody" in element_in_array):31 index_to_keep.append(index)32 clinical_header_in_string += str(element)+","33 index += 134 header_in_string = header_in_string[:-1]35 header_in_string = header_in_string.replace(" ", "")36 output.write(header_in_string+"\n")37 clinical_header_in_string = clinical_header_in_string[:-1]38 clinical_header_in_string = clinical_header_in_string.replace(" ", "")39 output_clinical.write(clinical_header_in_string+"\n")40 else:41 index = 042 line_in_string = ""43 clinical_line_in_string = ""44 for element in line_in_array:45 line_in_string += str(element)+","46 if(index in index_to_keep):47 clinical_line_in_string += str(element)+","48 index += 149 line_in_string = line_in_string[:-1]50 line_in_string = line_in_string.replace(" ", "")51 output.write(line_in_string+"\n")52 clinical_line_in_string = clinical_line_in_string[:-1]53 clinical_line_in_string = clinical_line_in_string.replace(" ", "")54 output_clinical.write(clinical_line_in_string+"\n")55 cmpt += 156output_clinical.close()57output.close()58data.close()59### RUN R SCRIPT ###60"""61-> load reformated data62-> perform mca63-> create figures64"""65import os66os.system("Rscript acm_clinical.R")67### CREATE TEX FILES ###68"""69-> create a tex file for each subset of data70"""71sub_data_list = ["lung", "kidney", "nerveSystem", "skin", "muscleAndSkeletal", "comorbidity", "vascular", "gastro", "heart", "diagnosis", "autoantibody", "symptom"]72for data in sub_data_list:73 data_file_name = "latex\\"+str(data)+"_report.tex"74 report_file = open(data_file_name, "w")75 report_file.write("\\documentclass[a4paper,9pt]{extarticle}\n")76 report_file.write("\\usepackage[utf8]{inputenc}\n")77 report_file.write("\\usepackage[T1]{fontenc}\n")78 report_file.write("\\usepackage{graphicx}\n")79 report_file.write("\\usepackage{xcolor}\n")80 report_file.write("\\usepackage{tikz}\n")81 report_file.write("\\usepackage{pgfplots}\n")82 report_file.write("\\usepackage{amsmath,amssymb,textcomp}\n")83 report_file.write("\\everymath{\displaystyle}\n\n")84 report_file.write("\\usepackage{times}\n")85 report_file.write("\\renewcommand\\familydefault{\\sfdefault}\n")86 report_file.write("\\usepackage{tgheros}\n")87 report_file.write("\\usepackage[defaultmono,scale=0.85]{droidmono}\n\n")88 report_file.write("\\usepackage{multicol}\n")89 report_file.write("\\setlength{\\columnseprule}{0pt}\n")90 report_file.write("\\setlength{\\columnsep}{20.0pt}\n\n")91 report_file.write("\\usepackage{geometry}\n")92 report_file.write("\\geometry{\n")93 report_file.write("a4paper,\n")94 report_file.write("total={210mm,297mm},\n")95 report_file.write("left=10mm,right=10mm,top=10mm,bottom=15mm}\n\n")96 report_file.write("\\linespread{1.30}\n\n")97 report_file.write("\\makeatletter\n")98 report_file.write("\\renewcommand*{\\maketitle}{%\n")99 report_file.write("\\noindent\n")100 report_file.write("\\begin{minipage}{0.4\\textwidth}\n")101 report_file.write("\\begin{tikzpicture}\n")102 report_file.write("\\node[rectangle,rounded corners=6pt,inner sep=10pt,fill=blue!50!black,text width= 0.75\\textwidth] {\\color{white}\\Huge \\@title};\n")103 report_file.write("\\end{tikzpicture}\n")104 report_file.write("\\end{minipage}\n")105 report_file.write("\\hfill\n")106 report_file.write("\\begin{minipage}{0.55\\textwidth}\n")107 report_file.write("\\begin{tikzpicture}\n")108 report_file.write("\\node[rectangle,rounded corners=3pt,inner sep=10pt,draw=blue!50!black,text width= 0.95\\textwidth] {\\LARGE \\@author};\n")109 report_file.write("\\end{tikzpicture}\n")110 report_file.write("\\end{minipage}\n")111 report_file.write("\\bigskip\\bigskip\n")112 report_file.write("}%\n")113 report_file.write("\\makeatother\n\n")114 report_file.write("\\usepackage[explicit]{titlesec}\n")115 report_file.write("\\newcommand*\\sectionlabel{}\n")116 report_file.write("\\titleformat{\\section}\n")117 report_file.write("\t{\\gdef\\sectionlabel{}\n")118 report_file.write("\t\\normalfont\\sffamily\\Large\\bfseries\\scshape}\n")119 report_file.write("\t{\\gdef\\sectionlabel{\\thesection\\ }}{0pt}\n")120 report_file.write("\t{\n")121 report_file.write("\\noindent\n")122 report_file.write("\\begin{tikzpicture}\n")123 report_file.write("\\node[rectangle,rounded corners=3pt,inner sep=4pt,fill=blue!50!black,text width= 0.95\\columnwidth] {\\color{white}\\sectionlabel#1};\n")124 report_file.write("\\end{tikzpicture}\n")125 report_file.write("\t}\n")126 report_file.write("\\titlespacing*{\\section}{0pt}{15pt}{10pt}\n\n")127 report_file.write("\\usepackage{fancyhdr}\n")128 report_file.write("\\makeatletter\n")129 report_file.write("\\pagestyle{fancy}\n")130 report_file.write("\\fancyhead{}\n")131 report_file.write("\\fancyfoot[C]{\\footnotesize \\textcopyright\\ \\@date\\ \\ \\@author}\n")132 report_file.write("\\renewcommand{\\headrulewidth}{0pt}\n")133 report_file.write("\\renewcommand{\\footrulewidth}{0pt}\n")134 report_file.write("\\makeatother\\title{"+str(data)+" dataset}\n")135 report_file.write("\\author{ACM exploration}\n")136 report_file.write("\\date{2017}\n")137 report_file.write("\\begin{document}\n")138 report_file.write("\\maketitle\n\n\n")139 report_file.write("\\section{Overview - Dimmensions}\n\n")140 report_file.write("\\begin{center}\n")141 report_file.write("\\begin{tabular}{c c}\n")142 report_file.write("\t\\includegraphics[scale=0.35]{\"IMAGES/explain_variance_"+str(data)+"\"} & \\includegraphics[scale=0.35]{\"IMAGES/variable_contribution_"+str(data)+"\"} \\\\ \n")143 report_file.write("\tExplained variability & Variables conributions \\\\ \n")144 report_file.write("\\end{tabular}{}\n")145 report_file.write("\\end{center}\n\n")146 report_file.write("\\section{Overview - individuals}\n\n")147 report_file.write("\\begin{center}\n")148 report_file.write("\\begin{tabular}{c c}\n")149 report_file.write("\t\\includegraphics[scale=0.35]{\"IMAGES/individuals_disease_"+str(data)+"\"} & \\includegraphics[scale=0.35]{\"IMAGES/individuals_sex_"+str(data)+"\"} \\\\ \n")150 report_file.write("\tGrouped by disease & Grouped by sex \\\\ \n")151 report_file.write("\\end{tabular}{}\n\n")152 report_file.write("\\begin{tabular}{c}\n")153 report_file.write("\t\\includegraphics[scale=0.35]{\"IMAGES/individuals_center_"+str(data)+"\"} \\\\ \n")154 report_file.write("Grouped by center \\\\ \n")155 report_file.write("\\end{tabular}{} \n\n")156 report_file.write("\\end{center}\n")157 report_file.write("\\end{document}\n")...
artifact_report.py
Source:artifact_report.py
1import html2import os3from scripts.html_parts import *4from scripts.version_info import macCocktail_version5class ArtifactHtmlReport:6 def __init__(self, artifact_name, artifact_category=''):7 self.report_file = None8 self.report_file_path = ''9 self.script_code = ''10 self.artifact_name = artifact_name11 self.artifact_category = artifact_category # unused12 def __del__(self):13 if self.report_file:14 self.end_artifact_report()15 def start_artifact_report(self, report_folder, artifact_file_name, artifact_description=''):16 '''Creates the report HTML file and writes the artifact name as a heading'''17 self.report_file = open(os.path.join(report_folder, f'{artifact_file_name}.temphtml'), 'w', encoding='utf8')18 self.report_file.write(page_header.format(f'macCocktail - {self.artifact_name} report'))19 self.report_file.write(body_start.format(f'macCocktail {macCocktail_version}'))20 self.report_file.write(body_sidebar_setup)21 self.report_file.write(body_sidebar_dynamic_data_placeholder) # placeholder for sidebar data22 self.report_file.write(body_sidebar_trailer)23 self.report_file.write(body_main_header)24 self.report_file.write(body_main_data_title.format(f'{self.artifact_name} report', artifact_description))25 self.report_file.write(body_spinner) # Spinner till data finishes loading26 #self.report_file.write(body_infinite_loading_bar) # Not working!27 def add_script(self, script=''):28 '''Adds a default script or the script supplied'''29 if script:30 self.script_code += script31 else:32 self.script_code += default_responsive_table_script33 def write_artifact_data_table(self, data_headers, data_list, source_path, 34 write_total=True, write_location=True, html_escape=True, cols_repeated_at_bottom=True,35 table_responsive=True, table_style='', table_id='dtBasicExample'):36 ''' Writes info about data, then writes the table to html file37 Parameters38 ----------39 data_headers : List/Tuple of table column names40 data_list : List/Tuple of lists/tuples which contain rows of data41 source_path : Source path of data42 write_total : Toggles whether to write out a line of total rows written43 write_location : Toggles whether to write the location of data source44 html_escape : If True (default), then html special characters are encoded45 cols_repeated_at_bottom : If True (default), then col names are also at the bottom of the table46 table_responsive : If True (default), div class is table_responsive47 table_style : Specify table style like "width: 100%;"48 table_id : Specify an identifier string, which will be referenced in javascript49 '''50 if (not self.report_file):51 raise ValueError('Output report file is closed/unavailable!')52 num_entries = len(data_list)53 if write_total:54 self.write_minor_header(f'Total number of entries: {num_entries}', 'h6')55 if write_location:56 self.write_lead_text(f'{self.artifact_name} parsed from: {source_path}')57 self.report_file.write('<br />')58 if table_responsive:59 self.report_file.write("<div class='table-responsive'>")60 61 table_head = '<table id="{}" class="table table-striped table-bordered table-xsm" cellspacing="0" {}>'\62 '<thead>'.format(table_id, (f'style="{table_style}"') if table_style else '')63 self.report_file.write(table_head)64 self.report_file.write('<tr>' + ''.join( ('<th class="th-sm">{}</th>'.format(html.escape(str(x))) for x in data_headers) ) + '</tr>')65 self.report_file.write('</thead><tbody>')66 if html_escape:67 for row in data_list:68 self.report_file.write('<tr>' + ''.join( ('<td>{}</td>'.format(html.escape(str(x) if x != None else '')) for x in row) ) + '</tr>')69 else:70 for row in data_list:71 self.report_file.write('<tr>' + ''.join( ('<td>{}</td>'.format(str(x) if x != None else '') for x in row) ) + '</tr>')72 73 self.report_file.write('</tbody>')74 if cols_repeated_at_bottom:75 self.report_file.write('<tfoot><tr>' + ''.join( ('<th>{}</th>'.format(html.escape(str(x))) for x in data_headers) ) + '</tr></tfoot>')76 self.report_file.write('</table>')77 if table_responsive:78 self.report_file.write("</div>")79 def add_section_heading(self, heading, size='h2'):80 heading = html.escape(heading)81 data = '<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">'\82 ' <{0} class="{0}">{1}</{0}>'\83 '</div>'84 self.report_file.write(data.format(size, heading))85 def write_minor_header(self, heading, heading_tag=''):86 heading = html.escape(heading)87 if heading_tag:88 self.report_file.write(f'<{heading_tag}>{heading}</{heading_tag}>')89 else:90 self.report_file.write(f'<h3 class="h3">{heading}</h3>')91 92 def write_lead_text(self, text):93 self.report_file.write(f'<p class="lead">{text}</p>')94 def write_raw_html(self, code):95 self.report_file.write(code)96 def end_artifact_report(self):97 if self.report_file:98 self.report_file.write(body_main_trailer + body_end + self.script_code + page_footer)99 self.report_file.close()100 self.report_file = None...
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!!