How to use __process_dashboard method in SeleniumBase

Best Python code snippet using SeleniumBase

base_case.py

Source:base_case.py Github

copy

Full Screen

...6340 if not self._dash_initialized:6341 sb_config._dashboard_initialized = True6342 sb_config._sbase_detected = True6343 self._dash_initialized = True6344 self.__process_dashboard(False, init=True)6345 has_url = False6346 if self._reuse_session:6347 if not hasattr(sb_config, 'shared_driver'):6348 sb_config.shared_driver = None6349 if sb_config.shared_driver:6350 try:6351 self._default_driver = sb_config.shared_driver6352 self.driver = sb_config.shared_driver6353 self._drivers_list = [sb_config.shared_driver]6354 url = self.get_current_url()6355 if url is not None:6356 has_url = True6357 if self._crumbs:6358 self.driver.delete_all_cookies()6359 except Exception:6360 pass6361 if self._reuse_session and sb_config.shared_driver and has_url:6362 if self.start_page and len(self.start_page) >= 4:6363 if page_utils.is_valid_url(self.start_page):6364 self.open(self.start_page)6365 else:6366 new_start_page = "http://" + self.start_page6367 if page_utils.is_valid_url(new_start_page):6368 self.open(new_start_page)6369 elif self._crumbs:6370 if self.get_current_url() != "data:,":6371 self.open("data:,")6372 else:6373 pass6374 else:6375 # Launch WebDriver for both Pytest and Nosetests6376 self.driver = self.get_new_driver(browser=self.browser,6377 headless=self.headless,6378 locale_code=self.locale_code,6379 servername=self.servername,6380 port=self.port,6381 proxy=self.proxy_string,6382 agent=self.user_agent,6383 switch_to=True,6384 cap_file=self.cap_file,6385 cap_string=self.cap_string,6386 disable_csp=self.disable_csp,6387 enable_ws=self.enable_ws,6388 enable_sync=self.enable_sync,6389 use_auto_ext=self.use_auto_ext,6390 no_sandbox=self.no_sandbox,6391 disable_gpu=self.disable_gpu,6392 incognito=self.incognito,6393 guest_mode=self.guest_mode,6394 devtools=self.devtools,6395 remote_debug=self.remote_debug,6396 swiftshader=self.swiftshader,6397 block_images=self.block_images,6398 user_data_dir=self.user_data_dir,6399 extension_zip=self.extension_zip,6400 extension_dir=self.extension_dir,6401 is_mobile=self.mobile_emulator,6402 d_width=self.__device_width,6403 d_height=self.__device_height,6404 d_p_r=self.__device_pixel_ratio)6405 self._default_driver = self.driver6406 if self._reuse_session:6407 sb_config.shared_driver = self.driver6408 if self.browser in ["firefox", "ie", "safari"]:6409 # Only Chromium-based browsers have the mobile emulator.6410 # Some actions such as hover-clicking are different on mobile.6411 self.mobile_emulator = False6412 # Configure the test time limit (if used).6413 self.set_time_limit(self.time_limit)6414 # Set the start time for the test (in ms).6415 # Although the pytest clock starts before setUp() begins,6416 # the time-limit clock starts at the end of the setUp() method.6417 sb_config.start_time_ms = int(time.time() * 1000.0)6418 def __set_last_page_screenshot(self):6419 """ self.__last_page_screenshot is only for pytest html report logs6420 self.__last_page_screenshot_png is for all screenshot log files """6421 if not self.__last_page_screenshot and (6422 not self.__last_page_screenshot_png):6423 try:6424 element = self.driver.find_element(6425 by=By.TAG_NAME, value="body")6426 if self.is_pytest and self.report_on:6427 self.__last_page_screenshot_png = (6428 self.driver.get_screenshot_as_png())6429 self.__last_page_screenshot = element.screenshot_as_base646430 else:6431 self.__last_page_screenshot_png = element.screenshot_as_png6432 except Exception:6433 if not self.__last_page_screenshot:6434 if self.is_pytest and self.report_on:6435 try:6436 self.__last_page_screenshot = (6437 self.driver.get_screenshot_as_base64())6438 except Exception:6439 pass6440 if not self.__last_page_screenshot_png:6441 try:6442 self.__last_page_screenshot_png = (6443 self.driver.get_screenshot_as_png())6444 except Exception:6445 pass6446 def __set_last_page_url(self):6447 if not self.__last_page_url:6448 try:6449 self.__last_page_url = log_helper.get_last_page(self.driver)6450 except Exception:6451 self.__last_page_url = None6452 def __set_last_page_source(self):6453 if not self.__last_page_source:6454 try:6455 self.__last_page_source = (6456 log_helper.get_html_source_with_base_href(6457 self.driver, self.driver.page_source))6458 except Exception:6459 self.__last_page_source = None6460 def __get_exception_info(self):6461 exc_message = None6462 if sys.version_info[0] >= 3 and hasattr(self, '_outcome') and (6463 hasattr(self._outcome, 'errors') and self._outcome.errors):6464 try:6465 exc_message = self._outcome.errors[0][1][1]6466 except Exception:6467 exc_message = "(Unknown Exception)"6468 else:6469 try:6470 exc_message = sys.last_value6471 except Exception:6472 exc_message = "(Unknown Exception)"6473 return str(exc_message)6474 def __insert_test_result(self, state, err):6475 from seleniumbase.core.testcase_manager import TestcaseDataPayload6476 data_payload = TestcaseDataPayload()6477 data_payload.runtime = int(time.time() * 1000) - self.case_start_time6478 data_payload.guid = self.testcase_guid6479 data_payload.execution_guid = self.execution_guid6480 data_payload.state = state6481 if err:6482 import traceback6483 tb_string = traceback.format_exc()6484 if "Message: " in tb_string:6485 data_payload.message = "Message: " + tb_string.split(6486 "Message: ")[-1]6487 elif "Exception: " in tb_string:6488 data_payload.message = tb_string.split("Exception: ")[-1]6489 elif "Error: " in tb_string:6490 data_payload.message = tb_string.split("Error: ")[-1]6491 else:6492 data_payload.message = self.__get_exception_info()6493 else:6494 test_id = self.__get_test_id_2()6495 if self.is_pytest and test_id in sb_config._results.keys() and (6496 sb_config._results[test_id] == "Skipped"):6497 if self.__skip_reason:6498 data_payload.message = "Skipped: " + self.__skip_reason6499 else:6500 data_payload.message = "Skipped: (no reason given)"6501 self.testcase_manager.update_testcase_data(data_payload)6502 def __add_pytest_html_extra(self):6503 if not self.__added_pytest_html_extra:6504 try:6505 if self.with_selenium:6506 if not self.__last_page_screenshot:6507 self.__set_last_page_screenshot()6508 self.__set_last_page_url()6509 self.__set_last_page_source()6510 if self.report_on:6511 extra_url = {}6512 extra_url['name'] = 'URL'6513 extra_url['format'] = 'url'6514 extra_url['content'] = self.get_current_url()6515 extra_url['mime_type'] = None6516 extra_url['extension'] = None6517 extra_image = {}6518 extra_image['name'] = 'Screenshot'6519 extra_image['format'] = 'image'6520 extra_image['content'] = self.__last_page_screenshot6521 extra_image['mime_type'] = 'image/png'6522 extra_image['extension'] = 'png'6523 self.__added_pytest_html_extra = True6524 self._html_report_extra.append(extra_url)6525 self._html_report_extra.append(extra_image)6526 except Exception:6527 pass6528 def __quit_all_drivers(self):6529 if self._reuse_session and sb_config.shared_driver:6530 if len(self._drivers_list) > 0:6531 sb_config.shared_driver = self._drivers_list[0]6532 self._default_driver = self._drivers_list[0]6533 self.switch_to_default_driver()6534 if len(self._drivers_list) > 1:6535 self._drivers_list = self._drivers_list[1:]6536 else:6537 self._drivers_list = []6538 # Close all open browser windows6539 self._drivers_list.reverse() # Last In, First Out6540 for driver in self._drivers_list:6541 try:6542 driver.quit()6543 except AttributeError:6544 pass6545 except Exception:6546 pass6547 self.driver = None6548 self._default_driver = None6549 self._drivers_list = []6550 def __has_exception(self):6551 has_exception = False6552 if hasattr(sys, 'last_traceback') and sys.last_traceback is not None:6553 has_exception = True6554 elif sys.version_info[0] >= 3 and hasattr(self, '_outcome'):6555 if hasattr(self._outcome, 'errors') and self._outcome.errors:6556 has_exception = True6557 else:6558 if sys.version_info[0] >= 3:6559 has_exception = sys.exc_info()[1] is not None6560 else:6561 if not hasattr(self, "_using_sb_fixture_class") and (6562 not hasattr(self, "_using_sb_fixture_no_class")):6563 has_exception = sys.exc_info()[1] is not None6564 else:6565 has_exception = (len(str(sys.exc_info()[1]).strip()) > 0)6566 return has_exception6567 def __get_test_id(self):6568 test_id = "%s.%s.%s" % (self.__class__.__module__,6569 self.__class__.__name__,6570 self._testMethodName)6571 if self._sb_test_identifier and len(str(self._sb_test_identifier)) > 6:6572 test_id = self._sb_test_identifier6573 return test_id6574 def __get_test_id_2(self):6575 """ The id for SeleniumBase Dashboard entries. """6576 test_id = "%s.%s.%s" % (self.__class__.__module__.split('.')[-1],6577 self.__class__.__name__,6578 self._testMethodName)6579 if self._sb_test_identifier and len(str(self._sb_test_identifier)) > 6:6580 test_id = self._sb_test_identifier6581 if test_id.count('.') > 1:6582 test_id = '.'.join(test_id.split('.')[1:])6583 return test_id6584 def __get_display_id(self):6585 test_id = "%s.py::%s::%s" % (6586 self.__class__.__module__.replace('.', '/'),6587 self.__class__.__name__,6588 self._testMethodName)6589 if self._sb_test_identifier and len(str(self._sb_test_identifier)) > 6:6590 test_id = self._sb_test_identifier6591 if hasattr(self, "_using_sb_fixture_class"):6592 if test_id.count('.') >= 2:6593 parts = test_id.split('.')6594 full = parts[-3] + '.py::' + parts[-2] + '::' + parts[-1]6595 test_id = full6596 elif hasattr(self, "_using_sb_fixture_no_class"):6597 if test_id.count('.') >= 1:6598 parts = test_id.split('.')6599 full = parts[-2] + '.py::' + parts[-1]6600 test_id = full6601 return test_id6602 def __create_log_path_as_needed(self, test_logpath):6603 if not os.path.exists(test_logpath):6604 try:6605 os.makedirs(test_logpath)6606 except Exception:6607 pass # Only reachable during multi-threaded runs6608 def __process_dashboard(self, has_exception, init=False):6609 ''' SeleniumBase Dashboard Processing '''6610 if len(sb_config._extra_dash_entries) > 0:6611 # First take care of existing entries from non-SeleniumBase tests6612 for test_id in sb_config._extra_dash_entries:6613 if test_id in sb_config._results.keys():6614 if sb_config._results[test_id] == "Skipped":6615 sb_config.item_count_skipped += 16616 sb_config.item_count_untested -= 16617 elif sb_config._results[test_id] == "Failed":6618 sb_config.item_count_failed += 16619 sb_config.item_count_untested -= 16620 elif sb_config._results[test_id] == "Passed":6621 sb_config.item_count_passed += 16622 sb_config.item_count_untested -= 16623 else: # Mark "Skipped" if unknown6624 sb_config.item_count_skipped += 16625 sb_config.item_count_untested -= 16626 sb_config._extra_dash_entries = [] # Reset the list to empty6627 # Process new entries6628 test_id = self.__get_test_id_2()6629 dud = "seleniumbase/plugins/pytest_plugin.py::BaseClass::base_method"6630 if not init:6631 duration_ms = int(time.time() * 1000) - sb_config.start_time_ms6632 duration = float(duration_ms) / 1000.06633 sb_config._duration[test_id] = duration6634 if test_id not in sb_config._display_id.keys():6635 sb_config._display_id[test_id] = self.__get_display_id()6636 if sb_config._display_id[test_id] == dud:6637 return6638 if hasattr(self, "_using_sb_fixture") and (6639 test_id not in sb_config._results.keys()):6640 if test_id.count('.') > 1:6641 alt_test_id = '.'.join(test_id.split('.')[1:])6642 if alt_test_id in sb_config._results.keys():6643 sb_config._results.pop(alt_test_id)6644 elif test_id.count('.') == 1:6645 alt_test_id = sb_config._display_id[test_id]6646 alt_test_id = alt_test_id.replace(".py::", ".")6647 alt_test_id = alt_test_id.replace("::", ".")6648 if alt_test_id in sb_config._results.keys():6649 sb_config._results.pop(alt_test_id)6650 if test_id in sb_config._results.keys() and (6651 sb_config._results[test_id] == "Skipped"):6652 sb_config.item_count_skipped += 16653 sb_config.item_count_untested -= 16654 sb_config._results[test_id] = "Skipped"6655 elif has_exception:6656 # pytest-rerunfailures may cause duplicate results6657 if test_id not in sb_config._results.keys() or (6658 (not sb_config._results[test_id] == "Failed")):6659 sb_config._results[test_id] = "Failed"6660 sb_config.item_count_failed += 16661 sb_config.item_count_untested -= 16662 else:6663 if test_id in sb_config._results.keys() and (6664 sb_config._results[test_id] == "Failed"):6665 # Possibly pytest-rerunfailures reran the test6666 sb_config.item_count_failed -= 16667 sb_config.item_count_untested += 16668 sb_config._results[test_id] = "Passed"6669 sb_config.item_count_passed += 16670 sb_config.item_count_untested -= 16671 num_passed = sb_config.item_count_passed6672 num_failed = sb_config.item_count_failed6673 num_skipped = sb_config.item_count_skipped6674 num_untested = sb_config.item_count_untested6675 self.create_pie_chart(title=constants.Dashboard.TITLE)6676 self.add_data_point("Passed", num_passed, color="#84d474")6677 self.add_data_point("Untested", num_untested, color="#eaeaea")6678 self.add_data_point("Skipped", num_skipped, color="#efd8b4")6679 self.add_data_point("Failed", num_failed, color="#f17476")6680 style = (6681 '<link rel="stylesheet" '6682 'href="%s">' % constants.Dashboard.STYLE_CSS)6683 auto_refresh_html = ''6684 if num_untested > 0:6685 # Refresh every X seconds when waiting for more test results6686 auto_refresh_html = constants.Dashboard.META_REFRESH_HTML6687 else:6688 # The tests are complete6689 if sb_config._using_html_report:6690 # Add the pie chart to the pytest html report6691 sb_config._saved_dashboard_pie = self.extract_chart()6692 head = (6693 '<head><meta charset="utf-8" />'6694 '<meta property="og:image" '6695 'content="https://seleniumbase.io/img/dash_pie.png">'6696 '<link rel="shortcut icon" '6697 'href="https://seleniumbase.io/img/dash_pie_2.png">'6698 '%s'6699 '<title>Dashboard</title>'6700 '%s</head>' % (auto_refresh_html, style))6701 table_html = (6702 '<div></div>'6703 '<table border="1px solid #e6e6e6;" width="100%;" padding: 5px;'6704 ' font-size="12px;" text-align="left;" id="results-table">'6705 '<thead id="results-table-head"><tr>'6706 '<th col="result">Result</th><th col="name">Test</th>'6707 '<th col="duration">Duration</th><th col="links">Links</th>'6708 '</tr></thead>')6709 the_failed = []6710 the_skipped = []6711 the_passed = []6712 the_untested = []6713 for key in sb_config._results.keys():6714 t_res = sb_config._results[key]6715 t_dur = sb_config._duration[key]6716 t_d_id = sb_config._display_id[key]6717 res_low = t_res.lower()6718 if sb_config._results[key] == "Failed":6719 the_failed.append([res_low, t_res, t_d_id, t_dur])6720 if sb_config._results[key] == "Skipped":6721 the_skipped.append([res_low, t_res, t_d_id, t_dur])6722 if sb_config._results[key] == "Passed":6723 the_passed.append([res_low, t_res, t_d_id, t_dur])6724 if sb_config._results[key] == "Untested":6725 the_untested.append([res_low, t_res, t_d_id, t_dur])6726 for row in the_failed:6727 row = (6728 '<tbody class="%s results-table-row"><tr>'6729 '<td class="col-result">%s</td><td>%s</td><td>%s</td>'6730 '<td><a href="latest_logs/">latest_logs/</a></td>'6731 '</tr></tbody>' % (row[0], row[1], row[2], row[3]))6732 table_html += row6733 for row in the_skipped:6734 row = (6735 '<tbody class="%s results-table-row"><tr>'6736 '<td class="col-result">%s</td><td>%s</td><td>%s</td>'6737 '<td></td></tr></tbody>' % (row[0], row[1], row[2], row[3]))6738 table_html += row6739 for row in the_passed:6740 row = (6741 '<tbody class="%s results-table-row"><tr>'6742 '<td class="col-result">%s</td><td>%s</td><td>%s</td>'6743 '<td></td></tr></tbody>' % (row[0], row[1], row[2], row[3]))6744 table_html += row6745 for row in the_untested:6746 row = (6747 '<tbody class="%s results-table-row"><tr>'6748 '<td class="col-result">%s</td><td>%s</td><td>%s</td>'6749 '<td></td></tr></tbody>' % (row[0], row[1], row[2], row[3]))6750 table_html += row6751 table_html += "</table>"6752 add_more = "<br /><b>Last updated:</b> "6753 timestamp, the_date, the_time = log_helper.get_master_time()6754 last_updated = "%s at %s" % (the_date, the_time)6755 add_more = add_more + "%s" % last_updated6756 status = "<p></p><div><b>Status:</b> Awaiting results..."6757 status += " (Refresh the page for updates)"6758 if num_untested == 0:6759 status = "<p></p><div><b>Status:</b> Test Run Complete:"6760 if num_failed == 0:6761 if num_passed > 0:6762 if num_skipped == 0:6763 status += " <b>Success!</b> (All tests passed)"6764 else:6765 status += " <b>Success!</b> (No failing tests)"6766 else:6767 status += " All tests were skipped!"6768 else:6769 latest_logs_dir = "latest_logs/"6770 log_msg = "See latest logs for details"6771 if num_failed == 1:6772 status += (6773 ' <b>1 test failed!</b> --- '6774 '(<b><a href="%s">%s</a></b>)'6775 '' % (latest_logs_dir, log_msg))6776 else:6777 status += (6778 ' <b>%s tests failed!</b> --- '6779 '(<b><a href="%s">%s</a></b>)'6780 '' % (num_failed, latest_logs_dir, log_msg))6781 status += "</div><p></p>"6782 add_more = add_more + status6783 gen_by = (6784 '<p><div>Generated by: <b><a href="https://seleniumbase.io/">'6785 'SeleniumBase</a></b></div></p><p></p>')6786 add_more = add_more + gen_by6787 # Have dashboard auto-refresh on updates when using an http server6788 refresh_line = (6789 '<script type="text/javascript" src="%s">'6790 '</script>' % constants.Dashboard.LIVE_JS)6791 if num_untested == 0 and sb_config._using_html_report:6792 sb_config._dash_final_summary = status6793 add_more = add_more + refresh_line6794 the_html = head + self.extract_chart() + table_html + add_more6795 abs_path = os.path.abspath('.')6796 file_path = os.path.join(abs_path, "dashboard.html")6797 out_file = codecs.open(file_path, "w+", encoding="utf-8")6798 out_file.writelines(the_html)6799 out_file.close()6800 time.sleep(0.05) # Add time for dashboard server to process updates6801 def has_exception(self):6802 """ (This method should ONLY be used in custom tearDown() methods.)6803 This method returns True if the test failed or raised an exception.6804 This is useful for performing additional steps in your tearDown()6805 method (based on whether or not the test passed or failed).6806 Example use cases:6807 * Performing cleanup steps if a test didn't complete.6808 * Sending test data and/or results to a dashboard service.6809 """6810 return self.__has_exception()6811 def save_teardown_screenshot(self):6812 """ (Should ONLY be used at the start of custom tearDown() methods.)6813 This method takes a screenshot of the current web page for a6814 failing test (or when running your tests with --save-screenshot).6815 That way your tearDown() method can navigate away from the last6816 page where the test failed, and still get the correct screenshot6817 before performing tearDown() steps on other pages. If this method6818 is not included in your custom tearDown() method, a screenshot6819 will still be taken after the last step of your tearDown(), where6820 you should be calling "super(SubClassOfBaseCase, self).tearDown()"6821 """6822 if self.__has_exception() or self.save_screenshot_after_test:6823 test_id = self.__get_test_id()6824 test_logpath = self.log_path + "/" + test_id6825 self.__create_log_path_as_needed(test_logpath)6826 self.__set_last_page_screenshot()6827 self.__set_last_page_url()6828 self.__set_last_page_source()6829 if self.is_pytest:6830 self.__add_pytest_html_extra()6831 def tearDown(self):6832 """6833 Be careful if a subclass of BaseCase overrides setUp()6834 You'll need to add the following line to the subclass's tearDown():6835 super(SubClassOfBaseCase, self).tearDown()6836 """6837 try:6838 is_pytest = self.is_pytest # This fails if overriding setUp()6839 if is_pytest:6840 with_selenium = self.with_selenium6841 except Exception:6842 sub_class_name = str(6843 self.__class__.__bases__[0]).split('.')[-1].split("'")[0]6844 sub_file_name = str(self.__class__.__bases__[0]).split('.')[-2]6845 sub_file_name = sub_file_name + ".py"6846 class_name = str(self.__class__).split('.')[-1].split("'")[0]6847 file_name = str(self.__class__).split('.')[-2] + ".py"6848 class_name_used = sub_class_name6849 file_name_used = sub_file_name6850 if sub_class_name == "BaseCase":6851 class_name_used = class_name6852 file_name_used = file_name6853 fix_setup = "super(%s, self).setUp()" % class_name_used6854 fix_teardown = "super(%s, self).tearDown()" % class_name_used6855 message = ("You're overriding SeleniumBase's BaseCase setUp() "6856 "method with your own setUp() method, which breaks "6857 "SeleniumBase. You can fix this by going to your "6858 "%s class located in your %s file and adding the "6859 "following line of code AT THE BEGINNING of your "6860 "setUp() method:\n%s\n\nAlso make sure "6861 "you have added the following line of code AT THE "6862 "END of your tearDown() method:\n%s\n"6863 % (class_name_used, file_name_used,6864 fix_setup, fix_teardown))6865 raise Exception(message)6866 # *** Start tearDown() officially ***6867 self.__slow_mode_pause_if_active()6868 has_exception = self.__has_exception()6869 if self.__deferred_assert_failures:6870 print(6871 "\nWhen using self.deferred_assert_*() methods in your tests, "6872 "remember to call self.process_deferred_asserts() afterwards. "6873 "Now calling in tearDown()...\nFailures Detected:")6874 if not has_exception:6875 self.process_deferred_asserts()6876 else:6877 self.process_deferred_asserts(print_only=True)6878 if self.is_pytest:6879 # pytest-specific code6880 test_id = self.__get_test_id()6881 if with_selenium:6882 # Save a screenshot if logging is on when an exception occurs6883 if has_exception:6884 self.__add_pytest_html_extra()6885 sb_config._has_exception = True6886 if self.with_testing_base and not has_exception and (6887 self.save_screenshot_after_test):6888 test_logpath = self.log_path + "/" + test_id6889 self.__create_log_path_as_needed(test_logpath)6890 if not self.__last_page_screenshot_png:6891 self.__set_last_page_screenshot()6892 self.__set_last_page_url()6893 self.__set_last_page_source()6894 log_helper.log_screenshot(6895 test_logpath,6896 self.driver,6897 self.__last_page_screenshot_png)6898 self.__add_pytest_html_extra()6899 if self.with_testing_base and has_exception:6900 test_logpath = self.log_path + "/" + test_id6901 self.__create_log_path_as_needed(test_logpath)6902 if ((not self.with_screen_shots) and (6903 not self.with_basic_test_info) and (6904 not self.with_page_source)):6905 # Log everything if nothing specified (if testing_base)6906 if not self.__last_page_screenshot_png:6907 self.__set_last_page_screenshot()6908 self.__set_last_page_url()6909 self.__set_last_page_source()6910 log_helper.log_screenshot(6911 test_logpath,6912 self.driver,6913 self.__last_page_screenshot_png)6914 log_helper.log_test_failure_data(6915 self, test_logpath, self.driver, self.browser,6916 self.__last_page_url)6917 log_helper.log_page_source(6918 test_logpath, self.driver, self.__last_page_source)6919 else:6920 if self.with_screen_shots:6921 if not self.__last_page_screenshot_png:6922 self.__set_last_page_screenshot()6923 self.__set_last_page_url()6924 self.__set_last_page_source()6925 log_helper.log_screenshot(6926 test_logpath,6927 self.driver,6928 self.__last_page_screenshot_png)6929 if self.with_basic_test_info:6930 log_helper.log_test_failure_data(6931 self, test_logpath, self.driver, self.browser,6932 self.__last_page_url)6933 if self.with_page_source:6934 log_helper.log_page_source(6935 test_logpath, self.driver,6936 self.__last_page_source)6937 if self.dashboard:6938 self.__process_dashboard(has_exception)6939 # (Pytest) Finally close all open browser windows6940 self.__quit_all_drivers()6941 if self.headless:6942 if self.headless_active:6943 try:6944 self.display.stop()6945 except AttributeError:6946 pass6947 except Exception:6948 pass6949 self.display = None6950 if self.with_db_reporting:6951 if has_exception:6952 self.__insert_test_result(constants.State.FAILED, True)...

Full Screen

Full Screen

webdriver_test.py

Source:webdriver_test.py Github

copy

Full Screen

...6177 sb_config._only_unittest = False6178 if not self._dash_initialized:6179 sb_config._dashboard_initialized = True6180 self._dash_initialized = True6181 self.__process_dashboard(False, init=True)6182 else:6183 sb_config._sbase_detected = True6184 sb_config._only_unittest = False6185 if not self._dash_initialized:6186 sb_config._dashboard_initialized = True6187 self._dash_initialized = True6188 self.__process_dashboard(False, init=True)6189 has_url = False6190 if self._reuse_session:6191 if not hasattr(sb_config, "shared_driver"):6192 sb_config.shared_driver = None6193 if sb_config.shared_driver:6194 try:6195 self._default_driver = sb_config.shared_driver6196 self.driver = sb_config.shared_driver6197 self._drivers_list = [sb_config.shared_driver]6198 url = self.get_current_url()6199 if url is not None:6200 has_url = True6201 if len(self.driver.window_handles) > 1:6202 while len(self.driver.window_handles) > 1:6203 self.switch_to_window(6204 len(self.driver.window_handles) - 16205 )6206 self.driver.close()6207 self.switch_to_window(0)6208 if self._crumbs:6209 self.driver.delete_all_cookies()6210 except Exception:6211 pass6212 if self._reuse_session and sb_config.shared_driver and has_url:6213 good_start_page = False6214 if self.start_page and len(self.start_page) >= 4:6215 if page_utils.is_valid_url(self.start_page):6216 good_start_page = True6217 self.__new_window_on_rec_open = False6218 self.open(self.start_page)6219 self.__new_window_on_rec_open = True6220 else:6221 new_start_page = "https://" + self.start_page6222 if page_utils.is_valid_url(new_start_page):6223 good_start_page = True6224 self.__dont_record_open = True6225 self.open(new_start_page)6226 self.__dont_record_open = False6227 else:6228 # Launch WebDriver for both Pytest and Nosetests6229 self.driver = self.get_new_driver(6230 browser=self.browser,6231 headless=self.headless,6232 locale_code=self.locale_code,6233 protocol=self.protocol,6234 servername=self.servername,6235 port=self.port,6236 proxy=self.proxy_string,6237 proxy_bypass_list=self.proxy_bypass_list,6238 agent=self.user_agent,6239 switch_to=True,6240 cap_file=self.cap_file,6241 cap_string=self.cap_string,6242 recorder_ext=self.recorder_ext,6243 disable_csp=self.disable_csp,6244 enable_ws=self.enable_ws,6245 enable_sync=self.enable_sync,6246 use_auto_ext=self.use_auto_ext,6247 no_sandbox=self.no_sandbox,6248 disable_gpu=self.disable_gpu,6249 incognito=self.incognito,6250 guest_mode=self.guest_mode,6251 devtools=self.devtools,6252 remote_debug=self.remote_debug,6253 swiftshader=self.swiftshader,6254 ad_block_on=self.ad_block_on,6255 block_images=self.block_images,6256 chromium_arg=self.chromium_arg,6257 firefox_arg=self.firefox_arg,6258 firefox_pref=self.firefox_pref,6259 user_data_dir=self.user_data_dir,6260 extension_zip=self.extension_zip,6261 extension_dir=self.extension_dir,6262 external_pdf=self.external_pdf,6263 is_mobile=self.mobile_emulator,6264 d_width=self.__device_width,6265 d_height=self.__device_height,6266 d_p_r=self.__device_pixel_ratio,6267 )6268 self._default_driver = self.driver6269 if self._reuse_session:6270 sb_config.shared_driver = self.driver6271 if self.browser in ["firefox", "ie", "safari", "opera"]:6272 # Only Chrome and Edge browsers have the mobile emulator.6273 # Some actions such as hover-clicking are different on mobile.6274 self.mobile_emulator = False6275 # Configure the test time limit (if used).6276 self.set_time_limit(self.time_limit)6277 # Set the start time for the test (in ms).6278 # Although the pytest clock starts before setUp() begins,6279 # the time-limit clock starts at the end of the setUp() method.6280 sb_config.start_time_ms = int(time.time() * 1000.0)6281 if not self.__start_time_ms:6282 # Call this once in case of multiple setUp() calls in the same test6283 self.__start_time_ms = sb_config.start_time_ms6284 def __set_last_page_screenshot(self):6285 """self.__last_page_screenshot is only for pytest html report logs.6286 self.__last_page_screenshot_png is for all screenshot log files."""6287 if not self.__last_page_screenshot and (6288 not self.__last_page_screenshot_png6289 ):6290 try:6291 element = self.driver.find_element(6292 by=By.TAG_NAME, value="body"6293 )6294 if self.is_pytest and self.report_on:6295 self.__last_page_screenshot_png = (6296 self.driver.get_screenshot_as_png()6297 )6298 self.__last_page_screenshot = element.screenshot_as_base646299 else:6300 self.__last_page_screenshot_png = element.screenshot_as_png6301 except Exception:6302 if not self.__last_page_screenshot:6303 if self.is_pytest and self.report_on:6304 try:6305 self.__last_page_screenshot = (6306 self.driver.get_screenshot_as_base64()6307 )6308 except Exception:6309 self.__last_page_screenshot = (6310 constants.Warnings.SCREENSHOT_UNDEFINED6311 )6312 if not self.__last_page_screenshot_png:6313 try:6314 self.__last_page_screenshot_png = (6315 self.driver.get_screenshot_as_png()6316 )6317 except Exception:6318 self.__last_page_screenshot_png = (6319 constants.Warnings.SCREENSHOT_UNDEFINED6320 )6321 def __set_last_page_url(self):6322 if not self.__last_page_url:6323 try:6324 self.__last_page_url = log_helper.get_last_page(self.driver)6325 except Exception:6326 self.__last_page_url = None6327 def __set_last_page_source(self):6328 if not self.__last_page_source:6329 try:6330 self.__last_page_source = (6331 log_helper.get_html_source_with_base_href(6332 self.driver, self.driver.page_source6333 )6334 )6335 except Exception:6336 self.__last_page_source = (6337 constants.Warnings.PAGE_SOURCE_UNDEFINED6338 )6339 def __get_exception_info(self):6340 exc_message = None6341 if (6342 python36343 and hasattr(self, "_outcome")6344 and (hasattr(self._outcome, "errors") and self._outcome.errors)6345 ):6346 try:6347 exc_message = self._outcome.errors[0][1][1]6348 except Exception:6349 exc_message = "(Unknown Exception)"6350 else:6351 try:6352 exc_message = sys.last_value6353 except Exception:6354 exc_message = "(Unknown Exception)"6355 return str(exc_message)6356 def __insert_test_result(self, state, err):6357 from seleniumbase.core.testcase_manager import TestcaseDataPayload6358 data_payload = TestcaseDataPayload()6359 data_payload.runtime = int(time.time() * 1000) - self.case_start_time6360 data_payload.guid = self.testcase_guid6361 data_payload.execution_guid = self.execution_guid6362 data_payload.state = state6363 if err:6364 import traceback6365 tb_string = traceback.format_exc()6366 if "Message: " in tb_string:6367 data_payload.message = (6368 "Message: " + tb_string.split("Message: ")[-1]6369 )6370 elif "Exception: " in tb_string:6371 data_payload.message = tb_string.split("Exception: ")[-1]6372 elif "Error: " in tb_string:6373 data_payload.message = tb_string.split("Error: ")[-1]6374 else:6375 data_payload.message = self.__get_exception_info()6376 else:6377 test_id = self.__get_test_id_2()6378 if (6379 self.is_pytest6380 and test_id in sb_config._results.keys()6381 and (sb_config._results[test_id] == "Skipped")6382 ):6383 if self.__skip_reason:6384 data_payload.message = "Skipped: " + self.__skip_reason6385 else:6386 data_payload.message = "Skipped: (no reason given)"6387 self.testcase_manager.update_testcase_data(data_payload)6388 def __add_pytest_html_extra(self):6389 if not self.__added_pytest_html_extra:6390 try:6391 if self.with_selenium:6392 if not self.__last_page_screenshot:6393 self.__set_last_page_screenshot()6394 self.__set_last_page_url()6395 self.__set_last_page_source()6396 if self.report_on:6397 extra_url = {}6398 extra_url["name"] = "URL"6399 extra_url["format"] = "url"6400 extra_url["content"] = self.get_current_url()6401 extra_url["mime_type"] = None6402 extra_url["extension"] = None6403 extra_image = {}6404 extra_image["name"] = "Screenshot"6405 extra_image["format"] = "image"6406 extra_image["content"] = self.__last_page_screenshot6407 extra_image["mime_type"] = "image/png"6408 extra_image["extension"] = "png"6409 self.__added_pytest_html_extra = True6410 if self.__last_page_screenshot != (6411 constants.Warnings.SCREENSHOT_UNDEFINED6412 ):6413 self._html_report_extra.append(extra_url)6414 self._html_report_extra.append(extra_image)6415 except Exception:6416 pass6417 def __has_exception(self):6418 has_exception = False6419 if hasattr(sys, "last_traceback") and sys.last_traceback is not None:6420 has_exception = True6421 elif python3 and hasattr(self, "_outcome"):6422 if hasattr(self._outcome, "errors") and self._outcome.errors:6423 has_exception = True6424 else:6425 if python3:6426 has_exception = sys.exc_info()[1] is not None6427 else:6428 if not hasattr(self, "_using_sb_fixture_class") and (6429 not hasattr(self, "_using_sb_fixture_no_class")6430 ):6431 has_exception = sys.exc_info()[1] is not None6432 else:6433 has_exception = len(str(sys.exc_info()[1]).strip()) > 06434 if (6435 self.__will_be_skipped6436 and (hasattr(self, "_using_sb_fixture") or not python3)6437 ):6438 has_exception = False6439 return has_exception6440 def __get_test_id(self):6441 """ The id used in various places such as the test log path. """6442 test_id = "%s.%s.%s" % (6443 self.__class__.__module__,6444 self.__class__.__name__,6445 self._testMethodName,6446 )6447 if self._sb_test_identifier and len(str(self._sb_test_identifier)) > 6:6448 test_id = self._sb_test_identifier6449 test_id = test_id.replace(".py::", ".").replace("::", ".")6450 return test_id6451 def __get_test_id_2(self):6452 """ The id for SeleniumBase Dashboard entries. """6453 if "PYTEST_CURRENT_TEST" in os.environ:6454 return os.environ["PYTEST_CURRENT_TEST"].split(" ")[0]6455 test_id = "%s.%s.%s" % (6456 self.__class__.__module__.split(".")[-1],6457 self.__class__.__name__,6458 self._testMethodName,6459 )6460 if self._sb_test_identifier and len(str(self._sb_test_identifier)) > 6:6461 test_id = self._sb_test_identifier6462 if test_id.count(".") > 1:6463 test_id = ".".join(test_id.split(".")[1:])6464 return test_id6465 def __get_display_id(self):6466 """ The id for running a test from pytest. (Displayed on Dashboard) """6467 if "PYTEST_CURRENT_TEST" in os.environ:6468 return os.environ["PYTEST_CURRENT_TEST"].split(" ")[0]6469 test_id = "%s.py::%s::%s" % (6470 self.__class__.__module__.replace(".", "/"),6471 self.__class__.__name__,6472 self._testMethodName,6473 )6474 if self._sb_test_identifier and len(str(self._sb_test_identifier)) > 6:6475 test_id = self._sb_test_identifier6476 if hasattr(self, "_using_sb_fixture_class"):6477 if test_id.count(".") >= 2:6478 parts = test_id.split(".")6479 full = parts[-3] + ".py::" + parts[-2] + "::" + parts[-1]6480 test_id = full6481 elif hasattr(self, "_using_sb_fixture_no_class"):6482 if test_id.count(".") >= 1:6483 parts = test_id.split(".")6484 full = parts[-2] + ".py::" + parts[-1]6485 test_id = full6486 return test_id6487 def __get_filename(self):6488 """ The filename of the current SeleniumBase test. (NOT Path) """6489 filename = None6490 if "PYTEST_CURRENT_TEST" in os.environ:6491 test_id = os.environ["PYTEST_CURRENT_TEST"].split(" ")[0]6492 filename = test_id.split("::")[0].split("/")[-1]6493 else:6494 filename = self.__class__.__module__.split(".")[-1] + ".py"6495 return filename6496 def __create_log_path_as_needed(self, test_logpath):6497 if not os.path.exists(test_logpath):6498 try:6499 os.makedirs(test_logpath)6500 except Exception:6501 pass # Only reachable during multi-threaded runs6502 # def __process_dashboard(self, has_exception, init=False):6503 # """ SeleniumBase Dashboard Processing """6504 # if self._multithreaded:6505 # existing_res = sb_config._results # For recording "Skipped" tests6506 # abs_path = os.path.abspath(".")6507 # dash_json_loc = constants.Dashboard.DASH_JSON6508 # dash_jsonpath = os.path.join(abs_path, dash_json_loc)6509 # if not init and os.path.exists(dash_jsonpath):6510 # with open(dash_jsonpath, "r") as f:6511 # dash_json = f.read().strip()6512 # dash_data, d_id, dash_rt, tlp, d_stats = json.loads(dash_json)6513 # num_passed, num_failed, num_skipped, num_untested = d_stats6514 # sb_config._results = dash_data6515 # sb_config._display_id = d_id6516 # sb_config._duration = dash_rt # Dashboard Run Time6517 # sb_config._d_t_log_path = tlp # Test Log Path6518 # sb_config.item_count_passed = num_passed6519 # sb_config.item_count_failed = num_failed6520 # sb_config.item_count_skipped = num_skipped6521 # sb_config.item_count_untested = num_untested6522 # if len(sb_config._extra_dash_entries) > 0:6523 # # First take care of existing entries from non-SeleniumBase tests6524 # for test_id in sb_config._extra_dash_entries:6525 # if test_id in sb_config._results.keys():6526 # if sb_config._results[test_id] == "Skipped":6527 # sb_config.item_count_skipped += 16528 # sb_config.item_count_untested -= 16529 # elif sb_config._results[test_id] == "Failed":6530 # sb_config.item_count_failed += 16531 # sb_config.item_count_untested -= 16532 # elif sb_config._results[test_id] == "Passed":6533 # sb_config.item_count_passed += 16534 # sb_config.item_count_untested -= 16535 # else: # Mark "Skipped" if unknown6536 # sb_config.item_count_skipped += 16537 # sb_config.item_count_untested -= 16538 # sb_config._extra_dash_entries = [] # Reset the list to empty6539 # # Process new entries6540 # log_dir = self.log_path6541 # ft_id = self.__get_test_id() # Full test id with path to log files6542 # test_id = self.__get_test_id_2() # The test id used by the DashBoard6543 # dud = "seleniumbase/plugins/pytest_plugin.py::BaseClass::base_method"6544 # dud2 = "pytest_plugin.BaseClass.base_method"6545 # if hasattr(self, "_using_sb_fixture") and self.__will_be_skipped:6546 # test_id = sb_config._test_id6547 # if not init:6548 # duration_ms = int(time.time() * 1000) - self.__start_time_ms6549 # duration = float(duration_ms) / 1000.06550 # duration = "{:.2f}".format(duration)6551 # sb_config._duration[test_id] = duration6552 # if (6553 # has_exception6554 # or self.save_screenshot_after_test6555 # or self.__screenshot_count > 06556 # or self.__will_be_skipped6557 # ):6558 # sb_config._d_t_log_path[test_id] = os.path.join(log_dir, ft_id)6559 # else:6560 # sb_config._d_t_log_path[test_id] = None6561 # if test_id not in sb_config._display_id.keys():6562 # sb_config._display_id[test_id] = self.__get_display_id()6563 # if sb_config._display_id[test_id] == dud:6564 # return6565 # if (6566 # hasattr(self, "_using_sb_fixture")6567 # and test_id not in sb_config._results.keys()6568 # ):6569 # if test_id.count(".") > 1:6570 # alt_test_id = ".".join(test_id.split(".")[1:])6571 # if alt_test_id in sb_config._results.keys():6572 # sb_config._results.pop(alt_test_id)6573 # elif test_id.count(".") == 1:6574 # alt_test_id = sb_config._display_id[test_id]6575 # alt_test_id = alt_test_id.replace(".py::", ".")6576 # alt_test_id = alt_test_id.replace("::", ".")6577 # if alt_test_id in sb_config._results.keys():6578 # sb_config._results.pop(alt_test_id)6579 # if test_id in sb_config._results.keys() and (6580 # sb_config._results[test_id] == "Skipped"6581 # ):6582 # if self.__passed_then_skipped:6583 # # Multiple calls of setUp() and tearDown() in the same test6584 # sb_config.item_count_passed -= 16585 # sb_config.item_count_untested += 16586 # self.__passed_then_skipped = False6587 # sb_config._results[test_id] = "Skipped"6588 # sb_config.item_count_skipped += 16589 # sb_config.item_count_untested -= 16590 # elif (6591 # self._multithreaded6592 # and test_id in existing_res.keys()6593 # and existing_res[test_id] == "Skipped"6594 # ):6595 # sb_config._results[test_id] = "Skipped"6596 # sb_config.item_count_skipped += 16597 # sb_config.item_count_untested -= 16598 # elif has_exception:6599 # if test_id not in sb_config._results.keys():6600 # sb_config._results[test_id] = "Failed"6601 # sb_config.item_count_failed += 16602 # sb_config.item_count_untested -= 16603 # elif not sb_config._results[test_id] == "Failed":6604 # # tearDown() was called more than once in the test6605 # if sb_config._results[test_id] == "Passed":6606 # # Passed earlier, but last run failed6607 # sb_config._results[test_id] = "Failed"6608 # sb_config.item_count_failed += 16609 # sb_config.item_count_passed -= 16610 # else:6611 # sb_config._results[test_id] = "Failed"6612 # sb_config.item_count_failed += 16613 # sb_config.item_count_untested -= 16614 # else:6615 # # pytest-rerunfailures caused a duplicate failure6616 # sb_config._results[test_id] = "Failed"6617 # else:6618 # if (6619 # test_id in sb_config._results.keys()6620 # and sb_config._results[test_id] == "Failed"6621 # ):6622 # # pytest-rerunfailures reran a test that failed6623 # sb_config._d_t_log_path[test_id] = os.path.join(6624 # log_dir, ft_id6625 # )6626 # sb_config.item_count_failed -= 16627 # sb_config.item_count_untested += 16628 # elif (6629 # test_id in sb_config._results.keys()6630 # and sb_config._results[test_id] == "Passed"6631 # ):6632 # # tearDown() was called more than once in the test6633 # sb_config.item_count_passed -= 16634 # sb_config.item_count_untested += 16635 # sb_config._results[test_id] = "Passed"6636 # sb_config.item_count_passed += 16637 # sb_config.item_count_untested -= 16638 # else:6639 # pass # Only initialize the Dashboard on the first processing6640 # num_passed = sb_config.item_count_passed6641 # num_failed = sb_config.item_count_failed6642 # num_skipped = sb_config.item_count_skipped6643 # num_untested = sb_config.item_count_untested6644 # self.create_pie_chart(title=constants.Dashboard.TITLE)6645 # self.add_data_point("Passed", num_passed, color="#84d474")6646 # self.add_data_point("Untested", num_untested, color="#eaeaea")6647 # self.add_data_point("Skipped", num_skipped, color="#efd8b4")6648 # self.add_data_point("Failed", num_failed, color="#f17476")6649 # style = (6650 # '<link rel="stylesheet" charset="utf-8" '6651 # 'href="%s">' % constants.Dashboard.STYLE_CSS6652 # )6653 # auto_refresh_html = ""6654 # if num_untested > 0:6655 # # Refresh every X seconds when waiting for more test results6656 # auto_refresh_html = constants.Dashboard.META_REFRESH_HTML6657 # else:6658 # # The tests are complete6659 # if sb_config._using_html_report:6660 # # Add the pie chart to the pytest html report6661 # sb_config._saved_dashboard_pie = self.extract_chart()6662 # if self._multithreaded:6663 # abs_path = os.path.abspath(".")6664 # dash_pie = json.dumps(sb_config._saved_dashboard_pie)6665 # dash_pie_loc = constants.Dashboard.DASH_PIE6666 # pie_path = os.path.join(abs_path, dash_pie_loc)6667 # pie_file = codecs.open(pie_path, "w+", encoding="utf-8")6668 # pie_file.writelines(dash_pie)6669 # pie_file.close()6670 # head = (6671 # '<head><meta charset="utf-8">'6672 # '<meta name="viewport" content="shrink-to-fit=no">'6673 # '<link rel="shortcut icon" href="%s">'6674 # "%s"6675 # "<title>Dashboard</title>"6676 # "%s</head>"6677 # % (constants.Dashboard.DASH_PIE_PNG_1, auto_refresh_html, style)6678 # )6679 # table_html = (6680 # "<div></div>"6681 # '<table border="1px solid #e6e6e6;" width="100%;" padding: 5px;'6682 # ' font-size="12px;" text-align="left;" id="results-table">'6683 # '<thead id="results-table-head">'6684 # '<tr style="background-color: #F7F7FD;">'6685 # '<th col="result">Result</th><th col="name">Test</th>'6686 # '<th col="duration">Duration</th><th col="links">Links</th>'6687 # "</tr></thead>"6688 # )6689 # the_failed = []6690 # the_skipped = []6691 # the_passed_hl = [] # Passed and has logs6692 # the_passed_nl = [] # Passed and no logs6693 # the_untested = []6694 # if dud2 in sb_config._results.keys():6695 # sb_config._results.pop(dud2)6696 # for key in sb_config._results.keys():6697 # t_res = sb_config._results[key]6698 # t_dur = sb_config._duration[key]6699 # t_d_id = sb_config._display_id[key]6700 # t_l_path = sb_config._d_t_log_path[key]6701 # res_low = t_res.lower()6702 # if sb_config._results[key] == "Failed":6703 # if not sb_config._d_t_log_path[key]:6704 # sb_config._d_t_log_path[key] = os.path.join(log_dir, ft_id)6705 # the_failed.append([res_low, t_res, t_d_id, t_dur, t_l_path])6706 # elif sb_config._results[key] == "Skipped":6707 # the_skipped.append([res_low, t_res, t_d_id, t_dur, t_l_path])6708 # elif sb_config._results[key] == "Passed" and t_l_path:6709 # the_passed_hl.append([res_low, t_res, t_d_id, t_dur, t_l_path])6710 # elif sb_config._results[key] == "Passed" and not t_l_path:6711 # the_passed_nl.append([res_low, t_res, t_d_id, t_dur, t_l_path])6712 # elif sb_config._results[key] == "Untested":6713 # the_untested.append([res_low, t_res, t_d_id, t_dur, t_l_path])6714 # for row in the_failed:6715 # row = (6716 # '<tbody class="%s results-table-row">'6717 # '<tr style="background-color: #FFF8F8;">'6718 # '<td class="col-result">%s</td><td>%s</td><td>%s</td>'6719 # '<td><a href="%s">Logs</a> / <a href="%s/">Data</a>'6720 # "</td></tr></tbody>"6721 # "" % (row[0], row[1], row[2], row[3], log_dir, row[4])6722 # )6723 # table_html += row6724 # for row in the_skipped:6725 # if not row[4]:6726 # row = (6727 # '<tbody class="%s results-table-row">'6728 # '<tr style="background-color: #FEFEF9;">'6729 # '<td class="col-result">%s</td><td>%s</td><td>%s</td>'6730 # "<td>-</td></tr></tbody>"6731 # % (row[0], row[1], row[2], row[3])6732 # )6733 # else:6734 # row = (6735 # '<tbody class="%s results-table-row">'6736 # '<tr style="background-color: #FEFEF9;">'6737 # '<td class="col-result">%s</td><td>%s</td><td>%s</td>'6738 # '<td><a href="%s">Logs</a> / <a href="%s/">Data</a>'6739 # "</td></tr></tbody>"6740 # "" % (row[0], row[1], row[2], row[3], log_dir, row[4])6741 # )6742 # table_html += row6743 # for row in the_passed_hl:6744 # # Passed and has logs6745 # row = (6746 # '<tbody class="%s results-table-row">'6747 # '<tr style="background-color: #F8FFF8;">'6748 # '<td class="col-result">%s</td><td>%s</td><td>%s</td>'6749 # '<td><a href="%s">Logs</a> / <a href="%s/">Data</a>'6750 # "</td></tr></tbody>"6751 # "" % (row[0], row[1], row[2], row[3], log_dir, row[4])6752 # )6753 # table_html += row6754 # for row in the_passed_nl:6755 # # Passed and no logs6756 # row = (6757 # '<tbody class="%s results-table-row">'6758 # '<tr style="background-color: #F8FFF8;">'6759 # '<td class="col-result">%s</td><td>%s</td><td>%s</td>'6760 # "<td>-</td></tr></tbody>" % (row[0], row[1], row[2], row[3])6761 # )6762 # table_html += row6763 # for row in the_untested:6764 # row = (6765 # '<tbody class="%s results-table-row"><tr>'6766 # '<td class="col-result">%s</td><td>%s</td><td>%s</td>'6767 # "<td>-</td></tr></tbody>" % (row[0], row[1], row[2], row[3])6768 # )6769 # table_html += row6770 # table_html += "</table>"6771 # add_more = "<br /><b>Last updated:</b> "6772 # timestamp, the_date, the_time = log_helper.get_master_time()6773 # last_updated = "%s at %s" % (the_date, the_time)6774 # add_more = add_more + "%s" % last_updated6775 # status = "<p></p><div><b>Status:</b> Awaiting results..."6776 # status += " (Refresh the page for updates)"6777 # if num_untested == 0:6778 # status = "<p></p><div><b>Status:</b> Test Run Complete:"6779 # if num_failed == 0:6780 # if num_passed > 0:6781 # if num_skipped == 0:6782 # status += " <b>Success!</b> (All tests passed)"6783 # else:6784 # status += " <b>Success!</b> (No failing tests)"6785 # else:6786 # status += " All tests were skipped!"6787 # else:6788 # latest_logs_dir = "latest_logs/"6789 # log_msg = "See latest logs for details"6790 # if num_failed == 1:6791 # status += (6792 # " <b>1 test failed!</b> --- "6793 # '(<b><a href="%s">%s</a></b>)'6794 # "" % (latest_logs_dir, log_msg)6795 # )6796 # else:6797 # status += (6798 # " <b>%s tests failed!</b> --- "6799 # '(<b><a href="%s">%s</a></b>)'6800 # "" % (num_failed, latest_logs_dir, log_msg)6801 # )6802 # status += "</div><p></p>"6803 # add_more = add_more + status6804 # gen_by = (6805 # '<p><div>Generated by: <b><a href="https://seleniumbase.io/">'6806 # "SeleniumBase</a></b></div></p><p></p>"6807 # )6808 # add_more = add_more + gen_by6809 # # Have dashboard auto-refresh on updates when using an http server6810 # refresh_line = (6811 # '<script type="text/javascript" src="%s">'6812 # "</script>" % constants.Dashboard.LIVE_JS6813 # )6814 # if num_untested == 0 and sb_config._using_html_report:6815 # sb_config._dash_final_summary = status6816 # add_more = add_more + refresh_line6817 # the_html = (6818 # '<html lang="en">'6819 # + head6820 # + self.extract_chart()6821 # + table_html6822 # + add_more6823 # )6824 # abs_path = os.path.abspath(".")6825 # file_path = os.path.join(abs_path, "dashboard.html")6826 # out_file = codecs.open(file_path, "w+", encoding="utf-8")6827 # out_file.writelines(the_html)6828 # out_file.close()6829 # sb_config._dash_html = the_html6830 # if self._multithreaded:6831 # d_stats = (num_passed, num_failed, num_skipped, num_untested)6832 # _results = sb_config._results6833 # _display_id = sb_config._display_id6834 # _rt = sb_config._duration # Run Time (RT)6835 # _tlp = sb_config._d_t_log_path # Test Log Path (TLP)6836 # dash_json = json.dumps((_results, _display_id, _rt, _tlp, d_stats))6837 # dash_json_loc = constants.Dashboard.DASH_JSON6838 # dash_jsonpath = os.path.join(abs_path, dash_json_loc)6839 # dash_json_file = codecs.open(dash_jsonpath, "w+", encoding="utf-8")6840 # dash_json_file.writelines(dash_json)6841 # dash_json_file.close()6842 def has_exception(self):6843 """(This method should ONLY be used in custom tearDown() methods.)6844 This method returns True if the test failed or raised an exception.6845 This is useful for performing additional steps in your tearDown()6846 method (based on whether or not the test passed or failed).6847 Example use cases:6848 * Performing cleanup steps if a test didn't complete.6849 * Sending test data and/or results to a dashboard service.6850 """6851 return self.__has_exception()6852 def save_teardown_screenshot(self):6853 """(Should ONLY be used at the start of custom tearDown() methods.)6854 This method takes a screenshot of the current web page for a6855 failing test (or when running your tests with --save-screenshot).6856 That way your tearDown() method can navigate away from the last6857 page where the test failed, and still get the correct screenshot6858 before performing tearDown() steps on other pages. If this method6859 is not included in your custom tearDown() method, a screenshot6860 will still be taken after the last step of your tearDown(), where6861 you should be calling "super(SubClassOfBaseCase, self).tearDown()"6862 """6863 try:6864 self.__check_scope__()6865 except Exception:6866 return6867 if self.__has_exception() or self.save_screenshot_after_test:6868 test_logpath = os.path.join(self.log_path, self.__get_test_id())6869 self.__create_log_path_as_needed(test_logpath)6870 self.__set_last_page_screenshot()6871 self.__set_last_page_url()6872 self.__set_last_page_source()6873 self.__add_pytest_html_extra()6874 def teardown(self):6875 """6876 Be careful if a subclass of BaseCase overrides setUp()6877 You'll need to add the following line to the subclass's tearDown():6878 super(SubClassOfBaseCase, self).tearDown()6879 """6880 if self._called_teardown:6881 logger.info("This test already called teardown()")6882 return6883 self._called_teardown = True6884 self._called_setup = False6885 try:6886 is_pytest = self.is_pytest # This fails if overriding setUp()6887 if is_pytest:6888 with_selenium = self.with_selenium6889 except Exception:6890 sub_class_name = (6891 str(self.__class__.__bases__[0]).split(".")[-1].split("'")[0]6892 )6893 sub_file_name = str(self.__class__.__bases__[0]).split(".")[-2]6894 sub_file_name = sub_file_name + ".py"6895 class_name = str(self.__class__).split(".")[-1].split("'")[0]6896 file_name = str(self.__class__).split(".")[-2] + ".py"6897 class_name_used = sub_class_name6898 file_name_used = sub_file_name6899 if sub_class_name == "BaseCase":6900 class_name_used = class_name6901 file_name_used = file_name6902 fix_setup = "super(%s, self).setUp()" % class_name_used6903 fix_teardown = "super(%s, self).tearDown()" % class_name_used6904 message = (6905 "You're overriding SeleniumBase's BaseCase setUp() "6906 "method with your own setUp() method, which breaks "6907 "SeleniumBase. You can fix this by going to your "6908 "%s class located in your %s file and adding the "6909 "following line of code AT THE BEGINNING of your "6910 "setUp() method:\n%s\n\nAlso make sure "6911 "you have added the following line of code AT THE "6912 "END of your tearDown() method:\n%s\n"6913 % (class_name_used, file_name_used, fix_setup, fix_teardown)6914 )6915 raise Exception(message)6916 # *** Start tearDown() officially ***6917 self._slow_mode_pause_if_active()6918 has_exception = self.__has_exception()6919 if self.__overrided_default_timeouts:6920 # Reset default timeouts in case there are more tests6921 # These were changed in set_default_timeout()6922 if sb_config._SMALL_TIMEOUT and sb_config._LARGE_TIMEOUT:6923 settings.SMALL_TIMEOUT = sb_config._SMALL_TIMEOUT6924 settings.LARGE_TIMEOUT = sb_config._LARGE_TIMEOUT6925 sb_config._is_timeout_changed = False6926 self.__overrided_default_timeouts = False6927 deferred_exception = None6928 if self.__deferred_assert_failures:6929 print(6930 "\nWhen using self.deferred_assert_*() methods in your tests, "6931 "remember to call self.process_deferred_asserts() afterwards. "6932 "Now calling in tearDown()...\nFailures Detected:"6933 )6934 if not has_exception:6935 try:6936 self.process_deferred_asserts()6937 except Exception as e:6938 deferred_exception = e6939 else:6940 self.process_deferred_asserts(print_only=True)6941 test_id = self.__get_test_id()6942 if with_selenium:6943 # Save a screenshot if logging is on when an exception occurs6944 if has_exception:6945 self.__add_pytest_html_extra()6946 sb_config._has_exception = True6947 if (6948 self.with_testing_base6949 and not has_exception6950 and self.save_screenshot_after_test6951 ):6952 test_logpath = os.path.join(self.log_path, test_id)6953 self.__create_log_path_as_needed(test_logpath)6954 if not self.__last_page_screenshot_png:6955 self.__set_last_page_screenshot()6956 self.__set_last_page_url()6957 self.__set_last_page_source()6958 log_helper.log_screenshot(6959 test_logpath,6960 self.driver,6961 self.__last_page_screenshot_png,6962 )6963 self.__add_pytest_html_extra()6964 if self.with_testing_base and has_exception:6965 test_logpath = os.path.join(self.log_path, test_id)6966 self.__create_log_path_as_needed(test_logpath)6967 if (6968 not self.with_screen_shots6969 and not self.with_basic_test_info6970 and not self.with_page_source6971 ):6972 # Log everything if nothing specified (if testing_base)6973 if not self.__last_page_screenshot_png:6974 self.__set_last_page_screenshot()6975 self.__set_last_page_url()6976 self.__set_last_page_source()6977 log_helper.log_screenshot(6978 test_logpath,6979 self.driver,6980 self.__last_page_screenshot_png,6981 )6982 log_helper.log_test_failure_data(6983 self,6984 test_logpath,6985 self.driver,6986 self.browser,6987 self.__last_page_url,6988 )6989 log_helper.log_page_source(6990 test_logpath, self.driver, self.__last_page_source6991 )6992 else:6993 if self.with_screen_shots:6994 if not self.__last_page_screenshot_png:6995 self.__set_last_page_screenshot()6996 self.__set_last_page_url()6997 self.__set_last_page_source()6998 log_helper.log_screenshot(6999 test_logpath,7000 self.driver,7001 self.__last_page_screenshot_png,7002 )7003 if self.with_basic_test_info:7004 log_helper.log_test_failure_data(7005 self,7006 test_logpath,7007 self.driver,7008 self.browser,7009 self.__last_page_url,7010 )7011 if self.with_page_source:7012 log_helper.log_page_source(7013 test_logpath,7014 self.driver,7015 self.__last_page_source,7016 )7017 if self.dashboard:7018 if self._multithreaded:7019 with self.dash_lock:7020 self.__process_dashboard(has_exception)7021 else:7022 self.__process_dashboard(has_exception)7023 # (Pytest) Finally close all open browser windows7024 self.__quit_all_drivers()7025 if self.config.getoption("headless") or self.config.getoption("xvfb"):7026 if self.headless_active:7027 try:7028 self.display.stop()7029 except AttributeError:7030 pass7031 except Exception:7032 pass7033 self.display = None7034 if self.config.getoption("with_db_reporting", False):7035 if has_exception:7036 self.__insert_test_result(constants.State.FAILED, True)...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run SeleniumBase automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful