Best Python code snippet using SeleniumBase
base_case.py
Source:base_case.py
...5068 self.__last_page_screenshot_png = (5069 self.driver.get_screenshot_as_png())5070 except Exception:5071 pass5072 def __set_last_page_url(self):5073 if not self.__last_page_url:5074 try:5075 self.__last_page_url = log_helper.get_last_page(self.driver)5076 except Exception:5077 self.__last_page_url = None5078 def __set_last_page_source(self):5079 if not self.__last_page_source:5080 try:5081 self.__last_page_source = (5082 log_helper.get_html_source_with_base_href(5083 self.driver, self.driver.page_source))5084 except Exception:5085 self.__last_page_source = None5086 def __insert_test_result(self, state, err):5087 from seleniumbase.core.testcase_manager import TestcaseDataPayload5088 data_payload = TestcaseDataPayload()5089 data_payload.runtime = int(time.time() * 1000) - self.case_start_time5090 data_payload.guid = self.testcase_guid5091 data_payload.execution_guid = self.execution_guid5092 data_payload.state = state5093 if err:5094 import traceback5095 tb_string = traceback.format_exc()5096 if "Message: " in tb_string:5097 data_payload.message = "Message: " + tb_string.split(5098 "Message: ")[-1]5099 elif "Exception: " in tb_string:5100 data_payload.message = tb_string.split("Exception: ")[-1]5101 elif "Error: " in tb_string:5102 data_payload.message = tb_string.split("Error: ")[-1]5103 else:5104 data_payload.message = "Unknown Error: See Stacktrace"5105 self.testcase_manager.update_testcase_data(data_payload)5106 def __add_pytest_html_extra(self):5107 if not self.__added_pytest_html_extra:5108 try:5109 if self.with_selenium:5110 if not self.__last_page_screenshot:5111 self.__set_last_page_screenshot()5112 self.__set_last_page_url()5113 self.__set_last_page_source()5114 if self.report_on:5115 extra_url = {}5116 extra_url['name'] = 'URL'5117 extra_url['format'] = 'url'5118 extra_url['content'] = self.get_current_url()5119 extra_url['mime_type'] = None5120 extra_url['extension'] = None5121 extra_image = {}5122 extra_image['name'] = 'Screenshot'5123 extra_image['format'] = 'image'5124 extra_image['content'] = self.__last_page_screenshot5125 extra_image['mime_type'] = 'image/png'5126 extra_image['extension'] = 'png'5127 self.__added_pytest_html_extra = True5128 self._html_report_extra.append(extra_url)5129 self._html_report_extra.append(extra_image)5130 except Exception:5131 pass5132 def __quit_all_drivers(self):5133 if self._reuse_session and sb_config.shared_driver:5134 if len(self._drivers_list) > 0:5135 sb_config.shared_driver = self._drivers_list[0]5136 self._default_driver = self._drivers_list[0]5137 self.switch_to_default_driver()5138 if len(self._drivers_list) > 1:5139 self._drivers_list = self._drivers_list[1:]5140 else:5141 self._drivers_list = []5142 # Close all open browser windows5143 self._drivers_list.reverse() # Last In, First Out5144 for driver in self._drivers_list:5145 try:5146 driver.quit()5147 except AttributeError:5148 pass5149 except Exception:5150 pass5151 self.driver = None5152 self._default_driver = None5153 self._drivers_list = []5154 def __has_exception(self):5155 has_exception = False5156 if sys.version_info[0] >= 3 and hasattr(self, '_outcome'):5157 if hasattr(self._outcome, 'errors') and self._outcome.errors:5158 has_exception = True5159 else:5160 has_exception = sys.exc_info()[1] is not None5161 return has_exception5162 def __get_test_id(self):5163 test_id = "%s.%s.%s" % (self.__class__.__module__,5164 self.__class__.__name__,5165 self._testMethodName)5166 return test_id5167 def __create_log_path_as_needed(self, test_logpath):5168 if not os.path.exists(test_logpath):5169 try:5170 os.makedirs(test_logpath)5171 except Exception:5172 pass # Only reachable during multi-threaded runs5173 def save_teardown_screenshot(self):5174 """ (Should ONLY be used at the start of custom tearDown() methods.)5175 This method takes a screenshot of the current web page for a5176 failing test (or when running your tests with --save-screenshot).5177 That way your tearDown() method can navigate away from the last5178 page where the test failed, and still get the correct screenshot5179 before performing tearDown() steps on other pages. If this method5180 is not included in your custom tearDown() method, a screenshot5181 will still be taken after the last step of your tearDown(), where5182 you should be calling "super(SubClassOfBaseCase, self).tearDown()"5183 """5184 if self.__has_exception() or self.save_screenshot_after_test:5185 test_id = self.__get_test_id()5186 test_logpath = self.log_path + "/" + test_id5187 self.__create_log_path_as_needed(test_logpath)5188 self.__set_last_page_screenshot()5189 self.__set_last_page_url()5190 self.__set_last_page_source()5191 if self.is_pytest:5192 self.__add_pytest_html_extra()5193 def tearDown(self):5194 """5195 Be careful if a subclass of BaseCase overrides setUp()5196 You'll need to add the following line to the subclass's tearDown():5197 super(SubClassOfBaseCase, self).tearDown()5198 """5199 self.__slow_mode_pause_if_active()5200 has_exception = self.__has_exception()5201 if self.__deferred_assert_failures:5202 print(5203 "\nWhen using self.deferred_assert_*() methods in your tests, "5204 "remember to call self.process_deferred_asserts() afterwards. "5205 "Now calling in tearDown()...\nFailures Detected:")5206 if not has_exception:5207 self.process_deferred_asserts()5208 else:5209 self.process_deferred_asserts(print_only=True)5210 if self.is_pytest:5211 # pytest-specific code5212 test_id = self.__get_test_id()5213 try:5214 with_selenium = self.with_selenium5215 except Exception:5216 sub_class_name = str(5217 self.__class__.__bases__[0]).split('.')[-1].split("'")[0]5218 sub_file_name = str(self.__class__.__bases__[0]).split('.')[-2]5219 sub_file_name = sub_file_name + ".py"5220 class_name = str(self.__class__).split('.')[-1].split("'")[0]5221 file_name = str(self.__class__).split('.')[-2] + ".py"5222 class_name_used = sub_class_name5223 file_name_used = sub_file_name5224 if sub_class_name == "BaseCase":5225 class_name_used = class_name5226 file_name_used = file_name5227 fix_setup = "super(%s, self).setUp()" % class_name_used5228 fix_teardown = "super(%s, self).tearDown()" % class_name_used5229 message = ("You're overriding SeleniumBase's BaseCase setUp() "5230 "method with your own setUp() method, which breaks "5231 "SeleniumBase. You can fix this by going to your "5232 "%s class located in your %s file and adding the "5233 "following line of code AT THE BEGINNING of your "5234 "setUp() method:\n%s\n\nAlso make sure "5235 "you have added the following line of code AT THE "5236 "END of your tearDown() method:\n%s\n"5237 % (class_name_used, file_name_used,5238 fix_setup, fix_teardown))5239 raise Exception(message)5240 if with_selenium:5241 # Save a screenshot if logging is on when an exception occurs5242 if has_exception:5243 self.__add_pytest_html_extra()5244 if self.with_testing_base and not has_exception and (5245 self.save_screenshot_after_test):5246 test_logpath = self.log_path + "/" + test_id5247 self.__create_log_path_as_needed(test_logpath)5248 if not self.__last_page_screenshot_png:5249 self.__set_last_page_screenshot()5250 self.__set_last_page_url()5251 self.__set_last_page_source()5252 log_helper.log_screenshot(5253 test_logpath,5254 self.driver,5255 self.__last_page_screenshot_png)5256 self.__add_pytest_html_extra()5257 if self.with_testing_base and has_exception:5258 test_logpath = self.log_path + "/" + test_id5259 self.__create_log_path_as_needed(test_logpath)5260 if ((not self.with_screen_shots) and (5261 not self.with_basic_test_info) and (5262 not self.with_page_source)):5263 # Log everything if nothing specified (if testing_base)5264 if not self.__last_page_screenshot_png:5265 self.__set_last_page_screenshot()5266 self.__set_last_page_url()5267 self.__set_last_page_source()5268 log_helper.log_screenshot(5269 test_logpath,5270 self.driver,5271 self.__last_page_screenshot_png)5272 log_helper.log_test_failure_data(5273 self, test_logpath, self.driver, self.browser,5274 self.__last_page_url)5275 log_helper.log_page_source(5276 test_logpath, self.driver, self.__last_page_source)5277 else:5278 if self.with_screen_shots:5279 if not self.__last_page_screenshot_png:5280 self.__set_last_page_screenshot()5281 self.__set_last_page_url()5282 self.__set_last_page_source()5283 log_helper.log_screenshot(5284 test_logpath,5285 self.driver,5286 self.__last_page_screenshot_png)5287 if self.with_basic_test_info:5288 log_helper.log_test_failure_data(5289 self, test_logpath, self.driver, self.browser,5290 self.__last_page_url)5291 if self.with_page_source:5292 log_helper.log_page_source(5293 test_logpath, self.driver,5294 self.__last_page_source)5295 # (Pytest) Finally close all open browser windows5296 self.__quit_all_drivers()5297 if self.headless:5298 if self.headless_active:5299 try:5300 self.display.stop()5301 except AttributeError:5302 pass5303 except Exception:5304 pass5305 self.display = None5306 if self.with_db_reporting:5307 if has_exception:5308 self.__insert_test_result(constants.State.ERROR, True)5309 else:5310 self.__insert_test_result(constants.State.PASS, False)5311 runtime = int(time.time() * 1000) - self.execution_start_time5312 self.testcase_manager.update_execution_data(5313 self.execution_guid, runtime)5314 if self.with_s3_logging and has_exception:5315 """ If enabled, upload logs to S3 during test exceptions. """5316 import uuid5317 from seleniumbase.core.s3_manager import S3LoggingBucket5318 s3_bucket = S3LoggingBucket()5319 guid = str(uuid.uuid4().hex)5320 path = "%s/%s" % (self.log_path, test_id)5321 uploaded_files = []5322 for logfile in os.listdir(path):5323 logfile_name = "%s/%s/%s" % (guid,5324 test_id,5325 logfile.split(path)[-1])5326 s3_bucket.upload_file(logfile_name,5327 "%s/%s" % (path, logfile))5328 uploaded_files.append(logfile_name)5329 s3_bucket.save_uploaded_file_names(uploaded_files)5330 index_file = s3_bucket.upload_index_file(test_id, guid)5331 print("\n\n*** Log files uploaded: ***\n%s\n" % index_file)5332 logging.info(5333 "\n\n*** Log files uploaded: ***\n%s\n" % index_file)5334 if self.with_db_reporting:5335 from seleniumbase.core.testcase_manager import (5336 TestcaseDataPayload)5337 from seleniumbase.core.testcase_manager import (5338 TestcaseManager)5339 self.testcase_manager = TestcaseManager(self.database_env)5340 data_payload = TestcaseDataPayload()5341 data_payload.guid = self.testcase_guid5342 data_payload.logURL = index_file5343 self.testcase_manager.update_testcase_log_url(data_payload)5344 else:5345 # (Nosetests)5346 if has_exception:5347 test_id = self.__get_test_id()5348 test_logpath = self.log_path + "/" + test_id5349 self.__create_log_path_as_needed(test_logpath)5350 log_helper.log_test_failure_data(5351 self, test_logpath, self.driver, self.browser,5352 self.__last_page_url)5353 if len(self._drivers_list) > 0:5354 if not self.__last_page_screenshot_png:5355 self.__set_last_page_screenshot()5356 self.__set_last_page_url()5357 self.__set_last_page_source()5358 log_helper.log_screenshot(5359 test_logpath,5360 self.driver,5361 self.__last_page_screenshot_png)5362 log_helper.log_page_source(5363 test_logpath, self.driver, self.__last_page_source)5364 elif self.save_screenshot_after_test:5365 test_id = self.__get_test_id()5366 test_logpath = self.log_path + "/" + test_id5367 self.__create_log_path_as_needed(test_logpath)5368 if not self.__last_page_screenshot_png:5369 self.__set_last_page_screenshot()5370 self.__set_last_page_url()5371 self.__set_last_page_source()5372 log_helper.log_screenshot(5373 test_logpath,5374 self.driver,5375 self.__last_page_screenshot_png)5376 if self.report_on:5377 self._last_page_screenshot = self.__last_page_screenshot_png5378 try:5379 self._last_page_url = self.get_current_url()5380 except Exception:5381 self._last_page_url = "(Error: Unknown URL)"5382 # Finally close all open browser windows...
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!!