Best Python code snippet using robotframework-anywherelibrary
WatchUI.py
Source:WatchUI.py
...147 self.robotlib.fail("*INFO* Save file with difference")148 else:149 img_diff = cv.hconcat([self.img1, self.img2])150 time_ = str(time.time())151 self.seleniumlib.capture_page_screenshot(152 save_folder + "/Img" + time_ + self.format153 )154 cv.imwrite(save_folder + "/Img" + time_ + self.format, img_diff)155 self.robotlib.log_to_console(156 "Image has diff: {} ".format(self.score)157 )158 else:159 raise AssertionError("Path doesnt exists")160 def compare_screen(self, path1, save_folder=save_folder_path, ssim=starts_ssim, image_format=starts_format_image):161 """ Compare the already save image with the browser screen162 Compares the already saved image with the screen that is on the screen. If there is a difference, it saves the163 highlighted image to the: ../Save Image164 path1 = path to the image to be compared to screen165 Example: Compare screen ../image1.png166 """167 self._check_dir(save_folder)168 self._check_ssim(float(ssim))169 self._check_image_format(image_format)170 save_folder = self.save_folder171 self.seleniumlib.capture_page_screenshot(save_folder + "/testscreen.png")172 path2 = save_folder + "/testscreen.png"173 if os.path.exists(path1):174 if os.path.exists(path2):175 # Compare image176 self._compare_images(path1, path2)177 # Create frame in diff area178 for c in self.cnts:179 (x, y, w, h) = cv.boundingRect(c)180 cv.rectangle(self.img1, (x, y), (x + w, y + h), (0, 0, 255), 2)181 cv.rectangle(self.img2, (x, y), (x + w, y + h), (0, 0, 255), 2)182 # Show image183 self.robotlib.log_to_console(self.ssim)184 if float(self.score) < self.ssim:185 self.robotlib.log_to_console(self.ssim)186 img_diff = cv.hconcat([self.img1, self.img2])187 time_ = str(time.time())188 score_percen = float(self.score) * 100189 self.seleniumlib.capture_page_screenshot(190 save_folder + "/Img" + time_ + self.format191 )192 cv.imwrite(save_folder + "/Img" + time_ + self.format, img_diff)193 self.robotlib.fail("Image has diff: {} %".format(score_percen))194 else:195 img_diff = cv.hconcat([self.img1, self.img2])196 time_ = str(time.time())197 self.seleniumlib.capture_page_screenshot(198 save_folder + "/Img" + time_ + self.format199 )200 cv.imwrite(save_folder + "/Img" + time_ + self.format, img_diff)201 self.robotlib.log_to_console(202 "Image has diff: {} ".format(self.score)203 )204 else:205 raise AssertionError("Path2 doesnt found:" + path2)206 else:207 raise AssertionError("Path1 doesnt found" + path1)208 if os.path.exists(save_folder + "/testscreen.png"):209 os.remove(save_folder + "/testscreen.png")210 def create_area(211 self, x1, y1, x2, y2, save_folder=save_folder_path, screen_name="screen", image_format=starts_format_image212 ):213 """ Creates a cut-out from the screen214 Creates a cut-out from the screen that is on screen and saves it in the folder: ../Create area215 x1 a y1 = x and y coordinates for the upper left corner of the square216 x2 and y2 = x and y coordinates for the bottom right corner of the square217 Example: Compare making area 0 0 25 25218 """219 self._check_dir(save_folder)220 save_folder = self.save_folder221 self._check_image_format(image_format)222 self.seleniumlib.capture_page_screenshot(save_folder + '/testscreen.png')223 img = save_folder + '/testscreen.png'224 img_crop = cv.imread(img)225 crop_img = img_crop[226 int(x1): int(y2), int(y1): int(x2)227 ] # Crop from {x, y, w, h } => {0, 0, 300, 400}228 if screen_name == "screen":229 cv.imwrite(save_folder + '/screen' + str(time.time()) + self.format, crop_img)230 else:231 cv.imwrite(save_folder + '/' + screen_name + self.format, crop_img)232 def create_screens(233 self, *resolution, save_folder=save_folder_path, screen_name="screen", image_format=starts_format_image234 ):235 """ Creates a screenshot on the screen236 Creates a screenshot on the screen, that corresponds to the specified resolution, so it is possible to create on one237 page an infinite number of screens with different resolutions.238 Screens are stored in the folder: ../Create rescreens239 *resolutin = The specified resolution in width and height format, you can enter as many as needed240 Warning: When you create one screen, name will be screen.png, but when you create more than one screen from same 4241 page, name will be screen screen_name_width_height.png242 Example: compare making rescreens 800 600 1280 800 1440 900 Creates 3 screens in 800x600 1280x800 and 1440x90243 """244 self._check_dir(save_folder)245 save_folder = self.save_folder246 self._check_image_format(image_format)247 leng_reso = len(resolution)248 if leng_reso % 2 == 0:249 if (leng_reso / 2) == 1:250 self.seleniumlib.set_window_size(int(resolution[0]), int(resolution[1]))251 time.sleep(1)252 self.seleniumlib.capture_page_screenshot(253 save_folder254 + "/"255 + screen_name256 + self.format257 )258 else:259 x = leng_reso / 2260 i = 0261 a = 0262 while i < x:263 width = int(resolution[0 + a])264 height = int(resolution[1 + a])265 self.seleniumlib.set_window_size(width, height)266 time.sleep(1)267 self.seleniumlib.capture_page_screenshot(268 save_folder269 + "/"270 + screen_name271 + str(width)272 + "x"273 + str(height)274 + self.format275 )276 a += 2277 i += 1278 else:279 raise AssertionError("Bad numbers of resolution")280 def compare_screen_areas(281 self, x1, y1, x2, y2, path1, save_folder=save_folder_path, ssim=starts_ssim, image_format=starts_format_image282 ):283 """Creates a cut-out from the screen284 Creates a cut-out from the screen that is on the screen and compares it to a previously created285 x1 and y1 = x and y coordinates for the upper left corner of the square286 x2 and y2 = x and y coordinates for the bottom right corner of the square287 path1 = Path to an already created viewport with which we want to compare the viewport created by us288 Example: Compare screen area 0 0 25 25 ../Crop_Image1.png Creates Crop_Image1.png from 0, 0, 25, 25289 """290 self._check_dir(save_folder)291 self._check_ssim(ssim)292 self._check_image_format(image_format)293 save_folder = self.save_folder294 self.seleniumlib.capture_page_screenshot(save_folder + '/test1.png')295 path2 = save_folder + '/test1.png'296 if os.path.exists(path1):297 if os.path.exists(path2):298 # load img299 img1 = cv.imread(path1, 1) # img from docu300 img2 = cv.imread(path2, 1) # img from screenshot301 # convert to grey302 gray_img1 = cv.cvtColor(img1, cv.COLOR_BGR2GRAY)303 gray_img2 = cv.cvtColor(img2, cv.COLOR_BGR2GRAY)304 # spliting area305 crop_img = gray_img2[306 int(x1): int(y2), int(y1): int(x2)307 ] # Crop from {x, y, w, h } => {0, 0, 300, 400}308 # SSIM diff img309 (self.score, diff) = structural_similarity(310 gray_img1, crop_img, full=True311 )312 diff = (diff * 255).astype('uint8')313 # Threshold diff img314 thresh = cv.threshold(315 diff, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU316 )[1]317 cnts = cv.findContours(318 thresh.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE319 )320 cnts = imutils.grab_contours(cnts)321 crop_img_color = img2[int(x1): int(y2), int(y1): int(x2)]322 # Create frame in diff area323 for c in cnts:324 (x, y, w, h) = cv.boundingRect(c)325 cv.rectangle(img1, (x, y), (x + w, y + h), (0, 0, 255), 2)326 cv.rectangle(crop_img_color, (x, y), (x + w, y + h), (0, 0, 255), 2)327 # Show image328 if float(self.score) < self.ssim:329 self.robotlib = BuiltIn().get_library_instance('BuiltIn')330 img_diff = cv.hconcat([img1, crop_img_color])331 time_ = str(time.time())332 self.seleniumlib.capture_page_screenshot(333 save_folder + '/img' + time_ + '.png'334 )335 cv.imwrite(save_folder + '/img' + time_ + self.format, img_diff)336 self.robotlib.fail('Image has diff: {} '.format(self.score))337 score_percen = float(self.score) * +100338 self.robotlib.fail('Image has diff: {} %'.format(score_percen))339 else:340 img_diff = cv.hconcat([self.img1, self.img2])341 time_ = str(time.time())342 self.seleniumlib.capture_page_screenshot(343 save_folder + "/Img" + time_ + self.format344 )345 cv.imwrite(save_folder + "/Img" + time_ + self.format, img_diff)346 self.robotlib.log_to_console(347 "Image has diff: {} ".format(self.score)348 )349 else:350 raise AssertionError("New screen doesnt exist anymore")351 else:352 raise AssertionError("You put bad path")353 if os.path.exists(save_folder + '/test1.png'):354 os.remove(save_folder + '/test1.png')355 def compare_screen_without_areas(356 self, path1, *args, save_folder=save_folder_path, ssim=starts_ssim, image_format=starts_format_image357 ):358 """359 Compares two pictures, which have parts to be ignored360 x1 and y1 = x and y coordinates for the upper left corner of the ignored area square361 x2 and y2 = x and y coordinates for the lower right corner of the square of the ignored part362 Attention! It is always necessary to enter in order x1 y1 x2 y2 x1 y1 x2 y2 etc ...363 Compare screen without areas ../Image1.png 0 0 30 40 50 50 100 100364 Creates 2 ignored parts at 0,0, 30,40 and 50, 50, 100, 100365 """366 self._check_dir(save_folder)367 self._check_ssim(ssim)368 self._check_image_format(image_format)369 save_folder = self.save_folder370 self.seleniumlib.capture_page_screenshot(save_folder + "/test1.png")371 path2 = save_folder + "/test1.png"372 if os.path.exists(path1) and os.path.exists(path2):373 lt = len(args)374 img1 = cv.imread(path1, 1)375 img2 = cv.imread(path2, 1)376 if lt % 4 == 0:377 x = lt / 4378 self.robotlib.log_to_console(x)379 i = 0380 a = 0381 while i < x:382 color = (0, 0, 0)383 x1 = int(args[0 + a])384 y1 = int(args[1 + a])385 x2 = int(args[2 + a])386 y2 = int(args[3 + a])387 cv.rectangle(img1, (x1, y1), (x2, y2), color, -1)388 cv.rectangle(img2, (x1, y1), (x2, y2), color, -1)389 a += 4390 i += 1391 cv.namedWindow("image", cv.WINDOW_NORMAL)392 # convert to grey393 gray_img1 = cv.cvtColor(img1, cv.COLOR_BGR2GRAY)394 gray_img2 = cv.cvtColor(img2, cv.COLOR_BGR2GRAY)395 # SSIM diff Img396 (self.score, diff) = structural_similarity(397 gray_img1, gray_img2, full=True398 )399 diff = (diff * 255).astype("uint8")400 # Threshold diff Img401 thresh = cv.threshold(402 diff, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU403 )[1]404 cnts = cv.findContours(405 thresh.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE406 )407 cnts = imutils.grab_contours(cnts)408 # Create frame in diff area409 for c in cnts:410 (x, y, w, h) = cv.boundingRect(c)411 cv.rectangle(img1, (x, y), (x + w, y + h), (0, 0, 255), 2)412 cv.rectangle(img2, (x, y), (x + w, y + h), (0, 0, 255), 2)413 # Show image414 if float(self.score) < self.ssim:415 img_diff = cv.hconcat([img1, img2])416 time_ = str(time.time())417 self.seleniumlib.capture_page_screenshot(418 save_folder + "/Img" + time_ + self.format419 )420 cv.imwrite(save_folder + "/Img" + time_ + self.format, img_diff)421 self.robotlib.fail("Image has diff: {} ".format(self.score))422 else:423 img_diff = cv.hconcat([img1, img2])424 time_ = str(time.time())425 self.seleniumlib.capture_page_screenshot(426 save_folder + "/Img" + time_ + self.format427 )428 cv.imwrite(save_folder + "/Img" + time_ + self.format, img_diff)429 self.robotlib.log_to_console(430 "Image has diff: {} ".format(self.score)431 )432 else:433 raise AssertionError("Path doesnt exists")434 def compare_screen_get_information(435 self,436 path1,437 save_folder=save_folder_path,438 folder_csv="../CSV_ERROR",439 ssim=starts_ssim,440 image_format=starts_format_image441 ):442 """ Compare the already save image with the browser screen443 Compares the already saved image with the screen that is on the screen. If there is a difference, it saves the444 highlighted image to the: ../Save Image and making csv file with coordinates and elements which exist on this445 coordinates446 path1 = path to the image to be compared to screen447 Example: Compare screen ../image1.png448 """449 self._check_dir(save_folder)450 self._check_dir(folder_csv)451 self._check_ssim(ssim)452 self._check_image_format(image_format)453 save_folder = self.save_folder454 # Making screen455 self.seleniumlib.capture_page_screenshot(save_folder + "/test1.png")456 path2 = save_folder + "/test1.png"457 if os.path.exists(path1):458 if os.path.exists(path2):459 # load Img460 self._compare_images(path1, path2)461 # write coordinate462 with open(folder_csv + "/bug_coordinates.csv", "w") as csvfile:463 writer = csv.writer(csvfile)464 a = "path", "x_center", "y_center", "x", "y", "x1", "y1"465 writer.writerow(a)466 # Create frame in diff area467 for c in self.cnts:468 (x, y, w, h) = cv.boundingRect(c)469 cv.rectangle(self.img1, (x, y), (x + w, y + h), (0, 0, 255), 2)470 cv.rectangle(self.img2, (x, y), (x + w, y + h), (0, 0, 255), 2)471 x2 = x + w472 y2 = y + h473 x_center = x + ((x2 - x) / 2)474 y_center = y + ((y2 - y) / 2)475 f = path1, x_center, y_center, x, y, x2, y2476 writer.writerow(f)477 # Save image and show report478 if float(self.score) < self.ssim:479 img_diff = cv.hconcat([self.img1, self.img2])480 time_ = str(time.time())481 self.seleniumlib.capture_page_screenshot(482 save_folder + "/Img{0}.{1}".format(time_, self.format)483 )484 cv.imwrite(save_folder + "/Img{0}.{1}".format(time_, self.format), img_diff)485 # start reading coordinates and saving element from coordinate486 df = pd.read_csv(r"" + folder_csv + "/bug_coordinates.csv")487 with open(488 folder_csv + "/bug_co_and_name{0}.csv".format(str(time.time())),489 "w",490 ) as csv_name:491 writer = csv.writer(csv_name)492 a = "web-page", "x_center", "y_center", "class", "id", "name"493 writer.writerow(a)494 # Get information from position495 for i in range(len(df)):...
_utils.py
Source:_utils.py
...25 elementValue = self.get_text_custom(xmlLocator)26 logger.info("Element Value %s" % elementValue)27 counter += 128 if (elementValue == text):29 self.seleniumlib.capture_page_screenshot()30 break31 elif (elementValue == "Error"):32 self.seleniumlib.capture_page_screenshot()33 raise ValueError("An error has occured!")34 elif (elementValue == "Queued") and (counter == 5):35 self.seleniumlib.capture_page_screenshot()36 break37 elif (counter > 120):38 self.seleniumlib.capture_page_screenshot()39 raise ValueError(("Expected value %s is not on screen") % (text))40 else:41 continue42 def _log_url_to_tracking_file(self):43 logUrls = self.builtIn.get_variable_value('${logUrls}')44 if logUrls == "Enabled":45 uiXmlContext = self.builtIn.get_variable_value('${uiXmlContext}')46 currentUrl = self.seleniumlib.get_location()47 suite = self.builtIn.get_variable_value('${SUITE_SOURCE}')48 test = self.builtIn.get_variable_value('${TEST_NAME}')49 fileName = os.path.join(os.path.expanduser('~'), "pageCoverage.csv")50 fo = open(fileName, "ab")51 #self.builtIn.log((("Appending to File: %s") % (fileName)), "INFO")52 baseUrl = self.__trunc_at(currentUrl, "/" , 3)...
AllureSeleniumPlugin.py
Source:AllureSeleniumPlugin.py
2from SeleniumLibrary import ScreenshotKeywords3from SeleniumLibrary.base import keyword, LibraryComponent4class AllureSeleniumPlugin(LibraryComponent):5 @keyword6 def capture_page_screenshot(self, filename='selenium-screenshot-{index}.png'):7 path = ScreenshotKeywords(ctx=self.ctx).capture_page_screenshot(filename)...
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!!