Best Python code snippet using Airtest
win.py
Source:win.py
1# -*- coding: utf-8 -*-2import ctypes3import time4import cv25import numpy as np6import win32api7import win32con8import win32gui9import win32ui10import pywintypes11from winAuto.utils.window import GetWindowInfo12from winAuto.cap_methods import BitBlt, WindowGraphicsCapture13from pywinauto.application import Application14from pywinauto import mouse, keyboard, win32structures15from pywinauto.win32functions import SetFocus16from baseImage import Rect, Point, Size, Image17from .constant import SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SCREENSHOT_MODE18from .exceptions import WinBaseError, WinConnectError19from typing import Dict, Union, Tuple, List20class Win(object):21 def __init__(self, handle: int = None, handle_title: str = None, handle_class: str = None,22 window_border: Union[Tuple, List, None] = None, cap_method=SCREENSHOT_MODE.WindowsGraphicsCapture):23 """24 Args:25 handle: çªå£å¥æ26 handle_title: çªå£å27 handle_class: çªå£ç±»å28 window_border: æ¯å¦åå¨å¸¦æçªå£å称ç顶é¨æ 29 """30 # user32 = ctypes.windll.user3231 # user32.SetProcessDPIAware()32 if handle:33 self._hwnd = int(handle)34 elif handle_class and handle_title:35 self._hwnd = self.find_window(hwnd_class=handle_class, hwnd_title=handle_title)36 elif handle_title:37 self._hwnd = self.find_window(hwnd_title=handle_title)38 elif handle_class:39 self._hwnd = self.find_window(hwnd_class=handle_class)40 else:41 self._hwnd = None42 self._hwnd = None if self._hwnd == 0 else self._hwnd43 self.app = None44 self._app = Application()45 self._top_window = None46 self._screenshot_size = Size(0, 0)47 self._window_size = Size(win32api.GetSystemMetrics(SM_CXVIRTUALSCREEN), # å
¨å±å¹å°ºå¯¸å¤§å°48 win32api.GetSystemMetrics(SM_CYVIRTUALSCREEN))49 if self._hwnd is None:50 self._hwnd = win32gui.GetDesktopWindow()51 self._screenshot_size = self._window_size52 else:53 rect = win32gui.GetClientRect(self._hwnd)54 self._screenshot_size.width = rect[2]55 self._screenshot_size.height = rect[3]56 self._window_border = window_border or self.get_window_border() # ä¸,ä¸,å·¦,å³57 self.cap_fun = None58 self.cap_method = cap_method59 if self.cap_method == SCREENSHOT_MODE.BitBlt:60 self.cap_fun = BitBlt(hwnd=self._hwnd, border=self._window_border,61 screenshot_size=self._screenshot_size)62 elif self.cap_method == SCREENSHOT_MODE.WindowsGraphicsCapture:63 self.cap_fun = WindowGraphicsCapture(hwnd=self._hwnd)64 else:65 raise ValueError('æªå¡«åcap_methodåæ°')66 self.keyboard = keyboard67 self.mouse = mouse68 print(f'设å¤å辨ç:{self._window_size}, çªå£æç¨å¥æ: {self._hwnd}')69 self.connect()70 def connect(self, timeout: int = 5):71 """72 Args:73 timeout: 设å®è¶
æ¶æ¶é¿74 Returns:75 None76 """77 # TODO: æ£æµå¯¹åºå¥ææ¯å¦å¨åå°78 try:79 self.app = self._app.connect(handle=self._hwnd, timeout=timeout)80 self._top_window = self.app.window(handle=self._hwnd)81 except pywintypes.error as err:82 raise WinConnectError(f"è¿æ¥å¥æ:'{self._hwnd}'è¶
æ¶, error={err}")83 self.set_foreground(self._hwnd)84 def click(self, point: Union[Tuple[int, int], List, Point], duration: Union[float, int, None] = 0.01,85 button: str = 'left'):86 """87 ç¹å»è¿æ¥çªå£çæå®ä½ç½® ps:ç¸å¯¹åæ ,以è¿æ¥çå¥æçªå£å·¦ä¸è§ä¸ºåç¹88 Args:89 point: éè¦ç¹å»çåæ 90 duration: 延è¿91 button: å·¦å³é® left/right92 Returns:93 None94 """95 if isinstance(point, (tuple, list)):96 point = Point(x=point[0], y=point[1])97 point = self._windowpos_to_screenpos(point)98 self.mouse.press(button=button, coords=(point.x, point.y))99 time.sleep(duration)100 self.mouse.release(button=button, coords=(point.x, point.y))101 def swipe(self, point1: Union[Tuple[int, int], List, Point], point2: Union[Tuple[int, int], List, Point],102 duration: Union[float, int, None] = 0.01, steps=5):103 """104 æ»å¨ä¸æ®µè·ç¦»105 Args:106 point1: èµ·å§ç¹107 point2: ç»ç¹108 duration: æ»å¨ç»æå延è¿å¤ä¹
æ¬èµ·109 steps: æ¥é¿110 Returns:111 """112 if isinstance(point1, (tuple, list)):113 point1 = Point(x=point1[0], y=point1[1])114 if isinstance(point2, (tuple, list)):115 point2 = Point(x=point2[0], y=point2[1])116 start = self._windowpos_to_screenpos(point1)117 end = self._windowpos_to_screenpos(point2)118 interval = float(duration) / (steps + 1)119 self.mouse.press(coords=(start.x, start.y))120 time.sleep(interval)121 for i in range(1, steps):122 x = int(start.x + (end.x - start.x) * i / steps)123 y = int(start.y + (end.y - start.y) * i / steps)124 self.mouse.move(coords=(x, y))125 time.sleep(interval)126 self.mouse.move(coords=(end.x, end.y))127 self.mouse.release(coords=(end.x, end.y))128 # # -----------129 # if isinstance(point1, (tuple, list)):130 # point1 = Point(x=point1[0], y=point1[1])131 #132 # if isinstance(point1, (tuple, list)):133 # point2 = Point(x=point2[0], y=point2[1])134 #135 # start = self._windowpos_to_screenpos(point1)136 # end = self._windowpos_to_screenpos(point2)137 # interval = float(duration) / (steps + 1)138 # self.mouse.press(coords=(start.x, start.x))139 # time.sleep(interval)140 # for i in range(1, steps):141 # x = int(start.x + (end.x - start.x) * i / steps)142 # y = int(start.y + (end.y - start.y) * i / steps)143 # self.mouse.move(coords=(x, y))144 # time.sleep(interval)145 # self.mouse.move(coords=(end.x, end.y))146 # self.mouse.release(coords=(end.x, end.y))147 def keyevent(self, keycode: str):148 """149 Perform a key event150 References:151 https://pywinauto.readthedocs.io/en/latest/code/pywinauto.keyboard.html152 Args:153 keycode: key code number or name154 Returns:155 None156 """157 self.keyboard.send_keys(keycode)158 def text(self, text: str):159 """160 è¾å
¥æå161 Args:162 text: å¾
è¾å
¥çæå163 Returns:164 None165 """166 self.keyevent(text)167 def screenshot(self):168 img = Image(self.cap_fun.screenshot())169 if self.cap_method == SCREENSHOT_MODE.WindowsGraphicsCapture:170 # ä¸,ä¸,å·¦,å³ self._window_border171 rect = Rect(x=self._window_border[2],172 y=self._window_border[0],173 width=self._screenshot_size.width,174 height=self._screenshot_size.height)175 return img.crop_image(rect)176 return img177 @staticmethod178 def set_foreground(handle) -> None:179 """180 å°æå®å¥æççªå£å¸¦å°åå°å¹¶æ¿æ´»è¯¥çªå£181 Returns:182 None183 """184 win32gui.SetForegroundWindow(handle)185 @property186 def rect(self) -> Rect:187 """188 è·åçªå£å®¢æ·ç«¯åºåå½åæå¨å±å¹çä½ç½®189 Returns:190 çªå£çä½ç½®(以å
¨å±å·¦ä¸è§å¼å§ä¸ºåç¹çåæ )191 """192 clientRect = win32gui.GetClientRect(self._hwnd)193 point = win32gui.ScreenToClient(self._hwnd, (0, 0))194 rect = Rect(x=abs(point[0]), y=abs(point[1]), width=clientRect[2], height=clientRect[3])195 return rect196 @property197 def title(self) -> str:198 """199 è·åçªå£å200 Returns:201 çªå£å202 """203 return self._top_window.texts()204 def kill(self) -> None:205 """206 å
³éçªå£207 Returns:208 None209 """210 self.app.kill()211 def _windowpos_to_screenpos(self, pos: Point):212 """213 转æ¢ç¸å¯¹åæ 为å±å¹çç»å¯¹åæ 214 Args:215 pos: éè¦è½¬æ¢çåæ 216 Returns:217 Point218 """219 windowpos = self.rect.tl220 pos = pos + windowpos221 return pos222 def get_window_border(self):223 info = GetWindowInfo(self._hwnd)224 print(f'rcWindow: {info.rcWindow.left} {info.rcWindow.top} {info.rcWindow.right} {info.rcWindow.bottom}')225 print(f'rcClient: {info.rcClient.left} {info.rcClient.top} {info.rcClient.right} {info.rcClient.bottom}')226 # ä¸,ä¸,å·¦,å³227 border = (abs(info.rcWindow.top - info.rcClient.top) + 1, 1, 1, 1)228 return border229 @staticmethod230 def find_window(hwnd_class: str = None, hwnd_title: str = None) -> int:231 """232 æ ¹æ®çªå£åæçªå£ç±»åè·å对åºçªå£å¥æ233 Args:234 hwnd_class: çªå£ç±»å235 hwnd_title: çªå£å236 Returns:237 çªå£å¥æ238 """239 return win32gui.FindWindow(hwnd_class, hwnd_title)240 @staticmethod241 def get_all_hwnd() -> Dict[int, str]:242 """243 è·åææå¥æ244 Returns:245 """246 hwnd_title = {}247 def _fun(hwnd, *args):248 if (win32gui.IsWindow(hwnd) and249 win32gui.IsWindowEnabled(hwnd) and250 win32gui.IsWindowVisible(hwnd)):251 hwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)})252 win32gui.EnumWindows(_fun, 0)...
more_wifi.py
Source:more_wifi.py
1from poco.drivers.android.uiautomation import AndroidUiautomationPoco2from airtest.core.api import *3import time4from airtest.core.android import Android5def huawei():6 # device_1 = connect_device('android://192.168.103.156:48887/339b19f1?cap_method=javacap&touch_method=adb')7 # device_1 = connect_device('android:///192.168.103.156:48887?cap_method=javacap&touch_method=adb')8 # device_1 = connect_device('android:///192.168.0.108:48887?cap_method=javacap&touch_method=adb')9 device_1 = connect_device('android:///192.168.103.253:48887?cap_method=javacap&touch_method=adb')10 # device_1 = Android('android://192.168.103.156:48887?cap_method=javacap&touch_method=adb')11 poco = AndroidUiautomationPoco(device=device_1, use_airtest_input=True, screenshot_each_action=False)12 # poco(text="ä»æ¥å¤´æ¡æéç").click()13 # poco(name="com.ss.android.article.lite:id/adg").click()14 # poco(name="com.ss.android.article.lite:id/qp").set_text("å¤åå¥è°ä¸")15 for i in range(500):16 print(i)17 time.sleep(1)18 poco.swipe([0.5,0.8],[0.5,0.2])19def vivo():20 # device_1 = connect_device('android://192.168.103.156:48887/339b19f1?cap_method=javacap&touch_method=adb')21 # device_1 = connect_device('android:///192.168.103.156:48887?cap_method=javacap&touch_method=adb')22 device_1 = connect_device('android:///192.168.0.106:48887?cap_method=javacap&touch_method=adb')23 # device_1 = Android('android://192.168.103.156:48887?cap_method=javacap&touch_method=adb')24 poco = AndroidUiautomationPoco(device=device_1, use_airtest_input=True, screenshot_each_action=False)25 # poco(text="ä»æ¥å¤´æ¡æéç").click()26 # poco(name="com.ss.android.article.lite:id/adg").click()27 # poco(name="com.ss.android.article.lite:id/qp").set_text("å¤åå¥è°ä¸")28 for i in range(500):29 print(i)30 time.sleep(1)31 poco.swipe([0.5,0.8],[0.5,0.2])32if __name__ == '__main__':33 # vivo()...
连接云手机并截图.py
Source:连接云手机并截图.py
1#!/usr/bin/python2# -*- coding: utf-8 -*-3import re4import time5import cv2 as cv6from airtest.core.api import connect_device, device, shell7from airtest.core.error import AdbShellError8class Phone(object):9 def __init__(self, serial_no, cap_method='javacap', touch_method='adb'):10 self.serial_no = str(serial_no)11 self.cap_method = str(cap_method)12 self.touch_method = str(touch_method)13 # è¿æ¥è®¾å¤14 device_url = 'android:///%s?cap_method=%s&touch_method=%s' % (15 self.serial_no, self.cap_method, self.touch_method)16 _device = connect_device(device_url)17 self.device = _device18 print("device connect done!")19 self._rx1 = None20 self._tx1 = None21 self._rx2 = None22 self._tx2 = None23 def shell(self, *args, **kwargs):24 result = self.device.shell(*args, **kwargs)25 return result26 def save_image(self, image, filename):27 cv.imwrite(filename, image)28 return filename29 def snapshot(self, save=False):30 image = self.device.snapshot()31 if save:32 self.save_image(image, filename=f'../dataset/image/snapshot_{str(int(time.time()))}.jpg')33 return image34if __name__ == '__main__':35 # serial_no = '139.159.250.28:8126'36 # serial_no = '139.159.250.28:8129'37 # serial_no = '139.159.250.28:8132'38 serial_no = '139.159.250.28:8135'39 phone = Phone(serial_no=serial_no)...
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!!