Best Python code snippet using toolium_python
visual_test.py
Source:visual_test.py
...29 force = False #: if True, screenshot is compared even if visual testing is disabled by configuration30 def __init__(self, driver_wrapper=None, force=False):31 self.driver_wrapper = driver_wrapper if driver_wrapper else DriverManager.get_default_wrapper()32 self.force = force33 if not self.driver_wrapper.config.getboolean_optional('VisualTests', 'enabled') and not self.force:34 return35 if 'PerceptualEngine' not in globals():36 raise Exception('The visual tests are enabled, but needle is not installed')37 self.utils = self.driver_wrapper.utils38 self.logger = logging.getLogger(__name__)39 self.output_directory = DriverManager.visual_output_directory40 # Update baseline with real platformVersion value41 if '{platformVersion}' in self.driver_wrapper.baseline_name:42 platform_version = self.driver_wrapper.driver.desired_capabilities['platformVersion']43 baseline_name = self.driver_wrapper.baseline_name.replace('{platformVersion}', platform_version)44 self.driver_wrapper.baseline_name = baseline_name45 self.driver_wrapper.visual_baseline_directory = os.path.join(DriverManager.visual_baseline_directory,46 utilities.get_valid_filename(baseline_name))47 self.baseline_directory = self.driver_wrapper.visual_baseline_directory48 self.engine = self._get_engine()49 self.save_baseline = self.driver_wrapper.config.getboolean_optional('VisualTests', 'save')50 # Create folders51 if not os.path.exists(self.baseline_directory):52 os.makedirs(self.baseline_directory)53 if not os.path.exists(self.output_directory):54 os.makedirs(self.output_directory)55 # Copy js, css and html template to output directory56 dst_template_path = os.path.join(self.output_directory, self.report_name)57 if not os.path.exists(dst_template_path):58 resources_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../resources')59 orig_template_path = os.path.join(resources_path, self.template_name)60 orig_javascript_path = os.path.join(resources_path, self.javascript_name)61 dst_javascript_path = os.path.join(self.output_directory, self.javascript_name)62 orig_css_path = os.path.join(resources_path, self.css_name)63 dst_css_path = os.path.join(self.output_directory, self.css_name)64 shutil.copyfile(orig_template_path, dst_template_path)65 shutil.copyfile(orig_javascript_path, dst_javascript_path)66 shutil.copyfile(orig_css_path, dst_css_path)67 self._add_summary_to_report()68 def _get_engine(self):69 engine_type = self.driver_wrapper.config.get_optional('VisualTests', 'engine', 'pil')70 if engine_type == 'perceptualdiff':71 engine = PerceptualEngine()72 elif engine_type == 'imagemagick' and 'MagickEngine' not in globals():73 self.logger.warning("Engine '%s' not found, using pil instead. You need needle 0.4+ to use this engine.",74 engine_type)75 engine = PilEngine()76 elif engine_type == 'imagemagick':77 engine = MagickEngine()78 elif engine_type == 'pil':79 engine = PilEngine()80 else:81 self.logger.warning("Engine '%s' not found, using pil instead. Review your properties.cfg file.",82 engine_type)83 engine = PilEngine()84 return engine85 def assert_screenshot(self, element, filename, file_suffix=None, threshold=0, exclude_elements=None):86 if exclude_elements is None:87 exclude_elements = []88 if not self.driver_wrapper.config.getboolean_optional('VisualTests', 'enabled') and not self.force:89 return90 if not (isinstance(threshold, int) or isinstance(threshold, float)) or threshold < 0 or threshold > 1:91 raise TypeError('Threshold must be a number between 0 and 1: {}'.format(threshold))92 # Search elements93 web_element = self.utils.get_web_element(element)94 exclude_web_elements = []95 for exclude_element in exclude_elements:96 try:97 exclude_web_elements.append(self.utils.get_web_element(exclude_element))98 except NoSuchElementException as e:99 self.logger.warning("Element to be excluded not found: %s", str(e))100 baseline_file = os.path.join(self.baseline_directory, '{}.png'.format(filename))101 filename_with_suffix = '{0}__{1}'.format(filename, file_suffix) if file_suffix else filename102 unique_name = '{0:0=2d}_{1}'.format(DriverManager.visual_number, filename_with_suffix)103 unique_name = '{}.png'.format(utilities.get_valid_filename(unique_name))104 output_file = os.path.join(self.output_directory, unique_name)105 report_name = '{}<br>({})'.format(file_suffix, filename) if file_suffix else '-<br>({})'.format(filename)106 # Get screenshot and modify it107 img = Image.open(BytesIO(self.driver_wrapper.driver.get_screenshot_as_png()))108 img = self.remove_scrolls(img)109 img = self.mobile_resize(img)110 img = self.exclude_elements(img, exclude_web_elements)111 img = self.crop_element(img, web_element)112 img.save(output_file)113 DriverManager.visual_number += 1114 # Determine whether we should save the baseline image115 if self.save_baseline or not os.path.exists(baseline_file):116 # Copy screenshot to baseline117 shutil.copyfile(output_file, baseline_file)118 if self.driver_wrapper.config.getboolean_optional('VisualTests', 'complete_report'):119 self._add_result_to_report('baseline', report_name, output_file, None, 'Screenshot added to baseline')120 self.logger.debug("Visual screenshot '%s' saved in visualtests/baseline folder", filename)121 else:122 # Compare the screenshots123 self.compare_files(report_name, output_file, baseline_file, threshold)124 def get_scrolls_size(self):125 scroll_x = 0126 scroll_y = 0127 if (self.driver_wrapper.config.get('Driver', 'type').split('-')[0] in ['chrome', 'iexplore'] and128 not self.driver_wrapper.is_mobile_test()):129 scroll_height = self.driver_wrapper.driver.execute_script("return document.body.scrollHeight")130 scroll_width = self.driver_wrapper.driver.execute_script("return document.body.scrollWidth")131 window_height = self.driver_wrapper.driver.execute_script("return window.innerHeight")132 window_width = self.driver_wrapper.driver.execute_script("return window.innerWidth")133 scroll_size = 21 if self.driver_wrapper.config.get('Driver', 'type').split('-')[0] == 'iexplore' else 17134 scroll_x = scroll_size if scroll_width > window_width else 0135 scroll_y = scroll_size if scroll_height > window_height else 0136 return {'x': scroll_x, 'y': scroll_y}137 def remove_scrolls(self, img):138 scrolls_size = self.get_scrolls_size()139 if scrolls_size['x'] > 0 or scrolls_size['y'] > 0:140 new_image_width = img.size[0] - scrolls_size['y']141 new_image_height = img.size[1] - scrolls_size['x']142 img = img.crop((0, 0, new_image_width, new_image_height))143 return img144 def mobile_resize(self, img):145 if self.driver_wrapper.is_ios_test() or self.driver_wrapper.is_android_web_test():146 scale = img.size[0] / self.utils.get_window_size()['width']147 if scale != 1:148 new_image_size = (int(img.size[0] / scale), int(img.size[1] / scale))149 img = img.resize(new_image_size, Image.ANTIALIAS)150 return img151 def get_element_box(self, web_element):152 if not self.driver_wrapper.is_mobile_test():153 scroll_x = self.driver_wrapper.driver.execute_script("return window.pageXOffset")154 scroll_x = scroll_x if scroll_x else 0155 scroll_y = self.driver_wrapper.driver.execute_script("return window.pageYOffset")156 scroll_y = scroll_y if scroll_y else 0157 offset_x = -scroll_x158 offset_y = -scroll_y159 else:160 offset_x = 0161 offset_y = self.utils.get_safari_navigation_bar_height()162 location = web_element.location163 size = web_element.size164 return (int(location['x']) + offset_x, int(location['y'] + offset_y),165 int(location['x'] + offset_x + size['width']), int(location['y'] + offset_y + size['height']))166 def crop_element(self, img, web_element):167 if web_element:168 element_box = self.get_element_box(web_element)169 # Reduce element box if it is greater than image size170 element_max_x = img.size[0] if element_box[2] > img.size[0] else element_box[2]171 element_max_y = img.size[1] if element_box[3] > img.size[1] else element_box[3]172 element_box = (element_box[0], element_box[1], element_max_x, element_max_y)173 img = img.crop(element_box)174 return img175 def exclude_elements(self, img, web_elements):176 if web_elements and len(web_elements) > 0:177 img = img.convert("RGBA")178 pixel_data = img.load()179 for web_element in web_elements:180 element_box = self.get_element_box(web_element)181 for x, y in itertools.product(moves.xrange(element_box[0], element_box[2]),182 moves.xrange(element_box[1], element_box[3])):183 try:184 pixel_data[x, y] = (0, 0, 0, 255)185 except IndexError:186 pass187 return img188 def compare_files(self, report_name, image_file, baseline_file, threshold):189 width, height = Image.open(image_file).size190 if isinstance(self.engine, PilEngine):191 # Pil needs a pixel number threshold instead of a percentage threshold192 threshold = int(width * height * threshold)193 try:194 if 'MagickEngine' in globals() and isinstance(self.engine, MagickEngine):195 # Workaround: ImageMagick hangs when images are not equal196 assert (width, height) == Image.open(baseline_file).size, 'Image dimensions do not match'197 self.engine.assertSameFiles(image_file, baseline_file, threshold)198 if self.driver_wrapper.config.getboolean_optional('VisualTests', 'complete_report'):199 self._add_result_to_report('equal', report_name, image_file, baseline_file)200 return None201 except AssertionError as exc:202 diff_message = self._get_diff_message(str(exc), width * height)203 self._add_result_to_report('diff', report_name, image_file, baseline_file, diff_message)204 self.logger.warning("Visual error in '%s': %s", os.path.splitext(os.path.basename(baseline_file))[0],205 diff_message)206 if self.driver_wrapper.config.getboolean_optional('VisualTests', 'fail') or self.force:207 raise exc208 else:209 return diff_message210 def _add_result_to_report(self, result, report_name, image_file, baseline_file, message=''):211 self.results[result] += 1212 row = self._get_html_row(result, report_name, image_file, baseline_file, message)213 self._add_data_to_report_before_tag(row, '</tbody>')214 self._update_report_summary()215 def _add_data_to_report_before_tag(self, data, tag):216 with open(os.path.join(self.output_directory, self.report_name), "r+") as f:217 report = f.read()218 index = report.find(tag)219 report = report[:index] + data + report[index:]220 f.seek(0)...
driver_wrapper.py
Source:driver_wrapper.py
...112 if self.server_type == 'grid':113 self.remote_node_video_enabled = self.utils.is_remote_video_enabled(self.remote_node)114 else:115 self.remote_node_video_enabled = True if self.server_type in ['ggr', 'selenoid'] else False116 if self.is_mobile_test() and not self.is_web_test() and self.config.getboolean_optional('Driver',117 'appium_app_strings'):118 self.app_strings = self.driver.app_strings()119 if self.is_maximizable():120 bounds_x, bounds_y = self.get_config_window_bounds()121 self.driver.set_window_position(bounds_x, bounds_y)122 self.logger.debug('Window bounds: %s x %s', bounds_x, bounds_y)123 if maximize:124 window_width = self.config.get_optional('Driver', 'window_width')125 window_height = self.config.get_optional('Driver', 'window_height')126 if window_width and window_height:127 self.driver.set_window_size(window_width, window_height)128 else:129 self.driver.maximize_window()130 window_size = self.utils.get_window_size()131 self.logger.debug('Window size: %s x %s', window_size['width'], window_size['height'])132 self.update_visual_baseline()133 self.utils.discard_logcat_logs()134 if self.config.get('Driver', 'type') != 'ios':135 self.utils.set_implicitly_wait()136 return self.driver137 def get_config_window_bounds(self):138 bounds_x = int(self.config.get_optional('Driver', 'bounds_x') or 0)139 bounds_y = int(self.config.get_optional('Driver', 'bounds_y') or 0)140 monitor_index = int(self.config.get_optional('Driver', 'monitor') or -1)141 if monitor_index > -1:142 try:143 monitor = screeninfo.get_monitors()[monitor_index]144 bounds_x += monitor.x145 bounds_y += monitor.y146 except NotImplementedError:147 self.logger.warn('Current environment doesn\'t support get_monitors')148 return bounds_x, bounds_y149 def is_android_test(self):150 driver_name = self.config.get('Driver', 'type').split('-')[0]151 return driver_name == 'android'152 def is_ios_test(self):153 driver_name = self.config.get('Driver', 'type').split('-')[0]154 return driver_name in ('ios', 'iphone')155 def is_mobile_test(self):156 return self.is_android_test() or self.is_ios_test()157 def is_web_test(self):158 appium_browser_name = self.config.get_optional('AppiumCapabilities', 'browserName')159 return not self.is_mobile_test() or appium_browser_name not in (None, '')160 def is_android_web_test(self):161 return self.is_android_test() and self.is_web_test()162 def is_ios_web_test(self):163 return self.is_ios_test() and self.is_web_test()164 def is_maximizable(self):165 return not self.is_mobile_test()166 def should_reuse_driver(self, scope, test_passed, context=None):167 reuse_driver = self.config.getboolean_optional('Driver', 'reuse_driver')168 reuse_driver_session = self.config.getboolean_optional('Driver', 'reuse_driver_session')169 restart_driver_after_failure = (self.config.getboolean_optional('Driver', 'restart_driver_after_failure') or170 self.config.getboolean_optional('Driver', 'restart_driver_fail'))171 if context and scope == 'function':172 reuse_driver = reuse_driver or (hasattr(context, 'reuse_driver_from_tags')173 and context.pytalos.reuse_driver_from_tags)174 return (((reuse_driver and scope == 'function') or (reuse_driver_session and scope != 'session'))175 and (test_passed or not restart_driver_after_failure))176 def get_driver_platform(self):177 platform = ''178 if 'platform' in self.driver.desired_capabilities:179 platform = self.driver.desired_capabilities['platform']180 elif 'platformName' in self.driver.desired_capabilities:181 platform = self.driver.desired_capabilities['platformName']...
selenoid.py
Source:selenoid.py
...9 from arc.core.driver.driver_manager import DriverManager10 self.videos_directory = kwargs.get('videos_dir', DriverManager.videos_directory)11 self.logs_directory = kwargs.get('logs_dir', DriverManager.logs_directory)12 self.output_directory = kwargs.get('output_dir', DriverManager.output_directory)13 self.browser_remote = driver_wrapper.config.getboolean_optional('Server', 'enabled', False)14 self.browser = driver_wrapper.driver.desired_capabilities['browserName']15 if self.browser_remote:16 self.session_id = driver_wrapper.driver.session_id17 self.server_url = driver_wrapper.utils.get_server_url()18 def __download_file(self, url, path_file, timeout):19 status_code = 020 init_time = time.time()21 self.driver_wrapper.logger.info(f"Downloading file from Selenoid node: {url}")22 body = None23 while status_code != constants.SEL_STATUS_OK and time.time() - init_time < float(timeout):24 body = requests.get(url)25 status_code = body.status_code26 if status_code != constants.SEL_STATUS_OK:27 time.sleep(1)28 took = time.time() - init_time29 if status_code == constants.SEL_STATUS_OK:30 path, name = os.path.split(path_file)31 if not os.path.exists(path):32 os.makedirs(path)33 try:34 fp = open(path_file, 'wb')35 fp.write(body.content)36 fp.close()37 self.driver_wrapper.logger.info(38 f"File has been downloaded successfully to {path_file} and took {took} seconds")39 return True40 except IOError as e:41 self.driver_wrapper.logger.warn(f"Error writing downloaded file in {path_file}:\n {e}")42 else:43 self.driver_wrapper.logger.warn(f"File {url} does not exist in the server after {timeout} seconds")44 return False45 @staticmethod46 def __remove_file(url):47 requests.delete(url)48 def get_selenoid_info(self):49 host_url = f"{self.server_url}/host/{self.session_id}"50 try:51 selenoid_info = requests.get(host_url).json()52 except Exception as ex:53 self.driver_wrapper.logger.warn(ex)54 return None55 self.driver_wrapper.logger.info(f"Selenoid host info: \n {selenoid_info}")56 return selenoid_info57 def is_the_session_still_active(self):58 server_url_list = self.server_url.split(":")59 host_url = f"{server_url_list[0]}:{server_url_list[1]}:{server_url_list[2]}:{constants.SEL_STATUS_PORT}/status"60 response = None61 try:62 response = requests.get(host_url).json()["browsers"][self.browser]63 except Exception as e:64 self.driver_wrapper.logger.warn(65 f"the GGR status request has failed: \nResponse: {response.content} \nError message: {e}\n")66 return None67 for browser in response:68 if response[browser] != {}:69 sessions = response[browser][server_url_list[1].split("@")[0].replace("//", "")]["sessions"]70 for session in sessions:71 if session["id"] == self.session_id:72 return True73 return False74 def download_session_video(self, scenario_name, timeout=5):75 if (self.driver_wrapper.get_driver_platform().lower() != 'linux' or76 not self.driver_wrapper.config.getboolean_optional('Capabilities', 'enableVideo')):77 return78 path_file = os.path.join(self.videos_directory, '%s.%s' % (scenario_name, constants.SEL_MP4_EXTENSION))79 if self.driver_wrapper.server_type == 'selenoid':80 filename = '%s.%s' % (self.session_id, constants.SEL_MP4_EXTENSION)81 else:82 filename = self.session_id83 video_url = f"{self.server_url}/video/{filename}"84 if self.browser_remote:85 self.__download_file(video_url, path_file, timeout)86 self.__remove_file(video_url)87 def download_session_log(self, scenario_name, timeout=5):88 if (self.driver_wrapper.get_driver_platform().lower() != 'linux' or89 not self.driver_wrapper.config.getboolean_optional('Capabilities', 'enableLog')):90 return91 path_file = os.path.join(self.logs_directory, '%s_ggr.%s' % (scenario_name, constants.SEL_LOG_EXTENSION))92 if self.driver_wrapper.server_type == 'selenoid':93 filename = '%s.%s' % (self.session_id, constants.SEL_LOG_EXTENSION)94 else:95 filename = self.session_id96 logs_url = f"{self.server_url}/logs/{filename}"97 if self.browser_remote:98 self.__download_file(logs_url, path_file, timeout)99 self.__remove_file(logs_url)100 def download_file(self, filename, timeout=5):101 path_file = os.path.join(self.output_directory, constants.SEL_DOWNLOADS_PATH, self.session_id[-8:], filename)102 file_url = f"{self.server_url}/download/{self.session_id}/{filename}"103 if self.browser_remote:...
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!!