How to use _register_rotation_watcher method in Airtest

Best Python code snippet using Airtest

android.py

Source:android.py Github

copy

Full Screen

...42 self.javacap = Javacap(self.adb)43 self.minitouch = Minitouch(self.adb, ori_function=self.get_display_info)44 self.yosemite_ime = YosemiteIme(self.adb)45 self.recorder = Recorder(self.adb)46 self._register_rotation_watcher()47 def get_default_device(self):48 """49 Get local default device when no serailno50 Returns:51 local device serialno52 """53 if not ADB().devices(state="device"):54 raise IndexError("ADB devices not found")55 return ADB().devices(state="device")[0][0]56 @property57 def uuid(self):58 return self.serialno59 def list_app(self, third_only=False):60 """61 Return list of packages62 Args:63 third_only: if True, only third party applications are listed64 Returns:65 array of applications66 """67 return self.adb.list_app(third_only)68 def path_app(self, package):69 """70 Print the full path to the package71 Args:72 package: package name73 Returns:74 the full path to the package75 """76 return self.adb.path_app(package)77 def check_app(self, package):78 """79 Check if package exists on the device80 Args:81 package: package name82 Returns:83 AirtestError: if package is not found84 True if package exists on the device85 """86 return self.adb.check_app(package)87 def start_app(self, package, activity=None):88 """89 Start the application and activity90 Args:91 package: package name92 activity: activity name93 Returns:94 None95 """96 return self.adb.start_app(package, activity)97 def start_app_timing(self, package, activity):98 """99 Start the application and activity, and measure time100 Args:101 package: package name102 activity: activity name103 Returns:104 app launch time105 """106 return self.adb.start_app_timing(package, activity)107 def stop_app(self, package):108 """109 Stop the application110 Args:111 package: package name112 Returns:113 None114 """115 return self.adb.stop_app(package)116 def clear_app(self, package):117 """118 Clear all application data119 Args:120 package: package name121 Returns:122 None123 """124 return self.adb.clear_app(package)125 def install_app(self, filepath, replace=False, install_options=None):126 """127 Install the application on the device128 Args:129 filepath: full path to the `apk` file to be installed on the device130 replace: True or False to replace the existing application131 install_options: list of options, default is []132 Returns:133 output from installation process134 """135 return self.adb.install_app(filepath, replace=replace, install_options=install_options)136 def install_multiple_app(self, filepath, replace=False):137 """138 Install multiple the application on the device139 Args:140 filepath: full path to the `apk` file to be installed on the device141 replace: True or False to replace the existing application142 Returns:143 output from installation process144 """145 return self.adb.install_multiple_app(filepath, replace=replace)146 def uninstall_app(self, package):147 """148 Uninstall the application from the device149 Args:150 package: package name151 Returns:152 output from the uninstallation process153 """154 return self.adb.uninstall_app(package)155 def snapshot(self, filename=None, ensure_orientation=True):156 """157 Take the screenshot of the display. The output is send to stdout by default.158 Args:159 filename: name of the file where to store the screenshot, default is None which si stdout160 ensure_orientation: True or False whether to keep the orientation same as display161 Returns:162 screenshot output163 """164 """default not write into file."""165 if self.cap_method == CAP_METHOD.MINICAP_STREAM:166 self.rotation_watcher.get_ready()167 screen = self.minicap.get_frame_from_stream()168 elif self.cap_method == CAP_METHOD.MINICAP:169 screen = self.minicap.get_frame()170 elif self.cap_method == CAP_METHOD.JAVACAP:171 screen = self.javacap.get_frame_from_stream()172 else:173 screen = self.adb.snapshot()174 # output cv2 object175 try:176 screen = aircv.utils.string_2_img(screen)177 except Exception:178 # may be black/locked screen or other reason, print exc for debugging179 import traceback180 traceback.print_exc()181 return None182 # ensure the orientation is right183 if ensure_orientation and self.display_info["orientation"]:184 # minicap screenshots are different for various sdk_version185 if self.cap_method in (CAP_METHOD.MINICAP, CAP_METHOD.MINICAP_STREAM) and self.sdk_version <= 16:186 h, w = screen.shape[:2] # cvshape是高度在前面!!!!187 if w < h: # 当前是横屏,但是图片是竖的,则旋转,针对sdk<=16的机器188 screen = aircv.rotate(screen, self.display_info["orientation"] * 90, clockwise=False)189 # adb 截图总是要根据orientation旋转,但是SDK版本大于等于25(Android7.1以后)无需额外旋转190 elif self.cap_method == CAP_METHOD.ADBCAP and self.sdk_version <= SDK_VERISON_NEW:191 screen = aircv.rotate(screen, self.display_info["orientation"] * 90, clockwise=False)192 if filename:193 aircv.imwrite(filename, screen)194 return screen195 def shell(self, *args, **kwargs):196 """197 Return `adb shell` interpreter198 Args:199 *args: optional shell commands200 **kwargs: optional shell commands201 Returns:202 None203 """204 return self.adb.shell(*args, **kwargs)205 def keyevent(self, keyname, **kwargs):206 """207 Perform keyevent on the device208 Args:209 keyname: keyeven name210 **kwargs: optional arguments211 Returns:212 None213 """214 self.adb.keyevent(keyname)215 def wake(self):216 """217 Perform wake up event218 Returns:219 None220 """221 self.home()222 self.recorder.install_or_upgrade() # 暂时Yosemite只用了ime223 self.adb.shell(['am', 'start', '-a', 'com.netease.nie.yosemite.ACTION_IDENTIFY'])224 time.sleep(0.5)225 self.keyevent("HOME")226 def home(self):227 """228 Press HOME button229 Returns:230 None231 """232 self.keyevent("HOME")233 def text(self, text, enter=True, **kwargs):234 """235 Input text on the device236 Args:237 text: text to input238 enter: True or False whether to press `Enter` key239 search: True or False whether to press `Search` key on IME after input240 Returns:241 None242 """243 search = False if "search" not in kwargs else kwargs["search"]244 if self.ime_method == IME_METHOD.YOSEMITEIME:245 self.yosemite_ime.text(text)246 else:247 self.adb.shell(["input", "text", text])248 if search:249 self.yosemite_ime.code("3")250 return251 # 游戏输入时,输入有效内容后点击Enter确认,如不需要,enter置为False即可。252 if enter:253 self.adb.shell(["input", "keyevent", "ENTER"])254 def touch(self, pos, duration=0.01):255 """256 Perform touch event on the device257 Args:258 pos: coordinates (x, y)259 duration: how long to touch the screen260 Returns:261 None262 """263 if self.touch_method == TOUCH_METHOD.MINITOUCH:264 pos = self._touch_point_by_orientation(pos)265 self.minitouch.touch(pos, duration=duration)266 else:267 self.adb.touch(pos)268 def double_click(self, pos):269 self.touch(pos)270 time.sleep(0.05)271 self.touch(pos)272 def swipe(self, p1, p2, duration=0.5, steps=5, fingers=1):273 """274 Perform swipe event on the device275 Args:276 p1: start point277 p2: end point278 duration: how long to swipe the screen, default 0.5279 steps: how big is the swipe step, default 5280 fingers: the number of fingers. 1 or 2.281 Returns:282 None283 """284 if self.touch_method == TOUCH_METHOD.MINITOUCH:285 p1 = self._touch_point_by_orientation(p1)286 p2 = self._touch_point_by_orientation(p2)287 if fingers == 1:288 self.minitouch.swipe(p1, p2, duration=duration, steps=steps)289 elif fingers == 2:290 self.minitouch.two_finger_swipe(p1, p2, duration=duration, steps=steps)291 else:292 raise Exception("param fingers should be 1 or 2")293 else:294 duration *= 1000 # adb的swipe操作时间是以毫秒为单位的。295 self.adb.swipe(p1, p2, duration=duration)296 def pinch(self, *args, **kwargs):297 """298 Perform pinch event on the device299 Args:300 *args: optional arguments301 **kwargs: optional arguments302 Returns:303 None304 """305 return self.minitouch.pinch(*args, **kwargs)306 def logcat(self, *args, **kwargs):307 """308 Perform `logcat`operations309 Args:310 *args: optional arguments311 **kwargs: optional arguments312 Returns:313 `logcat` output314 """315 return self.adb.logcat(*args, **kwargs)316 def getprop(self, key, strip=True):317 """318 Get properties for given key319 Args:320 key: key name321 strip: True or False whether to strip the output or not322 Returns:323 property value(s)324 """325 return self.adb.getprop(key, strip)326 def get_ip_address(self):327 """328 Perform several set of commands to obtain the IP address329 * `adb shell netcfg | grep wlan0`330 * `adb shell ifconfig`331 * `adb getprop dhcp.wlan0.ipaddress`332 Returns:333 None if no IP address has been found, otherwise return the IP address334 """335 return self.adb.get_ip_address()336 def get_top_activity(self):337 """338 Get the top activity339 Returns:340 package, activity and pid341 """342 return self.adb.get_top_activity()343 def get_top_activity_name_and_pid(self):344 dat = self.adb.shell('dumpsys activity top')345 activityRE = re.compile('\s*ACTIVITY ([A-Za-z0-9_.]+)/([A-Za-z0-9_.]+) \w+ pid=(\d+)')346 m = activityRE.search(dat)347 if m:348 return (m.group(1), m.group(2), m.group(3))349 else:350 warnings.warn("NO MATCH:" + dat)351 return None352 def get_top_activity_name(self):353 """354 Get the top activity name355 Returns:356 package, activity and pid357 """358 tanp = self.get_top_activity_name_and_pid()359 if tanp:360 return tanp[0] + '/' + tanp[1]361 else:362 return None363 def is_keyboard_shown(self):364 """365 Return True or False whether soft keyboard is shown or not366 Notes:367 Might not work on all devices368 Returns:369 True or False370 """371 return self.adb.is_keyboard_shown()372 def is_screenon(self):373 """374 Return True or False whether the screen is on or not375 Notes:376 Might not work on all devices377 Returns:378 True or False379 """380 return self.adb.is_screenon()381 def is_locked(self):382 """383 Return True or False whether the device is locked or not384 Notes:385 Might not work on some devices386 Returns:387 True or False388 """389 return self.adb.is_locked()390 def unlock(self):391 """392 Unlock the device393 Notes:394 Might not work on all devices395 Returns:396 None397 """398 return self.adb.unlock()399 @property400 def display_info(self):401 """402 Return the display info (width, height, orientation and max_x, max_y)403 Returns:404 display information405 """406 if not self._display_info:407 self._display_info = self.get_display_info()408 display_info = copy(self._display_info)409 # update ow orientation, which is more accurate410 if self._current_orientation is not None:411 display_info.update({412 "rotation": self._current_orientation * 90,413 "orientation": self._current_orientation,414 })415 return display_info416 def get_display_info(self):417 """418 Return the display info (width, height, orientation and max_x, max_y)419 Returns:420 display information421 """422 if self.ori_method == ORI_METHOD.MINICAP:423 display_info = self.minicap.get_display_info()424 else:425 display_info = self.adb.get_display_info()426 return display_info427 def get_current_resolution(self):428 """429 Return current resolution after rotation430 Returns:431 width and height of the display432 """433 # 注意黑边问题,需要用安卓接口获取区分两种分辨率434 w, h = self.display_info["width"], self.display_info["height"]435 if self.display_info["orientation"] in [1, 3]:436 w, h = h, w437 return w, h438 def start_recording(self, *args, **kwargs):439 """440 Start recording the device display441 Args:442 *args: optional arguments443 **kwargs: optional arguments444 Returns:445 None446 """447 return self.recorder.start_recording(*args, **kwargs)448 def stop_recording(self, *args, **kwargs):449 """450 Stop recording the device display. Recoding file will be kept in the device.451 Args:452 *args: optional arguments453 **kwargs: optional arguments454 Returns:455 None456 """457 return self.recorder.stop_recording(*args, **kwargs)458 def _register_rotation_watcher(self):459 """460 Register callbacks for Android and minicap when rotation of screen has changed461 callback is called in another thread, so be careful about thread-safety462 Returns:463 None464 """465 self.rotation_watcher.reg_callback(lambda x: setattr(self, "_current_orientation", x))466 self.rotation_watcher.reg_callback(lambda x: self.minicap.update_rotation(x * 90))467 def _touch_point_by_orientation(self, tuple_xy):468 """469 Convert image coordinates to physical display coordinates, the arbitrary point (origin) is upper left corner470 of the device physical display471 Args:472 tuple_xy: image coordinates (x, y)...

Full Screen

Full Screen

screen.py

Source:screen.py Github

copy

Full Screen

...12 self.rotation_watcher = RotationWatcher(self.adb)13 self.minicap = Minicap(self.adb)14 self._display_info = {}15 self._current_orientation = None16 self._register_rotation_watcher()17 def snapshot(self, filename=None, ensure_orientation=True):18 self.rotation_watcher.get_ready()19 screen = self.minicap.get_frame_from_stream()20 # output cv2 object21 try:22 screen = string_2_img(screen)23 except Exception:24 # may be black/locked screen or other reason, print exc for debugging25 import traceback26 traceback.print_exc()27 return None28 if ensure_orientation and self.display_info["orientation"]:29 if self.adb.sdk_version <= 16:30 h, w = screen.shape[:2] # cvshape是高度在前面!!!!31 if w < h: # 当前是横屏,但是图片是竖的,则旋转,针对sdk<=16的机器32 screen = rotate(33 screen, self.display_info["orientation"] * 90, clockwise=False)34 if filename:35 imwrite(filename, screen)36 return screen37 def is_screenon(self):38 return self.adb.is_screenon()39 def is_locked(self):40 return self.adb.is_locked()41 def unlock(self):42 return self.adb.unlock()43 @property44 def display_info(self):45 """46 Return the display info (width, height, orientation and max_x, max_y)47 Returns:48 display information49 """50 if not self._display_info:51 self._display_info = self._get_display_info()52 display_info = copy(self._display_info)53 # update ow orientation, which is more accurate54 if self._current_orientation is not None:55 display_info.update({56 "rotation": self._current_orientation * 90,57 "orientation": self._current_orientation,58 })59 return display_info60 def _get_display_info(self):61 """62 Return the display info (width, height, orientation and max_x, max_y)63 Returns:64 display information65 """66 display_info = self.adb.get_display_info()67 return display_info68 def _register_rotation_watcher(self):69 """70 Register callbacks for Android and minicap when rotation of screen has changed71 callback is called in another thread, so be careful about thread-safety72 Returns:73 None74 """75 self.rotation_watcher.reg_callback(lambda x: setattr(self, "_current_orientation", x))76 self.rotation_watcher.reg_callback(lambda x: self.minicap.update_rotation(x * 90))77 @property78 def name(self):79 return self._name80 81 @name.setter82 def name(self, value):83 self._name = value84class AndroidJAVACapScreenComponent(ScreenComponent):85 def __init__(self, name, dev):86 self._name = name87 self.adb = dev.adb88 self.javacap = Javacap(self.adb)89 self._display_info = {}90 self._current_orientation = None91 self.rotation_watcher = RotationWatcher(self.adb)92 self._register_rotation_watcher()93 94 def snapshot(self, filename=None, ensure_orientation=True):95 screen = self.javacap.get_frame_from_stream()96 try:97 screen = string_2_img(screen)98 except Exception:99 # may be black/locked screen or other reason, print exc for debugging100 import traceback101 traceback.print_exc()102 return None103 if filename:104 imwrite(filename, screen)105 return screen106 def is_screenon(self):107 return self.adb.is_screenon()108 def is_locked(self):109 return self.adb.is_locked()110 def unlock(self):111 return self.adb.unlock()112 @property113 def display_info(self):114 if not self._display_info:115 self._display_info = self._get_display_info()116 display_info = copy(self._display_info)117 # update ow orientation, which is more accurate118 if self._current_orientation is not None:119 display_info.update({120 "rotation": self._current_orientation * 90,121 "orientation": self._current_orientation,122 })123 return display_info124 def _get_display_info(self):125 display_info = self.adb.get_display_info()126 return display_info127 def _register_rotation_watcher(self):128 self.rotation_watcher.reg_callback(lambda x: setattr(self, "_current_orientation", x))129 @property130 def name(self):131 return self._name132 133 @name.setter134 def name(self, value):135 self._name = value136class AndroidMiniCapScreenComponent(ScreenComponent):137 def __init__(self, name, dev):138 self._name = name139 self.adb = dev.adb140 self.rotation_watcher = RotationWatcher(self.adb)141 self.minicap = Minicap(self.adb)142 self._display_info = {}143 self._current_orientation = None144 self._register_rotation_watcher()145 def snapshot(self, filename=None, ensure_orientation=True):146 screen = self.minicap.get_frame()147 try:148 screen = string_2_img(screen)149 except Exception:150 # may be black/locked screen or other reason, print exc for debugging151 import traceback152 traceback.print_exc()153 return None154 # ensure the orientation is right155 if ensure_orientation and self.display_info["orientation"]:156 # minicap screenshots are different for various sdk_version157 if self.adb.sdk_version <= 16:158 h, w = screen.shape[:2] # cvshape是高度在前面!!!!159 if w < h: # 当前是横屏,但是图片是竖的,则旋转,针对sdk<=16的机器160 screen = rotate(161 screen, self.display_info["orientation"] * 90, clockwise=False)162 if filename:163 imwrite(filename, screen)164 return screen165 def is_screenon(self):166 return self.adb.is_screenon()167 def is_locked(self):168 return self.adb.is_locked()169 def unlock(self):170 return self.adb.unlock()171 @property172 def display_info(self):173 if not self._display_info:174 self._display_info = self._get_display_info()175 display_info = copy(self._display_info)176 # update ow orientation, which is more accurate177 if self._current_orientation is not None:178 display_info.update({179 "rotation": self._current_orientation * 90,180 "orientation": self._current_orientation,181 })182 return display_info183 def _get_display_info(self):184 display_info = self.minicap.get_display_info()185 return display_info186 def _register_rotation_watcher(self):187 self.rotation_watcher.reg_callback(lambda x: setattr(self, "_current_orientation", x))188 self.rotation_watcher.reg_callback(lambda x: self.minicap.update_rotation(x * 90))189 @property190 def name(self):191 return self._name192 193 @name.setter194 def name(self, value):195 self._name = value196class AndroidADBScreenComponent(ScreenComponent):197 def __init__(self, name, dev):198 self._name = name199 self.adb = dev.adb200 self.rotation_watcher = RotationWatcher(self.adb)201 self._display_info = {}202 self._current_orientation = None203 self._register_rotation_watcher()204 def snapshot(self, filename=None, ensure_orientation=True):205 screen = self.adb.snapshot()206 # output cv2 object207 try:208 screen = string_2_img(screen)209 except Exception:210 # may be black/locked screen or other reason, print exc for debugging211 import traceback212 traceback.print_exc()213 return None214 # ensure the orientation is right215 if ensure_orientation and self.display_info["orientation"]:216 screen = rotate(217 screen, self.display_info["orientation"] * 90, clockwise=False)218 if filename:219 imwrite(filename, screen)220 return screen221 def is_screenon(self):222 return self.adb.is_screenon()223 def is_locked(self):224 return self.adb.is_locked()225 def unlock(self):226 return self.adb.unlock()227 @property228 def display_info(self):229 if not self._display_info:230 self._display_info = self._get_display_info()231 display_info = copy(self._display_info)232 # update ow orientation, which is more accurate233 if self._current_orientation is not None:234 display_info.update({235 "rotation": self._current_orientation * 90,236 "orientation": self._current_orientation,237 })238 return display_info239 def _get_display_info(self):240 display_info = self.adb.get_display_info()241 return display_info242 def _register_rotation_watcher(self):243 self.rotation_watcher.reg_callback(lambda x: setattr(self, "_current_orientation", x))244 @property245 def name(self):246 return self._name247 248 @name.setter249 def name(self, value):...

Full Screen

Full Screen

run.py

Source:run.py Github

copy

Full Screen

...40 self.maxtouch = Maxtouch(self.adb)41 self.EVENTTOUCH = EVENTTOUCH(self.adb)42 self.rotation_watcher = Rotation(self.adb)43 self.rotation_watcher.start()44 self._register_rotation_watcher()45 def screenshot(self):46 stamp = time.time()47 img_data = None48 if self.cap_method == CAP_METHOD.MINICAP:49 img_data = self.minicap.get_frame()50 elif self.cap_method == CAP_METHOD.JAVACAP:51 img_data = self.javacap.get_frame()52 elif self.cap_method == CAP_METHOD.ADBCAP:53 img_data = self.adbcap.get_frame()54 # 图片写入到缓存中55 self.tmp_image.imwrite(img_data)56 logger.info("screenshot time={:.2f}ms,size=({},{})", (time.time() - stamp) * 1000, *self.tmp_image.size)57 return self.tmp_image58 def down(self, x: int, y: int, index: int = 0, pressure: int = 50):59 if self.touch_method == TOUCH_METHOD.MINITOUCH:60 return self.minitouch.down(x, y, index, pressure)61 elif self.touch_method == TOUCH_METHOD.ADBTOUCH:62 return self.EVENTTOUCH.down(x, y, index)63 def up(self, x: int, y: int, index: int = 0):64 if self.touch_method == TOUCH_METHOD.MINITOUCH:65 return self.minitouch.up(x, y, index)66 elif self.touch_method == TOUCH_METHOD.ADBTOUCH:67 return self.EVENTTOUCH.up(x, y, index)68 def sleep(self, duration):69 if self.touch_method == TOUCH_METHOD.MINITOUCH:70 return self.minitouch.sleep(duration)71 elif self.touch_method == TOUCH_METHOD.ADBTOUCH:72 return self.EVENTTOUCH.sleep(duration)73 def click(self, x: int, y: int, index: int = 0, duration=0.1):74 logger.info("[{}]index={}, x={}, y={}", self.touch_method, index, x, y)75 if self.touch_method == TOUCH_METHOD.MINITOUCH:76 return self.minitouch.click(x, y, index=index, duration=duration)77 elif self.touch_method == TOUCH_METHOD.MAXTOUCH:78 return self.maxtouch.click(x, y, index=index, duration=duration)79 elif self.touch_method == TOUCH_METHOD.ADBTOUCH:80 return self.EVENTTOUCH.click(x, y, index=index, duration=duration)81 def display_info(self):82 if not self._display_info:83 self._display_info = self.get_display_info()84 def get_display_info(self):85 if self.cap_method == CAP_METHOD.MINICAP:86 try:87 return self.minicap.get_display_info()88 except RuntimeError:89 # Even if minicap execution fails, use adb instead90 return self.adb.get_display_info()91 return self.adb.get_display_info()92 def _get_touch_method(self):93 if self.touch_method == TOUCH_METHOD.MAXTOUCH:94 return self.maxtouch95 elif self.touch_method == TOUCH_METHOD.MINITOUCH:96 return self.minitouch97 elif self.touch_method == TOUCH_METHOD.ADBTOUCH:98 return self.EVENTTOUCH99 def _get_cap_func(self):100 if self.cap_method == CAP_METHOD.MINICAP:101 return self.minicap102 elif self.cap_method == CAP_METHOD.JAVACAP:103 return self.javacap104 elif self.cap_method == CAP_METHOD.ADBCAP:105 return self.adb.screenshot106 def _register_rotation_watcher(self):107 self.rotation_watcher.reg_callback(lambda x: self._get_touch_method().update_rotation(x * 90))108 if self.cap_method == CAP_METHOD.MINICAP:...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Airtest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful