Best Python code snippet using fMBT_python
fmbttizen.py
Source:fmbttizen.py  
...211        finger2startX = int(x + math.cos(math.radians(finger2Dir)) * startDistanceInPixels)212        finger2startY = int(y + math.sin(math.radians(finger2Dir)) * startDistanceInPixels)213        finger2endX = int(x + math.cos(math.radians(finger2Dir)) * endDistanceInPixels)214        finger2endY = int(y + math.sin(math.radians(finger2Dir)) * endDistanceInPixels)215        return self._conn.sendMtLinearGesture(216            [[(finger1startX, finger1startY), (finger1endX, finger1endY)],217             [(finger2startX, finger2startY), (finger2endX, finger2endY)]],218            duration, movePoints, sleepBeforeMove, sleepAfterMove)219    def pinchBitmap(self, bitmap, startDistance, endDistance,220                    **pinchAndOirArgs):221        """222        Make the pinch gesture using the bitmap as central point.223        Parameters:224          bitmap (string):225                  filename of the bitmap to be pinched.226          startDistance, endDistance (float):227                  distance from both finger tips to the central point228                  of the gesture, at the start and at the end of the229                  gesture. Values in range [0.0, 1.0] are scaled up to230                  the distance from the bitmap to screen edge. Both231                  finger tips will reach an edge if distance is 1.0.232          optical image recognition arguments (optional)233                  refer to help(obj.oirEngine()).234          rest of the parameters: refer to pinch documentation.235        Returns True if successful, otherwise False.236        """237        assert self._lastScreenshot != None, "Screenshot required."238        pinchArgs, rest = _takePinchArgs(pinchAndOirArgs)239        oirArgs, _ = fmbtgti._takeOirArgs(self._lastScreenshot, rest, thatsAll=True)240        oirArgs["limit"] = 1241        items = self._lastScreenshot.findItemsByBitmap(bitmap, **oirArgs)242        if len(items) == 0:243            return False244        return self.pinchItem(items[0], startDistance, endDistance, **pinchArgs)245    def pinchClose(self, (x, y) = (0.5, 0.5), startDistance=0.5, endDistance=0.1, **pinchKwArgs):246        """247        Make the close pinch gesture.248        Parameters:249          x, y (integer, optional):250                  the central point of the gesture, the default is in251                  the middle of the screen.252          startDistance, endDistance (float, optional):253                  refer to pinch documentation. The default is 0.5 and254                  0.1.255          rest of the parameters: refer to pinch documentation.256        """257        return self.pinch((x, y), startDistance, endDistance, **pinchKwArgs)258    def pinchItem(self, viewItem, startDistance, endDistance, **pinchKwArgs):259        """260        Pinch the center point of viewItem.261        Parameters:262          viewItem (GUIItem object):263                  item to be tapped, possibly returned by264                  findItemsBy... methods in Screenshot or View.265          pinchPos (pair of floats (x,y)):266                  position to tap, relational to the bitmap.267                  (0.0, 0.0) is the top-left corner,268                  (1.0, 0.0) is the top-right corner,269                  (1.0, 1.0) is the lower-right corner.270                  Values < 0 and > 1 tap coordinates outside the item.271          rest of the parameters: refer to pinch documentation.272        """273        if "pinchPos" in pinchKwArgs:274            posX, posY = pinchKwArgs["pinchPos"]275            del pinchKwArgs["pinchPos"]276            x1, y1, x2, y2 = viewItem.bbox()277            pinchCoords = (x1 + (x2-x1) * posX,278                           y1 + (y2-y1) * posY)279        else:280            pinchCoords = viewItem.coords()281        return self.pinch(pinchCoords, startDistance, endDistance, **pinchKwArgs)282    def pinchOpen(self, (x, y) = (0.5, 0.5), startDistance=0.1, endDistance=0.5, **pinchKwArgs):283        """284        Make the open pinch gesture.285        Parameters:286          x, y (integer, optional):287                  the central point of the gesture, the default is in288                  the middle of the screen.289          startDistance, endDistance (float, optional):290                  refer to pinch documentation. The default is 0.1 and291                  0.5.292          for the rest of the parameters, refer to pinch documentation.293        """294        return self.pinch((x, y), startDistance, endDistance, **pinchKwArgs)295    def pressPower(self, **pressKeyKwArgs):296        """297        Press the power button.298        Parameters:299          long, hold (optional):300                  refer to pressKey documentation.301        """302        return self.pressKey("POWER", **pressKeyKwArgs)303    def pressVolumeUp(self, **pressKeyKwArgs):304        """305        Press the volume up button.306        Parameters:307          long, hold (optional):308                  refer to pressKey documentation.309        """310        return self.pressKey("VOLUMEUP", **pressKeyKwArgs)311    def pressVolumeDown(self, **pressKeyKwArgs):312        """313        Press the volume down button.314        Parameters:315          long, hold (optional):316                  refer to pressKey documentation.317        """318        return self.pressKey("VOLUMEDOWN", **pressKeyKwArgs)319    def pressHome(self, **pressKeyKwArgs):320        """321        Press the home button.322        Parameters:323          long, hold (optional):324                  refer to pressKey documentation.325        """326        return self.pressKey("HOME", **pressKeyKwArgs)327    def setDisplayBacklightTime(self, timeout):328        """329        Set time the LCD backlight will be kept on.330        Parameters:331          timeout (integer):332                  inactivity time in seconds after which the backlight333                  will be switched off.334        """335        return self._conn.sendDisplayBacklightTime(timeout)336    def shell(self, shellCommand):337        """338        Execute shell command through sdb shell.339        Parameters:340          shellCommand (string)341                  command to be executed in sdb shell.342        Returns output of "sdb shell" command.343        If you wish to receive exitstatus or standard output and error344        separated from shellCommand, refer to shellSOE().345        """346        return _run(["sdb", "shell", shellCommand], expectedExitStatus=range(256))[1]347    def shellSOE(self, shellCommand, username="", password="", asyncStatus=None, asyncOut=None, asyncError=None):348        """349        Get status, output and error of executing shellCommand on Tizen device350        Parameters:351          shellCommand (string)352                  command to be executed on device.353          username (string, optional)354                  username who should execute the command. The default355                  is "", that is, run as the default user when logged356                  in using "sdb shell".357          password (string, optional)358                  if username is given, use given string as359                  password. The default is "tizen" for user "root",360                  otherwise "".361          asyncStatus (string or None)362                  filename (on device) to which the status of363                  asynchronously executed shellCommand will be364                  written. The default is None, that is, command will365                  be run synchronously, and status will be returned in366                  the tuple.367          asyncOut (string or None)368                  filename (on device) to which the standard output of369                  asynchronously executed shellCommand will be370                  written. The default is None.371          asyncError (string or None)372                  filename (on device) to which the standard error of373                  asynchronously executed shellCommand will be374                  written. The default is None.375        Returns tuple (exitStatus, standardOutput, standardError).376        If asyncStatus, asyncOut or asyncError is a string,377        shellCommand will be run asynchronously, and (0, None, None)378        will be returned. In case of asynchronous execution, if any of379        asyncStatus, asyncOut or asyncError is None, corresponding380        output will be written to /dev/null. The shellCommand will be381        executed even if the device would be disconnected. All async382        files are opened for appending, allowing writes to the same383        file.384        """385        if username == "root" and password == "":386            return self._conn.shellSOE(shellCommand, username, "tizen", asyncStatus, asyncOut, asyncError)387        else:388            return self._conn.shellSOE(shellCommand, username, password, asyncStatus, asyncOut, asyncError)389_g_sdbProcesses = set()390def _forceCloseSdbProcesses():391    for p in _g_sdbProcesses:392        try: p.write("quit\n")393        except: pass394        try: p.terminate()395        except: pass396atexit.register(_forceCloseSdbProcesses)397def _encode(obj):398    return base64.b64encode(cPickle.dumps(obj))399def _decode(string):400    return cPickle.loads(base64.b64decode(string))401class TizenDeviceConnection(fmbtgti.GUITestConnection):402    """403    TizenDeviceConnection copies _tizenAgent to Tizen device,404    and runs & communicates with it via sdb shell.405    """406    def __init__(self, serialNumber=None, loginCommand=None, debugAgentFile=None):407        if loginCommand == None:408            if serialNumber == None:409                self._serialNumber = self.recvSerialNumber()410            else:411                self._serialNumber = serialNumber412            self._loginCommand = None413        else:414            if serialNumber == None:415                self._serialNumber = "unknown"416            else:417                self._serialNumber = serialNumber418            if isinstance(loginCommand, str):419                self._loginCommand = shlex.split(loginCommand)420            else:421                self._loginCommand = loginCommand422        self._useSdb = (self._loginCommand == None)423        self._useSsh = not self._useSdb424        self._sdbShell = None425        self._debugAgentFile = debugAgentFile426        self._agentNeedsResolution = True427        self.open()428    def __del__(self):429        self.close()430    def open(self):431        if self._serialNumber == "unknown" and self._useSdb:432            raise TizenDeviceNotFoundError("Tizen device not found.")433        self.close()434        agentFilename = os.path.join(435            os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))),436            "fmbttizen-agent.py")437        remoteUploadPath = "/tmp"438        agentRemoteFilename = remoteUploadPath + "/fmbttizen-agent.py"439        uploadFiles = [(agentFilename,440                        agentRemoteFilename),441                       (os.path.join(os.path.dirname(agentFilename),442                                     "fmbtuinput.py"),443                        remoteUploadPath + "/fmbtuinput.py")]444        # Upload fmbttizen-agent to the device445        if self._useSdb:446            for src, dst in uploadFiles:447                uploadCmd = ["sdb", "-s", self._serialNumber, "push", src, dst]448                status, out, err = _run(uploadCmd, range(256))449                if status == 127:450                    raise TizenConnectionError('Executing "sdb -s %s push" failed. Check your Tizen SDK installation.' % (self._serialNumber,))451                elif status != 0:452                    if "device not found" in err:453                        raise TizenDeviceNotFoundError('Tizen device "%s" not found.' % (self._serialNumber,))454                    else:455                        raise TizenConnectionError('Executing "%s" failed: %s' % (' '.join(uploadCmd), err + " " + out))456        else: # using SSH457            if self._loginCommand:458                for src, dst in uploadFiles:459                    uploadCmd = self._loginCommand + ["cat", ">", dst]460                    p = subprocess.Popen(uploadCmd, shell=False, stdin=subprocess.PIPE)461                    p.stdin.write(file(src).read())462                    p.stdin.close()463                    p.wait()464            else: # run locally without remote login, no upload465                agentRemoteFilename = agentFilename466        # Launch agent, create persistent connection to it467        if self._useSdb:468            remoteShellCmd = ["sdb", "-s", self._serialNumber, "shell"]469        else: # using SSH470            remoteShellCmd = self._loginCommand + ["python", agentRemoteFilename]471        try:472            self._sdbShell = subprocess.Popen(remoteShellCmd,473                                              shell=False,474                                              stdin=subprocess.PIPE,475                                              stdout=subprocess.PIPE,476                                              stderr=subprocess.PIPE,477                                              close_fds=True)478        except OSError, msg:479            raise TizenConnectionError('Executing "%s" failed.' % (480                " ".join(remoteShellCmd),))481        _g_sdbProcesses.add(self._sdbShell)482        self._sdbShellErrQueue = Queue.Queue()483        thread.start_new_thread(_fileToQueue, (self._sdbShell.stderr, self._sdbShellErrQueue))484        if self._useSdb:485            self._sdbShell.stdin.write("\r")486            try:487                ok, self._platformInfo = self._agentCmd("python %s; exit" % (agentRemoteFilename,))488            except IOError:489                raise TizenConnectionError('Connecting to a Tizen device/emulator with "sdb -s %s shell" failed.' % (self._serialNumber,))490        else: # using SSH491            ok, self._platformInfo = self._agentCmd("")492            pass # agent already started by remoteShellCmd493        return ok494    def reportErrorsInQueue(self):495        while True:496            try: l = self._sdbShellErrQueue.get_nowait()497            except Queue.Empty: return498            if self._debugAgentFile: self._debugAgentFile.write("<2 %s" % (l,))499            _adapterLog("fmbttizen agent error: %s" % (l,))500    def close(self):501        if self._sdbShell != None:502            try: self._agentCmd("quit", retry=0)503            except: pass504            try: self._sdbShell.terminate()505            except: pass506            try: self._sdbShell.stdin.close()507            except: pass508            try: self._sdbShell.stdout.close()509            except: pass510            try: self._sdbShell.stderr.close()511            except: pass512            self.reportErrorsInQueue()513            _g_sdbProcesses.remove(self._sdbShell)514        self._sdbShell = None515    def _agentAnswer(self):516        errorLinePrefix = "FMBTAGENT ERROR "517        okLinePrefix = "FMBTAGENT OK "518        l = self._sdbShell.stdout.readline()519        output = []520        while True:521            if self._debugAgentFile:522                if len(l) > 72: self._debugAgentFile.write("<1 %s...\n" % (l[:72],))523                else: self._debugAgentFile.write("<1 %s\n" % (l,))524            if l.startswith(okLinePrefix):525                return True, _decode(l[len(okLinePrefix):])526            elif l.startswith(errorLinePrefix):527                return False, _decode(l[len(errorLinePrefix):])528            else:529                output.append(l)530                pass531            l = self._sdbShell.stdout.readline()532            if l == "":533                raise IOError("Unexpected termination of sdb shell: %s" % ("\n".join(output)))534            l = l.strip()535    def _agentCmd(self, command, retry=3):536        if command[:2] in ["tt", "td", "tm", "tu", "er"]:537            # Operating on coordinates on with a touch devices538            # may require information on screen resolution.539            # The agent does not know about possible rotation, so540            # the resolution needs to be sent from here.541            if self._agentNeedsResolution:542                self._agentCmd("sd %s %s" % self._gti.screenSize())543                self._agentNeedsResolution = False544        if self._sdbShell == None: return False, "disconnected"545        if self._debugAgentFile: self._debugAgentFile.write(">0 %s\n" % (command,))546        if self._useSdb:547            eol = "\r"548        else:549            eol = "\n"550        try:551            if len(command) > 0:552                self._sdbShell.stdin.write("%s%s" % (command, eol))553                self._sdbShell.stdin.flush()554        except IOError, msg:555            if retry > 0:556                time.sleep(.2)557                self.reportErrorsInQueue()558                _adapterLog('Error when sending command "%s": %s.' % (command, msg))559                self.open()560                self._agentCmd(command, retry=retry-1)561            else:562                raise563        return self._agentAnswer()564    def sendPress(self, keyName):565        return self._agentCmd("kp %s" % (keyName,))[0]566    def sendKeyDown(self, keyName):567        return self._agentCmd("kd %s" % (keyName,))[0]568    def sendKeyUp(self, keyName):569        return self._agentCmd("ku %s" % (keyName,))[0]570    def sendMtLinearGesture(self, *args):571        return self._agentCmd("ml %s" % (_encode(args)))[0]572    def sendScreenshotRotation(self, angle):573        return self._agentCmd("sa %s" % (angle,))[0]574    def sendTap(self, x, y):575        return self._agentCmd("tt %s %s 1" % (x, y))[0]576    def sendTouchDown(self, x, y):577        return self._agentCmd("td %s %s 1" % (x, y))[0]578    def sendTouchMove(self, x, y):579        return self._agentCmd("tm %s %s" % (x, y))[0]580    def sendTouchUp(self, x, y):581        return self._agentCmd("tu %s %s 1" % (x, y))[0]582    def sendType(self, string):583        return self._agentCmd("kt %s" % (_encode(string)))[0]584    def sendDisplayBacklightTime(self, timeout):...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!!
