Best Python code snippet using fMBT_python
fmbtandroid.py
Source:fmbtandroid.py
...439 def accelerometerRotation(self):440 """441 Returns True if accelerometer changes screen rotation.442 See also:443 setAccelerometerRotation()444 userRotation()445 """446 return self.existingConnection().recvAccelerometerRotation()447 def autoRotateScreenshot(self):448 """449 Return True if screenshots are rotated automatically,450 otherwise False.451 See also: setAutoRotateScreenshot452 """453 return self._autoRotateScreenshot454 def callContact(self, contact):455 """456 Call to given contact.457 Return True if successful, otherwise False.458 """459 callCommand = 'service call phone 1 s16 "%s"' % (contact,)460 status, out, err = self.shellSOE(callCommand)461 if status != 0:462 _logFailedCommand("callContact", callCommand, status, out, err)463 return False464 else:465 return True466 def callNumber(self, number):467 """468 Call to given phone number.469 Return True if successful, otherwise False.470 """471 callCommand = "am start -a android.intent.action.CALL -d 'tel:%s'" % (number,)472 status, out, err = self.shellSOE(callCommand)473 if status != 0:474 _logFailedCommand("callNumber", callCommand, status, out, err)475 return False476 else:477 return True478 def close(self):479 fmbtgti.GUITestInterface.close(self)480 if hasattr(self, "_conn"):481 del self._conn482 if hasattr(self, "_lastView"):483 del self._lastView484 import gc485 gc.collect()486 def deviceLog(self, msg, priority="i", tag="fMBT"):487 """488 Write a message to device log (seen via logcat)489 Parameters:490 msg (string):491 message to be written.492 priority (string, optional):493 priorityChar, one of "v", "d", "i", "w", "e".494 The default is "i".495 tag (string, optional):496 tag for the log entry, the default is "fMBT".497 """498 if not priority.lower() in ["v", "d", "i", "w", "e"]:499 return False500 return self.existingConnection().sendDeviceLog(501 msg, priority.lower(), tag)502 def displayRotation(self):503 """504 Returns current rotation of the display.505 Returns integer, that is ROTATION_0, ROTATION_90, ROTATION_180506 or ROTATION_270. Returns None if rotation is not available.507 Example: take a screenshot rotated to current display orientation508 d.refreshScreenshot(rotate=-d.displayRotation())509 """510 if self._conn:511 return self._conn.recvCurrentDisplayOrientation()512 else:513 return None514 def displayPowered(self):515 """516 Returns True if display is powered, otherwise False.517 """518 if self._conn:519 return self._conn.recvDisplayPowered()520 else:521 return None522 def drag(self, (x1, y1), (x2, y2), delayBetweenMoves=None, delayBeforeMoves=None, delayAfterMoves=None, movePoints=None):523 """524 Touch the screen on coordinates (x1, y1), drag along straight525 line to coordinates (x2, y2), and raise fingertip.526 coordinates (floats in range [0.0, 1.0] or integers):527 floating point coordinates in range [0.0, 1.0] are528 scaled to full screen width and height, others are529 handled as absolute coordinate values.530 delayBeforeMoves (float, optional):531 seconds to wait after touching and before dragging.532 If negative, starting touch event is not sent.533 delayBetweenMoves (float, optional):534 seconds to wait when moving between points when535 dragging.536 delayAfterMoves (float, optional):537 seconds to wait after dragging, before raising538 fingertip.539 If negative, fingertip is not raised.540 movePoints (integer, optional):541 the number of intermediate move points between end542 points of the line.543 Returns True on success, False if sending input failed.544 """545 if (delayBetweenMoves == None and546 delayBeforeMoves == None and547 delayAfterMoves == None and548 movePoints == None and549 self.platformVersion() >= "4.3"):550 x1, y1 = self.intCoords((x1, y1))551 x2, y2 = self.intCoords((x2, y2))552 return self.existingConnection().sendSwipe(x1, y1, x2, y2)553 else:554 kwArgs = {}555 if delayBetweenMoves != None: kwArgs["delayBetweenMoves"] = delayBetweenMoves556 if delayBeforeMoves != None: kwArgs["delayBeforeMoves"] = delayBeforeMoves557 if delayAfterMoves != None: kwArgs["delayAfterMoves"] = delayAfterMoves558 if movePoints != None: kwArgs["movePoints"] = movePoints559 return fmbtgti.GUITestInterface.drag(560 self, (x1, y1), (x2, y2),561 **kwArgs)562 def dumpIni(self):563 """564 Returns contents of current device configuration as a string (in565 INI format).566 """567 return self._conf.dump()568 def ini(self):569 """570 Returns an Ini object containing effective device571 configuration.572 """573 return self._conf574 def install(self, filename, lock=False, reinstall=False, downgrade=False,575 sdcard=False, algo=None, key=None, iv=None):576 """577 Install apk on the device.578 Parameters:579 filename (string):580 APK filename on host.581 lock (boolean, optional):582 forward-lock the app. Correspond to adb install "-l".583 The default is False.584 reinstall (boolean, optional):585 Reinstall the app, keep its data. Corresponds to "-r".586 The default is False.587 downgrade (boolean, optional):588 Allow downgrading the application. Corresponds to "-d".589 The default is False.590 sdcard (boolean, optional):591 Install on SD card. Corresponds to "-s".592 The default is False.593 algo (string, optional):594 Algorithm name. Corresponds to "--algo".595 The default is None.596 key (string, optional):597 Hex-encoded key. Corresponds to "--key".598 The default is None.599 iv (string, optional):600 Hex-encoded iv. Corresponds to "--iv".601 The default is None.602 Returns True if successful, False if device is not connected,603 and "adb install" command output (string) otherwise.604 Example:605 status = d.install("/tmp/PythonAPK.apk")606 if status != True:607 print "Installation failed, output:", status608 """609 if self._conn:610 return self._conn.install(filename, lock, reinstall, downgrade,611 sdcard, algo, key, iv)612 else:613 return False614 def keyNames(self):615 """616 Returns list of keyNames supported by pressKey.617 """618 return sorted(_g_keyNames)619 def loadConfig(self, filenameOrObj, override=True, level=""):620 try:621 if type(filenameOrObj) == str:622 filename = filenameOrObj623 fileObj = file(filenameOrObj)624 else:625 fileObj = filenameOrObj626 filename = getattr(fileObj, "name", "<string>")627 if hasattr(fileObj, "seek"):628 fileObj.seek(0)629 self._conf.addFile(fileObj, override=override)630 except Exception, e:631 _adapterLog('Loading %s configuration from "%s" failed: %s' % (level, filename, e))632 return633 _adapterLog('Loaded %s configuration from "%s"' % (level, filename))634 def navigationBarVisible(self):635 """636 Returns True if the navigation bar is showing, otherwise False.637 """638 return self.existingConnection().recvNavigationBarVisible()639 def pinch(self, (x, y), startDistance, endDistance,640 finger1Dir=90, finger2Dir=270, movePoints=100):641 """642 Pinch (open or close) on coordinates (x, y).643 Parameters:644 x, y (integer):645 the central point of the gesture. Values in range646 [0.0, 1.0] are scaled to full screen width and647 height.648 startDistance, endDistance (float):649 distance from both finger tips to the central point650 of the gesture, at the start and at the end of the651 gesture. Values in range [0.0, 1.0] are scaled up to652 the distance from the coordinates to the edge of the653 screen. Both finger tips will reach an edge if654 distance is 1.0.655 finger1Dir, finger2Dir (integer, optional):656 directions for finger tip movements, in range [0,657 360]. 0 is to the east, 90 to the north, etc. The658 defaults are 90 and 270.659 movePoints (integer, optional):660 number of points to which finger tips are moved661 after laying them to the initial positions. The662 default is 100.663 """664 screenWidth, screenHeight = self.screenSize()665 screenDiagonal = math.sqrt(screenWidth**2 + screenHeight**2)666 if x == None: x = 0.5667 if y == None: y = 0.5668 x, y = self.intCoords((x, y))669 if type(startDistance) == float and 0.0 <= startDistance <= 1.0:670 startDistanceInPixels = (startDistance *671 max(fmbtgti._edgeDistanceInDirection((x, y), self.screenSize(), finger1Dir),672 fmbtgti._edgeDistanceInDirection((x, y), self.screenSize(), finger2Dir)))673 else: startDistanceInPixels = int(startDistance)674 if type(endDistance) == float and 0.0 <= endDistance <= 1.0:675 endDistanceInPixels = (endDistance *676 max(fmbtgti._edgeDistanceInDirection((x, y), self.screenSize(), finger1Dir),677 fmbtgti._edgeDistanceInDirection((x, y), self.screenSize(), finger2Dir)))678 else: endDistanceInPixels = int(endDistance)679 finger1startX = int(x + math.cos(math.radians(finger1Dir)) * startDistanceInPixels)680 finger1startY = int(y - math.sin(math.radians(finger1Dir)) * startDistanceInPixels)681 finger1endX = int(x + math.cos(math.radians(finger1Dir)) * endDistanceInPixels)682 finger1endY = int(y - math.sin(math.radians(finger1Dir)) * endDistanceInPixels)683 finger2startX = int(x + math.cos(math.radians(finger2Dir)) * startDistanceInPixels)684 finger2startY = int(y - math.sin(math.radians(finger2Dir)) * startDistanceInPixels)685 finger2endX = int(x + math.cos(math.radians(finger2Dir)) * endDistanceInPixels)686 finger2endY = int(y - math.sin(math.radians(finger2Dir)) * endDistanceInPixels)687 self.existingConnection().sendMonkeyPinchZoom(688 finger1startX, finger1startY, finger1endX, finger1endY,689 finger2startX, finger2startY, finger2endX, finger2endY,690 movePoints)691 return True692 def pinchOpen(self, (x, y) = (0.5, 0.5), startDistance=0.1, endDistance=0.5, **pinchKwArgs):693 """694 Make the open pinch gesture.695 Parameters:696 x, y (integer, optional):697 the central point of the gesture, the default is in698 the middle of the screen.699 startDistance, endDistance (float, optional):700 refer to pinch documentation. The default is 0.1 and701 0.5.702 for the rest of the parameters, refer to pinch documentation.703 """704 return self.pinch((x, y), startDistance, endDistance, **pinchKwArgs)705 def pinchClose(self, (x, y) = (0.5, 0.5), startDistance=0.5, endDistance=0.1, **pinchKwArgs):706 """707 Make the close pinch gesture.708 Parameters:709 x, y (integer, optional):710 the central point of the gesture, the default is in711 the middle of the screen.712 startDistance, endDistance (float, optional):713 refer to pinch documentation. The default is 0.5 and714 0.1.715 rest of the parameters: refer to pinch documentation.716 """717 return self.pinch((x, y), startDistance, endDistance, **pinchKwArgs)718 def platformVersion(self):719 """720 Returns the platform version of the device.721 """722 try:723 return self.existingConnection().recvPlatformVersion()724 except:725 return "nosoftware"726 def pressAppSwitch(self, **pressKeyKwArgs):727 """728 Press the app switch button.729 Optional parameters are the same as for pressKey.730 """731 return self.pressKey("KEYCODE_APP_SWITCH", **pressKeyKwArgs)732 def pressBack(self, **pressKeyKwArgs):733 """734 Press the back button.735 Optional parameters are the same as for pressKey.736 """737 return self.pressKey("KEYCODE_BACK", **pressKeyKwArgs)738 def pressHome(self, **pressKeyKwArgs):739 """740 Press the home button.741 Optional parameters are the same as for pressKey.742 """743 return self.pressKey("KEYCODE_HOME", **pressKeyKwArgs)744 def pressKey(self, keyName, long=False, hold=0.0, modifiers=None):745 """746 Press a key on the device.747 Parameters:748 keyName (string):749 the name of the key, like KEYCODE_HOME. If KEYCODE_750 prefix is not given, it is added. Refer to Android751 KeyEvent documentation.752 long (boolean, optional):753 if True, press the key for long time.754 hold (float, optional):755 time in seconds to hold the key down.756 modifiers (list of strings, optional):757 modifier key(s) to be pressed at the same time.758 """759 if not keyName.upper().startswith("KEYCODE_"):760 keyName = "KEYCODE_" + keyName761 keyName = keyName.upper()762 if modifiers != None:763 modifiers = [764 m.upper() if m.upper().startswith("KEYCODE_") else "KEYCODE_" + m.upper()765 for m in modifiers]766 return fmbtgti.GUITestInterface.pressKey(self, keyName, long, hold, modifiers)767 def pressMenu(self, **pressKeyKwArgs):768 """769 Press the menu button.770 Optional parameters are the same as for pressKey.771 """772 return self.pressKey("KEYCODE_MENU", **pressKeyKwArgs)773 def pressPower(self, **pressKeyKwArgs):774 """775 Press the power button.776 Optional parameters are the same as for pressKey.777 """778 return self.pressKey("KEYCODE_POWER", **pressKeyKwArgs)779 def pressSearch(self, **pressKeyKwArgs):780 """781 Press the search button.782 Optional parameters are the same as for pressKey.783 """784 return self.pressKey("KEYCODE_SEARCH", **pressKeyKwArgs)785 def pressVolumeUp(self, **pressKeyKwArgs):786 """787 Press the volume up button.788 Optional parameters are the same as for pressKey.789 """790 return self.pressKey("KEYCODE_VOLUME_UP", **pressKeyKwArgs)791 def pressVolumeDown(self, **pressKeyKwArgs):792 """793 Press the volume down button.794 Optional parameters are the same as for pressKey.795 """796 return self.pressKey("KEYCODE_VOLUME_DOWN", **pressKeyKwArgs)797 def reboot(self, reconnect=True, firstBoot=False, timeout=120):798 """799 Reboot the device.800 Parameters801 reconnect (boolean, optional)802 If True, do not return until the device has been803 connected after boot. Otherwise return once reboot804 command has been sent. The default is True.805 firstBoot (boolean, optional)806 If True, the device boots like it would have been807 flashed. Requires that "adb root" works. The default808 is False.809 timeout (integer, optional)810 Timeout in seconds for reconnecting after reboot.811 The default is 120 s.812 Returns True on success, otherwise False.813 """814 return self.existingConnection().reboot(reconnect, firstBoot, timeout)815 def reconnect(self):816 """817 Close connections to the device and reconnect.818 """819 conn = self.connection()820 if hasattr(conn, "settings"):821 self._lastConnectionSettings = conn.settings()822 connSettings = self._lastConnectionSettings823 self.setConnection(None)824 self._lastConnectionSettings = connSettings825 del conn # make sure gc will collect the connection object826 import gc827 gc.collect()828 try:829 self.setConnection(_AndroidDeviceConnection(830 self.serialNumber, **connSettings))831 return True832 except Exception, e:833 _adapterLog("reconnect failed: %s" % (e,))834 return False835 def refreshScreenshot(self, forcedScreenshot=None, rotate=None):836 # convert Android display/user rotation to degrees837 if rotate in ROTATIONS:838 rotate = ROTATION_DEGS[rotate]839 elif rotate in [-ROTATION_0, -ROTATION_90, -ROTATION_180, -ROTATION_270]:840 rotate = -ROTATION_DEGS[-rotate]841 elif rotate == None:842 if self._autoRotateScreenshot:843 if not forcedScreenshot:844 drot = self.displayRotation()845 else:846 drot = None847 if drot != None:848 return self.refreshScreenshot(forcedScreenshot, rotate=-drot)849 rv = fmbtgti.GUITestInterface.refreshScreenshot(self, forcedScreenshot, rotate)850 if rv:851 if not forcedScreenshot:852 self._screenSize = self.existingConnection().recvScreenSize()853 else:854 self._screenSize = self.screenshot().size()855 else:856 self._screenSize = self.existingConnection().recvScreenSize()857 return rv858 refreshScreenshot.__doc__ = fmbtgti.GUITestInterface.refreshScreenshot.__doc__859 def refreshView(self, forcedView=None, uiautomatorDump=None):860 """861 (Re)reads view items on display and updates the latest View862 object.863 Parameters:864 forcedView (View or filename, optional):865 use given View object or view file instead of reading866 items from the device.867 uiautomatorDump (boolean, optional):868 use uiautomator to read view dump from the device.869 If not given, uiautomatorDump() default will be used.870 Returns created View object.871 """872 def formatErrors(errors, filename):873 return 'refreshView parse errors in "%s":\n %s' % (874 filename,875 "\n ".join(["line %s: %s error: %s" % e for e in errors]),)876 if self._conn:877 displayToScreen = self._conn._displayToScreen878 else:879 displayToScreen = None880 if forcedView != None:881 if isinstance(forcedView, View):882 self._lastView = forcedView883 elif type(forcedView) == str:884 self._lastView = View(self.screenshotDir(), self.serialNumber, file(forcedView).read(), displayToScreen, self.itemOnScreen, self.intCoords)885 _adapterLog(formatErrors(self._lastView.errors(), self._lastView.filename()))886 else:887 raise ValueError("forcedView must be a View object or a filename")888 return self._lastView889 retryCount = 0890 while True:891 if uiautomatorDump == True or (uiautomatorDump == None and self.uiautomatorDump()):892 dump = self.existingConnection().recvUiautomatorDump()893 else:894 try:895 dump = self.existingConnection().recvViewData()896 except AndroidConnectionError:897 self._lastView = None898 raise899 if dump != None:900 viewDir = os.path.dirname(self._newScreenshotFilepath())901 view = View(viewDir, self.serialNumber, dump, displayToScreen, self.itemOnScreen, self.intCoords)902 else:903 _adapterLog("refreshView window dump reading failed")904 view = None905 # fail quickly if there is no answer906 retryCount += self._PARSE_VIEW_RETRY_LIMIT / 2907 if dump == None or len(view.errors()) > 0:908 if view:909 _adapterLog(formatErrors(view.errors(), view.filename()))910 if retryCount < self._PARSE_VIEW_RETRY_LIMIT:911 retryCount += 1912 time.sleep(0.2) # sleep before retry913 else:914 self._lastView = None915 raise AndroidConnectionError("Cannot read window dump")916 else:917 # successfully parsed or parsed with errors but no more retries918 self._lastView = view919 self._screenSize = self.existingConnection().recvScreenSize()920 return view921 def screenLocked(self):922 """923 Return True if showing lockscreen, otherwise False.924 """925 if self._conn:926 return self._conn.recvShowingLockscreen()927 else:928 return None929 def screenSize(self):930 if self._screenSize:931 return self._screenSize932 else:933 self._screenSize = fmbtgti.GUITestInterface.screenSize(self)934 return self._screenSize935 def setAccelerometer(self, abc):936 """937 Set emulator accelerometer readings938 Parameters:939 abc (tuple of floats):940 new 3-axis accelerometer readings, one to three values.941 Returns True if successful, False if failed. Raises an exception942 if emulator cannot be connected to. Does not work with real hardware.943 Note: to rotate display with real hardware, see setUserRotation().944 Example:945 d.setAccelerometer((9.8, 0))946 d.setAccelerometer((0, 9.8))947 d.setAccelerometer((-9.6, 0.2, 0.8))948 """949 if self._conn:950 return self._conn.sendAcceleration(abc)951 else:952 return False953 def setAccelerometerRotation(self, value):954 """955 Enable or disable accelerometer-based screen rotation956 Parameters:957 value (boolean):958 True: enable accelerometer-based rotation959 False: disable accelerometer-based rotation.960 Returns True if successful, otherwise False.961 """962 if self._conn:963 return self._conn.sendAccelerometerRotation(value)964 else:965 return False966 def setAutoRotateScreenshot(self, value):967 """968 Enable or disable automatic screenshot rotation.969 Parameters:970 value (boolean):971 If True, rotate screenshot automatically to compensate972 current display rotation.973 refreshScreenshot()'s optional rotate parameter overrides this974 setting.975 See also autoRotateScreenshot(), displayRotation().976 """977 if value:978 self._autoRotateScreenshot = True979 else:980 self._autoRotateScreenshot = False981 def setConnection(self, connection):982 self._lastConnectionSettings = {}983 fmbtgti.GUITestInterface.setConnection(self, connection)984 if hasattr(self.connection(), "_serialNumber"):985 self.serialNumber = self.connection()._serialNumber986 def setDisplaySize(self, size=(None, None)):987 """988 Transform coordinates of synthesized events from screenshot989 resolution to given input area size. By default events are990 synthesized directly to screenshot coordinates.991 Parameters:992 size (pair of integers (width, height), optional):993 width and height of display in pixels. If not994 given, values from Android system properties995 "mDisplayWidth" and "mDisplayHeight" will be used.996 Returns None.997 """998 width, height = size999 if width == None or height == None:1000 w, h = self.existingConnection().recvScreenSize()1001 if w == h == 0:1002 w, h = self.existingConnection().recvDefaultViewportSize()1003 if width == None:1004 width = w1005 if height == None:1006 height = h1007 screenWidth, screenHeight = self.screenSize()1008 self.existingConnection().setScreenToDisplayCoords(1009 lambda x, y: (x * width / screenWidth,1010 y * height / screenHeight))1011 self.existingConnection().setDisplayToScreenCoords(1012 lambda x, y: (x * screenWidth / width,1013 y * screenHeight / height))1014 def setUiautomatorDump(self, uiautomatorDump):1015 """1016 Enable or disable using uiautomator on refreshView()1017 Parameters:1018 uiautomatorDump (boolean):1019 If True, uiautomator will be used on refreshView()1020 by default.1021 """1022 self._uiautomatorDump = uiautomatorDump1023 def setUserRotation(self, rotation):1024 """1025 Enable or disable accelerometer-based screen rotation1026 Parameters:1027 rotation (integer):1028 values 0, 1, 2 and 3 correspond to1029 ROTATION_0, ROTATION_90, ROTATION_180, ROTATION_270.1030 Returns True if successful, otherwise False.1031 Example:1032 # Disable accelerometer-based rotation for user rotation1033 # to take effect.1034 d.setAccelerometerRotation(False)1035 d.setUserRotation(fmbtandroid.ROTATION_90)1036 time.sleep(2)1037 d.setUserRotation(fmbtandroid.ROTATION_0)1038 time.sleep(2)1039 d.setAccelerometerRotation(True)1040 """1041 if rotation in ROTATIONS:1042 pass # already in correct scale1043 elif rotation in ROTATION_DEGS:1044 rotation = ROTATION_DEGS.index(rotation)1045 else:1046 raise ValueError('invalid rotation "%s"' % (rotation,))1047 if self._conn:1048 return self._conn.sendUserRotation(rotation)1049 else:1050 return False1051 def shell(self, shellCommand, timeout=None):1052 """1053 Execute shellCommand in adb shell....
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!!