Best Python code snippet using playwright-python
utilities.py
Source:utilities.py
1import functools2import pygame3from baopig.pybao.issomething import is_point4from baopig.pybao.objectutilities import PackedFunctions, PrefilledFunction, TypedDict, WeakTypedSet, Object5from baopig._debug import debug_with_assert6from baopig.ressources import *7from baopig.communicative import ApplicationExit8from baopig.io import LOGGER, mouse, keyboard9"""10 NOTE : handle functionnement11 In order to execute a function at handle_something, write :12 handle_something.add(function)13 14"""15import threading16paint_lock = threading.RLock()17# TODO : deproteger les attributs handle_something18class Size(tuple):19 def __init__(self, size):20 assert len(self) is 2, f"Wrong length : {self} (a size only have 2 elements)"21 for coord in self:22 assert isinstance(coord, (int, float)), f"Wrong value in size : {coord} (must be a number)"23 assert coord >= 0, f"Wrong value in size : {coord} (must be positive)"24class Color(pygame.Color):25 """26 Very close to pygame.Color :27 Color(tuple) -> Color28 Color(name) -> Color29 Color(r, g, b, a) -> Color30 Color(rgbvalue) -> Color31 pygame object for color representations32 """33 def __init__(self, *args, transparency=None, **kwargs):34 if transparency is None:35 try:36 pygame.Color.__init__(self, *args, **kwargs)37 except ValueError:38 pygame.Color.__init__(self, *args[0])39 else:40 try:41 color = pygame.Color(*args, **kwargs)42 except ValueError:43 color = pygame.Color(*args[0])44 pygame.Color.__init__(self, color.r, color.g, color.b, transparency)45 def set_hsv(self, val):46 if val[1] > 100:47 val = val[0], 100, val[2]48 try:49 self.hsva = val + (100,)50 except ValueError as e:51 raise ValueError(str(e) + f" : {val}")52 hsv = property(lambda self: self.hsva[:-1], set_hsv)53 def set_hsl(self, val):54 if val[1] > 100:55 val = val[0], 100, val[2]56 try:57 self.hsla = val + (100,)58 except ValueError as e:59 raise ValueError(str(e) + f" : {val}")60 hsl = property(lambda self: self.hsla[:-1], set_hsl)61 def set_hue(self, h):62 self.hsv = (h,) + self.hsv[1:]63 h = property(lambda self: self.hsva[0], set_hue)64 def get_saturation(self):65 s = self.hsva[1]66 if s > 100: # sometime 100.0000000000000167 s = 10068 return s69 def set_saturation(self, s):70 self.hsv = self.h, s, self.v71 s = property(get_saturation, set_saturation)72 def set_value(self, v):73 self.hsv = self.hsva[:2] + (v,)74 v = property(lambda self: self.hsva[2], set_value)75 def set_lightness(self, l):76 self.hsl = self.hsla[:2] + (l,)77 l = property(lambda self: self.hsla[2], set_lightness)78 def copy(self):79 return self.__class__(self)80 def has_transparency(self):81 return self.a < 25582class MarginType:83 def __init__(self, margin):84 if margin is None:85 margin = 0, 0, 0, 086 elif isinstance(margin, int):87 margin = tuple([margin] * 4)88 elif isinstance(margin, MarginType):89 margin = margin.left, margin.top, margin.right, margin.bottom90 else:91 l = len(margin)92 if l is 2:93 margin = tuple(margin) + tuple(margin)94 elif l is 3:95 margin = tuple(margin) + tuple([margin[1]])96 else:97 assert l is 4, f"Wrong value for margin type : {margin}"98 self.left = margin[0]99 self.top = margin[1]100 self.right = margin[2]101 self.bottom = margin[3]102 def __repr__(self):103 return f"MarginType(left={self.left}, top={self.top}, right={self.right}, bottom={self.bottom})"104 is_null = property(lambda self: self.left == self.top == self.right == self.bottom == 0)105def decorator_enable(widget, enable):106 functools.wraps(enable)107 def wrapped_func(*args, **kwargs):108 if widget.is_enabled: return109 widget._is_enabled = True110 res = enable(*args, **kwargs)111 widget.signal.ENABLE.emit()112 return res113 return wrapped_func114def decorator_disable(widget, disable):115 functools.wraps(disable)116 def wrapped_func(*args, **kwargs):117 if widget.is_enabled is False: return118 widget._is_enabled = False119 res = disable(*args, **kwargs)120 widget.signal.DISABLE.emit()121 return res122 return wrapped_func123class Enablable:124 def __init__(self):125 self.enable = decorator_enable(self, self.enable)126 self.disable = decorator_disable(self, self.disable)127 self._is_enabled = True128 self.create_signal("ENABLE")129 self.create_signal("DISABLE")130 is_enabled = property(lambda self: self._is_enabled)131 def enable(self):132 """Stuff to do when enable is called (decorated method)"""133 @staticmethod134 def enabled_from(enables_list):135 return tuple(Enablable.ienabled_from(enables_list))136 def disable(self):137 """Stuff to do when disable is called (decorated method)"""138 @staticmethod139 def ienabled_from(enables_list):140 for enablable in enables_list:141 if enablable.is_enabled:142 yield enablable143def decorator_validate(widget, validate):144 functools.wraps(validate)145 def wrapped_func(*args, **kwargs):146 if widget._catch_errors:147 res = None148 try:149 res = validate(*args, **kwargs)150 except Exception as e:151 if isinstance(e, ApplicationExit):152 raise e153 LOGGER.warning("Error while executing {} validation: {}".format(widget, e))154 else:155 res = validate(*args, **kwargs)156 widget.signal.VALIDATE.emit(res)157 return res158 return wrapped_func159class Validable:160 def __init__(self, catching_errors=False):161 self.validate = decorator_validate(self, self.validate)162 self._catch_errors = catching_errors163 self.create_signal("VALIDATE")164 if isinstance(self, Focusable):165 self.connect("_check_validate", self.signal.KEYDOWN)166 catching_erros = property(lambda self: self._catch_errors)167 def _check_validate(self, key):168 """Checks if the keydown asks for validation"""169 if key is keyboard.RETURN:170 # Enter or validation key171 self.validate()172 def validate(self):173 """Stuff to do when validate is called (decorated method)"""174class Focusable(Enablable):175 """176 A Focusable is a Widget who listen to keyboard input, when it has the focus. Only one177 widget can be focused in the same time. When a new clic occurs and it doesn't collide178 this widget, it is defocused. If disabled, it cannot be focused.179 It has no 'focus' method since it is the application who decide who is focused or not.180 However, it can defocus itself or send a request for focusing the next focusable in the181 container parent182 When the mouse click on a Text inside a Button inside a focusable Zone inside a Scene,183 then the only the youngest Focusable is focused184 Here, it is the Button -> display.focused_comp = Button185 """186 def __init__(self):187 Enablable.__init__(self)188 self._is_focused = False189 self.create_signal("FOCUS")190 self.create_signal("DEFOCUS")191 self.create_signal("KEYDOWN")192 self.create_signal("KEYUP")193 self.connect("defocus", self.signal.DISABLE)194 self.connect("handle_focus", self.signal.FOCUS)195 self.connect("handle_defocus", self.signal.DEFOCUS)196 self.connect("handle_keydown", self.signal.KEYDOWN)197 self.connect("handle_keyup", self.signal.KEYUP)198 is_focused = property(lambda self: self._is_focused)199 def defocus(self):200 """Send a request for defousing this widget"""201 if not self.is_focused:202 return203 self.scene._focus(None)204 def focus_antecedant(self):205 """206 Give the focus to the previous focusable (ranked by position) is self.parent207 """208 all_focs = self.parent.children.focusables209 all_focs.sort()210 all_focs = Enablable.enabled_from(self.ivisibles_from(all_focs))211 for foc in all_focs:212 assert foc.is_visible and foc.is_enabled213 if len(all_focs) > 1:214 self.scene._focus(all_focs[(all_focs.index(self) -1) % len(all_focs)])215 def focus_next(self):216 """217 Give the focus to the next focusable (ranked by position) is self.parent218 """219 all_focs = self.parent.children.focusables220 all_focs.sort()221 all_focs = Enablable.enabled_from(self.ivisibles_from(all_focs))222 for foc in all_focs:223 assert foc.is_visible and foc.is_enabled224 if len(all_focs) > 1:225 self.scene._focus(226 all_focs[(all_focs.index(self) + (1 if keyboard.mod.maj == 0 else -1))227 % len(all_focs)])228 def handle_defocus(self):229 """Stuff to do when the widget loose the focus"""230 def handle_focus(self):231 """Stuff to do when the widget receive the focus"""232 def handle_keydown(self, key):233 """Stuff to do when a key is pressed"""234 # Default code :235 # Checks if the keydown asks for swap focus236 # TODO : should we say that the TAB has to focus the next (other method connected to KEYDOWN) or let an override ?237 if key == keyboard.TAB:238 self.focus_next()239 def handle_keyup(self, key):240 """Stuff to do when a key is released"""241class Linkable(Focusable):242 """243 Abstract class for components who need to capture mouse clicks244 A Linkable is linked when a mouse LEFT BUTTON DOWN collide with it,245 and unlinked when the LEFT BUTTON UP occurs246 It has no 'link' or 'link_motion' method since it is the mouse who manages links.247 However, it can unlink itself248 WARNING : If a Linkable parent contains a Linkable child, and the LEFT BUTTON249 DOWN has occured on the child, then only the child will be linked250 NOTE : when a component is linked, you can access it via mouse.linked_comp251 """252 def __init__(self):253 Focusable.__init__(self)254 self.is_linked = False255 self.create_signal("LINK")256 self.create_signal("LINK_MOTION")257 self.create_signal("UNLINK")258 self.connect("handle_link", self.signal.LINK)259 self.connect("handle_link_motion", self.signal.LINK_MOTION)260 self.connect("handle_unlink", self.signal.UNLINK)261 def handle_link(self):262 """Stuff to do when the widget gets linked"""263 def handle_link_motion(self, link_motion_event):264 """Stuff to do when the widget'link has changed"""265 def handle_unlink(self):266 """Stuff to do when the widget's link is over"""267 def unlink(self):268 """Send a request for unlinking this widget"""269 if self is not mouse.linked_comp:270 raise PermissionError(f"{self} is not linked")271 mouse._unlink()272class Clickable(Linkable, Validable):273 """274 Abstract class for components who need to handle when they are clicked275 A component is clicked when the link is released while the mouse is still276 hovering it (for more explanations about links, see Linkable)277 WARNING : If a Clickable parent contains a Clickable child, and the click278 has occured on the child, then only the child will handle the click279 """280 def __init__(self, catching_errors=False):281 Linkable.__init__(self)282 Validable.__init__(self, catching_errors=catching_errors)283 def unlink():284 if self.collidemouse(): self.validate()285 self.signal.UNLINK.connect(unlink)286class Closable:287 """288 A Closable is a widget whose 'close' function is called when its scene is closed289 """290 def close(self):291 """Stuff to do when the widget'scene is closed"""292class Dragable(Linkable):293 """294 Abstract class for components who want to be moved by mouse295 NOTE : a link_motion pointing a dragable's child will drag the parent if the child is not Linkable296 """297 # TODO : solve : a component can be set dragable two times, wich create an overdrag298 def __init__(self):299 Linkable.__init__(self)300 def drag(drag_event):301 self.move(*drag_event.rel)302 self.signal.LINK_MOTION.connect(drag)303 @staticmethod304 def set_dragable(widget):305 if not hasattr(widget, "is_linked"):306 Linkable.__init__(widget)307 widget.is_linked = False308 # widget.handle_link.add(lambda: setattr(widget, "is_linked", True))309 # widget.handle_unlink.add(lambda: setattr(widget, "is_linked", False))310 def drag(drag_event):311 widget.move(*drag_event.rel)312 widget.signal.LINK_MOTION.connect(drag)313class Openable:314 """315 An Openable is a widget whose 'open' function is called when its scene gets open316 """317 # TODO : rework318 def open(self):...
textToimg.py
Source:textToimg.py
...97 # messages.append(buttons_template_message)98 line_bot_api.reply_message(event.reply_token, messages)99 100@handler.add(MessageEvent, message=TextMessage)101def handle_something(event):102 103 recrive_text=event.message.text104 FlexMessage_index = json.load(open('index.json','r',encoding='utf-8'))105 buttons_template_message = TemplateSendMessage(106 alt_text='Buttons template',107 template=ButtonsTemplate(108 thumbnail_image_url='https://img.technews.tw/wp-content/uploads/2020/12/08132944/female-tourists-travel-map-624x378.jpg',109 title='æ
éå©æ',110 text='è«é¸ææ¨éè¦çæå',111 actions=[112 MessageAction(113 label='æå辨èèç¿»è¯',114 text='æå辨èèç¿»è¯'115 ),...
dtest.py
Source:dtest.py
...35 handler = self.handlers.get(message_name, None)36 return handler37class DTest(object):38 msg_handlers = HandlerCollection()39 def handle_something(self, key):40 method = self.msg_handlers.handler_for(key)41 if method is None:42 print "error: unknown key", key43 else:44 print "calling method", method.__name__45 method(self, "123456789")46 @msg_handlers.handler("dupa")47 def dupa_handler(self, arg):48 print self49 print "I am a dupa handler", arg50 @msg_handlers.handler("ble")51 def another_handler(self, arg):52 print self53 print "tralala", arg54 @msg_handlers.default_handler()55 def default_handler(self, arg):56 print "default handler --------"57class D(DTest):58 msg_handlers = super.msg_handlers.new_from(DTest.msg_handlers)59 @msg_handlers.handler("ble")60 def assasd(self, arg):61 """changed"""62 print "changed"63 @msg_handlers.handler("dupa")64 def dupa_handler(self, arg):65 """Subclassed"""66 print "subcl"67class A(DTest):68 msg_handlers = HandlerCollection.new_from(DTest.msg_handlers)69 @DTest.msg_handlers.handler("ble")70 def assd(self, arg):71 """AAA changed"""72 print "----"73 @DTest.msg_handlers.handler("dupa")74 def dupa_handler(self, arg):75 """AAAA Subclassed"""76 print "AAAA subcl"77print "subclass", D.msg_handlers78if __name__ == '__main__':79 dt = D()80 aa = A()81 dt.handle_something("dupa")82 dt.handle_something("ble")...
scripts.py
Source:scripts.py
...34 # èªå¨æ§è¡æµè½¬35 WfService.handle_ticket(ticket=ticket, transition=transition_obj, new_ticket_data=ticket.ticket_data, by_task=True)36 return ticket37 @classmethod38 def handle_something(cls, ticket:Ticket):39 """å¤çä¸äºå·¥ä½"""40 # ä»»å¡å¤ç代ç åº41 # è°ç¨èªå¨æµè½¬42 ticket = cls.to_next(ticket=ticket, by_task=True, script_str= 'handle_something')...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!