How to use _add_summary_to_report method in toolium

Best Python code snippet using toolium_python

visual_test.py

Source:visual_test.py Github

copy

Full Screen

...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)221 f.write(report)222 def _update_report_summary(self):223 """Update asserts counter in report"""224 new_results = 'Visual asserts</b>: {} ({} failed)'.format(sum(self.results.values()), self.results['diff'])225 with open(os.path.join(self.output_directory, self.report_name), "r+") as f:226 report = f.read()227 report = re.sub(r'Visual asserts</b>: [0-9]* \([0-9]* failed\)', new_results, report)228 f.seek(0)229 f.write(report)230 def _add_summary_to_report(self):231 summary = '<p><b>Execution date</b>: {}</p>'.format(datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S'))232 summary += '<p><b>Baseline name</b>: {}</p>'.format(path.basename(self.baseline_directory))233 summary += '<p><b>Visual asserts</b>: {} ({} failed)</p>'.format(sum(self.results.values()),234 self.results['diff'])235 self._add_data_to_report_before_tag(summary, '</div>')236 def _get_html_row(self, result, report_name, image_file, baseline_file, message=''):237 row = '<tr class=' + result + '>'238 row += '<td>' + report_name + '</td>'239 # Create baseline column240 baseline_col = self._get_img_element(baseline_file, 'Baseline image')241 row += '<td>' + baseline_col + '</td>'242 # Create image column243 image_col = self._get_img_element(image_file, 'Screenshot image')244 row += '<td>' + image_col + '</td>'...

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 toolium 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