Best Python code snippet using Airtest
adb.py
Source:adb.py
...712 'max_x': 4095,713 'max_y': 4095714 }715 """716 display_info = self.getPhysicalDisplayInfo()717 orientation = self.getDisplayOrientation()718 max_x, max_y = self.getMaxXY()719 display_info.update({720 "orientation": orientation,721 "rotation": orientation * 90,722 "max_x": max_x,723 "max_y": max_y,724 })725 return display_info726 def getMaxXY(self):727 """728 Get device display maximum values for x and y coordinates729 Returns:730 max x and max y coordinates731 """732 ret = self.shell('getevent -p').split('\n')733 max_x, max_y = None, None734 for i in ret:735 if i.find("0035") != -1:736 patten = re.compile(r'max [0-9]+')737 ret = patten.search(i)738 if ret:739 max_x = int(ret.group(0).split()[1])740 if i.find("0036") != -1:741 patten = re.compile(r'max [0-9]+')742 ret = patten.search(i)743 if ret:744 max_y = int(ret.group(0).split()[1])745 return max_x, max_y746 def getRestrictedScreen(self):747 """748 Get value for mRestrictedScreen (without black border / virtual keyboard)`749 Returns:750 screen resolution mRestrictedScreen value as tuple (x, y)751 """752 # get the effective screen resolution of the device753 result = None754 # get the corresponding mRestrictedScreen parameters according to the device serial number755 dumpsys_info = self.shell("dumpsys window")756 match = re.search(r'mRestrictedScreen=.+', dumpsys_info)757 if match:758 infoline = match.group(0).strip() # like 'mRestrictedScreen=(0,0) 720x1184'759 resolution = infoline.split(" ")[1].split("x")760 if isinstance(resolution, list) and len(resolution) == 2:761 result = int(str(resolution[0])), int(str(resolution[1]))762 return result763 def getPhysicalDisplayInfo(self):764 """765 Get value for display dimension and density from `mPhysicalDisplayInfo` value obtained from `dumpsys` command.766 Returns:767 physical display info for dimension and density768 """769 # use adb shell wm size770 displayInfo = {}771 wm_size = re.search(r'(?P<width>\d+)x(?P<height>\d+)\s*$', self.raw_shell('wm size'))772 if wm_size:773 displayInfo = dict((k, int(v)) for k, v in wm_size.groupdict().items())774 displayInfo['density'] = self._getDisplayDensity(strip=True)775 return displayInfo776 phyDispRE = re.compile('.*PhysicalDisplayInfo{(?P<width>\d+) x (?P<height>\d+), .*, density (?P<density>[\d.]+).*')777 out = self.raw_shell('dumpsys display')778 m = phyDispRE.search(out)779 if m:780 for prop in ['width', 'height']:781 displayInfo[prop] = int(m.group(prop))782 for prop in ['density']:783 # In mPhysicalDisplayInfo density is already a factor, no need to calculate784 displayInfo[prop] = float(m.group(prop))785 return displayInfo786 # This could also be mSystem or mOverscanScreen787 phyDispRE = re.compile('\s*mUnrestrictedScreen=\((?P<x>\d+),(?P<y>\d+)\) (?P<width>\d+)x(?P<height>\d+)')788 # This is known to work on older versions (i.e. API 10) where mrestrictedScreen is not available789 dispWHRE = re.compile('\s*DisplayWidth=(?P<width>\d+) *DisplayHeight=(?P<height>\d+)')790 out = self.raw_shell('dumpsys window')791 m = phyDispRE.search(out, 0)792 if not m:793 m = dispWHRE.search(out, 0)794 if m:795 for prop in ['width', 'height']:796 displayInfo[prop] = int(m.group(prop))797 for prop in ['density']:798 d = self._getDisplayDensity(strip=True)799 if d:800 displayInfo[prop] = d801 else:802 # No available density information803 displayInfo[prop] = -1.0804 return displayInfo805 # gets C{mPhysicalDisplayInfo} values from dumpsys. This is a method to obtain display dimensions and density806 phyDispRE = re.compile('Physical size: (?P<width>\d+)x(?P<height>\d+).*Physical density: (?P<density>\d+)', re.S)807 m = phyDispRE.search(self.raw_shell('wm size; wm density'))808 if m:809 for prop in ['width', 'height']:810 displayInfo[prop] = int(m.group(prop))811 for prop in ['density']:812 displayInfo[prop] = float(m.group(prop))813 return displayInfo814 return displayInfo815 def _getDisplayDensity(self, strip=True):816 """817 Get display density818 Args:819 strip: strip the output820 Returns:821 display density822 """823 BASE_DPI = 160.0824 d = self.getprop('ro.sf.lcd_density', strip)825 if d:826 return float(d) / BASE_DPI827 d = self.getprop('qemu.sf.lcd_density', strip)828 if d:829 return float(d) / BASE_DPI830 return -1.0831 def getDisplayOrientation(self):832 """833 Another way to get the display orientation, this works well for older devices (SDK version 15)834 Returns:835 display orientation information836 """837 # another way to get orientation, for old sumsung device(sdk version 15) from xiaoma838 SurfaceFlingerRE = re.compile('orientation=(\d+)')839 output = self.shell('dumpsys SurfaceFlinger')840 m = SurfaceFlingerRE.search(output)841 if m:842 return int(m.group(1))843 # Fallback method to obtain the orientation844 # See https://github.com/dtmilano/AndroidViewClient/issues/128845 surfaceOrientationRE = re.compile('SurfaceOrientation:\s+(\d+)')846 output = self.shell('dumpsys input')847 m = surfaceOrientationRE.search(output)848 if m:849 return int(m.group(1))850 # We couldn't obtain the orientation851 warnings.warn("Could not obtain the orientation, return 0")852 return 0853 def update_cur_display(self, display_info):854 """855 Some phones support resolution modification, try to get the modified resolution from dumpsys856 adb shell dumpsys window displays | find "cur="857 æ¬æ¹æ³è½ç¶å¯ä»¥æ´å¥½å°è·åå°é¨åä¿®æ¹è¿å辨ççææºä¿¡æ¯858 ä½æ¯ä¼å 为cur=(\d+)x(\d+)çæ°å¼å¨ä¸å设å¤ä¸widthåheightç顺åºå¯è½ä¸åï¼å¯¼è´æ¨ªç«å±è¯å«åºç°é®é¢859 airtestä¸å使ç¨æ¬æ¹æ³ä½ä¸ºéç¨çå±å¹å°ºå¯¸è·åæ¹æ³ï¼ä½ä¾ç¶å¯ç¨äºé¨å设å¤è·åå½å被修æ¹è¿çå辨ç860 Examples:861 >>> # é¨åä¸æåå为设å¤ï¼è¥å辨ç没ææå®ä¸ºæé«ï¼å¯è½ä¼å¯¼è´ç¹å»å移ï¼å¯ä»¥ç¨è¿ä¸ªæ¹å¼å¼ºå¶ä¿®æ¹ï¼862 >>> # For some Samsung and Huawei devices, if the resolution is not specified as the highest,863 >>> # it may cause click offset, which can be modified in this way:864 >>> dev = device()865 >>> info = dev.display_info866 >>> info2 = dev.adb.update_cur_display(info)867 >>> dev.display_info.update(info2)868 Args:869 display_info: the return of self.getPhysicalDisplayInfo()870 Returns:871 display_info872 """873 # adb shell dumpsys window displays | find "init="874 # ä¸é¢çå½ä»¤è¡å¨dumpsys windowéæ¥æ¾init=widthxheightï¼å¾å°çç»ææ¯ç©çå辨çï¼ä¸é¨ååå·ææºä¸æ¢ä¸ä¸ªç»æ875 # å¦ææ¹ä¸ºè¯»å cur=widthxheight çæ°æ®ï¼å¾å°çæ¯ä¿®æ¹è¿å辨çææºçç»æï¼ä¾å¦ä¸æS8ï¼876 actual = self.shell("dumpsys window displays")877 arr = re.findall(r'cur=(\d+)x(\d+)', actual)878 if len(arr) > 0:879 # 强å¶è®¾å®å®½åº¦width为æ´å°çæ°åãheight为æ´å¤§çæ°åï¼é¿å
å 为åææºååè¿åç»æç顺åºä¸å导è´é®é¢880 # Set the width to a smaller number and the height to a larger number881 width, height = min(list(map(int, arr[0]))), max(list(map(int, arr[0])))882 display_info['physical_width'] = display_info['width']883 display_info['physical_height'] = display_info['height']...
adbclient.py
Source:adbclient.py
...275 def getDisplayInfo(self):276 displayInfo = self.getLogicalDisplayInfo()277 if displayInfo:278 return displayInfo279 displayInfo = self.getPhysicalDisplayInfo()280 if displayInfo:281 return displayInfo282 raise RuntimeError("Couldn't find display info in 'wm size', 'dumpsys display' or 'dumpsys window'")283 def getLogicalDisplayInfo(self):284 '''285 Gets C{mDefaultViewport} and then C{deviceWidth} and C{deviceHeight} values from dumpsys.286 This is a method to obtain display logical dimensions and density287 '''288 logicalDisplayRE = re.compile('.*DisplayViewport{valid=true, .*orientation=(?P<orientation>\d+), .*deviceWidth=(?P<width>\d+), deviceHeight=(?P<height>\d+).*')289 for line in self.shell('dumpsys display').splitlines():290 m = logicalDisplayRE.search(line, 0)291 if m:292 self.__displayInfo = {}293 for prop in [ 'width', 'height', 'orientation' ]:294 self.__displayInfo[prop] = int(m.group(prop))295 for prop in [ 'density' ]:296 d = self.__getDisplayDensity(None, strip=True, invokeGetPhysicalDisplayIfNotFound=False)297 if d:298 self.__displayInfo[prop] = d299 else:300 # No available density information301 self.__displayInfo[prop] = -1.0302 return self.__displayInfo303 return None304 def getPhysicalDisplayInfo(self):305 ''' Gets C{mPhysicalDisplayInfo} values from dumpsys. This is a method to obtain display dimensions and density'''306 phyDispRE = re.compile('Physical size: (?P<width>)x(?P<height>).*Physical density: (?P<density>)', re.MULTILINE)307 m = phyDispRE.search(self.shell('wm size; wm density'))308 if m:309 displayInfo = {}310 for prop in [ 'width', 'height' ]:311 displayInfo[prop] = int(m.group(prop))312 for prop in [ 'density' ]:313 displayInfo[prop] = float(m.group(prop))314 return displayInfo315 phyDispRE = re.compile('.*PhysicalDisplayInfo{(?P<width>\d+) x (?P<height>\d+), .*, density (?P<density>[\d.]+).*')316 for line in self.shell('dumpsys display').splitlines():317 m = phyDispRE.search(line, 0)318 if m:319 displayInfo = {}320 for prop in [ 'width', 'height' ]:321 displayInfo[prop] = int(m.group(prop))322 for prop in [ 'density' ]:323 # In mPhysicalDisplayInfo density is already a factor, no need to calculate324 displayInfo[prop] = float(m.group(prop))325 return displayInfo326 # This could also be mSystem or mOverscanScreen327 phyDispRE = re.compile('\s*mUnrestrictedScreen=\((?P<x>\d+),(?P<y>\d+)\) (?P<width>\d+)x(?P<height>\d+)')328 # This is known to work on older versions (i.e. API 10) where mrestrictedScreen is not available329 dispWHRE = re.compile('\s*DisplayWidth=(?P<width>\d+) *DisplayHeight=(?P<height>\d+)')330 for line in self.shell('dumpsys window').splitlines():331 m = phyDispRE.search(line, 0)332 if not m:333 m = dispWHRE.search(line, 0)334 if m:335 displayInfo = {}336 for prop in [ 'width', 'height' ]:337 displayInfo[prop] = int(m.group(prop))338 for prop in [ 'density' ]:339 d = self.__getDisplayDensity(None, strip=True, invokeGetPhysicalDisplayIfNotFound=False)340 if d:341 displayInfo[prop] = d342 else:343 # No available density information344 displayInfo[prop] = -1.0345 return displayInfo346 def __getProp(self, key, strip=True):347 if DEBUG:348 print >> sys.stderr, "__getProp(%s, %s)" % (key, strip)349 prop = self.shell('getprop %s' % key)350 if strip:351 prop = prop.rstrip('\r\n')352 if DEBUG:353 print >> sys.stderr, " __getProp: returning '%s'" % prop354 return prop355 def __getDisplayWidth(self, key, strip=True):356 if self.__displayInfo and 'width' in self.__displayInfo:357 return self.__displayInfo['width']358 return self.getDisplayInfo()['width']359 def __getDisplayHeight(self, key, strip=True):360 if self.__displayInfo and 'height' in self.__displayInfo:361 return self.__displayInfo['height']362 return self.getDisplayInfo()['height']363 def __getDisplayOrientation(self, key, strip=True):364 if self.__displayInfo and 'orientation' in self.__displayInfo:365 return self.__displayInfo['orientation']366 displayInfo = self.getDisplayInfo()367 if 'orientation' in displayInfo:368 return displayInfo['orientation']369 # We couldn't obtain the orientation370 return -1371 def __getDisplayDensity(self, key, strip=True, invokeGetPhysicalDisplayIfNotFound=True):372 if self.__displayInfo and 'density' in self.__displayInfo:373 return self.__displayInfo['density']374 BASE_DPI = 160.0375 d = self.getProperty('ro.sf.lcd_density', strip)376 if d:377 return float(d)/BASE_DPI378 d = self.getProperty('qemu.sf.lcd_density', strip)379 if d:380 return float(d)/BASE_DPI381 if invokeGetPhysicalDisplayIfNotFound:382 return self.getPhysicalDisplayInfo()['density']383 return -1.0384 def getSystemProperty(self, key, strip=True):385 return self.getProperty(key, strip)386 def getProperty(self, key, strip=True):387 ''' Gets the property value for key '''388 import collections389 MAP_PROPS = collections.OrderedDict([390 (re.compile('display.width'), self.__getDisplayWidth),391 (re.compile('display.height'), self.__getDisplayHeight),392 (re.compile('display.density'), self.__getDisplayDensity),393 (re.compile('display.orientation'), self.__getDisplayOrientation),394 (re.compile('.*'), self.__getProp),395 ])396 '''Maps properties key values (as regexps) to instance methods to obtain its values.'''...
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!!