Best Python code snippet using SeleniumBase
master_qa.py
Source:master_qa.py
...50 def tearDown(self):51 if self.headless and self.check_count > 0:52 print("WARNING: %s manual checks were skipped!" % self.check_count)53 if sys.exc_info()[1]:54 self.__add_failure(sys.exc_info()[1])55 self.__process_manual_check_results(self.auto_close_results_page)56 super(MasterQA, self).tearDown()57 ####################58 def __get_timestamp(self):59 return str(int(time.time() * 1000))60 def __manual_check_setup(self):61 self.manual_check_count = 062 self.manual_check_successes = 063 self.incomplete_runs = 064 self.page_results_list = []65 self.__clear_out_old_logs(archive_past_runs=False)66 def __clear_out_old_logs(67 self, archive_past_runs=True, get_log_folder=False):68 abs_path = os.path.abspath('.')69 file_path = abs_path + "/%s" % self.LATEST_REPORT_DIR70 if not os.path.exists(file_path):71 os.makedirs(file_path)72 if archive_past_runs:73 archive_timestamp = int(time.time())74 if not os.path.exists("%s/../%s/" % (file_path, self.ARCHIVE_DIR)):75 os.makedirs("%s/../%s/" % (file_path, self.ARCHIVE_DIR))76 archive_dir = "%s/../%s/log_%s" % (77 file_path, self.ARCHIVE_DIR, archive_timestamp)78 shutil.move(file_path, archive_dir)79 os.makedirs(file_path)80 if get_log_folder:81 return archive_dir82 else:83 # Just delete bad pages to make room for the latest run.84 filelist = [f for f in os.listdir(85 "./%s" % self.LATEST_REPORT_DIR) if (86 f.startswith("failed_")) or (87 f == self.RESULTS_PAGE) or (88 f.startswith("automation_failure")) or (89 f == self.BAD_PAGE_LOG)]90 for f in filelist:91 os.remove("%s/%s" % (file_path, f))92 def __jq_confirm_dialog(self, question):93 count = self.manual_check_count + 194 title = self.DEFAULT_VALIDATION_TITLE95 title_content = ('<center><font color="#7700bb">%s #%s:'96 '</font></center><hr><font color="#0066ff">%s</font>'97 '' % (title, count, question))98 title_content = js_utils.escape_quotes_if_needed(title_content)99 jqcd = ("""jconfirm({100 boxWidth: '32.5%%',101 useBootstrap: false,102 containerFluid: false,103 animationBounce: 1,104 type: 'default',105 theme: 'bootstrap',106 typeAnimated: true,107 animation: 'scale',108 draggable: true,109 dragWindowGap: 1,110 container: 'body',111 title: '%s',112 content: '',113 buttons: {114 fail_button: {115 btnClass: 'btn-red',116 text: 'NO / FAIL',117 action: function(){118 $jqc_status = "Failure!"119 }120 },121 pass_button: {122 btnClass: 'btn-green',123 text: 'YES / PASS',124 action: function(){125 $jqc_status = "Success!"126 }127 }128 }129 });""" % title_content)130 self.execute_script(jqcd)131 def __manual_page_check(self, *args):132 if not args:133 instructions = self.DEFAULT_VALIDATION_MESSAGE # self.verify()134 else:135 instructions = str(args[0])136 if len(args) > 1:137 pass138 question = "Approve?" # self.verify("")139 if instructions and "?" not in instructions:140 question = instructions + " <> Approve?"141 elif instructions and "?" in instructions:142 question = instructions143 wait_time_before_verify = self.WAIT_TIME_BEFORE_VERIFY144 if self.verify_delay:145 wait_time_before_verify = float(self.verify_delay)146 # Allow a moment to see the full page before the dialog box pops up147 time.sleep(wait_time_before_verify)148 use_jqc = False149 self.wait_for_ready_state_complete()150 if js_utils.is_jquery_confirm_activated(self.driver):151 use_jqc = True152 else:153 js_utils.activate_jquery_confirm(self.driver)154 get_jqc = None155 try:156 get_jqc = self.execute_script("return jconfirm")157 get_jqc = get_jqc["instances"]158 use_jqc = True159 except Exception:160 use_jqc = False161 if use_jqc:162 # Use the jquery_confirm library for manual page checks163 self.__jq_confirm_dialog(question)164 time.sleep(0.02)165 waiting_for_response = True166 while waiting_for_response:167 time.sleep(0.05)168 jqc_open = self.execute_script(169 "return jconfirm.instances.length")170 if str(jqc_open) == "0":171 break172 time.sleep(0.1)173 status = None174 try:175 status = self.execute_script("return $jqc_status")176 except Exception:177 status = "Failure!"178 pre_status = self.execute_script(179 "return jconfirm.lastClicked.hasClass('btn-green')")180 if pre_status:181 status = "Success!"182 else:183 # Fallback to plain js confirm dialogs if can't load jquery_confirm184 if self.browser == 'ie':185 text = self.execute_script(186 '''if(confirm("%s")){return "Success!"}187 else{return "Failure!"}''' % question)188 elif self.browser == 'chrome':189 self.execute_script('''if(confirm("%s"))190 {window.master_qa_result="Success!"}191 else{window.master_qa_result="Failure!"}''' % question)192 time.sleep(0.05)193 self.__wait_for_special_alert_absent()194 text = self.execute_script('return window.master_qa_result')195 else:196 try:197 self.execute_script(198 '''if(confirm("%s"))199 {window.master_qa_result="Success!"}200 else{window.master_qa_result="Failure!"}''' % question)201 except WebDriverException:202 # Fix for https://github.com/mozilla/geckodriver/issues/431203 pass204 time.sleep(0.05)205 self.__wait_for_special_alert_absent()206 text = self.execute_script('return window.master_qa_result')207 status = text208 self.manual_check_count += 1209 try:210 current_url = self.driver.current_url211 except Exception:212 current_url = self.execute_script("return document.URL")213 if "Success!" in str(status):214 self.manual_check_successes += 1215 self.page_results_list.append(216 '"%s","%s","%s","%s","%s","%s","%s","%s"' % (217 self.manual_check_count,218 "Success",219 "-",220 current_url,221 self.browser,222 self.__get_timestamp()[:-3],223 instructions,224 "*"))225 return 1226 else:227 bad_page_name = "failed_check_%s.png" % self.manual_check_count228 self.save_screenshot(bad_page_name, folder=self.LATEST_REPORT_DIR)229 self.page_results_list.append(230 '"%s","%s","%s","%s","%s","%s","%s","%s"' % (231 self.manual_check_count,232 "FAILED!",233 bad_page_name,234 current_url,235 self.browser,236 self.__get_timestamp()[:-3],237 instructions,238 "*"))239 return 0240 def __wait_for_special_alert_absent(self):241 timeout = self.MAX_IDLE_TIME_BEFORE_QUIT242 for x in range(int(timeout * 20)):243 try:244 alert = self.driver.switch_to.alert245 dummy_variable = alert.text # Raises exception if no alert246 if "?" not in dummy_variable:247 return248 time.sleep(0.05)249 except NoAlertPresentException:250 return251 self.driver.quit()252 raise Exception(253 "%s seconds passed without human action! Stopping..." % timeout)254 def __add_failure(self, exception=None):255 exc_info = None256 if exception:257 if hasattr(exception, 'msg'):258 exc_info = exception.msg259 elif hasattr(exception, 'message'):260 exc_info = exception.message261 else:262 exc_info = '(Unknown Exception)'263 self.incomplete_runs += 1264 error_page = "automation_failure_%s.png" % self.incomplete_runs265 self.save_screenshot(error_page, folder=self.LATEST_REPORT_DIR)266 self.page_results_list.append(267 '"%s","%s","%s","%s","%s","%s","%s","%s"' % (268 "ERR",...
response.py
Source:response.py
...24 def add(self, response: Union[Success[T], Failure[E]]):25 if isinstance(response, Success):26 self.__add_success(response)27 else:28 self.__add_failure(response)29 def success_at(self, index) -> Success[T]:30 return self.__success[index]31 def failure_at(self, index) -> Failure[T]:32 return self.__failure[index]33 def success_count(self) -> int:34 return len(self.__success)35 def failure_count(self) -> int:36 return len(self.__failure)37 def all_success_t(self) -> List[T]:38 return [success.t() for success in self.__success]39 def all_failure_t(self) -> List[E]:40 return [failure.e() for failure in self.__failure]41 def __add_success(self, t: T):42 self.__success.append(t)43 def __add_failure(self, e: E):...
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!!