Best Python code snippet using fMBT_python
ivi_apps.py
Source:ivi_apps.py  
...65    def eventPlayback(self, ev_script, wait_time=1):66        cmd = "ev_playback /usr/lib/event_scripts/%s/%s" \67              % (self.dev_display, ev_script)68        print "++ run device cmd: " + cmd69        (ret, so, se) = self.shellSOE(cmd)70        if ret != 0:71            print "++ fail to playback event"72            print "++ standard output: " + so 73            print "++ standard error:" + se74        time.sleep(wait_time)75        return ret76    def swipeToEast(self, wait_time=1):77        print "++ swipe to the east"78        ret = self.swipe((0.5,0.5), direction="e")79        time.sleep(wait_time)80        return ret81    def swipeToWest(self, wait_time=1):82        print "++ swipe to the west"83        ret = self.swipe((0.5,0.5), direction="w")84        time.sleep(wait_time)85        return ret86    def swipeToNorth(self, wait_time=1):87        print "++ swipe to the north"88        ret = self.swipe((0.5,0.5), direction="n")89        time.sleep(wait_time)90        return ret91    def swipeToSouth(self, wait_time=1):92        print "++ swipe to the south"93        ret = self.swipe((0.5,0.5), direction="s")94        time.sleep(wait_time)95        return ret96    97    def tap(self, *args, **kwds):98        ret = fmbttizen.Device.tap(self, *args, **kwds)99        time.sleep(1)100        return ret101    def refAndTapBitmap(self, png, wait_time=1):102        print "++ refresh screen and tapBitmap " + png103        ret = self.refreshScreenshot() and self.tapBitmap(png)104        time.sleep(wait_time)105        return ret106    def refAndVerifyBitmap(self, png, wait_time=1):107        print "++ refresh screen and verify bitmap " + png108        ret = self.refreshScreenshot() and self.verifyBitmap(png)109        time.sleep(wait_time)110        return ret111        112    def refAndWaitAllBitmap(self, picture_list):113        print "++ refresh screen and wait all bitmap: " \114               + ', '.join(picture_list)115        self.refreshScreenshot()116        ret = True117        for p in picture_list:118            if not self.waitBitmap(p):119                print "++ %s not found" % p120                ret = False121        return ret122    def findPid(self, process_name):123        cmd = "pgrep -f '%s'" % process_name124        (r, so, se ) = self.shellSOE(cmd)125        pids = []126        if r == 0:127            pids = [string.atoi(n) for n in filter(lambda l: len(l)>0, so.split("\n"))]128        return r, pids129    def verifyAllProcess(self, process_list):130        print "++ check process: " + ', '.join(process_list)131        ret = True132        for p in process_list:133            if len(self.findPid(p)[1]) == 0:134                print "++ %s not found" % p135                ret = False136            else:137                print "++ found %s" % p138        return ret139    def _hoover(self, x, y):140        self.drag((x, y), (x, y), delayBeforeMoves=-1, delayAfterMoves=-1, movePoints=1)141    def refreshScreenshot(self):142        ret = False143        if self.move_cursor == True:144            if self.maxX != 0:145                print "++ move cursor to %d, %d" % (self.maxX, self.maxY)146                self._hoover(self.maxX, self.maxY)147            ret = fmbttizen.Device.refreshScreenshot(self)148            if self.maxX != 0:149                print "++ move cursor to 0, 0"150                self._hoover(0, 0)151        else:152            ret = fmbttizen.Device.refreshScreenshot(self)153        return ret154            155    def check_call(self, cmd):156        (ret, so, se) = self.shellSOE(cmd)157        if ret != 0:158            print "++ fail to run cmd `%s'" % (cmd)159            print "++ standard output: " + so 160            print "++ standard error:" + se161            raise TizenError("cmd_issue", "fail to run cmd `%s'" % (cmd))162        return so163class cl_app():164    def __init__(self, name, process, controller):165        self.name = name166        self.process = process167        self.controllerImp = controller168class NightModeController():169    def __init__(self, controller):170        self.controllerImp = controller171        self.theme = ""172    173    def refNightMode(self):174        self.theme = ""175        (ret, so, se) = self.controllerImp.shellSOE("amb-get NightMode")176        if ret == 0:177            if '"NightMode": 1' in so:178                self.theme = "night"179            elif '"NightMode": 0' in so:180                self.theme = "day"181        if self.theme:182            print "++ get NightMode successfully, the theme is " + self.theme183        else:184            self.theme = "day"185            print "++ fail to get NightMode, use default theme `%s'" % self.theme186        theme_str = app_icons_str.replace("%theme%", self.theme)187        exec(theme_str)188        print "++ app_icons: %s" % app_icons189    def setNightMode(self, night_mode=True):190        if night_mode:191            pass192        else:193            pass194        self.refNightMode()195class WestonDesktop(cl_app):196    def __init__(self, controller):197        cl_app.__init__(self, "WestonDesktop", "", controller)198        self.night_mode_ctrl = NightModeController(controller)199    def wrt_launch(self, app_name):200        out = self.controllerImp.check_call("wrt-launcher -l")201        for l in out.splitlines():202            if l.find(app_name) != -1:203                app_id = l.split()[-1]204                if app_id.find(".%s" % app_name) == -1:205                    print "++ app_id format is not correct `%s'" % (app_id)206                    return False207                print "++ found app_id `%s'" % (app_id)208                break209        else:210            print "++ not found app_id for %s" % (app_name)211            return False212        self.controllerImp.type("wrt-launcher -s %s\n" % app_id)213    def cmd_launch(self, app_name):214        self.controllerImp.type("%s\n" % app_name)215    def launch_app(self, app_name):216        self.controllerImp.type("launch_app %s\n" % app_name)217    def launch(self, app_name, picture_list=[], process_list=[]):218        if self.controllerImp.refAndTapBitmap("term.icon.png") or \219           self.controllerImp.refAndTapBitmap("term.icon.png"):220            print "++ sucessfully tap western term icon"221        else:222            return False223        # to fetch focus, tricky !!224        self.controllerImp._hoover(self.controllerImp.maxX, self.controllerImp.maxY)225        print "++ proper launch app"226        if app_name in ["saythis", "Settings", "GhostCluster", "MediaPlayer"]:227            self.wrt_launch(app_name)228        elif app_name in ["org.tizen.dialer"]:229            self.launch_app(app_name)230        else:231            self.cmd_launch(app_name)232        print "++ try to refresh screenshot"233        self.controllerImp.refreshScreenshot()234        time.sleep(2)235        if process_list:236            print "++ verify started process..."237            if not self.controllerImp.verifyAllProcess(process_list):238                print "++ expected process not found"239                return False240        if picture_list:241            print "++ verify expected bitmap..."242            if not self.controllerImp.refAndWaitAllBitmap(picture_list):243                print "++ fail to verify bitmap"244                return False245        print "++ launch %s successfully" % (app_name)246        time.sleep(2)247        return True248    def refNightMode(self):249        self.night_mode_ctrl.refNightMode()250class ICOHomeScreen(cl_app):251    def __init__(self, controller):252        cl_app.__init__(self, "homescreen", "", controller)253        self.current_page = 0254        self.app_status = {}255        self.max_page = 3256        self.night_mode_ctrl = NightModeController(controller)257        self.apps = []258    def registerApp(self, app):259        self.apps.append(app)260    def clickApplist(self):261        return self.controllerImp.refAndTapBitmap(app_icons["applist"])262    263    def swipeToWest(self):264        ret = self.controllerImp.swipeToWest()265        if self.current_page < self.max_page - 1:266            self.current_page += 1267        print "++ current page: %d" % self.current_page268        assert(self.current_page < self.max_page)269        return ret270    def swipeToEast(self):271        ret = self.controllerImp.swipeToEast()272        if self.current_page > 0:273            self.current_page -= 1274        print "++ current page: %d" % self.current_page275        assert(self.current_page >= 0)276        return ret277    def swipePages(self, start, end):278        assert start >= 0, "wrong start page %d"  % start279        assert end < self.max_page, "wrong end page %d" % end280        print "++ current_page: %d, start page: %d, end page: %d" \281            % (self.current_page, start, end)282        if start > end:283            for i in range(start - end):284                if not self.swipeToEast():285                    return False286        else:287            for i in range(end - start):288                if not self.swipeToWest():289                    return False290        return True291    def swipeToPage(self, end):292        return self.swipePages(self.current_page, end)293    def swipeToLeftmost(self):294        return self.swipePages(self.current_page, 0)295    def launch(self, app_name, app_icon, picture_list=[], process_list=[]):296        print "++ click applist button"297        if not self.clickApplist():298            print "++ fail to click applist button!"299            return False300        301        first_launch = False302        icon = app_icon303        print "++ try to launch %s" % app_name304        if app_name in self.app_status.keys():305            print "++ %s is already launched" % app_name306            app_page = self.app_status[app_name][0]307            print "++ swipe to app page %d" % app_page308            if not self.swipeToPage(app_page):309                print "++ fail to swipe to the specified page! cur page: %d" \310                    % self.current_page311                return False312            print "++ try to tap the old item"313            if not self.controllerImp.tapItem((self.app_status[app_name])[1]):314                print "++ fail to tap item!"315                return False316        else: # first launch317            print "++ %s is the first launch" % app_name318            first_launch = True319            print "++ swipe to the left most side"320            if not self.swipeToLeftmost():321                print "++ fail to swipe to the left most side!"322                return False323            for i in range(self.max_page):324                print "++ check app page %d" % i325                if self.controllerImp.refreshScreenshot() == None:326                    print "++ fail to refresh screenshot!"327                    return False328                if self.controllerImp.tapBitmap(icon) == True:329                    print "++ found icon " + icon330                    app_item = self.controllerImp._lastScreenshot.findItemsByBitmap(icon)[0]331                    break332                else:333                    print "++ swipe to the next page"334                    if not self.swipeToWest():335                        print "++ fail to swipe to next page!"336                        return False337            else:338                print "++ not found app icon %s" % icon339                if not self.clickApplist():340                    print "++ fail to click applist button!"341                return False342        343        if process_list:344            print "++ verify started process..."345            if not self.controllerImp.verifyAllProcess(process_list):346                print "++ expected process not found"347                return False348        if picture_list:349            print "++ verify expected bitmap..."350            if not self.controllerImp.refAndWaitAllBitmap(picture_list):351                print "++ fail to verify bitmap"352                return False353        354        print "++ launch %s successfully at page %d" % (app_name, self.current_page)355        if first_launch:356            self.app_status[app_name] = [self.current_page, app_item, process_list[0]] 357        time.sleep(2)358        return True359    def clickCloseYes(self, wait_time=1):360        self.controllerImp.tap((0.4, 0.55))361        time.sleep(wait_time)362    def clickCloseNo(self, wait_time=1):363        pass364    def close(self, app_name, process_name):365        def calculateRedClosePosition(item):366            center = item.coords()367            width, height = self.controllerImp.screenSize()368            row = int(float(center[1])/float(height)/0.16)369            col = int(float(center[0])/float(width)/0.3) + 1370            print "++ %s location is: row %d, col %d" %(app_name, row, col)371            y = row * 0.16 372            x = col * 0.3373            return (x,y)374        ret = True375        if app_name in self.app_status.keys():376            pids = self.controllerImp.findPid(process_name)[1]377            if len(pids) == 0:378                print "++ %s closed unexpectedly" %app_name379                return False       380            print "++ click applist button"381            if not self.clickApplist():382                print "++ fail to click applist button!"383                return False384            app_page = self.app_status[app_name][0]385            print "++ swipe to app page %d" % app_page386            if not self.swipeToPage(app_page):387                print "++ fail to swipe to the specified page! cur page: %d" \388                    % self.current_page389                return False390            print "++ try to long tap the center of old item"391            if not self.controllerImp.tapItem(self.app_status[app_name][1], 392                                        tapPos=(0.5, 0.5), long=True, hold=7.0):393                print "++ fail to long tap the old item!"394                return False395            self.controllerImp.tap(calculateRedClosePosition(self.app_status[app_name][1]))396            time.sleep(1)397            self.clickCloseYes()398        else:399            print "++ warning: %s is not launched" % app_name400        time.sleep(1)401        pids = self.controllerImp.findPid(process_name)[1]402        print "++ check process existence: " + process_name403        for i in range(len(pids)):404            print "++ pid: %d" % pids[i]405        if len(pids) != 0:406            print "++ process still exsits, fail to close %s" % app_name407            ret = False408        else:# closed successfully409            print "++ %s closed successfully" %app_name410            self.app_status.pop(app_name)411        return ret412    def closeByKill(self, app_name, process_name):413        ret = True414        pids = self.controllerImp.findPid(process_name)[1]415        print "++ process_name: %s, pids: %s" % (process_name, pids)416        for p in pids:417            cmd = "kill %d" % p418            (r, so, se) =self.controllerImp.shellSOE(cmd)419            if r != 0:420                print "faile to kill pid %d" % pid_list[0]421                ret = False422            time.sleep(1)423        time.sleep(1)424        print "++ check process existence: " + process_name425        pids = self.controllerImp.findPid(process_name)[1]426        print "++ process_name: %s, pids: %s" % (process_name, pids)427        if len(pids) != 0:428            print "++ pid check fail, fail to close %s" % app_name429            ret = False430        else:431            print "++ no process exists"432            try:...fmbtchromiumos.py
Source:fmbtchromiumos.py  
...54                  rotation).55        """56        fmbtgti.GUITestInterface.__init__(self, **kwargs)57        self.setConnection(ChromiumOSConnection(loginCommand))58    def shellSOE(self, shellCommand, username="", password="", asyncStatus=None, asyncOut=None, asyncError=None, usePty=False):59        """60        Get status, output and error of executing shellCommand on Chromium OS device61        Parameters:62          shellCommand (string)63                  command to be executed on device.64          username (string, optional)65                  username who should execute the command. The default66                  is "root".67          asyncStatus (string or None)68                  filename (on device) to which the status of69                  asynchronously executed shellCommand will be70                  written. The default is None, that is, command will71                  be run synchronously, and status will be returned in72                  the tuple.73          asyncOut (string or None)74                  filename (on device) to which the standard output of75                  asynchronously executed shellCommand will be76                  written. The default is None.77          asyncError (string or None)78                  filename (on device) to which the standard error of79                  asynchronously executed shellCommand will be80                  written. The default is None.81          usePty (optional, boolean)82                  execute shellCommand in pseudoterminal. The default83                  is False.84        Returns tuple (exitStatus, standardOutput, standardError).85        If asyncStatus, asyncOut or asyncError is a string,86        shellCommand will be run asynchronously, and (0, None, None)87        will be returned. In case of asynchronous execution, if any of88        asyncStatus, asyncOut or asyncError is None, corresponding89        output will be written to /dev/null. The shellCommand will be90        executed even if the device would be disconnected. All async91        files are opened for appending, allowing writes to the same92        file.93        """94        return self._conn.shellSOE(shellCommand, username, asyncStatus, asyncOut, asyncError, usePty)95class ChromiumOSConnection(fmbtgti.GUITestConnection):96    def __init__(self, loginCommand):97        fmbtgti.GUITestConnection.__init__(self)98        self._loginCommand = loginCommand99        self._loginTuple = tuple(shlex.split(self._loginCommand))100        self.open()101    def sendFilesInTar(self, localDir, files, destDir):102        package = StringIO.StringIO()103        t = tarfile.TarFile(mode="w", fileobj=package)104        for filename in files:105            t.add(os.path.join(localDir, filename), arcname=filename)106        t.close()107        package.seek(0)108        _run(self._loginTuple +109             ("mkdir -p %s; tar x -C %s" % (destDir, destDir),),110             package.read())111    def agentExec(self, pythonCode):112        self._agent.exec_in(self._agent_ns, pythonCode)113    def agentEval(self, pythonExpression):114        return self._agent.eval_in(self._agent_ns, pythonExpression)115    def open(self):116        myDir = os.path.dirname(os.path.abspath(117            inspect.getfile(inspect.currentframe())))118        self.sendFilesInTar(myDir,119                            ("fmbtx11_conn.py",120                             "fmbtpng.py",121                             "fmbtuinput.py"),122                            "/tmp/fmbtchromiumos")123        if os.access(os.path.join(myDir, "pythonshare", "__init__.py"), os.R_OK):124            pythonshareDir = myDir125        elif os.access(os.path.join(myDir, "..", "pythonshare", "pythonshare",126                                    "__init__.py"), os.R_OK):127            pythonshareDir = os.path.join(myDir, "..", "pythonshare")128        self.sendFilesInTar(pythonshareDir,129                            ("pythonshare/__init__.py",130                             "pythonshare/server.py",131                             "pythonshare/client.py",132                             "pythonshare/messages.py"),133                            "/tmp/fmbtchromiumos")134        if os.name != "nt":135            pythonshareServer = distutils.spawn.find_executable("pythonshare-server")136        else:137            pythonshareServer = os.path.join(138                os.path.dirname(__file__), "..", "Scripts", "pythonshare-server")139        if not pythonshareServer or not os.access(pythonshareServer, os.R_OK):140            raise FMBTChromiumOsError("cannot find pythonshare-server executable")141        self.sendFilesInTar(os.path.dirname(pythonshareServer),142                            ("pythonshare-server",),143                            "/tmp/fmbtchromiumos")144        agentCmd = (self._loginCommand +145                    " sudo DISPLAY=:0 XAUTHORITY=/home/chronos/.Xauthority" +146                    " LD_LIBRARY_PATH=/usr/local/lib:/usr/local/lib64:/usr/lib:/usr/lib64" +147                    " python /tmp/fmbtchromiumos/pythonshare-server -p stdin")148        self._agent = pythonshare.connection("shell://" + agentCmd)149        self._agent_ns = "fmbtchromiumos-agent"150        try:151            self.agentExec("import fmbtx11_conn")152        except pythonshare.PythonShareError, e:153            raise FMBTChromiumOsError(154                "Cannot connect to pythonshare-server on device (%s): %s" %155                (e, agentCmd))156        self.agentExec("x = fmbtx11_conn.Display()")157    def recvScreenshot(self, filename):158        img = self.agentEval("x.recvScreenshot()")159        if img.startswith("FMBTRAWX11"):160            try:161                header, zdata = img.split('\n', 1)162                width, height, depth, bpp = [int(n) for n in header.split()[1:]]163                data = zlib.decompress(zdata)164            except Exception, e:165                raise FMBTChromiumOsError("Corrupted screenshot data: %s" % (e,))166            if len(data) != width * height * 4:167                raise FMBTChromiumOsError("Image data size mismatch.")168            fmbtgti.eye4graphics.bgrx2rgb(data, width, height)169            # TODO: use libimagemagick directly to save data to png?170            ppm_header = "P6\n%d %d\n%d\n" % (width, height, 255)171            f = file(filename + ".ppm", "wb").write(ppm_header + data[:width*height*3])172            _run([fmbt_config.imagemagick_convert, filename + ".ppm", filename])173            os.remove("%s.ppm" % (filename,))174        else:175            file(filename, "wb").write(img)176        return True177    def sendType(self, text):178        return self.agentEval('x.sendType(%s)' % (repr(text),))179    def sendPress(self, keyCode, modifiers=None):180        if modifiers != None:181            raise NotImplementedError182        return self.agentEval("x.sendPress(%s)" % (repr(keyCode),))183    def sendKeyDown(self, keyCode, modifiers=None):184        if modifiers != None:185            raise NotImplementedError186        return self.agentEval("x.sendKeyDown(%s)" % (repr(keyCode),))187    def sendKeyUp(self, keyCode, modifiers=None):188        if modifiers != None:189            raise NotImplementedError190        return self.agentEval("x.sendKeyUp(%s)" % (repr(keyCode),))191    def sendTap(self, x, y, button=None):192        if button == None:193            # TODO: synthesize touch display event, if available194            command = "x.sendTap(%s, %s)" % (x, y)195        else:196            command = "x.sendTap(%s, %s, %s)" % (x, y, button)197        return self.agentEval(command)198    def sendTouchDown(self, x, y, button=None):199        if button == None:200            # TODO: synthesize touch display event, if available201            command = "x.sendTouchDown(%s, %s)" % (x, y)202        else:203            command = "x.sendTouchDown(%s, %s, %s)" % (x, y, button)204        return self.agentEval(command)205    def sendTouchMove(self, x, y, button=None):206        if button == None:207            # TODO: synthesize touch display event, if available208            command = "x.sendTouchMove(%s, %s)" % (x, y)209        else:210            command = "x.sendTouchMove(%s, %s)" % (x, y)211        return self.agentEval(command)212    def sendTouchUp(self, x, y, button=None):213        if button == None:214            # TODO: synthesize touch display event, if available215            command = "x.sendTouchUp(%s, %s)" % (x, y)216        else:217            command = "x.sendMouseUp(%s, %s, %s)" % (x, y, button)218        return self.agentEval(command)219    def shellSOE(self, shellCommand, username, asyncStatus, asyncOut, asyncError, usePty):220        _, (s, o, e) = self.agentEval(221            "fmbtx11_conn.shellSOE(%s, %s, %s, %s, %s, %s)" % (222                repr(shellCommand), repr(username), repr(asyncStatus),223                repr(asyncOut), repr(asyncError), repr(usePty)))224        return s, o, e...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!!
