Best JavaScript code snippet using differencify
status.py
Source:status.py
1#!/usr/bin/python2#-*- coding:utf-8 -*-3# Copyright (C) 2011 ~ 2012 Deepin, Inc.4# 2011 ~ 2012 Long Changjin5# 6# Author: Long Changjin <admin@longchangjin.cn>7# Maintainer: Long Changjin <admin@longchangjin.cn>8# 9# This program is free software: you can redistribute it and/or modify10# it under the terms of the GNU General Public License as published by11# the Free Software Foundation, either version 3 of the License, or12# any later version.13# 14# This program is distributed in the hope that it will be useful,15# but WITHOUT ANY WARRANTY; without even the implied warranty of16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the17# GNU General Public License for more details.18# 19# You should have received a copy of the GNU General Public License20# along with this program. If not, see <http://www.gnu.org/licenses/>.21from constant import *22from action import *23import utils24class BaseProcess():25 ''' BaseProcess Class. it must be inherited and refactored'''26 def __init__(self, screenshot=None, window=None):27 '''28 init process29 @param screenshot: a Screenshot object30 @param window: a RootWindow object31 '''32 self.screenshot = screenshot33 self.win = window34 self.event = None35 self.func_map = {36 ACTION_INIT: self.action_init,37 ACTION_ARROW: self.action_arrow,38 ACTION_ELLIPSE: self.action_ellipse,39 ACTION_LINE: self.action_line,40 ACTION_RECTANGLE: self.action_rectangle,41 ACTION_SELECT: self.action_select,42 ACTION_TEXT: self.action_text,43 ACTION_WINDOW: self.action_window,44 None: self._none_action}45 46 def update(self, event):47 '''48 update event info49 @param event: a gtk.gdk.Event50 '''51 self.event = event52 53 def action_init(self, screenshot, event):54 '''55 process the in event in ACTION_INIT status56 @param screenshot: a Screenshot object57 @param event: a gtk.gdk.Event58 '''59 pass60 61 def action_arrow(self, screenshot, event):62 '''63 process the in event in ACTION_ARROW status64 @param screenshot: a Screenshot object65 @param event: a gtk.gdk.Event66 '''67 pass68 69 def action_ellipse(self, screenshot, event):70 '''71 process the in event in ACTION_ELLIPSE status72 @param screenshot: a Screenshot object73 @param event: a gtk.gdk.Event74 '''75 pass76 77 def action_line(self, screenshot, event):78 '''79 process the in event in ACTION_LINE status80 @param screenshot: a Screenshot object81 @param event: a gtk.gdk.Event82 '''83 pass84 85 def action_rectangle(self, screenshot, event):86 '''87 process the in event in ACTION_RECTANGLE status88 @param screenshot: a Screenshot object89 @param event: a gtk.gdk.Event90 '''91 pass92 93 def action_select(self, screenshot, event):94 '''95 process the in event in ACTION_SELECT status96 @param screenshot: a Screenshot object97 @param event: a gtk.gdk.Event98 '''99 pass100 101 def action_text(self, screenshot, event):102 '''103 process the in event in ACTION_TEXT status104 @param screenshot: a Screenshot object105 @param event: a gtk.gdk.Event106 '''107 pass108 109 def action_window(self, screenshot, event):110 '''111 process the in event in ACTION_WINDOW status112 @param screenshot: a Screenshot object113 @param event: a gtk.gdk.Event114 '''115 pass116 117 def _none_action(self, *arg):118 ''' process the in event in Action None status '''119 pass120 121class ButtonPressProcess(BaseProcess):122 ''' buton press status class'''123 def __init__(self, screenshot=None, window=None):124 BaseProcess.__init__(self, screenshot, window)125 def process(self):126 '''Press process button press event'''127 if self.event is None:128 return129 if self.screenshot.show_text_window_flag:130 allocation = self.screenshot.text_window.allocation131 text_view_x = allocation.x + self.screenshot.monitor_x132 text_view_y = allocation.y + self.screenshot.monitor_y133 # in text view area, ignore134 if text_view_x <= self.event.x_root <= text_view_x + allocation.width \135 and text_view_y <= self.event.y_root <= text_view_y + allocation.height:136 return137 if self.event.button == BUTTON_EVENT_LEFT:138 self.screenshot.drag_flag = True139 self.func_map[self.screenshot.action](self.screenshot, self.event)140 self.adjust(self.screenshot, self.event)141 elif self.event.button == BUTTON_EVENT_RIGHT:142 ev = self.event143 screenshot = self.screenshot144 if screenshot.window_flag: # has not select area, press right button quit145 self.win.quit()146 if is_in_rect((ev.x_root, ev.y_root), screenshot.get_rectangel()):147 self.win.make_menu((int(ev.x_root), int(ev.y_root))) # popup menu148 else:149 while screenshot.action_list:150 screenshot.action_list.pop()151 while screenshot.text_action_list:152 screenshot.text_action_list.pop()153 screenshot.text_action_info.clear()154 screenshot.undo()155 156 def action_window(self, screenshot, event):157 '''Press ACTION_WINDOW '''158 screenshot.window_flag = False159 def action_init(self, screenshot, event):160 '''Press ACTION_INIT '''161 (screenshot.x, screenshot.y) = self.win.get_event_coord(event)162 def action_select(self, screenshot, event):163 '''Press ACTION_SELECT '''164 # Init drag position.165 screenshot.drag_position = self.win.get_position(event)166 # Set cursor.167 self.win.set_cursor(screenshot.drag_position)168 # Get drag coord and offset.169 (screenshot.dragStartX, screenshot.dragStartY) = self.win.get_event_coord(event)170 screenshot.dragStartOffsetX = screenshot.dragStartX - screenshot.x171 screenshot.dragStartOffsetY = screenshot.dragStartY - screenshot.y172 def action_rectangle(self, screenshot, event):173 '''Press ACTION_RECTANGLE '''174 # Just create new action when drag position at inside of select area.175 if self.win.get_position(event) == DRAG_INSIDE:176 screenshot.current_action = RectangleAction(ACTION_RECTANGLE, screenshot.action_size, screenshot.action_color)177 # calculate the coord in the window178 #event_coord = self.win.get_event_coord(event)179 #action_x = event_coord[0] - screenshot.monitor_x180 #action_y = event_coord[1] - screenshot.monitor_y181 (action_x, action_y) = self.win.get_event_coord_in_monitor(event)182 screenshot.current_action.start_draw((action_x, action_y))183 184 def action_ellipse(self, screenshot, event):185 '''Press ACTION_ELLIPSE '''186 # Just create new action when drag position at inside of select area.187 if self.win.get_position(event) == DRAG_INSIDE:188 screenshot.current_action = EllipseAction(ACTION_ELLIPSE, screenshot.action_size, screenshot.action_color)189 # calculate the coord in the window190 #event_coord = self.win.get_event_coord(event)191 #action_x = event_coord[0] - screenshot.monitor_x192 #action_y = event_coord[1] - screenshot.monitor_y193 (action_x, action_y) = self.win.get_event_coord_in_monitor(event)194 screenshot.current_action.start_draw((action_x, action_y))195 def action_arrow(self, screenshot, event):196 '''Press ACTION_ARROW '''197 # Just create new action when drag position at inside of select area.198 if self.win.get_position(event) == DRAG_INSIDE:199 screenshot.current_action = ArrowAction(ACTION_ARROW, screenshot.action_size, screenshot.action_color)200 # calculate the coord in the window201 #event_coord = self.win.get_event_coord(event)202 #action_x = event_coord[0] - screenshot.monitor_x203 #action_y = event_coord[1] - screenshot.monitor_y204 (action_x, action_y) = self.win.get_event_coord_in_monitor(event)205 screenshot.current_action.start_draw((action_x, action_y))206 def action_line(self, screenshot, event):207 '''Press ACTION_LINE '''208 # Just create new action when drag position at inside of select area.209 if self.win.get_position(event) == DRAG_INSIDE:210 screenshot.current_action = LineAction(ACTION_LINE, screenshot.action_size, screenshot.action_color)211 # calculate the coord in the window212 #event_coord = self.win.get_event_coord(event)213 #action_x = event_coord[0] - screenshot.monitor_x214 #action_y = event_coord[1] - screenshot.monitor_y215 (action_x, action_y) = self.win.get_event_coord_in_monitor(event)216 screenshot.current_action.start_draw((action_x, action_y))217 def action_text(self, screenshot, event):218 '''Press ACTION_TEXT '''219 if screenshot.show_text_window_flag: # complete input text, changed action to None220 self.win.save_text_window()221 self.screenshot.toolbar.set_button_active("text", False)222 self.screenshot.current_text_action = None223 else: # create a new text224 # calculate the coord in the window225 #event_coord = self.win.get_event_coord(event)226 #action_x = event_coord[0] - screenshot.monitor_x227 #action_y = event_coord[1] - screenshot.monitor_y228 (action_x, action_y) = self.win.get_event_coord_in_monitor(event)229 self.win.show_text_window((action_x, action_y))230 def adjust(self, screenshot, event):231 '''Press adjust '''232 if screenshot.action in [ACTION_RECTANGLE, ACTION_ELLIPSE, ACTION_ARROW, ACTION_LINE] \233 and screenshot.show_toolbar_flag \234 and screenshot.y < screenshot.toolbarY < screenshot.y + screenshot.rect_height:235 self.win.hide_toolbar()236 self.win.hide_colorbar()237 # drag text 238 if screenshot.current_text_action and screenshot.action is None:239 # calculate the coord in the window240 #event_coord = self.win.get_event_coord(event)241 #currentX = event_coord[0] - screenshot.monitor_x242 #currentY = event_coord[1] - screenshot.monitor_y243 currentX, currentY = self.win.get_event_coord_in_monitor(event)244 drawTextX,drawTextY = screenshot.current_text_action.get_layout_info()[:2]245 screenshot.textDragOffsetX = currentX - drawTextX246 screenshot.textDragOffsetY = currentY - drawTextY247 screenshot.text_drag_flag = True 248class ButtonReleaseProcess(BaseProcess):249 ''' button release process'''250 def __init__(self, screenshot=None, window=None):251 BaseProcess.__init__(self, screenshot, window)252 253 def process(self):254 '''Release process button release event'''255 if self.event is None:256 return257 if self.event.button == BUTTON_EVENT_LEFT:258 self.screenshot.text_drag_flag = False259 self.screenshot.drag_flag = False260 self.func_map[self.screenshot.action](self.screenshot, self.event)261 self.adjust(self.screenshot, self.event)262 def action_window(self, screenshot, event):263 '''Release ACTION_WINDOW'''264 if screenshot.rect_width > 5 and screenshot.rect_height > 5:265 self.win.show_toolbar()266 self.win.adjust_toolbar()267 screenshot.action = ACTION_SELECT268 self.win.refresh()269 else:270 screenshot.window_flag = True271 272 def action_init(self, screenshot, event):273 '''Release ACTION_INIT'''274 screenshot.action = ACTION_SELECT275 (ex, ey) = self.win.get_event_coord(event)276 # Adjust rectangle when button release.277 if ex > screenshot.x:278 screenshot.rect_width = ex - screenshot.x279 else:280 screenshot.rect_width = abs(ex - screenshot.x)281 screenshot.x = max(ex, screenshot.monitor_x)282 if ey > screenshot.y:283 screenshot.rect_height = ey - screenshot.y284 else:285 screenshot.rect_height = abs(ey - screenshot.y)286 screenshot.y = max(ey, screenshot.monitor_y)287 # min rect 2 * 2288 if screenshot.rect_width < 2:289 screenshot.rect_width = 2290 if screenshot.rect_width + screenshot.x > screenshot.width:291 screenshot.x = screenshot.width - screenshot.rect_width292 if screenshot.rect_height < 2:293 screenshot.rect_height = 2294 if screenshot.rect_height + screenshot.y > screenshot.height:295 screenshot.y = screenshot.height - screenshot.rect_height296 self.win.refresh()297 self.win.show_toolbar()298 self.win.adjust_toolbar()299 def action_select(self, screenshot, event):300 '''Release ACTION_SELECT '''301 # min rect 2 * 2302 if screenshot.rect_width < 2:303 screenshot.rect_width = 2304 if screenshot.rect_width + screenshot.x > screenshot.width:305 screenshot.x = screenshot.width - screenshot.rect_width306 if screenshot.rect_height < 2:307 screenshot.rect_height = 2308 if screenshot.rect_height + screenshot.y > screenshot.height:309 screenshot.y = screenshot.height - screenshot.rect_height310 self.win.refresh()311 312 def action_rectangle(self, screenshot, event):313 '''Release ACTION_RECTANGLE '''314 if screenshot.current_action:315 # calculate the coord in the window316 #event_coord = self.win.get_event_coord(event)317 #action_x = event_coord[0] - screenshot.monitor_x318 #action_y = event_coord[1] - screenshot.monitor_y319 (action_x, action_y) = self.win.get_event_coord_in_monitor(event)320 screenshot.current_action.end_draw((action_x, action_y), screenshot.get_rectangel_in_monitor())321 screenshot.action_list.append(screenshot.current_action)322 screenshot.current_action = None323 self.win.refresh()324 def action_ellipse(self, screenshot, event):325 '''Release ACTION_ELLIPSE '''326 if screenshot.current_action:327 #event_coord = self.win.get_event_coord(event)328 #action_x = event_coord[0] - screenshot.monitor_x329 #action_y = event_coord[1] - screenshot.monitor_y330 (action_x, action_y) = self.win.get_event_coord_in_monitor(event)331 screenshot.current_action.end_draw((action_x, action_y), screenshot.get_rectangel_in_monitor())332 screenshot.action_list.append(screenshot.current_action)333 screenshot.current_action = None334 self.win.refresh()335 def action_arrow(self, screenshot, event):336 '''Release ACTION_ARROW '''337 if screenshot.current_action:338 #event_coord = self.win.get_event_coord(event)339 #action_x = event_coord[0] - screenshot.monitor_x340 #action_y = event_coord[1] - screenshot.monitor_y341 (action_x, action_y) = self.win.get_event_coord_in_monitor(event)342 screenshot.current_action.end_draw((action_x, action_y), screenshot.get_rectangel_in_monitor())343 screenshot.action_list.append(screenshot.current_action)344 screenshot.current_action = None345 self.win.refresh()346 def action_line(self, screenshot, event):347 '''Release ACTION_LINE '''348 if screenshot.current_action:349 #event_coord = self.win.get_event_coord(event)350 #action_x = event_coord[0] - screenshot.monitor_x351 #action_y = event_coord[1] - screenshot.monitor_y352 (action_x, action_y) = self.win.get_event_coord_in_monitor(event)353 screenshot.current_action.end_draw((action_x, action_y), screenshot.get_rectangel_in_monitor())354 screenshot.action_list.append(screenshot.current_action)355 screenshot.current_action = None356 self.win.refresh()357 358 def adjust(self, screenshot, event):359 '''Release adjust '''360 if screenshot.action in [ACTION_RECTANGLE, ACTION_ELLIPSE, ACTION_ARROW, ACTION_LINE, ACTION_TEXT] \361 and not screenshot.show_toolbar_flag \362 and screenshot.y < screenshot.toolbarY < screenshot.y + screenshot.rect_height:363 self.win.show_toolbar()364 self.win.adjust_toolbar()365 self.win.show_colorbar()366 self.win.adjust_colorbar()367class MotionProcess(BaseProcess):368 ''' Motion process'''369 def __init__(self, screenshot=None, window=None):370 BaseProcess.__init__(self, screenshot, window)371 372 def process(self):373 '''Motion process motion event'''374 if self.event is None:375 return376 self.func_map[self.screenshot.action](self.screenshot, self.event)377 self.adjust(self.screenshot, self.event)378 def action_window(self, screenshot, event):379 '''Motion ACTION_WINDOW'''380 # can drag and has selected area381 if screenshot.drag_flag and not screenshot.window_flag:382 (ex, ey) = self.win.get_event_coord(event)383 screenshot.action = ACTION_INIT384 (screenshot.x, screenshot.y) = self.win.get_event_coord(event)385 self.win.refresh()386 else: # update magnifier387 size = "%d x %d " % (screenshot.rect_width, screenshot.rect_height)388 rgb = utils.get_coord_rgb(screenshot, event.x, event.y)389 self.win.update_magnifier(event.x, event.y, size=size, rgb=str(rgb))390 391 def action_init(self, screenshot, event):392 '''Motion ACTION_INIT'''393 if screenshot.drag_flag:394 (ex, ey) = self.win.get_event_coord(event)395 (screenshot.rect_width, screenshot.rect_height) = (ex - screenshot.x, ey - screenshot.y)396 self.win.refresh()397 else:398 pass399 def action_select(self, screenshot, event):400 '''Motion ACTION_SELECT '''401 # drag the selected area402 if screenshot.drag_flag:403 (ex, ey) = self.win.get_event_coord(event)404 if screenshot.drag_position == DRAG_INSIDE:405 screenshot.x = min(max(ex - screenshot.dragStartOffsetX, screenshot.monitor_x),406 screenshot.monitor_x + screenshot.width - screenshot.rect_width)407 screenshot.y = min(max(ey - screenshot.dragStartOffsetY, screenshot.monitor_y),408 screenshot.monitor_y + screenshot.height - screenshot.rect_height)409 elif screenshot.drag_position == DRAG_TOP_SIDE:410 self.win.drag_frame_top(ex, ey)411 elif screenshot.drag_position == DRAG_BOTTOM_SIDE:412 self.win.drag_frame_bottom(ex, ey)413 elif screenshot.drag_position == DRAG_LEFT_SIDE:414 self.win.drag_frame_left(ex, ey)415 elif screenshot.drag_position == DRAG_RIGHT_SIDE:416 self.win.drag_frame_right(ex, ey)417 elif screenshot.drag_position == DRAG_TOP_LEFT_CORNER:418 self.win.drag_frame_top(ex, ey)419 self.win.drag_frame_left(ex, ey)420 elif screenshot.drag_position == DRAG_TOP_RIGHT_CORNER:421 self.win.drag_frame_top(ex, ey)422 self.win.drag_frame_right(ex, ey)423 elif screenshot.drag_position == DRAG_BOTTOM_LEFT_CORNER:424 self.win.drag_frame_bottom(ex, ey)425 self.win.drag_frame_left(ex, ey)426 elif screenshot.drag_position == DRAG_BOTTOM_RIGHT_CORNER:427 self.win.drag_frame_bottom(ex, ey)428 self.win.drag_frame_right(ex, ey) 429 self.win.refresh()430 self.win.show_toolbar()431 self.win.adjust_toolbar()432 else:433 screenshot.drag_position = self.win.get_position(event)434 # to avoid set cursor again435 if screenshot.last_drag_position != screenshot.drag_position:436 screenshot.last_drag_position = screenshot.drag_position437 self.win.set_cursor(screenshot.drag_position)438 439 def action_rectangle(self, screenshot, event):440 '''Motion ACTION_RECTANGLE '''441 if screenshot.drag_flag and screenshot.current_action:442 #event_coord = self.win.get_event_coord(event)443 #ex = event_coord[0] - screenshot.monitor_x444 #ey = event_coord[1] - screenshot.monitor_y445 (ex, ey) = self.win.get_event_coord_in_monitor(event)446 screenshot.current_action.drawing((ex, ey), screenshot.get_rectangel_in_monitor())447 self.win.refresh()448 else:449 pass450 def action_ellipse(self, screenshot, event):451 '''Motion ACTION_ELLIPSE '''452 if screenshot.drag_flag and screenshot.current_action:453 #event_coord = self.win.get_event_coord(event)454 #ex = event_coord[0] - screenshot.monitor_x455 #ey = event_coord[1] - screenshot.monitor_y456 (ex, ey) = self.win.get_event_coord_in_monitor(event)457 screenshot.current_action.drawing((ex, ey), screenshot.get_rectangel_in_monitor())458 self.win.refresh()459 else:460 pass461 def action_arrow(self, screenshot, event):462 '''Motion ACTION_ARROW '''463 if screenshot.drag_flag and screenshot.current_action:464 #event_coord = self.win.get_event_coord(event)465 #ex = event_coord[0] - screenshot.monitor_x466 #ey = event_coord[1] - screenshot.monitor_y467 (ex, ey) = self.win.get_event_coord_in_monitor(event)468 screenshot.current_action.drawing((ex, ey), screenshot.get_rectangel_in_monitor())469 self.win.refresh()470 else:471 pass472 def action_line(self, screenshot, event):473 '''Motion ACTION_LINE '''474 if screenshot.drag_flag and screenshot.current_action:475 #event_coord = self.win.get_event_coord(event)476 #ex = event_coord[0] - screenshot.monitor_x477 #ey = event_coord[1] - screenshot.monitor_y478 (ex, ey) = self.win.get_event_coord_in_monitor(event)479 screenshot.current_action.drawing((ex, ey), screenshot.get_rectangel_in_monitor())480 self.win.refresh()481 else:482 pass483 def adjust(self, screenshot, event):484 '''Motion adjust '''485 # can't drag and has not selected area486 if not screenshot.drag_flag and screenshot.window_flag:487 self.win.hide_toolbar()488 (wx, wy) = self.win.get_event_coord(event)489 for each in screenshot.screenshot_window_info:490 if each.x <= wx <= (each.x + each.width) and each.y <= wy <= (each.y + each.height):491 screenshot.x = each.x492 screenshot.y = each.y493 screenshot.rect_width = each.width494 screenshot.rect_height = each.height495 break496 self.win.refresh()497 498 # input text over499 if screenshot.action is None:500 (tx, ty) = self.win.get_event_coord_in_monitor(event) 501 # drag text502 if screenshot.text_drag_flag and screenshot.current_text_action:503 layout_info = screenshot.current_text_action.get_layout_info()504 des_x = tx - screenshot.textDragOffsetX505 des_y = ty - screenshot.textDragOffsetY506 if des_x < screenshot.x - screenshot.monitor_x: # left507 des_x = screenshot.x - screenshot.monitor_x508 elif des_x + layout_info[2] > screenshot.x - screenshot.monitor_x + screenshot.rect_width: # right509 des_x = screenshot.x - screenshot.monitor_x + screenshot.rect_width - layout_info[2]510 if des_y < screenshot.y - screenshot.monitor_y: # top511 des_y = screenshot.y - screenshot.monitor_y512 elif des_y + layout_info[3] > screenshot.y - screenshot.monitor_y + screenshot.rect_height: # bottom513 des_y = screenshot.y - screenshot.monitor_y + screenshot.rect_height - layout_info[3]514 screenshot.current_text_action.update_coord(des_x, des_y)515 screenshot.draw_text_layout_flag = True516 self.win.refresh()517 else:518 for each, info in screenshot.text_action_info.items():519 if screenshot.text_drag_flag: # has draged a text already520 break521 if info[0] <= tx <= info[0]+info[2] and info[1] <= ty <= info[1]+info[3]:522 screenshot.current_text_action = each523 524 if screenshot.current_text_action:525 drawTextX, drawTextY, drawTextWidth, drawTextHeight = screenshot.current_text_action.get_layout_info()526 if drawTextX <= tx <= drawTextX + drawTextWidth and drawTextY <= ty <= drawTextY + drawTextHeight:527 screenshot.draw_text_layout_flag = True528 self.win.set_cursor('drag')529 self.win.refresh()530 elif not screenshot.text_drag_flag: # drag text over, and not in text rectangle531 screenshot.draw_text_layout_flag = False 532 screenshot.current_text_action = None533 self.win.set_cursor(screenshot.action)...
screenshot.py
Source:screenshot.py
...29#------------------------------------------------------------------30driver = webdriver.Chrome(DRIVER, chrome_options = chrome_options)31driver.get('https://p2p.danamas.co.id/')32time.sleep(5)33screenshot = driver.save_screenshot('FolderPNG/danamas.png')34time.sleep(2)35driver.get('https://www.investree.id/')36time.sleep(5)37screenshot = driver.save_screenshot('FolderPNG/investree.png')38time.sleep(2)39driver.get('https://amartha.com/')40driver.execute_script("window.scrollTo(0, 500)") 41time.sleep(5)42screenshot = driver.save_screenshot('FolderPNG/amartha.png')43time.sleep(2)44driver.get('https://www.dompetkilat.co.id/')45time.sleep(5)46screenshot = driver.save_screenshot('FolderPNG/dompetkilat.png')47time.sleep(2)48driver.get('http://kimo.co.id/')49driver.execute_script("window.scrollTo(0, 450)") 50time.sleep(5)51screenshot = driver.save_screenshot('FolderPNG/kimo.png')52time.sleep(2)53driver.get('https://www.tokomodal.co.id/')54time.sleep(5)55screenshot = driver.save_screenshot('FolderPNG/tokomodal.png')56time.sleep(2)57driver.get('https://uangteman.com/')58time.sleep(5)59screenshot = driver.save_screenshot('FolderPNG/uangteman.png')60time.sleep(2)61driver.get('https://koinworks.com/')62time.sleep(5)63screenshot = driver.save_screenshot('FolderPNG/koinworks.png')64time.sleep(2)65driver.get('https://modalku.co.id/')66time.sleep(5)67screenshot = driver.save_screenshot('FolderPNG/modalku.png')68time.sleep(2)69driver.get('http://www.pendanaan.com/')70time.sleep(5)71screenshot = driver.save_screenshot('FolderPNG/pendanaan.png')72time.sleep(2)73driver.get('https://www.awantunai.com/')74time.sleep(5)75screenshot = driver.save_screenshot('FolderPNG/awantunai.png')76time.sleep(2)77driver.get('https://klikacc.com/')78time.sleep(5)79screenshot = driver.save_screenshot('FolderPNG/klikacc.png')80time.sleep(2)81driver.get('https://crowdo.co.id/')82time.sleep(5)83screenshot = driver.save_screenshot('FolderPNG/crowdo.png')84time.sleep(2)85driver.get('https://www.akseleran.com/')86time.sleep(5)87screenshot = driver.save_screenshot('FolderPNG/akseleran.png')88time.sleep(2)89driver.get('https://www.taralite.com/')90time.sleep(5)91screenshot = driver.save_screenshot('FolderPNG/teralite.png')92time.sleep(2)93driver.get('http://fintag.id/')94time.sleep(5)95screenshot = driver.save_screenshot('FolderPNG/fintag.png')96time.sleep(2)97driver.get('http://invoila.co.id/')98time.sleep(5)99screenshot = driver.save_screenshot('FolderPNG/invoila.png')100time.sleep(2)101driver.get('https://www.tunaikita.com/')102driver.execute_script("window.scrollTo(0, 800)") 103time.sleep(5)104screenshot = driver.save_screenshot('FolderPNG/tunaikita.png')105time.sleep(2)106driver.get('https://igrow.asia/')107driver.execute_script("window.scrollTo(0, 2800)") 108time.sleep(5)109screenshot = driver.save_screenshot('FolderPNG/igrow.png')110time.sleep(2)111driver.get('https://www.cicil.co.id/')112time.sleep(5)113screenshot = driver.save_screenshot('FolderPNG/cicil.png')114time.sleep(2)115driver.get('http://danamerdeka.co.id/')116driver.execute_script("window.scrollTo(0, 500)") 117time.sleep(5)118screenshot = driver.save_screenshot('FolderPNG/danamerdeka.png')119time.sleep(2)120driver.get('https://cashwagon.id/')121time.sleep(5)122screenshot = driver.save_screenshot('FolderPNG/cashwagon.png')123time.sleep(2)124driver.get('https://www.estakapital.co.id/')125driver.execute_script("document.body.style.zoom='70%'")126time.sleep(5)127screenshot = driver.save_screenshot('FolderPNG/estacapital.png')128time.sleep(2)129driver.get('https://ammana.id/')130time.sleep(5)131screenshot = driver.save_screenshot('FolderPNG/ammana.png')132time.sleep(2)133driver.get('https://gradana.co.id/')134time.sleep(5)135screenshot = driver.save_screenshot('FolderPNG/noinfo_gradana.png')136time.sleep(2)137driver.get('http://www.danamapan.id/')138time.sleep(5)139screenshot = driver.save_screenshot('FolderPNG/noinfo_danamapan.png')140time.sleep(2)141driver.get('http://www.aktivaku.com/')142time.sleep(5)143screenshot = driver.save_screenshot('FolderPNG/aktivaku.png')144time.sleep(2)145driver.get('https://danakini.co.id/')146wait = WebDriverWait(driver, 10)147element = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.pum-close.popmake-close"))).click()148driver.execute_script("window.scrollTo(0, 2200)") 149time.sleep(5)150screenshot = driver.save_screenshot('FolderPNG/danakini.png')151time.sleep(2)152driver.get('https://www.finmas.co.id/')153time.sleep(5)154screenshot = driver.save_screenshot('FolderPNG/finmas.png')155time.sleep(2)156driver.get('http://indodana.id/')157time.sleep(5)158screenshot = driver.save_screenshot('FolderPNG/indodana.png')159time.sleep(2)160driver.get('https://www.kredivo.id/')161time.sleep(5)162screenshot = driver.save_screenshot('FolderPNG/kredivo.png')163time.sleep(2)164driver.get('https://mekar.id/')165time.sleep(5)166screenshot = driver.save_screenshot('FolderPNG/mekar.png')167time.sleep(2)168driver.get('https://www.pinjamango.co.id/')169time.sleep(5)170screenshot = driver.save_screenshot('FolderPNG/pinjamango.png')171time.sleep(2)172driver.get('https://iternak.id/')173time.sleep(5)174screenshot = driver.save_screenshot('FolderPNG/iternak.png')175time.sleep(2)176driver.get('http://kreditpintar.co.id/')177time.sleep(5)178screenshot = driver.save_screenshot('FolderPNG/kreditpintar.png')179time.sleep(2)180driver.get('https://kredito.id/')181time.sleep(5)182screenshot = driver.save_screenshot('FolderPNG/kredito.png')183time.sleep(2)184driver.get('https://crowdo.co.id/')185time.sleep(5)186screenshot = driver.save_screenshot('FolderPNG/crowdo.png')187time.sleep(2)188driver.get('http://www.kreditplusteknologi.id/')189time.sleep(5)190screenshot = driver.save_screenshot('FolderPNG/kreditplusteknologi.png')191time.sleep(2)192driver.get('https://tanifund.com/')193time.sleep(5)194screenshot = driver.save_screenshot('FolderPNG/tanifund.png')195time.sleep(2)196driver.get('https://m.danain.co.id/beranda')197element = driver.find_element_by_css_selector('div.no-padding-bottom')198driver.execute_script("arguments[0].scrollIntoView()", element)199time.sleep(5)200screenshot = driver.save_screenshot('FolderPNG/danain.png')201time.sleep(2)202driver.get('https://indofund.id/')203time.sleep(5)204screenshot = driver.save_screenshot('FolderPNG/indofund.png')205time.sleep(2)206driver.get('http://kreditpro.id/')207time.sleep(5)208screenshot = driver.save_screenshot('FolderPNG/kreditpro.png')209time.sleep(2)210driver.get('http://www.avantee.co.id/')211driver.execute_script("window.scrollTo(0, 700)") 212time.sleep(5)213screenshot = driver.save_screenshot('FolderPNG/avantee.png')214time.sleep(2)215driver.get('http://www.do-it.id/')216time.sleep(5)217screenshot = driver.save_screenshot('FolderPNG/do-it.png')218time.sleep(2)219driver.get('http://www.rupiahcepat.co.id/')220time.sleep(5)221screenshot = driver.save_screenshot('FolderPNG/rupiahcepat.png')222time.sleep(2)223driver.get('http://www.danarupiah.id/')224time.sleep(5)225screenshot = driver.save_screenshot('FolderPNG/danarupiah.png')226time.sleep(2)227driver.get('http://danabijak.co.id/')228time.sleep(5)229screenshot = driver.save_screenshot('FolderPNG/danabijak.png')230time.sleep(2)231driver.get('http://cashcepat.id/')232time.sleep(5)233screenshot = driver.save_screenshot('FolderPNG/cashcepat.png')234time.sleep(2)235driver.get('http://danalaut.id/')236time.sleep(5)237screenshot = driver.save_screenshot('FolderPNG/noinfo_danalaut.png')238time.sleep(2)239driver.get('http://danasyariah.id/')240driver.execute_script("window.scrollTo(0, 750)") 241time.sleep(5)242screenshot = driver.save_screenshot('FolderPNG/danasyariah.png')243time.sleep(2)244driver.get('http://telefin.co.id/')245driver.execute_script("window.scrollTo(0, 200)") 246time.sleep(5)247screenshot = driver.save_screenshot('FolderPNG/telefin.png')248time.sleep(2)249driver.get('http://modalrakyat.id/')250time.sleep(5)251screenshot = driver.save_screenshot('FolderPNG/modalrakyat.png')252time.sleep(2)253driver.get('http://kawancicil.co.id/')254time.sleep(5)255screenshot = driver.save_screenshot('FolderPNG/kawancicil.png')256time.sleep(2)257driver.get('http://sanders.co.id/')258time.sleep(5)259screenshot = driver.save_screenshot('FolderPNG/sanders.png')260time.sleep(2)261driver.get('http://kreditcepat.co.id/')262time.sleep(5)263screenshot = driver.save_screenshot('FolderPNG/kreditcepat.png')264time.sleep(2)265driver.get('http://uangme.id/')266time.sleep(5)267screenshot = driver.save_screenshot('FolderPNG/uangme.png')268time.sleep(2)269driver.get('http://pinjamduit.co.id/')270time.sleep(5)271screenshot = driver.save_screenshot('FolderPNG/noinfo_pinjamduit.png')272time.sleep(2)273driver.get('http://www.pinjamyuk.co.id/')274driver.execute_script("document.body.style.zoom='80%'")275time.sleep(5)276screenshot = driver.save_screenshot('FolderPNG/pinjamyuk.png')277time.sleep(2)278driver.get('http://pinjammodal.id/')279time.sleep(5)280screenshot = driver.save_screenshot('FolderPNG/pinjammodal.png')281time.sleep(2)282driver.get('http://julo.co.id/')283time.sleep(5)284screenshot = driver.save_screenshot('FolderPNG/julo.png')285time.sleep(2)286driver.get('http://indo.geteasycash.asia/')287time.sleep(5)288screenshot = driver.save_screenshot('FolderPNG/noinfo_geteasycash.png')289time.sleep(2)290driver.get('http://maucash.id/')291time.sleep(5)292screenshot = driver.save_screenshot('FolderPNG/maucash.png')293time.sleep(2)294driver.get('http://rupiahone.co.id/')295time.sleep(5)296screenshot = driver.save_screenshot('FolderPNG/rupiahone.png')297time.sleep(2)298driver.get('http://pohondana.id/')299time.sleep(5)300screenshot = driver.save_screenshot('FolderPNG/pohondana.png')301time.sleep(2)302driver.get('http://danacita.co.id/')303time.sleep(5)304screenshot = driver.save_screenshot('FolderPNG/danacita.png')305time.sleep(2)306driver.get('http://danadidik.id/')307time.sleep(5)308screenshot = driver.save_screenshot('FolderPNG/danadidik.png')309time.sleep(2)310driver.get('http://trustiq.id/')311time.sleep(5)312screenshot = driver.save_screenshot('FolderPNG/trustiq.png')313time.sleep(2)314driver.get('http://danai.id/')315time.sleep(5)316screenshot = driver.save_screenshot('FolderPNG/danai.png')317time.sleep(2)318driver.get('http://pinduit.id/')319time.sleep(5)320screenshot = driver.save_screenshot('FolderPNG/noinfo_pinduit.png')321time.sleep(2)322driver.get('http://smartcapital.id/')323time.sleep(5)324screenshot = driver.save_screenshot('FolderPNG/noinfo_smartcapital.png')325time.sleep(2)326driver.get('http://danamart.id/')327time.sleep(5)328screenshot = driver.save_screenshot('FolderPNG/danamart.png')329time.sleep(2)330driver.get('http://samakita.co.id/')331time.sleep(5)332driver.execute_script("window.scrollTo(0, 600)")333time.sleep(2) 334screenshot = driver.save_screenshot('FolderPNG/samakita.png')335time.sleep(2)336driver.get('http://sayamodalin.co.id/')337driver.execute_script("window.scrollTo(0, 300)") 338time.sleep(5)339screenshot = driver.save_screenshot('FolderPNG/sayamodalin.png')340time.sleep(2)341driver.get('http://plazapinjaman.id/')342time.sleep(5)343screenshot = driver.save_screenshot('FolderPNG/noinfo_plazapinjaman.png')344time.sleep(2)345driver.get('http://web.vestia.co.id/')346wait = WebDriverWait(driver, 10)347time.sleep(10)348screenshot = driver.save_screenshot('FolderPNG/vestia.png')349time.sleep(2)350driver.get('http://singa.id/')351time.sleep(5)352screenshot = driver.save_screenshot('FolderPNG/singa.png')353time.sleep(2)354driver.get('https://www.adakami.id')355time.sleep(5)356screenshot = driver.save_screenshot('FolderPNG/adakami.png')357time.sleep(2)358driver.get('http://modalusaha.id/')359driver.execute_script("window.scrollTo(0, 300)") 360time.sleep(5)361screenshot = driver.save_screenshot('FolderPNG/modalusaha.png')362time.sleep(2)363driver.get('http://asetku.co.id/')364time.sleep(5)365screenshot = driver.save_screenshot('FolderPNG/asetku.png')366time.sleep(2)367driver.get('http://danafix.id/')368time.sleep(5)369screenshot = driver.save_screenshot('FolderPNG/noinfo_danafix.png')370time.sleep(2)371driver.get('http://lumbungdana.co.id/')372time.sleep(5)373screenshot = driver.save_screenshot('FolderPNG/lumbungdana.png')374time.sleep(2)375driver.get('http://lahansikam.co.id')376time.sleep(5)377screenshot = driver.save_screenshot('FolderPNG/lahansikam.png')378time.sleep(2)379driver.get('http://www.modalnasional.co.id/')380time.sleep(5)381screenshot = driver.save_screenshot('FolderPNG/modalnasional.png')382time.sleep(2)383driver.get('http://www.danabagus.id/')384driver.execute_script("window.scrollTo(0, 700)") 385time.sleep(5)386screenshot = driver.save_screenshot('FolderPNG/danabagus.png')387time.sleep(2)388driver.get('https://www.lenteradana.co.id/lender/lender-home')389time.sleep(5)390screenshot = driver.save_screenshot('FolderPNG/noinfo_lenteradana.png')391time.sleep(2)392driver.get('http://www.ikredo.id/')393time.sleep(5)394screenshot = driver.save_screenshot('FolderPNG/ikredo.png')395time.sleep(2)396driver.get('https://www.adakita.co.id/')397time.sleep(5)398screenshot = driver.save_screenshot('FolderPNG/adakita.png')399time.sleep(2)400driver.get('http://www.ukuindo.com/')401time.sleep(5)402screenshot = driver.save_screenshot('FolderPNG/ukuindo.png')403time.sleep(2)404driver.get('http://www.pinjamwinwin.com/')405time.sleep(5)406screenshot = driver.save_screenshot('FolderPNG/pinjamwinwin.png')407time.sleep(2)408driver.get('http://www.pasarpinjam.co.id/')409time.sleep(5)410screenshot = driver.save_screenshot('FolderPNG/pasarpinjam.png')411time.sleep(2)412driver.get('http://www.kredinesia.id/')413time.sleep(5)414screenshot = driver.save_screenshot('FolderPNG/kredinesia.png')415time.sleep(2)416driver.get('http://www.bkdana.id/')417time.sleep(5)418screenshot = driver.save_screenshot('FolderPNG/bkdana.png')419time.sleep(2)420driver.get('http://www.gandengtangan.co.id/')421time.sleep(5)422screenshot = driver.save_screenshot('FolderPNG/gandengtangan.png')423time.sleep(2)424driver.get('http://www.modalantara.id/')425time.sleep(5)426screenshot = driver.save_screenshot('FolderPNG/modalantara.png')427time.sleep(2)428driver.get('http://www.komunal.co.id/')429time.sleep(5)430screenshot = driver.save_screenshot('FolderPNG/komunal.png')431time.sleep(2)432driver.get('http://www.prosperitree.co.id/')433time.sleep(5)434screenshot = driver.save_screenshot('FolderPNG/prosperitree.png')435time.sleep(2)436driver.get('http://www.danakoo.id/')437driver.execute_script("window.scrollTo(0, 1000)") 438time.sleep(5)439screenshot = driver.save_screenshot('FolderPNG/danakoo.png')440time.sleep(2)441driver.get('http://www.cairin.id/')442time.sleep(5)443screenshot = driver.save_screenshot('FolderPNG/cairin.png')444time.sleep(2)445driver.get('http://www.batumbu.id/')446time.sleep(5)447screenshot = driver.save_screenshot('FolderPNG/batumbu.png')448time.sleep(2)449driver.get('http://www.empatkali.co.id/')450time.sleep(5)451screenshot = driver.save_screenshot('FolderPNG/noinfo_empatkali.png')452time.sleep(2)453driver.get('http://www.jembatanemas.id/')454time.sleep(5)455screenshot = driver.save_screenshot('FolderPNG/noinfo_jembatanemas.png')456time.sleep(2)457driver.get('http://www.klikumkm.co.id/')458time.sleep(5)459screenshot = driver.save_screenshot('FolderPNG/klikumkm.png')460time.sleep(2)461driver.get('http://www.kredible.co.id/')462time.sleep(5)463screenshot = driver.save_screenshot('FolderPNG/kredible.png')464time.sleep(2)465driver.get('http://www.klikkami.co.id/')466time.sleep(5)467screenshot = driver.save_screenshot('FolderPNG/noinfo_klikkami.png')468time.sleep(2)469driver.get('http://www.kaching.id/')470time.sleep(5)471screenshot = driver.save_screenshot('FolderPNG/noinfo_kaching.png')472time.sleep(2)473driver.get('http://www.finplus.co.id/')474time.sleep(5)475screenshot = driver.save_screenshot('FolderPNG/noinfo_finplus.png')476time.sleep(2)477driver.get('http://www.p2p.alamisharia.co.id/')478time.sleep(5)479screenshot = driver.save_screenshot('FolderPNG/alamisharia.png')480time.sleep(2)481driver.get('http://www.syarfi.id/')482time.sleep(5)483screenshot = driver.save_screenshot('FolderPNG/noinfo_syarfi.png')484time.sleep(2)485driver.get('http://www.digilend.id/')486time.sleep(5)487screenshot = driver.save_screenshot('FolderPNG/digilend.png')488time.sleep(2)489driver.get('http://www.asakita.id/')490time.sleep(5)491driver.execute_script("document.body.style.zoom='50%'")492screenshot = driver.save_screenshot('FolderPNG/noinfo_asakita.png')493time.sleep(2)494driver.get('http://www.duhasyariah.com/')495time.sleep(5)496screenshot = driver.save_screenshot('FolderPNG/duhasyariah.png')497time.sleep(2)498driver.get('http://bocil.id')499time.sleep(5)500screenshot = driver.save_screenshot('FolderPNG/noinfo_bocil.png')501time.sleep(2)502driver.get('http://www.qazwa.id/bermasalah')503time.sleep(5)504screenshot = driver.save_screenshot('FolderPNG/qazwa.png')505time.sleep(2)506driver.get('http://www.bsalam.id/')507time.sleep(5)508screenshot = driver.save_screenshot('FolderPNG/bsalam.png')509time.sleep(2)510driver.get('http://www.onehope.co.id/')511time.sleep(5)512screenshot = driver.save_screenshot('FolderPNG/noinfo_onehope.png')513time.sleep(2)514driver.get('http://www.ladangmodal.com/')515time.sleep(5)516screenshot = driver.save_screenshot('FolderPNG/noinfo_ladangmodal.png')517time.sleep(2)518driver.get('http://www.dhanapala.id/')519time.sleep(5)520screenshot = driver.save_screenshot('FolderPNG/dhanapala.png')521time.sleep(2)522driver.get('http://www.restock.id/')523time.sleep(5)524screenshot = driver.save_screenshot('FolderPNG/noinfo_restock.png')525time.sleep(2)526driver.get('http://www.solusi-ku.id/')527time.sleep(5)528screenshot = driver.save_screenshot('FolderPNG/noinfo_solusi-ku.png')529time.sleep(2)530driver.get('http://www.pinjamdisini.com/')531time.sleep(5)532screenshot = driver.save_screenshot('FolderPNG/pinjamdisini.png')533time.sleep(2)534driver.get('http://www.adapundi.com/')535time.sleep(5)536screenshot = driver.save_screenshot('FolderPNG/noinfo_adapundi.png')537time.sleep(2)538driver.get('http://www.treeplus.id/')539time.sleep(5)540screenshot = driver.save_screenshot('FolderPNG/treeplus.png')541time.sleep(2)542driver.get('http://www.assetkita.com/')543time.sleep(5)544screenshot = driver.save_screenshot('FolderPNG/assetkita.png')545time.sleep(2)546driver.get('http://www.edufund.co.id/')547time.sleep(5)548screenshot = driver.save_screenshot('FolderPNG/noinfo_edufund.png')549time.sleep(2)550driver.get('http://finanku.com/')551time.sleep(5)552screenshot = driver.save_screenshot('FolderPNG/finanku.png')553time.sleep(2)554driver.get('http://www.tunasaku.co.id/')555time.sleep(5)556screenshot = driver.save_screenshot('FolderPNG/noinfo_tunasaku.png')557time.sleep(2)558driver.get('http://www.uatas.id/')559time.sleep(5)560screenshot = driver.save_screenshot('FolderPNG/noinfo_uatas.png')561time.sleep(2)562targetPath_PNG = os.path.join(cwd, datestring)563while not os.path.exists(targetPath_PNG):564 os.mkdir(targetPath_PNG)565cwd = os.getcwd()566source = cwd+'/FolderPNG/'567dest1 = targetPath_PNG568files = os.listdir(source)569for f in files:...
test_with_screenshot.py
Source:test_with_screenshot.py
...22 viewer.add_image(data, colormap='red', name='red')23 viewer.add_image(data, colormap='green', name='green')24 viewer.add_image(data, colormap='blue', name='blue')25 # Check that blue is visible26 screenshot = viewer.screenshot(canvas_only=True, flash=False)27 center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))28 np.testing.assert_almost_equal(screenshot[center], [0, 0, 255, 255])29 # Remove and re-add image30 viewer.layers.remove('red')31 viewer.add_image(data, colormap='red', name='red')32 # Check that red is visible33 screenshot = viewer.screenshot(canvas_only=True, flash=False)34 np.testing.assert_almost_equal(screenshot[center], [255, 0, 0, 255])35 # Remove two other images36 viewer.layers.remove('green')37 viewer.layers.remove('blue')38 # Check that red is still visible39 screenshot = viewer.screenshot(canvas_only=True, flash=False)40 np.testing.assert_almost_equal(screenshot[center], [255, 0, 0, 255])41 # Add two other layers back42 viewer.add_image(data, colormap='green', name='green')43 viewer.add_image(data, colormap='blue', name='blue')44 # Check that blue is visible45 screenshot = viewer.screenshot(canvas_only=True, flash=False)46 np.testing.assert_almost_equal(screenshot[center], [0, 0, 255, 255])47 # Hide blue48 viewer.layers['blue'].visible = False49 # Check that green is visible. Note this assert was failing before #146350 screenshot = viewer.screenshot(canvas_only=True, flash=False)51 np.testing.assert_almost_equal(screenshot[center], [0, 255, 0, 255])52@skip_on_win_ci53@skip_local_popups54def test_z_order_images(make_napari_viewer):55 """Test changing order of images changes z order in display."""56 data = np.ones((11, 11))57 viewer = make_napari_viewer(show=True)58 viewer.add_image(data, colormap='red')59 viewer.add_image(data, colormap='blue')60 screenshot = viewer.screenshot(canvas_only=True, flash=False)61 center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))62 # Check that blue is visible63 np.testing.assert_almost_equal(screenshot[center], [0, 0, 255, 255])64 viewer.layers.move(1, 0)65 screenshot = viewer.screenshot(canvas_only=True, flash=False)66 center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))67 # Check that red is now visible68 np.testing.assert_almost_equal(screenshot[center], [255, 0, 0, 255])69@skip_on_win_ci70@skip_local_popups71def test_z_order_image_points(make_napari_viewer):72 """Test changing order of image and points changes z order in display."""73 data = np.ones((11, 11))74 viewer = make_napari_viewer(show=True)75 viewer.add_image(data, colormap='red')76 viewer.add_points([5, 5], face_color='blue', size=10)77 screenshot = viewer.screenshot(canvas_only=True, flash=False)78 center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))79 # Check that blue is visible80 np.testing.assert_almost_equal(screenshot[center], [0, 0, 255, 255])81 viewer.layers.move(1, 0)82 screenshot = viewer.screenshot(canvas_only=True, flash=False)83 center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))84 # Check that red is now visible85 np.testing.assert_almost_equal(screenshot[center], [255, 0, 0, 255])86@skip_on_win_ci87@skip_local_popups88def test_z_order_images_after_ndisplay(make_napari_viewer):89 """Test z order of images remanins constant after chaning ndisplay."""90 data = np.ones((11, 11))91 viewer = make_napari_viewer(show=True)92 viewer.add_image(data, colormap='red')93 viewer.add_image(data, colormap='blue')94 screenshot = viewer.screenshot(canvas_only=True, flash=False)95 center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))96 # Check that blue is visible97 np.testing.assert_almost_equal(screenshot[center], [0, 0, 255, 255])98 # Switch to 3D rendering99 viewer.dims.ndisplay = 3100 screenshot = viewer.screenshot(canvas_only=True, flash=False)101 center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))102 # Check that blue is still visible103 np.testing.assert_almost_equal(screenshot[center], [0, 0, 255, 255])104 # Switch back to 2D rendering105 viewer.dims.ndisplay = 2106 screenshot = viewer.screenshot(canvas_only=True, flash=False)107 center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))108 # Check that blue is still visible109 np.testing.assert_almost_equal(screenshot[center], [0, 0, 255, 255])110@skip_on_win_ci111@skip_local_popups112def test_z_order_image_points_after_ndisplay(make_napari_viewer):113 """Test z order of image and points remanins constant after chaning ndisplay."""114 data = np.ones((11, 11))115 viewer = make_napari_viewer(show=True)116 viewer.add_image(data, colormap='red')117 viewer.add_points([5, 5], face_color='blue', size=5)118 screenshot = viewer.screenshot(canvas_only=True, flash=False)119 center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))120 # Check that blue is visible121 np.testing.assert_almost_equal(screenshot[center], [0, 0, 255, 255])122 # Switch to 3D rendering123 viewer.dims.ndisplay = 3124 screenshot = viewer.screenshot(canvas_only=True, flash=False)125 center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))126 # Check that blue is still visible127 np.testing.assert_almost_equal(screenshot[center], [0, 0, 255, 255])128 # Switch back to 2D rendering129 viewer.dims.ndisplay = 2130 screenshot = viewer.screenshot(canvas_only=True, flash=False)131 center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))132 # Check that blue is still visible133 np.testing.assert_almost_equal(screenshot[center], [0, 0, 255, 255])134@skip_on_win_ci135@skip_local_popups136def test_changing_image_colormap(make_napari_viewer):137 """Test changing colormap changes rendering."""138 viewer = make_napari_viewer(show=True)139 data = np.ones((20, 20, 20))140 layer = viewer.add_image(data, contrast_limits=[0, 1])141 screenshot = viewer.screenshot(canvas_only=True, flash=False)142 center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))143 np.testing.assert_almost_equal(screenshot[center], [255, 255, 255, 255])144 layer.colormap = 'red'145 screenshot = viewer.screenshot(canvas_only=True, flash=False)146 np.testing.assert_almost_equal(screenshot[center], [255, 0, 0, 255])147 viewer.dims.ndisplay = 3148 screenshot = viewer.screenshot(canvas_only=True, flash=False)149 np.testing.assert_almost_equal(screenshot[center], [255, 0, 0, 255])150 layer.colormap = 'blue'151 screenshot = viewer.screenshot(canvas_only=True, flash=False)152 np.testing.assert_almost_equal(screenshot[center], [0, 0, 255, 255])153 viewer.dims.ndisplay = 2154 screenshot = viewer.screenshot(canvas_only=True, flash=False)155 np.testing.assert_almost_equal(screenshot[center], [0, 0, 255, 255])156@skip_on_win_ci157@skip_local_popups158def test_changing_image_gamma(make_napari_viewer):159 """Test changing gamma changes rendering."""160 viewer = make_napari_viewer(show=True)161 data = np.ones((20, 20, 20))162 layer = viewer.add_image(data, contrast_limits=[0, 2])163 screenshot = viewer.screenshot(canvas_only=True, flash=False)164 center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))165 assert 127 <= screenshot[center + (0,)] <= 129166 layer.gamma = 0.1167 screenshot = viewer.screenshot(canvas_only=True, flash=False)168 assert screenshot[center + (0,)] > 230169 viewer.dims.ndisplay = 3170 screenshot = viewer.screenshot(canvas_only=True, flash=False)171 assert screenshot[center + (0,)] > 230172 layer.gamma = 1.9173 screenshot = viewer.screenshot(canvas_only=True, flash=False)174 assert screenshot[center + (0,)] < 80175 viewer.dims.ndisplay = 2176 screenshot = viewer.screenshot(canvas_only=True, flash=False)177 assert screenshot[center + (0,)] < 80178@skip_on_win_ci179@skip_local_popups180def test_grid_mode(make_napari_viewer):181 """Test changing gamma changes rendering."""182 viewer = make_napari_viewer(show=True)183 # Add images184 data = np.ones((6, 15, 15))185 viewer.add_image(data, channel_axis=0, blending='translucent')186 assert not viewer.grid.enabled187 assert viewer.grid.actual_shape(6) == (1, 1)188 assert viewer.grid.stride == 1189 translations = [layer._translate_grid for layer in viewer.layers]190 expected_translations = np.zeros((6, 2))191 np.testing.assert_allclose(translations, expected_translations)192 # check screenshot193 screenshot = viewer.screenshot(canvas_only=True, flash=False)194 center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))195 np.testing.assert_almost_equal(screenshot[center], [0, 0, 255, 255])196 # enter grid view197 viewer.grid.enabled = True198 assert viewer.grid.enabled199 assert viewer.grid.actual_shape(6) == (2, 3)200 assert viewer.grid.stride == 1201 translations = [layer._translate_grid for layer in viewer.layers]202 expected_translations = [203 [0, 0],204 [0, 15],205 [0, 30],206 [15, 0],207 [15, 15],208 [15, 30],209 ]210 np.testing.assert_allclose(translations, expected_translations[::-1])211 # check screenshot212 screenshot = viewer.screenshot(canvas_only=True, flash=False)213 # sample 6 squares of the grid and check they have right colors214 pos = [215 (1 / 3, 1 / 4),216 (1 / 3, 1 / 2),217 (1 / 3, 3 / 4),218 (2 / 3, 1 / 4),219 (2 / 3, 1 / 2),220 (2 / 3, 3 / 4),221 ]222 # BGRMYC color order223 color = [224 [0, 0, 255, 255],225 [0, 255, 0, 255],226 [255, 0, 0, 255],227 [255, 0, 255, 255],228 [255, 255, 0, 255],229 [0, 255, 255, 255],230 ]231 for c, p in zip(color, pos):232 coord = tuple(233 np.round(np.multiply(screenshot.shape[:2], p)).astype(int)234 )235 np.testing.assert_almost_equal(screenshot[coord], c)236 # reorder layers, swapping 0 and 5237 viewer.layers.move(5, 0)238 viewer.layers.move(1, 6)239 # check screenshot240 screenshot = viewer.screenshot(canvas_only=True, flash=False)241 # CGRMYB color order242 color = [243 [0, 255, 255, 255],244 [0, 255, 0, 255],245 [255, 0, 0, 255],246 [255, 0, 255, 255],247 [255, 255, 0, 255],248 [0, 0, 255, 255],249 ]250 for c, p in zip(color, pos):251 coord = tuple(252 np.round(np.multiply(screenshot.shape[:2], p)).astype(int)253 )254 np.testing.assert_almost_equal(screenshot[coord], c)255 # return to stack view256 viewer.grid.enabled = False257 assert not viewer.grid.enabled258 assert viewer.grid.actual_shape(6) == (1, 1)259 assert viewer.grid.stride == 1260 translations = [layer._translate_grid for layer in viewer.layers]261 expected_translations = np.zeros((6, 2))262 np.testing.assert_allclose(translations, expected_translations)263 # check screenshot264 screenshot = viewer.screenshot(canvas_only=True, flash=False)265 center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))266 np.testing.assert_almost_equal(screenshot[center], [0, 255, 255, 255])267@skip_on_win_ci268@skip_local_popups269def test_changing_image_attenuation(make_napari_viewer):270 """Test changing attenuation value changes rendering."""271 data = np.zeros((100, 10, 10))272 data[-1] = 1273 viewer = make_napari_viewer(show=True)274 viewer.dims.ndisplay = 3275 viewer.add_image(data, contrast_limits=[0, 1])276 # normal mip277 viewer.layers[0].rendering = 'mip'278 screenshot = viewer.screenshot(canvas_only=True, flash=False)279 center = tuple(np.round(np.divide(screenshot.shape[:2], 2)).astype(int))280 mip_value = screenshot[center][0]281 # zero attenuation (still attenuated!)282 viewer.layers[0].rendering = 'attenuated_mip'283 viewer.layers[0].attenuation = 0.0284 screenshot = viewer.screenshot(canvas_only=True, flash=False)285 zero_att_value = screenshot[center][0]286 # increase attenuation287 viewer.layers[0].attenuation = 0.5288 screenshot = viewer.screenshot(canvas_only=True, flash=False)289 more_att_value = screenshot[center][0]290 # Check that rendering has been attenuated291 assert zero_att_value < more_att_value < mip_value292@skip_on_win_ci293@skip_local_popups294def test_labels_painting(make_napari_viewer):295 """Test painting labels updates image."""296 data = np.zeros((100, 100), dtype=np.int32)297 viewer = make_napari_viewer(show=True)298 viewer.add_labels(data)299 layer = viewer.layers[0]300 screenshot = viewer.screenshot(canvas_only=True, flash=False)301 # Check that no painting has occurred302 assert layer.data.max() == 0303 assert screenshot[:, :, :2].max() == 0304 # Enter paint mode305 viewer.cursor.position = (0, 0)306 layer.mode = 'paint'307 layer.selected_label = 3308 # Simulate click309 Event = collections.namedtuple(310 'Event', field_names=['type', 'is_dragging', 'position']311 )312 # Simulate click313 event = ReadOnlyWrapper(314 Event(315 type='mouse_press',316 is_dragging=False,317 position=viewer.cursor.position,318 )319 )320 mouse_press_callbacks(layer, event)321 viewer.cursor.position = (100, 100)322 # Simulate drag323 event = ReadOnlyWrapper(324 Event(325 type='mouse_move',326 is_dragging=True,327 position=viewer.cursor.position,328 )329 )330 mouse_move_callbacks(layer, event)331 # Simulate release332 event = ReadOnlyWrapper(333 Event(334 type='mouse_release',335 is_dragging=False,336 position=viewer.cursor.position,337 )338 )339 mouse_release_callbacks(layer, event)340 event = ReadOnlyWrapper(341 Event(342 type='mouse_press',343 is_dragging=False,344 position=viewer.cursor.position,345 )346 )347 mouse_press_callbacks(layer, event)348 screenshot = viewer.screenshot(canvas_only=True, flash=False)349 # Check that painting has now occurred350 assert layer.data.max() > 0351 assert screenshot[:, :, :2].max() > 0352@pytest.mark.skip("Welcome visual temporarily disabled")353@skip_on_win_ci354@skip_local_popups355def test_welcome(make_napari_viewer):356 """Test that something visible on launch."""357 viewer = make_napari_viewer(show=True)358 # Check something is visible359 screenshot = viewer.screenshot(canvas_only=True, flash=False)360 assert len(viewer.layers) == 0361 assert screenshot[..., :-1].max() > 0362 # Check adding zeros image makes it go away363 viewer.add_image(np.zeros((1, 1)))364 screenshot = viewer.screenshot(canvas_only=True, flash=False)365 assert len(viewer.layers) == 1366 assert screenshot[..., :-1].max() == 0367 # Remove layer and check something is visible again368 viewer.layers.pop(0)369 screenshot = viewer.screenshot(canvas_only=True, flash=False)370 assert len(viewer.layers) == 0371 assert screenshot[..., :-1].max() > 0372@skip_on_win_ci373@skip_local_popups374def test_axes_visible(make_napari_viewer):375 """Test that something appears when axes become visible."""376 viewer = make_napari_viewer(show=True)377 viewer.window._qt_viewer.set_welcome_visible(False)378 # Check axes are not visible379 launch_screenshot = viewer.screenshot(canvas_only=True, flash=False)380 assert not viewer.axes.visible381 # Make axes visible and check something is seen382 viewer.axes.visible = True383 on_screenshot = viewer.screenshot(canvas_only=True, flash=False)384 assert viewer.axes.visible385 assert abs(on_screenshot - launch_screenshot).max() > 0386 # Make axes not visible and check they are gone387 viewer.axes.visible = False388 off_screenshot = viewer.screenshot(canvas_only=True, flash=False)389 assert not viewer.axes.visible390 np.testing.assert_almost_equal(launch_screenshot, off_screenshot)391@skip_on_win_ci392@skip_local_popups393def test_scale_bar_visible(make_napari_viewer):394 """Test that something appears when scale bar becomes visible."""395 viewer = make_napari_viewer(show=True)396 viewer.window._qt_viewer.set_welcome_visible(False)397 # Check scale bar is not visible398 launch_screenshot = viewer.screenshot(canvas_only=True, flash=False)399 assert not viewer.scale_bar.visible400 # Make scale bar visible and check something is seen401 viewer.scale_bar.visible = True402 on_screenshot = viewer.screenshot(canvas_only=True, flash=False)403 assert viewer.scale_bar.visible404 assert abs(on_screenshot - launch_screenshot).max() > 0405 # Make scale bar not visible and check it is gone406 viewer.scale_bar.visible = False407 off_screenshot = viewer.screenshot(canvas_only=True, flash=False)408 assert not viewer.scale_bar.visible409 np.testing.assert_almost_equal(launch_screenshot, off_screenshot)410@skip_on_win_ci411@skip_local_popups412def test_screenshot_has_no_border(make_napari_viewer):413 """See https://github.com/napari/napari/issues/3357"""414 viewer = make_napari_viewer(show=True)415 image_data = np.ones((60, 80))416 viewer.add_image(image_data, colormap='red')417 # Zoom in dramatically to make the screenshot all red.418 viewer.camera.zoom = 1000419 screenshot = viewer.screenshot(canvas_only=True, flash=False)420 expected = np.broadcast_to([255, 0, 0, 255], screenshot.shape)...
test_screenshot.py
Source:test_screenshot.py
...54 self.assertEqual(imghdr.what("", image), "png")55 def assert_formats(self, element=None):56 if element is None:57 element = self.document_element58 screenshot_default = self.marionette.screenshot(element=element)59 screenshot_image = self.marionette.screenshot(element=element, format="base64")60 binary1 = self.marionette.screenshot(element=element, format="binary")61 binary2 = self.marionette.screenshot(element=element, format="binary")62 hash1 = self.marionette.screenshot(element=element, format="hash")63 hash2 = self.marionette.screenshot(element=element, format="hash")64 # Valid data should have been returned65 self.assert_png(screenshot_image)66 self.assertEqual(imghdr.what("", binary1), "png")67 self.assertEqual(screenshot_image, base64.b64encode(binary1))68 self.assertEqual(hash1, hashlib.sha256(screenshot_image).hexdigest())69 # Different formats produce different data70 self.assertNotEqual(screenshot_image, binary1)71 self.assertNotEqual(screenshot_image, hash1)72 self.assertNotEqual(binary1, hash1)73 # A second capture should be identical74 self.assertEqual(screenshot_image, screenshot_default)75 self.assertEqual(binary1, binary2)76 self.assertEqual(hash1, hash2)77 def get_element_dimensions(self, element):78 rect = element.rect79 return rect["width"], rect["height"]80 def get_image_dimensions(self, screenshot):81 self.assert_png(screenshot)82 image = base64.decodestring(screenshot)83 width, height = struct.unpack(">LL", image[16:24])84 return int(width), int(height)85 def scale(self, rect):86 return (int(rect[0] * self.device_pixel_ratio),87 int(rect[1] * self.device_pixel_ratio))88class TestScreenCaptureChrome(WindowManagerMixin, ScreenCaptureTestCase):89 def setUp(self):90 super(TestScreenCaptureChrome, self).setUp()91 self.marionette.set_context("chrome")92 def tearDown(self):93 self.close_all_windows()94 super(TestScreenCaptureChrome, self).tearDown()95 @property96 def window_dimensions(self):97 return tuple(self.marionette.execute_script("""98 let el = document.documentElement;99 let rect = el.getBoundingClientRect();100 return [rect.width, rect.height];101 """))102 def open_dialog(self, url=None, width=None, height=None):103 if url is None:104 url = "chrome://marionette/content/test_dialog.xul"105 def opener():106 features = "chrome"107 if height is not None:108 features += ",height={}".format(height)109 if width is not None:110 features += ",width={}".format(width)111 self.marionette.execute_script("""112 window.open(arguments[0], "", arguments[1]);113 """, script_args=[url, features])114 return self.open_window(opener)115 def test_capture_different_context(self):116 """Check that screenshots in content and chrome are different."""117 with self.marionette.using_context("content"):118 screenshot_content = self.marionette.screenshot()119 screenshot_chrome = self.marionette.screenshot()120 self.assertNotEqual(screenshot_content, screenshot_chrome)121 @skip_if_mobile("Fennec doesn't support other chrome windows")122 def test_capture_element(self):123 dialog = self.open_dialog()124 self.marionette.switch_to_window(dialog)125 # Ensure we only capture the element126 el = self.marionette.find_element(By.ID, "test-list")127 screenshot_element = self.marionette.screenshot(element=el)128 self.assertEqual(self.scale(self.get_element_dimensions(el)),129 self.get_image_dimensions(screenshot_element))130 # Ensure we do not capture the full window131 screenshot_dialog = self.marionette.screenshot()132 self.assertNotEqual(screenshot_dialog, screenshot_element)133 self.marionette.close_chrome_window()134 self.marionette.switch_to_window(self.start_window)135 @skip_if_mobile("Fennec doesn't support other chrome windows")136 def test_capture_flags(self):137 dialog = self.open_dialog()138 self.marionette.switch_to_window(dialog)139 textbox = self.marionette.find_element(By.ID, "text-box")140 textbox.send_keys("")141 screenshot_focus = self.marionette.screenshot()142 self.marionette.execute_script("arguments[0].blur();", script_args=[textbox])143 screenshot_no_focus = self.marionette.screenshot()144 self.marionette.close_chrome_window()145 self.marionette.switch_to_window(self.start_window)146 self.assertNotEqual(screenshot_focus, screenshot_no_focus)147 def test_capture_full_area(self):148 # A full capture is not the outer dimensions of the window,149 # but instead the bounding box of the window's root node (documentElement).150 screenshot_full = self.marionette.screenshot()151 screenshot_root = self.marionette.screenshot(element=self.document_element)152 self.assert_png(screenshot_full)153 self.assert_png(screenshot_root)154 self.assertEqual(screenshot_root, screenshot_full)155 self.assertEqual(self.scale(self.get_element_dimensions(self.document_element)),156 self.get_image_dimensions(screenshot_full))157 @skip_if_mobile("Fennec doesn't support other chrome windows")158 def test_capture_viewport(self):159 # Load a HTML test page into the chrome window to get scrollbars160 test_page = self.marionette.absolute_url("test.html")161 dialog = self.open_dialog(url=test_page, width=50, height=50)162 self.marionette.switch_to_window(dialog)163 # Size of screenshot has to match viewport size164 screenshot = self.marionette.screenshot(full=False)165 self.assert_png(screenshot)166 self.assertEqual(self.scale(self.viewport_dimensions),167 self.get_image_dimensions(screenshot))168 self.assertNotEqual(self.scale(self.window_dimensions),169 self.get_image_dimensions(screenshot))170 self.marionette.close_chrome_window()171 self.marionette.switch_to_window(self.start_window)172 @skip_if_mobile("Fennec doesn't support other chrome windows")173 def test_capture_window_already_closed(self):174 dialog = self.open_dialog()175 self.marionette.switch_to_window(dialog)176 self.marionette.close_chrome_window()177 self.assertRaises(NoSuchWindowException, self.marionette.screenshot)178 self.marionette.switch_to_window(self.start_window)179 @skip_if_mobile("Fennec doesn't support other chrome windows")180 def test_formats(self):181 dialog = self.open_dialog()182 self.marionette.switch_to_window(dialog)183 self.assert_formats()184 self.marionette.close_chrome_window()185 self.marionette.switch_to_window(self.start_window)186 def test_format_unknown(self):187 with self.assertRaises(ValueError):188 self.marionette.screenshot(format="cheese")189 @skip_if_mobile("Fennec doesn't support other chrome windows")190 def test_highlight_elements(self):191 dialog = self.open_dialog()192 self.marionette.switch_to_window(dialog)193 # Highlighting the element itself shouldn't make the image larger194 element = self.marionette.find_element(By.ID, "test-list")195 screenshot_element = self.marionette.screenshot(element=element)196 screenshot_highlight = self.marionette.screenshot(element=element,197 highlights=[element])198 self.assertEqual(self.scale(self.get_element_dimensions(element)),199 self.get_image_dimensions(screenshot_element))200 self.assertNotEqual(screenshot_element, screenshot_highlight)201 # Highlighting a sub element202 button = self.marionette.find_element(By.ID, "choose-button")203 screenshot_highlight_button = self.marionette.screenshot(element=element,204 highlights=[button])205 self.assertNotEqual(screenshot_element, screenshot_highlight_button)206 self.assertNotEqual(screenshot_highlight, screenshot_highlight_button)207 self.marionette.close_chrome_window()208 self.marionette.switch_to_window(self.start_window)209 def test_highlight_element_not_seen(self):210 """Check that for not found elements an exception is raised."""211 with self.marionette.using_context('content'):212 self.marionette.navigate(box)213 content_element = self.marionette.find_element(By.ID, "green")214 self.assertRaisesRegexp(JavascriptException, "Element reference not seen before",215 self.marionette.screenshot, highlights=[content_element])216 chrome_document_element = self.document_element217 with self.marionette.using_context('content'):218 self.assertRaisesRegexp(JavascriptException, "Element reference not seen before",219 self.marionette.screenshot,220 highlights=[chrome_document_element])221class TestScreenCaptureContent(WindowManagerMixin, ScreenCaptureTestCase):222 def setUp(self):223 super(TestScreenCaptureContent, self).setUp()224 self.marionette.set_context("content")225 def tearDown(self):226 self.close_all_tabs()227 super(TestScreenCaptureContent, self).tearDown()228 @property229 def scroll_dimensions(self):230 return tuple(self.marionette.execute_script("""231 return [document.body.scrollWidth, document.body.scrollHeight]232 """))233 @skip_if_mobile("Needs application independent method to open a new tab")234 def test_capture_tab_already_closed(self):235 tab = self.open_tab()236 self.marionette.switch_to_window(tab)237 self.marionette.close()238 self.assertRaises(NoSuchWindowException, self.marionette.screenshot)239 self.marionette.switch_to_window(self.start_tab)240 def test_capture_element(self):241 self.marionette.navigate(box)242 el = self.marionette.find_element(By.TAG_NAME, "div")243 screenshot = self.marionette.screenshot(element=el)244 self.assert_png(screenshot)245 self.assertEqual(self.scale(self.get_element_dimensions(el)),246 self.get_image_dimensions(screenshot))247 @skip("Bug 1213875")248 def test_capture_element_scrolled_into_view(self):249 self.marionette.navigate(long)250 el = self.marionette.find_element(By.TAG_NAME, "p")251 screenshot = self.marionette.screenshot(element=el)252 self.assert_png(screenshot)253 self.assertEqual(self.scale(self.get_element_dimensions(el)),254 self.get_image_dimensions(screenshot))255 self.assertGreater(self.page_y_offset, 0)256 @skip("Bug 1330560 - AssertionError: u'iVBORw0KGgoA... (images unexpectedly equal)")257 def test_capture_flags(self):258 self.marionette.navigate(input)259 textbox = self.marionette.find_element(By.ID, "text-input")260 textbox.send_keys("")261 screenshot_focus = self.marionette.screenshot()262 self.marionette.execute_script("arguments[0].blur();", script_args=[textbox])263 screenshot_no_focus = self.marionette.screenshot()264 self.assertNotEqual(screenshot_focus, screenshot_no_focus)265 @skip_if_mobile("Bug 1330642 - Tuples differ: (1960, 11130) != (1960, 11129)")266 def test_capture_html_document_element(self):267 self.marionette.navigate(long)268 screenshot = self.marionette.screenshot()269 self.assert_png(screenshot)270 self.assertEqual(self.scale(self.scroll_dimensions),271 self.get_image_dimensions(screenshot))272 def test_capture_svg_document_element(self):273 self.marionette.navigate(svg)274 screenshot = self.marionette.screenshot()275 self.assert_png(screenshot)276 self.assertEqual(self.scale(self.get_element_dimensions(self.document_element)),277 self.get_image_dimensions(screenshot))278 def test_capture_viewport(self):279 url = self.marionette.absolute_url("clicks.html")280 self.marionette.navigate(short)281 self.marionette.navigate(url)282 screenshot = self.marionette.screenshot(full=False)283 self.assert_png(screenshot)284 self.assertEqual(self.scale(self.viewport_dimensions),285 self.get_image_dimensions(screenshot))286 def test_capture_viewport_after_scroll(self):287 self.marionette.navigate(long)288 before = self.marionette.screenshot()289 el = self.marionette.find_element(By.TAG_NAME, "p")290 self.marionette.execute_script(291 "arguments[0].scrollIntoView()", script_args=[el])292 after = self.marionette.screenshot(full=False)293 self.assertNotEqual(before, after)294 self.assertGreater(self.page_y_offset, 0)295 def test_formats(self):296 self.marionette.navigate(box)297 # Use a smaller region to speed up the test298 element = self.marionette.find_element(By.TAG_NAME, "div")299 self.assert_formats(element=element)300 def test_format_unknown(self):301 with self.assertRaises(ValueError):302 self.marionette.screenshot(format="cheese")303 def test_highlight_elements(self):304 self.marionette.navigate(box)305 element = self.marionette.find_element(By.TAG_NAME, "div")306 # Highlighting the element itself shouldn't make the image larger307 screenshot_element = self.marionette.screenshot(element=element)308 screenshot_highlight = self.marionette.screenshot(element=element,309 highlights=[element])310 self.assertEqual(self.scale(self.get_element_dimensions(element)),311 self.get_image_dimensions(screenshot_highlight))312 self.assertNotEqual(screenshot_element, screenshot_highlight)313 # Highlighting a sub element314 paragraph = self.marionette.find_element(By.ID, "green")315 screenshot_highlight_paragraph = self.marionette.screenshot(element=element,316 highlights=[paragraph])317 self.assertNotEqual(screenshot_element, screenshot_highlight_paragraph)318 self.assertNotEqual(screenshot_highlight, screenshot_highlight_paragraph)319 def test_scroll_default(self):320 self.marionette.navigate(long)321 before = self.page_y_offset322 el = self.marionette.find_element(By.TAG_NAME, "p")323 self.marionette.screenshot(element=el, format="hash")324 self.assertNotEqual(before, self.page_y_offset)325 def test_scroll(self):326 self.marionette.navigate(long)327 before = self.page_y_offset328 el = self.marionette.find_element(By.TAG_NAME, "p")329 self.marionette.screenshot(element=el, format="hash", scroll=True)330 self.assertNotEqual(before, self.page_y_offset)331 def test_scroll_off(self):332 self.marionette.navigate(long)333 el = self.marionette.find_element(By.TAG_NAME, "p")334 before = self.page_y_offset335 self.marionette.screenshot(element=el, format="hash", scroll=False)336 self.assertEqual(before, self.page_y_offset)337 def test_scroll_no_element(self):338 self.marionette.navigate(long)339 before = self.page_y_offset340 self.marionette.screenshot(format="hash", scroll=True)...
csvparser.py
Source:csvparser.py
1import csv2import os3from shutil import copyfile4from PIL import Image5class CSVParser:6 eyevido_ds = dict()7 id_mapping = dict()8 merged_mouse_data = []9 merged_gaze_data = []10 def csv_import(self):11 # print('import started')12 path = 'csv_in/'13 listing = os.listdir(path)14 for file in listing:15 fn = file[:-7]16 if fn not in self.eyevido_ds.keys():17 with open(path + file) as f:18 i = 019 for line in f:20 line = line[:-1]21 vals = []22 if line.find('"') == -1:23 vals = line.split(',')24 else:25 lines = line.split(',"')26 for l in lines:27 if l.find('"') == -1:28 vals = vals + l.split(',')29 else:30 vals.append(l.split('"')[0])31 temp = l.split('"')[1]32 if temp.startswith(','):33 temp = temp[1:]34 temp = temp.split(',')35 vals = vals + temp36 if i == 0:37 self.eyevido_ds[fn] = dict()38 self.eyevido_ds[fn]['label'] = vals39 self.eyevido_ds[fn]['values'] = []40 else:41 self.eyevido_ds[fn]['values'].append(vals)42 i += 143 # print('import finished')44 def csv_export(self):45 print('export started')46 global_gaze_out = dict()47 global_mouse_out = dict()48 global_screenshot_mapping = []49 metadata = []50 # iterate over web_groups51 for web_group in self.eyevido_ds['web_groups']['values']:52 mouse_out = []53 gaze_out = []54 max_screen = -155 # iterate over web_results56 for web_result in self.eyevido_ds['web_results']['values']:57 if web_result[3][:-2] == web_group[0]:58 print('load web_result ' + web_result[0] + ' in web_group ' + web_group[0])59 # iterate over mouse data60 for interaction in self.eyevido_ds['interactions']['values']:61 if interaction[1] == web_result[0]:62 # user; timestamp; x; y; type63 mouse_out.append(64 [web_result[1], interaction[2], interaction[3], interaction[4], interaction[5]])65 # iterate over gaze data66 for image_fixation in self.eyevido_ds['image_fixations']['values']:67 if image_fixation[1] == web_result[0]:68 # user; timestamp; x; y; duration69 gaze_out.append([web_result[1], image_fixation[2], image_fixation[3], image_fixation[4],70 image_fixation[5]])71 try:72 if max_screen != -1:73 if os.path.getsize('screenshots/' + web_result[8]) >= os.path.getsize(74 'screenshots/' + max_screen):75 max_screen = web_result[8]76 else:77 if os.path.isfile('screenshots/' + web_result[8]):78 max_screen = web_result[8]79 else:80 pass81 except FileNotFoundError:82 pass83 # web_group_id; web_id; study_id; url to screenshot84 if max_screen == -1:85 max_screen = 'NULL'86 if max_screen != 'NULL':87 screenshot_pil = Image.open('screenshots/' + max_screen)88 screenshot_width, screenshot_height = screenshot_pil.size89 self.id_mapping[web_group[0]] = self.aux_create_filename(web_group[2])90 study_id = self.aux_find_study_id(web_group[2])91 global_screenshot_mapping.append(92 [web_group[0], web_group[2], study_id, max_screen, screenshot_width,93 screenshot_height])94 # TODO: implement95 # study_id; study_title; web_id; web_title; web_group_id; web_group_title; url; screenshot; width; height; num_user96 metadata.append(97 [study_id, web_group[2], web_group[0], self.id_mapping[web_group[0]], web_group[1], max_screen,98 screenshot_width, screenshot_height])99 global_mouse_out[web_group[0]] = mouse_out100 for elem in mouse_out:101 # study_id; web_id; web_group_id; filename; user; timestamp; x; y; type102 self.merged_mouse_data.append(103 [study_id, web_group[2], web_group[0], self.id_mapping[web_group[0]],104 elem[0], elem[1], elem[2], elem[3], elem[4]])105 global_gaze_out[web_group[0]] = gaze_out106 for elem in gaze_out:107 # study_id; web_id; web_group_id; filename; user; timestamp; x; y; duration108 self.merged_gaze_data.append(109 [study_id, web_group[2], web_group[0], self.id_mapping[web_group[0]],110 elem[0], elem[1], elem[2], elem[3], elem[4]])111 copyfile('screenshots/' + max_screen, 'screenshot_out/img_' + self.id_mapping[web_group[0]] + '.jpg')112 # iterate over web_result to find the single group results113 for web_result in self.eyevido_ds['web_results']['values']:114 mouse_out = []115 gaze_out = []116 if web_result[3] == '':117 virtual_web_group_id = web_result[1] + web_result[0]118 print('load web_result ' + web_result[0] + ' in virtual_single_node ' + virtual_web_group_id)119 # iterate over mouse data120 for interaction in self.eyevido_ds['interactions']['values']:121 if interaction[1] == web_result[0]:122 # user; timestamp; x; y; type123 mouse_out.append(124 [web_result[1], interaction[2], interaction[3], interaction[4], interaction[5]])125 # iterate over gaze data126 for image_fixation in self.eyevido_ds['image_fixations']['values']:127 if image_fixation[1] == web_result[0]:128 # user; timestamp; x; y; duration129 gaze_out.append(130 [web_result[1], image_fixation[2], image_fixation[3], image_fixation[4], image_fixation[5]])131 # check whether screenshot file exists132 if os.path.isfile('screenshots/' + web_result[8]):133 screenshot_url = web_result[8]134 screenshot_pil = Image.open('screenshots/' + screenshot_url)135 screenshot_width, screenshot_height = screenshot_pil.size136 else:137 screenshot_url = 'NULL'138 # web_group_id; web_id; study_id; url to screenshot139 if screenshot_url != 'NULL':140 self.id_mapping[virtual_web_group_id] = self.aux_create_filename(web_result[2])141 study_id = self.aux_find_study_id(web_result[2])142 global_screenshot_mapping.append(143 [virtual_web_group_id, web_result[2], study_id, screenshot_url,144 screenshot_width, screenshot_height])145 # TODO: implement146 # study_id; study_title; web_id; web_title; web_group_id; web_group_title; url; screenshot; width; height; num_user147 metadata.append(148 [study_id, web_result[2], virtual_web_group_id, self.id_mapping[virtual_web_group_id],149 web_result[5], screenshot_url, screenshot_width, screenshot_height])150 global_mouse_out[virtual_web_group_id] = mouse_out151 for elem in mouse_out:152 # study_id; web_id; web_group_id; filename; user; timestamp; x; y; type153 self.merged_mouse_data.append(154 [study_id, web_result[2], virtual_web_group_id, self.id_mapping[virtual_web_group_id],155 elem[0], elem[1], elem[2], elem[3], elem[4]])156 global_gaze_out[virtual_web_group_id] = gaze_out157 for elem in gaze_out:158 # study_id; web_id; web_group_id; filename; user; timestamp; x; y; duration159 self.merged_gaze_data.append(160 [study_id, web_result[2], virtual_web_group_id, self.id_mapping[virtual_web_group_id],161 elem[0], elem[1], elem[2], elem[3], elem[4]])162 copyfile('screenshots/' + web_result[8],163 'screenshot_out/img_' + self.id_mapping[virtual_web_group_id] + '.jpg')164 # iterate over mouse data and print csv files165 for mouse_out_key in global_mouse_out.keys():166 mouse_filename = 'csv_out/mouse_' + self.id_mapping[mouse_out_key] + '.csv'167 aux_write_file(mouse_filename, ['user_id', 'timestamp', 'x', 'y', 'type'],168 global_mouse_out[mouse_out_key])169 # iterate over gaze data and print csv files170 for gaze_out_key in global_gaze_out.keys():171 gaze_filename = 'csv_out/gaze_' + self.id_mapping[gaze_out_key] + '.csv'172 aux_write_file(gaze_filename, ['user_id', 'timestamp', 'x', 'y', 'duration'],173 global_gaze_out[gaze_out_key])174 # print screenshot mapping file175 aux_write_file('csv_out/screenshot_mapping.csv',176 ['web_group_id', 'web_id', 'study_id', 'screenshot', 'width', 'height'],177 global_screenshot_mapping)178 # print merged mouse data file179 aux_write_file('csv_out/merged_mouse.csv',180 ['study_id', 'web_id', 'web_group_id', 'filename', 'user_id', 'timestamp', 'x', 'y', 'type'],181 self.merged_mouse_data)182 # print merged gaze data file183 aux_write_file('csv_out/merged_gaze.csv',184 ['study_id', 'web_id', 'web_group_id', 'filename', 'user_id', 'timestamp', 'x', 'y', 'duration'],185 self.merged_gaze_data)186 # print metadata file187 aux_write_file('csv_out/metadata.csv',188 ['study_id', 'web_id', 'web_group_id', 'title', 'url', 'screenshot', 'width', 'height'],189 metadata)190 print('export finished')191 # helper function for finding study id192 def aux_find_study_id(self, web_id_in):193 for web_id in self.eyevido_ds['webs']['values']:194 if web_id[0] == web_id_in:195 return web_id[1]196 # helper function to check, wheater all screenshots are loaded197 def aux_check_files(self):198 listing = os.listdir('csv_out')199 g = []200 for file in listing:201 if file.startswith('gaze'):202 fn = file[5:-4]203 g.append(fn)204 listing = os.listdir('screenshot_out')205 s = []206 for file in listing:207 if file.startswith('img'):208 fn = file[4:-4]209 s.append(fn)210 print('compare screenshots and gaze files -> ' + str(bool(set(s).intersection(g))))211 # helper function that creates filenames212 def aux_create_filename(self, web_id):213 for web_shortcut in self.eyevido_ds['webs-shortcuts']['values']:214 if web_shortcut[0] == web_id:215 ws_prefix = str(web_shortcut[1]) + '_' + str(web_shortcut[2])216 i = 0217 for ws_id in self.id_mapping.values():218 if str(ws_id).startswith(ws_prefix):219 i += 1220 return ws_prefix + '_' + str(i)221# helper function for printing csv file222def aux_write_file(filename, schema, data):223 print('write ' + filename + ' with schema: ' + str(schema))224 with open(filename, 'w', newline='') as csvfile:225 w = csv.writer(csvfile, delimiter=';')226 w.writerow(schema)227 for elem in data:228 w.writerow(elem)229p = CSVParser()230p.csv_import()231p.csv_export()...
test_review_screenshot_comment.py
Source:test_review_screenshot_comment.py
...9 """10 if not comment_text:11 comment_text = "Test screenshot comment with an opened issue"12 review_request = self.create_review_request(publish=True, submitter=self.user)13 screenshot = self.create_screenshot(review_request)14 review = self.create_review(review_request, user=self.user, publish=publish)15 comment = self.create_screenshot_comment(review, screenshot, comment_text, issue_opened=True)16 return comment, review, review_request17@six.add_metaclass(BasicTestsMetaclass)18class ResourceListTests(CommentListMixin, ReviewRequestChildListMixin, BaseTestCase):19 """Testing the ReviewScreenshotCommentResource list APIs."""20 sample_api_url = "review-requests/<id>/reviews/<id>/screenshot-comments/"21 resource = resources.review_screenshot_comment22 def setup_review_request_child_test(self, review_request):23 self.create_screenshot(review_request)24 review = self.create_review(review_request, user=self.user)25 return (get_review_screenshot_comment_list_url(review), screenshot_comment_list_mimetype)26 def compare_item(self, item_rsp, comment):27 self.assertEqual(item_rsp["id"], comment.pk)28 self.assertEqual(item_rsp["text"], comment.text)29 self.assertEqual(item_rsp["x"], comment.x)30 self.assertEqual(item_rsp["y"], comment.y)31 self.assertEqual(item_rsp["w"], comment.w)32 self.assertEqual(item_rsp["h"], comment.h)33 self.assertEqual(item_rsp["extra_data"], comment.extra_data)34 if comment.rich_text:35 self.assertEqual(item_rsp["text_type"], "markdown")36 else:37 self.assertEqual(item_rsp["text_type"], "plain")38 def setup_basic_get_test(self, user, with_local_site, local_site_name, populate_items):39 review_request = self.create_review_request(with_local_site=with_local_site, submitter=user, publish=True)40 screenshot = self.create_screenshot(review_request)41 review = self.create_review(review_request, user=user)42 if populate_items:43 items = [self.create_screenshot_comment(review, screenshot)]44 else:45 items = []46 return (get_review_screenshot_comment_list_url(review, local_site_name), screenshot_comment_list_mimetype, items)47 def setup_basic_post_test(self, user, with_local_site, local_site_name, post_valid_data):48 review_request = self.create_review_request(with_local_site=with_local_site, submitter=user, publish=True)49 screenshot = self.create_screenshot(review_request)50 review = self.create_review(review_request, user=user)51 return (get_review_screenshot_comment_list_url(review, local_site_name), screenshot_comment_item_mimetype, {"screenshot_id": screenshot.pk, "text": "Test comment", "x": 2, "y": 2, "w": 10, "h": 10}, [review, screenshot])52 def check_post_result(self, user, rsp, review, screenshot):53 comment = ScreenshotComment.objects.get(pk=rsp["screenshot_comment"]["id"])54 self.compare_item(rsp["screenshot_comment"], comment)55 def test_post_with_issue(self):56 """Testing the57 POST review-requests/<id>/reviews/<id>/screenshot-comments/ API58 with an issue59 """60 comment_text = "Test screenshot comment with an opened issue"61 comment, review, review_request = self._create_screenshot_review_with_issue(publish=False, comment_text=comment_text)62 rsp = self.api_get(get_review_screenshot_comment_list_url(review), expected_mimetype=screenshot_comment_list_mimetype)63 self.assertEqual(rsp["stat"], "ok")64 self.assertIn("screenshot_comments", rsp)65 self.assertEqual(len(rsp["screenshot_comments"]), 1)66 self.assertEqual(rsp["screenshot_comments"][0]["text"], comment_text)67 self.assertTrue(rsp["screenshot_comments"][0]["issue_opened"])68@six.add_metaclass(BasicTestsMetaclass)69class ResourceItemTests(CommentItemMixin, ReviewRequestChildItemMixin, BaseTestCase):70 """Testing the ReviewScreenshotCommentResource item APIs."""71 fixtures = ["test_users"]72 sample_api_url = "review-requests/<id>/reviews/<id>/screenshot-comments/<id>/"73 resource = resources.review_screenshot_comment74 def compare_item(self, item_rsp, comment):75 self.assertEqual(item_rsp["id"], comment.pk)76 self.assertEqual(item_rsp["text"], comment.text)77 self.assertEqual(item_rsp["x"], comment.x)78 self.assertEqual(item_rsp["y"], comment.y)79 self.assertEqual(item_rsp["w"], comment.w)80 self.assertEqual(item_rsp["h"], comment.h)81 self.assertEqual(item_rsp["extra_data"], comment.extra_data)82 if comment.rich_text:83 self.assertEqual(item_rsp["text_type"], "markdown")84 else:85 self.assertEqual(item_rsp["text_type"], "plain")86 def setup_review_request_child_test(self, review_request):87 screenshot = self.create_screenshot(review_request)88 review = self.create_review(review_request, user=self.user)89 comment = self.create_screenshot_comment(review, screenshot)90 return (get_review_screenshot_comment_item_url(review, comment.pk), screenshot_comment_item_mimetype)91 def setup_basic_delete_test(self, user, with_local_site, local_site_name):92 review_request = self.create_review_request(with_local_site=with_local_site, submitter=user, publish=True)93 screenshot = self.create_screenshot(review_request)94 review = self.create_review(review_request, user=user)95 comment = self.create_screenshot_comment(review, screenshot)96 return (get_review_screenshot_comment_item_url(review, comment.pk, local_site_name), [comment, review])97 def check_delete_result(self, user, comment, review):98 self.assertNotIn(comment, review.screenshot_comments.all())99 def test_delete_with_does_not_exist_error(self):100 """Testing the101 DELETE review-requests/<id>/reviews/<id>/screenshot-comments/<id>/ API102 with Does Not Exist error103 """104 review_request = self.create_review_request(publish=True)105 self.create_screenshot(review_request)106 review = self.create_review(review_request, user=self.user)107 self.api_delete(get_review_screenshot_comment_item_url(review, 123), expected_status=404)108 def setup_basic_get_test(self, user, with_local_site, local_site_name):109 review_request = self.create_review_request(with_local_site=with_local_site, submitter=user, publish=True)110 screenshot = self.create_screenshot(review_request)111 review = self.create_review(review_request, user=user)112 comment = self.create_screenshot_comment(review, screenshot)113 return (get_review_screenshot_comment_item_url(review, comment.pk, local_site_name), screenshot_comment_item_mimetype, comment)114 def setup_basic_put_test(self, user, with_local_site, local_site_name, put_valid_data):115 review_request = self.create_review_request(with_local_site=with_local_site, submitter=user, publish=True)116 screenshot = self.create_screenshot(review_request)117 review = self.create_review(review_request, user=user)118 comment = self.create_screenshot_comment(review, screenshot)119 return (get_review_screenshot_comment_item_url(review, comment.pk, local_site_name), screenshot_comment_item_mimetype, {"text": "Test comment"}, comment, [])120 def check_put_result(self, user, item_rsp, comment, *args):121 comment = ScreenshotComment.objects.get(pk=comment.pk)122 self.assertEqual(item_rsp["text_type"], "plain")123 self.assertEqual(item_rsp["text"], "Test comment")124 self.compare_item(item_rsp, comment)125 def test_put_with_issue(self):126 """Testing the127 PUT review-requests/<id>/reviews/<id>/screenshot-comments/<id>/ API128 with an issue, removing issue_opened129 """130 comment, review, review_request = self._create_screenshot_review_with_issue()131 rsp = self.api_put(get_review_screenshot_comment_item_url(review, comment.pk), {"issue_opened": False}, expected_mimetype=screenshot_comment_item_mimetype)132 self.assertEqual(rsp["stat"], "ok")133 self.assertFalse(rsp["screenshot_comment"]["issue_opened"])134 def test_put_issue_status_before_publish(self):135 """Testing the136 PUT review-requests/<id>/reviews/<id>/screenshot-comments/<id> API137 with an issue, before review is published138 """139 comment, review, review_request = self._create_screenshot_review_with_issue()140 rsp = self.api_put(get_review_screenshot_comment_item_url(review, comment.pk), {"issue_status": "resolved"}, expected_mimetype=screenshot_comment_item_mimetype)141 self.assertEqual(rsp["stat"], "ok")142 self.assertEqual(rsp["screenshot_comment"]["issue_status"], "open")143 def test_put_issue_status_after_publish(self):144 """Testing the145 PUT review-requests/<id>/reviews/<id>/screenshot-comments/<id>/ API146 with an issue, after review is published147 """148 comment, review, review_request = self._create_screenshot_review_with_issue(publish=True)149 rsp = self.api_put(get_review_screenshot_comment_item_url(review, comment.pk), {"issue_status": "resolved"}, expected_mimetype=screenshot_comment_item_mimetype)150 self.assertEqual(rsp["stat"], "ok")151 self.assertEqual(rsp["screenshot_comment"]["issue_status"], "resolved")152 def test_put_issue_status_by_issue_creator(self):153 """Testing the154 PUT review-requests/<id>/reviews/<id>/screenshot-comments/<id>/ API155 permissions for issue creator156 """157 comment, review, review_request = self._create_screenshot_review_with_issue(publish=True)158 review_request.submitter = User.objects.get(username="doc")159 review_request.save()160 rsp = self.api_put(get_review_screenshot_comment_item_url(review, comment.pk), {"issue_status": "dropped"}, expected_mimetype=screenshot_comment_item_mimetype)161 self.assertEqual(rsp["stat"], "ok")162 self.assertEqual(rsp["screenshot_comment"]["issue_status"], "dropped")163 def test_put_issue_status_by_uninvolved_user(self):164 """Testing the165 PUT review-requests/<id>/reviews/<id>/screenshot-comments/<id>/ API166 permissions for an uninvolved user167 """168 comment, review, review_request = self._create_screenshot_review_with_issue(publish=True)169 new_owner = User.objects.get(username="doc")170 review_request.submitter = new_owner171 review_request.save()172 review.user = new_owner173 review.save()174 rsp = self.api_put(get_review_screenshot_comment_item_url(review, comment.pk), {"issue_status": "dropped"}, expected_status=403)175 self.assertEqual(rsp["stat"], "fail")176 self.assertEqual(rsp["err"]["code"], PERMISSION_DENIED.code)177 def test_put_deleted_screenshot_comment_issue_status(self):178 """Testing the179 PUT review-requests/<id>/reviews/<id>/screenshot-comments/<id>180 API with an issue and a deleted screenshot181 """182 comment_text = "Test screenshot comment with an opened issue"183 x, y, w, h = (2, 2, 10, 10)184 review_request = self.create_review_request(publish=True, submitter=self.user, target_people=[self.user])185 screenshot = self.create_screenshot(review_request)186 review = self.create_review(review_request, user=self.user)187 comment = self.create_screenshot_comment(review, screenshot, comment_text, x, y, w, h, issue_opened=True)188 rsp = self.api_put(get_review_screenshot_comment_item_url(review, comment.pk), {"issue_status": "resolved"}, expected_mimetype=screenshot_comment_item_mimetype)189 self.assertEqual(rsp["stat"], "ok")190 self.assertEqual(rsp["screenshot_comment"]["issue_status"], "open")191 review.public = True192 review.save()193 rsp = self.api_put(rsp["screenshot_comment"]["links"]["self"]["href"], {"issue_status": "resolved"}, expected_mimetype=screenshot_comment_item_mimetype)194 self.assertEqual(rsp["stat"], "ok")195 self.assertEqual(rsp["screenshot_comment"]["issue_status"], "resolved")196 self._delete_screenshot(review_request, screenshot)197 review_request.publish(review_request.submitter)198 rsp = self.api_put(rsp["screenshot_comment"]["links"]["self"]["href"], {"issue_status": "open"}, expected_mimetype=screenshot_comment_item_mimetype)199 self.assertEqual(rsp["stat"], "ok")...
areafinder.py
Source:areafinder.py
1#!/usr/bin/env python32import pyautogui as pg3# im = pg.screenshot(region=(600,635,720,150)) #local and online4# im = pg.screenshot(region=(965,635,355,150)) #online only5# im = pg.screenshot(region=(782,650,360,100)) #find public game6# im = pg.screenshot(region=(435, 335, 1050, 650)) #public game search7# im = pg.screenshot(region=(1480, 335, 135, 135)) # public game refresh X: 1550 Y: 4008# im = pg.screenshot(region=(782,350,360,100)) #Create Game Online9# im = pg.screenshot(region=(1600, 965, 280, 80)) #Confirm Host Game10# im = pg.screenshot(region=(590, 946, 200, 70)) # switch private to public11# im = pg.screenshot(region=(1182, 957, 130, 50)) #max lobby count12# im = pg.screenshot(region=(793, 712, 335, 196)) #start hosted lobby13# im = pg.screenshot(region=(420,88,1000,145)) #announcements X:464 Y:13314# im = pg.screenshot(region=(420,400,1000,280)) #Disconnected From Server15# im = pg.screenshot(region=(420,400,1000,280)) #Game ban for disconnecting X: Y:16# im = pg.screenshot(region=(420,400,1000,280)) #Matchmaker is full17# im = pg.screenshot(region=(420,400,1000,280)) #Game Session Is Full18# im = pg.screenshot(region=(420,400,1000,280)) #Game Session Kicked19# im = pg.screenshot(region=(420,400,1000,280)) #Game Session Banned20# im = pg.screenshot(region=(420,400,1000,280)) #Game Session Has Started21# im = pg.screenshot(region=(420,400,1000,280)) #Game Matchmacker Has Been Disconnected22# im = pg.screenshot(region=(420,400,1000,280)) #Server Closed to inactivity23# im = pg.screenshot(region=(420,400,1000,280)) #Game is not upto date24# im = pg.screenshot(region=(420,400,1000,280)) #Matchmaker disconnected25# im = pg.screenshot(region=(420,400,1000,280)) #Game not found26#im = pg.screenshot(region=(1650, 0, 125, 125)) #Game Comment Icon X:1518 Y:13027# im = pg.screenshot(region=(1650, 0, 125, 125)) #Game Comment Icon2 X:1518 Y:13028# im = pg.screenshot(region=(1450, 70, 125, 125)) # Meeting Game Comment Icon X: 1513 Y: 12829# im = pg.screenshot(region=(1450, 70, 125, 125)) # Meeting Game Comment Icon2 X:1513 Y: 12830# im = pg.screenshot(region=(1450, 70, 125, 125)) # open meeting game comment icon X: 1513 Y: 12831# im = pg.screenshot(region=(1680, 770, 210, 300)) #Play Again Button32# im = pg.screenshot(region=(290,910,205,55)) # Click Vote to skip33# im = pg.screenshot(region=(525, 890, 95, 95)) #Confirm Vote To Skip34# im = pg.screenshot(region=(270, 850, 1150, 130)) #Comment Box X: Y: 35# im = pg.screenshot(region=(1320, 875, 80, 75)) #Comment submit X: 1360 Y: 90636# im = pg.screenshot(region=(550, 100, 728, 88)) #Who is imposter X: Y: 37# im = pg.screenshot(region=(420,400,1000,280)) # game requires update X: 1513 Y: 12838# im = pg.screenshot(region=(420,400,1000,280)) #Packets no response39# im = pg.screenshot(region=(850,240,590,455)) #upload data X:959 Y: 65540# im = pg.screenshot(region=(850,310,575,400)) #download dataX:959 Y: 65541# im = pg.screenshot(region=(580,140,780,260)) #calibrate yellow distributor X:1234 Y:30642# im = pg.screenshot(region=(580,140,780,530)) #calibrate dark blue distributor X:1234 Y:58043# im = pg.screenshot(region=(580,140,780,800)) #calibrate light blue distributor X:1234 Y:83544#im = pg.screenshot(region=(375,88,1200,275)) #User is Imposter X: Y:45# im = pg.screenshot(region=(365,88,1200,275)) #User is crewmate X: Y:46# im = pg.screenshot(region=(909,477,99,121)) #Get user on screen X: Y:47#####For Keyboard Moving########48# im = pg.screenshot(region=(0,0,908,485)) #Screen Area 1 X: Y:49# im = pg.screenshot(region=(900,0,125,454)) #Screen Area 2 X: Y: 50# im = pg.screenshot(region=(1000,0,908,485)) #Screen Area 3 X: Y:51# im = pg.screenshot(region=(0,450,908,160)) #Screen Area 4 X: Y:52# im = pg.screenshot(region=(1012,450,908,160)) #Screen Area 5 X: Y:53# im = pg.screenshot(region=(0,580,908,500)) #Screen Area 6 X: Y:54# im = pg.screenshot(region=(900,580,125,500)) #Screen Area 7 X: Y: 55# im = pg.screenshot(region=(1000,580,908,500)) #Screen Area 8 X: Y:56#####For Keyboard Moving########57#im = pg.screenshot(region=(70,100,1600,890)) #Get area on screen for mouse moving X: Y:58# im = pg.screenshot(region=(0,0,1700,485)) #Top of screen X: Y:59# im = pg.screenshot(region=(0,300,908,450)) #Left side of screen X: Y:60im = pg.screenshot(region=(1012,300,700,450)) #Right side of screen X: Y:61# im = pg.screenshot(region=(0,580,1700,500)) #Bottom Of screenX: Y:62# Todo for tasks for the skeld63# admin swipe card64# weapons clear asteroids65# Electrical Divert Power66# Fix Wiring67# Medbay inspect sample68# Medbay Submit Scan69# Empty Garbage70# Navigation Stabilize Steering71# Align Engine output72# Clean o2 filter73# Fuel Engines74# Start Reactor75# Navigation chart course...
screenshot_utils.py
Source:screenshot_utils.py
...17 driver.maximize_window()18 screenshot = "./result/screenshot/"19 file_name = str(time.time())20 screenshot = screenshot + file_name + ".png"21 driver.save_screenshot(screenshot)22 time.sleep(3)23 allure.attach.file(screenshot, attachment_type=AttachmentType.PNG)24 time.sleep(2)25 except Exception as e:26 pass27def take_full_screenshot(driver, scenario_name):28 if(driver == None):29 return None30 driver.maximize_window()31 from Screenshot import Screenshot_Clipping32 screen_img_path = "./result/screenshot/"33 img_file_name = str(time.time())34 img_file_name = img_file_name + ".png"35 browserScreenShot = Screenshot_Clipping.Screenshot()36 img_url = browserScreenShot.full_Screenshot(driver, save_path=screen_img_path, image_name=img_file_name)37 # print(img_url)38 # allure.attach.file(source=img_url, name=scenario_name, attachment_type=AttachmentType.PNG)39 allure.attach.file(img_url, attachment_type=AttachmentType.PNG)40 # driver.quit()41def take_test_screen_shot(driver, scenario_name):42 import time43 import allure44 from allure_commons.types import AttachmentType45 if (driver == None):46 return None47 try:48 # time.sleep(5)49 # driver.maximize_window()50 screenshot = "./result/screenshot/"51 file_name = str(time.time())52 screenshot = screenshot + file_name + ".png"53 driver.save_screenshot(screenshot)54 time.sleep(3)55 allure.attach.file(screenshot, attachment_type=AttachmentType.PNG)56 time.sleep(2)57 except Exception as e:58 pass...
Using AI Code Generation
1const differencify = require('differencify');2const { setDefaultOptions } = require('expect-puppeteer');3const { toMatchImageSnapshot } = require('jest-image-snapshot');4expect.extend({ toMatchImageSnapshot });5setDefaultOptions({ timeout: 1000 });6describe('Google', () => {7 let differencifyInstance;8 beforeAll(async () => {9 differencifyInstance = await differencify.init(page, {10 { x: 0, y: 0, width: 100, height: 100 },11 { x: 200, y: 200, width: 300, height: 300 },12 });13 });14 afterAll(async () => {15 await differencify.cleanup();16 });17 it('should match the baseline', async () => {18 await page.waitForSelector('input[name="q"]');19 await page.type('input[name="q"]', 'Hello World');20 const image = await differencifyInstance.screenshot();21 expect(image).toMatchImageSnapshot();22 });23});
Using AI Code Generation
1const differencify = require('differencify');2const differencifyConfig = require('./differencify.config.js');3const differencifyInstance = differencify.init(differencifyConfig);4const assert = require('assert');5describe('Differencify', () => {6 it('should take a screenshot', async () => {7 const screenshot = await browser.takeScreenshot();8 const result = await differencifyInstance.check(screenshot, 'webdriverio');9 assert.strictEqual(result.isWithinMisMatchTolerance, true);10 });11});12const differencify = require('differencify');13const differencifyConfig = require('./differencify.config.js');14const differencifyInstance = differencify.init(differencifyConfig);15const assert = require('assert');16describe('Differencify', () => {17 it('should take a screenshot', async () => {18 const screenshot = await browser.takeScreenshot();19 const result = await differencifyInstance.check(screenshot, 'webdriverio');20 assert.strictEqual(result.isWithinMisMatchTolerance, true);21 });22});23const differencify = require('differencify');24const differencifyConfig = require('./differencify.config.js');25const differencifyInstance = differencify.init(differencifyConfig);26const assert = require('assert');27describe('Differencify', () => {28 it('should take a screenshot', async () => {29 const screenshot = await browser.takeScreenshot();30 const result = await differencifyInstance.check(screenshot, 'webdriverio');31 assert.strictEqual(result.isWithinMisMatchTolerance, true);32 });33});34const differencify = require('differencify');35const differencifyConfig = require('./differencify
Using AI Code Generation
1const differencify = require('differencify');2const differencifyPuppeteer = require('differencify/dist/puppeteer');3const puppeteer = require('puppeteer');4const { toMatchImageSnapshot } = require('jest-image-snapshot');5expect.extend({ toMatchImageSnapshot });6jest.setTimeout(30000);7const initDifferencify = async () => {8 const browser = await puppeteer.launch({9 });10 const differencifyInstance = differencify.init(browser);11 differencify.use(differencifyPuppeteer);12 return differencifyInstance;13};14describe('Google', () => {15 let differencifyInstance;16 beforeAll(async () => {17 differencifyInstance = await initDifferencify();18 });19 afterAll(async () => {20 await differencifyInstance.cleanup();21 });22 it('should match the home page', async () => {23 const page = await differencifyInstance.newPage();24 const image = await page.screenshot();25 expect(image).toMatchImageSnapshot();26 });27});
Using AI Code Generation
1const differencify = require('differencify');2const { setDefaultOptions } = require('expect-puppeteer');3setDefaultOptions({ timeout: 5000 });4describe('Google', () => {5 beforeAll(async () => {6 });7 it('should display "google" text on page', async () => {8 await expect(page).toMatch('google');9 });10 it('should display "google" text on page', async () => {11 await expect(page).toMatch('google');12 });13 it('should display "google" text on page', async () => {14 await expect(page).toMatch('google');15 });16 it('should display "google" text on page', async () => {17 await expect(page).toMatch('google');18 });19 it('should display "google" text on page', async () => {20 await expect(page).toMatch('google');21 });22 it('should display "google" text on page', async () => {23 await expect(page).toMatch('google');24 });25 it('should display "google" text on page', async () => {26 await expect(page).toMatch('google');27 });28 it('should display "google" text on page', async () => {29 await expect(page).toMatch('google');30 });31});32const differencify = require('differencify');33const { setDefaultOptions } = require('expect-puppeteer');34setDefaultOptions({ timeout: 5000 });35describe('Google', () => {36 beforeAll(async () => {37 });38 it('should display "google" text on page', async () => {39 await expect(page).toMatch('google');40 });41});
Using AI Code Generation
1const differencify = require('differencify');2const { toMatchImageSnapshot } = require('jest-image-snapshot');3expect.extend({ toMatchImageSnapshot });4describe('Visual Regression', () => {5 it('should match the home page', async () => {6 const differencifyInstance = differencify.init(browser);7 const image = await differencifyInstance.screenshot();8 expect(image).toMatchImageSnapshot();9 });10});11const differencify = require('differencify');12const { toMatchDifferencifySnapshot } = require('differencify/jest');13expect.extend({ toMatchDifferencifySnapshot });14describe('Visual Regression', () => {15 it('should match the home page', async () => {16 const image = await browser.takeScreenshot();17 expect(image).toMatchDifferencifySnapshot();18 });19});20const differencify = require('differencify');21const { toMatchDifferencifySnapshot } = require('differencify/jest');22expect.extend({ toMatchDifferencifySnapshot });23describe('Visual Regression', () => {24 it('should match the home page', async () => {25 const image = await browser.takeScreenshot();26 expect(image).toMatchDifferencifySnapshot({
Using AI Code Generation
1const differencify = require('differencify');2const assert = require('assert');3describe('Test', function() {4 this.timeout(10000);5 let browser;6 before(async () => {7 browser = await differencify.launch();8 });9 after(async () => {10 await browser.close();11 });12 it('should take screenshot', async () => {13 const page = await browser.newPage();14 const image = await page.screenshot();15 assert.ok(image);16 });17});18### differencify.launch([options])19Launches a new browser instance. The `options` object will be passed to [puppeteer.launch](
Using AI Code Generation
1const { toMatchImageSnapshot } = require('jest-image-snapshot');2const { takeScreenshot } = require('differencify');3expect.extend({ toMatchImageSnapshot });4describe('Google', () => {5 it('should match google homepage', async () => {6 const image = await takeScreenshot(page);7 expect(image).toMatchImageSnapshot();8 });9});
Using AI Code Generation
1const differencify = require("differencify");2const { expect } = require("chai");3const { By } = require("selenium-webdriver");4describe("Test", function () {5 this.timeout(0);6 let driver;7 let differencifyInstance;8 before(async () => {9 differencifyInstance = await differencify.init(browser);10 driver = differencifyInstance.driver;11 });12 it("should take screenshot", async () => {13 const screenshot = await driver.takeScreenshot();14 const element = await driver.findElement(By.name("q"));15 const elementScreenshot = await element.takeScreenshot();16 expect(screenshot).to.matchImage("screenshot");17 expect(elementScreenshot).to.matchImage("elementScreenshot");18 });19 after(async () => {20 await differencifyInstance.cleanup();21 });22});
Using AI Code Generation
1const differencify = require('differencify');2const assert = require('assert');3describe('Test', function() {4 this.timeout(5describe('Differencify', () => {6 it('should take a screenshot', async () => {7 const screenshot = await browser.takeScreenshot();8 const result = await differencifyInstance.check(screenshot, 'webdriverio');9 assert.strictEqual(result.isWithinMisMatchTolerance, true);10 });11});12const differencify = require('differencify');13const differencifyConfig = require('./differencify.config.js');14const differencifyInstance = differencify.init(differencifyConfig);15const assert = require('assert');16describe('Differencify', () => {17 it('should take a screenshot', async () => {18 const screenshot = await browser.takeScreenshot();(
Using AI Code Generation
1const { toMatchImageSnapshot } = require('jest-image-snapshot');2const { takeScreenshot } = require('differencify');3expect.extend({ toMatchImageSnapshot });4describe('Google', () => {5 it('should match google homepage', async () => {6 const image = await takeScreenshot(page);7 expect(image).toMatchImageSnapshot();8 });9});
Using AI Code Generation
1const differencify = require("differencify");2const { expect } = require("chai");3const { By } = require("selenium-webdriver");4describe("Test", function () {5 this.timeout(0);6 let driver;7 let differencifyInstance;8 before(async () => {9 differencifyInstance = await differencify.init(browser);10 driver = differencifyInstance.driver;11 });12 it("should take screenshot", async () => {13 const screenshot = await driver.takeScreenshot);14 const element = await driver.findElement(By.name("q"));15 const elementScreenshot = await element.takeScreenshot();16 expect(screenshot).to.matchImage("screenshot");17 expect(elementScreenshot).to.matchImage("elementScreenshot");18 });19 after(async () => {20 await differencifyInstance.cleanup();21 });22});23 const result = await differencifyInstance.check(screenshot, 'webdriverio');24 assert.strictEqual(result.isWithinMisMatchTolerance, true);25 });26});27const differencify = require('differencify');28const differencifyConfig = require('./differencify.config.js');29const differencifyInstance = differencify.init(differencifyConfig);30const assert = require('assert');31describe('Differencify', () => {32 it('should take a screenshot', async () => {33 const screenshot = await browser.takeScreenshot();34 const result = await differencifyInstance.check(screenshot, 'webdriverio');35 assert.strictEqual(result.isWithinMisMatchTolerance, true);36 });37});38const differencify = require('differencify');39const differencifyConfig = require('./differencify
Using AI Code Generation
1const differencify = require('differencify');2const assert = require('assert');3describe('Test', function() {4 this.timeout(10000);5 let browser;6 before(async () => {7 browser = await differencify.launch();8 });9 after(async () => {10 await browser.close();11 });12 it('should take screenshot', async () => {13 const page = await browser.newPage();14 const image = await page.screenshot();15 assert.ok(image);16 });17});18### differencify.launch([options])19Launches a new browser instance. The `options` object will be passed to [puppeteer.launch](
Using AI Code Generation
1const differencify = require("differencify");2const { expect } = require("chai");3const { By } = require("selenium-webdriver");4describe("Test", function () {5 this.timeout(0);6 let driver;7 let differencifyInstance;8 before(async () => {9 differencifyInstance = await differencify.init(browser);10 driver = differencifyInstance.driver;11 });12 it("should take screenshot", async () => {13 const screenshot = await driver.takeScreenshot();14 const element = await driver.findElement(By.name("q"));15 const elementScreenshot = await element.takeScreenshot();16 expect(screenshot).to.matchImage("screenshot");17 expect(elementScreenshot).to.matchImage("elementScreenshot");18 });19 after(async () => {20 await differencifyInstance.cleanup();21 });22});
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!!