Best Python code snippet using Testify_python
tests.py
Source:tests.py
...111 test_name=test_name,112 data=results)113 logging.debug(output)114 return output115 def _save_result(result, result_dir):116 """docstring for _save_result"""117 with open(os.path.join(result_dir,118 'testresult_process_is_running.xml'), 'w') as f:119 f.write(result)120 _save_result(_run(), os.path.abspath(result_dir))121def verify_dmesg(dut, plan, result_dir):122 """123 Read kernel logs and check whether error log exists or not.124 This testcase runs \'dmesg\' and \'grep\' commands on device.125 :param device dut: device instance126 :param dict plan: test plan127 :param str result_dir: directory to save test result xml128 Example:129 >>> from litmus.helper.tests import verify_dmesg130 >>> verify_dmesg(dut,131 [{\'name\': \'panel_is_alive\',132 \'param\': \'panel\',133 \'pattern\': \'.*panel is dead.*\'},134 ],135 \'result\')136 """137 test_name = 'verify_dmesg'138 template_report = """<report categ='SmokeTest' failures='{failure_cnt}' name='{test_name}'>139{data}</report>"""140 template_test = """ <test executed='yes' name='{tc_name}'>141 <result>142 <success passed='{tc_result}' state='{tc_state}' />143 </result>144 </test>145"""146 def _verify(item):147 """docstring for _verify"""148 cmd = ['dmesg', '|', 'grep', item['param']]149 res = dut.run_cmd(cmd)150 p = re.compile(item['pattern'])151 if not p.search(res):152 return True153 else:154 return False155 def _run():156 results = ''157 failure_cnt = 0158 for item in plan:159 tc_result = 'yes' if _verify(item) else 'no'160 failure_cnt = failure_cnt+1 if tc_result != 'yes' else failure_cnt161 dict_for_output = {'tc_name': item['name'],162 'tc_result': tc_result,163 'tc_state': 100 if tc_result == 'yes' else 0}164 results += template_test.format(**dict_for_output)165 output = template_report.format(failure_cnt=failure_cnt,166 test_name=test_name,167 data=results)168 logging.debug(output)169 return output170 def _save_result(result, result_dir):171 """docstring for _save_result"""172 with open(os.path.join(result_dir, 'testresult_dmesg.xml'), 'w') as f:173 f.write(result)174 _save_result(_run(), os.path.abspath(result_dir))175def verify_wifi_is_working(dut, wifi_apname, wifi_password, result_dir):176 """177 Try to connect wifi ap and publish the test result as a xml file.178 This testcase runs 'wifi_test' command on device.179 :param device dut: device instance180 :param str wifi_apname: wifi ap name181 :param str wifi_password: wifi ap password182 :param str result_dir: directory to save test result xml183 Example:184 >>> from litmus.helper.tests import verify_wifi_is_working185 >>> verify_wifi_is_working(dut, 'setup', '', 'result')186 """187 test_name = 'wifi_is_working'188 template_report = """<report categ='SmokeTest' failures='{failure_cnt}' name='{test_name}'>189{data}</report>"""190 template_test = """ <test executed='yes' name='{tc_name}'>191 <result>192 <success passed='{tc_result}' state='{tc_state}' />193 </result>194 </test>195"""196 def _enqueue_output(out, queue):197 for line in iter(out.readline, b''):198 queue.put(line.strip().decode())199 out.close()200 def _write_cmd(cmd, status_pass, status_fail, timeout=10):201 """docstring for _write_cmd"""202 status_pass = convert_single_item_to_list(status_pass)203 status_fail = convert_single_item_to_list(status_fail)204 logging.debug('===== cmd : {} ====='.format(cmd))205 cmd = cmd + '\r'206 start_time = time.perf_counter()207 sdbshell.stdin.write(cmd.encode())208 sdbshell.stdin.flush()209 time.sleep(0.5)210 logging.debug('response:')211 while True:212 try:213 line = q.get(timeout=0.1)214 logging.debug(line)215 except queue.Empty:216 wait_time = time.perf_counter() - start_time217 if wait_time > timeout:218 raise Exception('timeout')219 elif wait_time > (timeout / 2):220 sdbshell.stdin.write('\r'.encode())221 sdbshell.stdin.flush()222 time.sleep(1)223 else:224 if line in status_pass:225 break226 elif line in status_fail:227 raise Exception('wifi test return fail : {}'.format(line))228 def _run():229 """docstring for _run"""230 try:231 _write_cmd('wifi_test; exit', 'Test Thread created...', None)232 _write_cmd('1', 'Operation succeeded!', 'Operation failed!')233 _write_cmd('3',234 ['Success to activate Wi-Fi device',235 'Wi-Fi Activation Succeeded',236 'Fail to activate Wi-Fi device [ALREADY_EXISTS]'],237 None)238 time.sleep(7)239 _write_cmd('9', 'Operation succeeded!', 'Operation failed!')240 time.sleep(3)241 for loop in range(3):242 _write_cmd('b', 'Get AP list finished', None)243 time.sleep(3)244 _write_cmd('c',245 'Input a part of AP name to connect :',246 ['Wi-Fi Activation Failed! error : OPERATION_FAILED',247 'Device state changed callback, state : Deactivated',248 'Operation failed!'])249 _write_cmd(wifi_apname,250 ['Passphrase required : TRUE',251 'Passphrase required : FALSE'],252 ['Wi-Fi Activation Failed! error : OPERATION_FAILED',253 'Device state changed callback, state : Deactivated',254 'Operation failed!'])255 if wifi_password and wifi_password != '':256 _write_cmd(wifi_password,257 'Connection step finished',258 ['Wi-Fi Activation Failed! error : '259 'OPERATION_FAILED',260 'Device state changed callback, state : '261 'Deactivated',262 'Operation failed!'])263 _write_cmd('6',264 ['Success to get connection state : Connected',265 'Wi-Fi Connection Succeeded'],266 ['Wi-Fi Activation Failed! error : OPERATION_FAILED',267 'Wi-Fi Connection Failed! error : INVALID_KEY',268 'Device state changed callback, state : Deactivated',269 'Operation failed!',270 'Success to get connection state : Disconnected',271 'Connection state changed callback, state : '272 'Disconnected, AP name : {}'.format(wifi_apname)])273 _write_cmd('0', 'exit', None)274 dict_for_output = {'tc_name': test_name,275 'tc_result': 'yes',276 'tc_state': 100}277 results = template_test.format(**dict_for_output)278 output = template_report.format(failure_cnt=0,279 test_name=test_name,280 data=results)281 except Exception:282 dict_for_output = {'tc_name': test_name,283 'tc_result': 'no',284 'tc_state': 0}285 results = template_test.format(**dict_for_output)286 output = template_report.format(failure_cnt=1,287 test_name=test_name,288 data=results)289 finally:290 sdbshell.terminate()291 return output292 def _save_result(result, result_dir):293 """docstring for _save_result"""294 logging.debug(result)295 with open(os.path.join(result_dir, 'testresult_wifi.xml'), 'w') as f:296 f.write(result)297 sdbshell = subprocess.Popen(['sdb', '-s', dut.get_id(), 'shell'],298 stdin=subprocess.PIPE,299 stdout=subprocess.PIPE,300 stderr=subprocess.PIPE)301 q = queue.Queue()302 t = Thread(target=_enqueue_output, args=(sdbshell.stdout, q))303 t.daemon = True304 t.start()...
cost_analysis.py
Source:cost_analysis.py
...40 self._compute_coverage_rate()41 self._compute_globally_sold_production()42 self._compute_self_consumption()43 self._compute_costs()44 self._save_result(self.delta_costs, 'delta_costs', self._output_path)45 self._save_result(self.ssr_user_no_production, 'ssr_user_no_production', self._output_path)46 self._save_result(self.cost_users_no_deviation, 'costs_users_no_deviations', self._output_path)47 self._save_result(self.cost_users, 'costs_users', self._output_path)48 self._save_result(self.costs_users_no_rec, 'costs_users', self._output_path)49 def _compute_costs_comparison(self):50 """51 Compares the costs with and without REC for each user.52 """53 self.delta_costs = (54 (1 - self.local_discount) * self._ssr_user55 )56 def _compute_coverage_rate(self):57 """58 Computes the coverage rate of the users.59 """60 self.ssr_user_no_production = (61 self._verified_allocated_production.sum(axis=0) / self._initial_consumption.sum(axis=0)62 ).fillna(0.0) # Self-sufficiency rate without taking into account the production63 def _compute_globally_sold_production(self):64 """65 Computes the global sales of the producers.66 """67 self.global_sales = (68 self._net_production - self._locally_sold_production69 )70 def _compute_self_consumption(self):71 """72 Computes the self-consumption of prosumers.73 """74 self.self_consumption = (75 self._initial_consumption - self._net_consumption76 )77 def _compute_costs(self):78 """79 Computes the costs of each consumer or prosumer independently.80 """81 self.cost_users_no_deviation = (82 pd.Series(self._price_retailer_in) * (self._net_consumption - self._verified_allocated_production).sum(axis=0) +83 pd.Series(self._price_local_in) * self._verified_allocated_production.sum(axis=0) -84 pd.Series(self._price_retailer_out) * (self._net_production - self._locally_sold_production).sum(axis=0) -85 pd.Series(self._price_local_out) * self._locally_sold_production.sum(axis=0)86 )87 costs_deviations = (self._costs_rec - self.cost_users_no_deviation.sum()) / len(self._users)88 self.cost_users = self.cost_users_no_deviation + costs_deviations.values89 self.costs_users_no_rec = (90 pd.Series(self._price_retailer_in) * self._net_consumption.sum(axis=0) -91 pd.Series(self._price_retailer_out) * self._net_production.sum(axis=0)92 )93 @staticmethod94 def _save_result(which_data: pd.DataFrame, name: str, output_path: str):95 """96 Saves the cost-comparison result.97 """98 df_to_save = pd.DataFrame(data=which_data)...
save_result.py
Source:save_result.py
...18 os.makedirs(author_links_dir)19 return author_links_dir, scholar_links_dir, authors_dir, scholars_dir20def save_authors(gf, result):21 global authors_dir22 _save_result(gf, result, authors_dir)23def save_scholars(gf, result):24 global scholars_dir25 _save_result(gf, result, scholars_dir)26def save_author_links(gf, result):27 global author_links_dir28 _save_result(gf, result, author_links_dir)29def save_scholar_links(gf, result):30 global scholar_links_dir31 _save_result(gf, result, scholar_links_dir)32def _save_result(gf, result, path):33 start = gf.start34 35 end = start + len(result) - 136 37 df = pd.DataFrame(result)38 df.to_csv(f'{path}/{start}_{end}.csv', index=False)39 print(f'save {path}/{start}_{end}.csv')...
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!!