当前位置: 首页>>代码示例>>Python>>正文


Python Device.swipe方法代码示例

本文整理汇总了Python中uiautomator.Device.swipe方法的典型用法代码示例。如果您正苦于以下问题:Python Device.swipe方法的具体用法?Python Device.swipe怎么用?Python Device.swipe使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在uiautomator.Device的用法示例。


在下文中一共展示了Device.swipe方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Mobile

# 需要导入模块: from uiautomator import Device [as 别名]
# 或者: from uiautomator.Device import swipe [as 别名]

#.........这里部分代码省略.........

    def press_volume_up(self):
        """
        press volume up key
        """
        self.device.press.volume_up()

    def press_volume_down(self):
        """
        press volume down key
        """
        self.device.press.volume_down()

    def press_camera(self):
        """
        press camera key
        """
        self.device.press.camera()

    def press_power(self):
        """
        press power key
        """
        self.device.press.power()

#Gesture interaction of the device

    def click(self, x, y):
        """
        click (x, y) on screen
        """
        self.device.click(x, y)

    def swipe(self, sx, sy, ex, ey, steps=10):
        """
        swipe from (sx, sy) to (ex, ey) with steps
        """
        self.device.swipe(sx, sy, ex, ey, steps)

# Swipe from the center of the ui object to its edge

    def swipe_left(self, obj, steps=10):
        """
        swipe the *obj* from center to left
        """
        obj.swipe.left(steps=steps)

    def swipe_right(self, obj, steps=10):
        """
        swipe the *obj* from center to right
        """
        obj.swipe.right(steps=steps)

    def swipe_top(self, obj, steps=10):
        """
        swipe the *obj* from center to top
        """
        obj.swipe.top(steps=steps)

    def swipe_bottom(self, obj, steps=10):
        """
        swipe the *obj* from center to bottom
        """
        obj.swipe.bottom(steps=steps)

    def drag(self,sx, sy, ex, ey, steps=10):
开发者ID:am01230123,项目名称:parallelization,代码行数:70,代码来源:Mobile.py

示例2: test

# 需要导入模块: from uiautomator import Device [as 别名]
# 或者: from uiautomator.Device import swipe [as 别名]
class test(object):
    dev_sn = ""
    dev_displayHeight = 0
    dev_displayWidth = 0
    icon_x = 0
    icon_y = 0
    app_name = ""
    app_path = ""
    app_package_name = ""
    class_name = ""
    result = ""
    install_time = ""
    device = Device();

    DIR_VERT, DIR_HORIZ ,DIR_NONE = range(3)
    SWIPE_DIR_UP, SWIPE_DIR_DOWN, SWIPE_DIR_LEFT, SWIPE_DIR_RIGHT = range(4)

    def __init__(self,sn,app):
        self.dev_sn = sn
        self.device = Device(self.dev_sn)
        self.dev_displayHeight = self.device.info['displayHeight']
        self.dev_displayWidth = self.device.info['displayWidth']
        self.icon_x = self.dev_displayWidth * 12 / 100
        self.icon_y = self.dev_displayHeight * 52 / 100
        self.is_app_settings_done = False
        if len(app) > 0 and app[0] != '':
            self.app_name = app[0]
        if len(app) > 1 and app[1] != '':
            self.app_path = app[1]
            self.app_package_name = self.get_package_name()
            self.install_app()
        if len(app) > 2 and app[2] != '':
            self.app_package_name = app[2]
        else:
            self.app_package_name = os.popen("adb -s %s shell pm list package | grep -i %s | awk -F ':' '{print$2}'"%(self.dev_sn,self.app_name)).read().strip("\r\n")
        self.set_app_settings_done_flag()
        self.clean_result()
        self.load_resource()

    def get_package_name(self):
        p = re.compile(r"package: name=\'([\w+.]*)\'")
        s = os.popen("./aapt dump badging  %s | grep -i package"%(self.app_path)).read()
        package_name = re.findall(p,s)
        return ''.join(package_name)

    def icon_click(self):
        os.system("adb -s %s shell input tap %s %s"%(self.dev_sn,self.icon_x,self.icon_y))

    def my_func_name(self):
        return inspect.stack()[1][3]

    def logout(self,function_name,log):
        print ">>> (%s) [%s.%s] :"%(self.app_name, self.__class__.__name__, function_name)+log

    def is_AppBench_root_page(self):
        if self.device(text="AppBench").exists and self.device(text="Tutorial").exists:
            return True
        else:
            return False

    def wait_for_fps_result(self):
        self.logout(self.my_func_name(),"...")
        while True:
            if self.is_AppBench_root_page() == False:
                if self.device(text="AppBench").exists:
                    return True
                else:
                    continue
            else:
                return False

    def swipe_vert(self,swipe_times,direction):
        if direction == self.SWIPE_DIR_UP:
            src_x = self.dev_displayWidth / 2
            src_y = self.dev_displayHeight * 4 / 5
            des_x = self.dev_displayWidth / 2
            des_y = self.dev_displayHeight * 1 / 5
        elif direction == self.SWIPE_DIR_DOWN:
            src_x = self.dev_displayWidth / 2
            src_y = self.dev_displayHeight * 1 / 5
            des_x = self.dev_displayWidth / 2
            des_y = self.dev_displayHeight * 4 / 5
        else:
            self.logout(self.my_func_name(),"direction is error...")
            return False
        for i in range(swipe_times):
            self.device.swipe(src_x,src_y,des_x,des_y,steps=20)
        return True


    def swipe_horiz(self,swipe_times,direction):
        if direction == self.SWIPE_DIR_RIGHT:
            src_x = self.dev_displayWidth  * 1 / 5
            src_y = self.dev_displayHeight / 3
            des_x = self.dev_displayWidth * 4 / 5
            des_y = self.dev_displayHeight  / 2
        elif direction == self.SWIPE_DIR_LEFT:
            src_x = self.dev_displayWidth  * 4 / 5
            src_y = self.dev_displayHeight / 3
            des_x = self.dev_displayWidth * 1 / 5
#.........这里部分代码省略.........
开发者ID:yangjiandagege,项目名称:AutoTestPython,代码行数:103,代码来源:test.py

示例3: ModelInfo

# 需要导入模块: from uiautomator import Device [as 别名]
# 或者: from uiautomator.Device import swipe [as 别名]

#.........这里部分代码省略.........
            
    def pressDelete(self):
        return self.mstrDevice.press.delete() # or del
        
    def pressRecent(self):
        return self.mstrDevice.press.recent()
            
    def pressVol_Up(self):
        return self.mstrDevice.press.volume_up()
            
    def pressVol_Down(self):
        return self.mstrDevice.press.volume_down()
            
    def pressVol_Mute(self):
        return self.mstrDevice.press.volume_mute()
            
    def pressPower(self):
        return self.mstrDevice.press.power()
            
    def clik(self, x, y):
        return self.mstrDevice.click(x, y)
            
    def longClik(self,x, y):
        '''
            Description:
                
            param:
                x, y : start first point x, y
                
            return : Boolean
        '''
        return self.mstrDevice.long_click(x, y)
            
    def swipe(self, sx, sy, ex, ey, steps=10):
        '''
            Description:
                
            param:
                sx, xy : start first x, y
                ex, ey : move to x, y
            return : Boolean
        '''
        return self.mstrDevice.swipe(sx, sy, ex, ey, steps)
           
    def drage(self,sx, sy, ex, ey, steps=10):
        '''
            Description:
                
            param:
                sx, xy : start first x, y
                ex, ey : move to x, y
            return : Boolean
        '''
        return self.mstrDevice.drag(sx, sy, ex, ey, steps)
       
    #screen action of the device   
    def setOrientation(self,scrAct='natural', choiceDevice='mstr'):
        '''
            Description
                
            param
                d.orientation = 'l' or 'left'
                d.orientation = 'r' or 'right'
                d.orientation = 'n' or 'natural'
            return : None
        '''
开发者ID:sqler21c,项目名称:Python,代码行数:70,代码来源:ModelInfo.py

示例4: AndroidDevice

# 需要导入模块: from uiautomator import Device [as 别名]
# 或者: from uiautomator.Device import swipe [as 别名]

#.........这里部分代码省略.........
            if k and v:
                shellcmd.append('-e')
                shellcmd.append(k)
                shellcmd.append(str(v))
        shellcmd.append(pkgname)
        result = self.d.server.adb.cmd(*shellcmd).communicate()
        return result

    def TODOinstallPackage(self, **kwargs):
        pass

    def TODOremovePackage(self, **kwargs):
        pass

    def press(self, keyname, waittime=1):
        #hard, soft key: home,back,up,down,right,left,center,menu,power or ANDROID_KEYEVENT
        self.d.press(keyname)
        time.sleep(waittime)
        return self

    def click(self, x, y, waittime=1):
        self.d.click(x, y)
        time.sleep(waittime)
        return self

    def click_image(self, imagename, waittime=1, threshold=0.01):
        '''
        if the wanted image found on current screen click it.
        if the wanted image not found raise exception and set test to be failure.
        '''
        expect_image_path = os.path.join(configer['right_dir_path'], imagename)
        assert os.path.exists(expect_image_path), 'the local expected image %s not found!' % imagename
        current_image_path = os.path.join(configer['report_dir_path'], imagename)
        self.d.screenshot(current_image_path)
        assert os.path.exists(current_image_path), 'fetch current screen shot image %s failed!' % imagename
        pos = getMatchedCenterOffset(expect_image_path, current_image_path, threshold)
        assert pos, 'Fail Reason: The wanted image \'%s\' not found on screen!' % imagename
        self.d.click(pos[0], pos[1])
        time.sleep(waittime)
        return self

    def swipe(self, sx, sy, ex, ey, steps=100, waittime=1):
        self.d.swipe(sx, sy, ex, ey, steps)
        time.sleep(waittime)
        return self

    def drag(self, sx, sy, ex, ey, steps=100, waittime=1):
        self.d.drag(sx, sy, ex, ey, steps)
        time.sleep(waittime)
        return self

    #inspect
    def exists(self, **kwargs):
        '''
        if the expected component exists on current screen layout return true else return false.
        '''
        return self.d.exists(**kwargs)

    #device snapshot
    def screenshot(self, filename, waittime=1):
        path = os.path.join(configer['report_dir_path'], filename)
        self.d.screenshot(path)
        return self

    def expect(self, imagename, interval=2, timeout=4, threshold=0.01, msg=''):
        '''
        if the expected image found on current screen return self 
        else raise exception. set test to be failure.
        '''
        expect_image_path = os.path.join(configer['right_dir_path'], imagename)
        assert os.path.exists(expect_image_path)
        current_image_path = os.path.join(configer['report_dir_path'], imagename)
        begin = time.time()
        while (time.time() - begin < timeout):
            self.d.screenshot(current_image_path)
            if isMatch(expect_image_path , current_image_path , threshold):
                return self
            time.sleep(interval)
        name, ext = os.path.splitext(os.path.basename(imagename))
        shutil.copyfile(expect_image_path, os.path.join(configer['report_dir_path'], '%s%s%s' % (name, '_expect', ext)))
        reason = msg if not msg else 'Fail Reason: Image \'%s\' not found on screen!' % imagename
        assert False, reason

    def find(self, imagename, interval=2, timeout=4, threshold=0.01):
        '''
        if the expected image found on current screen return true else return false
        '''
        expect_image_path = os.path.join(configer['right_dir_path'], imagename)
        assert os.path.exists(expect_image_path)
        current_image_path = os.path.join(configer['report_dir_path'], imagename)
        begin = time.time()
        isExists = False
        while (time.time() - begin < timeout):
            time.sleep(interval)
            self.d.screenshot(current_image_path)
            isExists = isMatch(expect_image_path , current_image_path , threshold)
            if not isExists:
                time.sleep(interval)
                continue
        return isExists
开发者ID:lucker6666,项目名称:devicewrapper,代码行数:104,代码来源:android.py

示例5: AdbDevice

# 需要导入模块: from uiautomator import Device [as 别名]
# 或者: from uiautomator.Device import swipe [as 别名]

#.........这里部分代码省略.........

    @staticmethod
    def getBoundsCenter(bounds):
        bounds = re.match('\[(?P<x1>[\d]+),(?P<y1>[\d]+)\]\[(?P<x2>[\d]+),(?P<y2>[\d]+)\]', bounds)
        x = (int(bounds.group('x2')) + int(bounds.group('x1'))) / 2
        y = (int(bounds.group('y2')) + int(bounds.group('y1'))) / 2
        return x, y

    @staticmethod
    def _parseRange(point, point1, point2):
        if point1[0] <= point[0] <= point2[0] and point1[1] <= point[1] <= point2[1]:
            area = (point2[0] - point1[0]) * (point2[1] - point1[1])
            return True, area
        else:
            return False, None

    def viewFilter(self, view):
        if view.getClass() == self.viewClass:
            return True
        else:
            return False

    def screenOn(self, status):
        if status == True:
            self.d.screen.on()
        else:
            self.d.screen.off()

    def clearLog(self):
        self.cmd.shell(['logcat', '-c'])

    def longClick(self, x, y, duration):
        if y <= self.d.info['displayHeight']:
            self.d.swipe(x, y, x, y, steps=duration / 10)
        else:
            self.cmd.shell(['input', 'tap', str(x), str(y)])

    def click(self, x, y):
        if y <= self.d.info['displayHeight']:
            self.d.click(x, y)
        else:
            self.cmd.shell(['input', 'tap', str(x), str(y)])

    def drag(self, x, y, duration):
        self.d.drag(x[0], x[1], y[0], y[1], steps=duration / 10)

    def swipe(self, x, y, duration):
        self.cmd.shell(['input', 'swipe', str(x[0]), str(x[1]), str(y[0]), str(y[1]), str(duration)])

    def type(self, text):
        translate = re.sub(r'([#\(\)\&\*\'\\\"\~\`\|\<\>?\;])', r'\\\1', text)
        self.cmd.shell(['input', 'text', translate])
        # self.d(className="android.widget.EditText").set_text(text)

    def hideKeyboard(self):
        if self.isKeyboardShown():
            self.backBtn()

    def unlock(self):
        if self.isLocked():
            self.menuBtn()

    def isLocked(self):
        lockScreenRE = re.compile('mShowingLockscreen=(true|false)')
        m = lockScreenRE.search(self.cmd.dumpsys(['window', 'policy']))
        if m is not None:
开发者ID:ChenYuTingJerry,项目名称:AutoSense_2,代码行数:70,代码来源:Adb.py

示例6: Mobile

# 需要导入模块: from uiautomator import Device [as 别名]
# 或者: from uiautomator.Device import swipe [as 别名]

#.........这里部分代码省略.........

    def press_volume_up(self):
        """
        Press volume up key
        """
        self.device.press.volume_up()

    def press_volume_down(self):
        """
        Press volume down key
        """
        self.device.press.volume_down()

    def press_camera(self):
        """
        Press camera key
        """
        self.device.press.camera()

    def press_power(self):
        """
        Press power key
        """
        self.device.press.power()

#Gesture interaction of the device

    def click_at_coordinates(self, x, y):
        """
        Click at (x,y) coordinates.
        """
        self.device.click(x, y)

    def swipe_by_coordinates(self, sx, sy, ex, ey, steps=10):
        """
        Swipe from (sx, sy) to (ex, ey) with *steps* .

        Example:
        | Swipe By Coordinates | 540 | 1340 | 940 | 1340 | | # Swipe from (540, 1340) to (940, 100) with default steps 10 |
        | Swipe By Coordinates | 540 | 1340 | 940 | 1340 | 100 | # Swipe from (540, 1340) to (940, 100) with steps 100 |
        """
        self.device.swipe(sx, sy, ex, ey, steps)

# Swipe from the center of the ui object to its edge

    def swipe_left(self, steps=10, *args, **selectors):
        """
        Swipe the UI object with *selectors* from center to left.

        Example:

        | Swipe Left | description=Home screen 3 | | # swipe the UI object left |
        | Swipe Left | 5 | description=Home screen 3 | # swipe the UI object left with steps=5 |

        See `introduction` for details about identified UI object.
        """
        self.device(**selectors).swipe.left(steps=steps)

    def swipe_right(self, steps=10, *args, **selectors):
        """
        Swipe the UI object with *selectors* from center to right

        See `Swipe Left` for more details.
        """
        self.device(**selectors).swipe.right(steps=steps)
开发者ID:am01230123,项目名称:furry-ironman,代码行数:69,代码来源:Mobile.py

示例7: UiTestLib

# 需要导入模块: from uiautomator import Device [as 别名]
# 或者: from uiautomator.Device import swipe [as 别名]

#.........这里部分代码省略.........
        | Action     | Argument   |  Argument  |  Argument  |  Argument  |
        |Assert UI Exists | timeout | text=XXXX | className=XXX.xxxx | resourceId=xxxxxx |
        """
        if not self.d(**selectors).wait.exists():
            raise AssertionError("UiObject does not exists %s" % selectors.items())

    def result_should_be(self, expected):
        """Verifies that the current result is `expected`.

        Example:
        | Action     | Argument   |
        |  Open application    | com.android.settings/com.android.settings.Settings |
        |  Result Should Be    | 0       |
        """
        print ("result is: %s\n", self._result)
        print ("ex is: %s\n", expected)
        if str(self._result) != expected:
            raise AssertionError("%s != %s" % (self._result, expected))

    def click_at_coordinates(self, x, y):
        """ Click at (x,y) coordinates.
        Example:
        | Action     | Argument   |  Argument  |
        | Click At Corrdinates | x | y |
        """
        return self.d.click(int(x), int(y))

    def long_click_at_coordinates(self, x, y):
        """
        # long click (x, y) on screen
        """
        return self.d.long_click(int(x), int(y))

    def swipe(self, sx, sy, ex, ey, steps=20):
        """
        Swipe from (sx,sy) to (ex,ey)
        """
        return self.d.swipe(int(sx), int(sy), int(ex), int(ex), int(steps))

    def drag(self, sx, sy, ex, ey, steps=20):
        """
        Drag from (sx,sy) to (ex,ey)
        """
        return self.d.drag(int(sx), int(sy), int(ex), int(ex), int(steps))

    def freeze_rotation(self, rotation=True):
        """
        Freeze rotation,
        *rotation*, True is default,
        """
        return self.d.freeze_rotation(rotation)

    def set_rotation(self, rotation):
        """
        # retrieve orientation,
        # it should be "natural" or "left" or "right" or "upsidedown"

        Example:
        | Action       | Argument   |
        | Set Rotation | nature      |
        | Set Rotation | left        |
        | Set Rotation | right       |
        | Set Rotation | upsidedown  |

        """
        orientation = self.d.orientation
开发者ID:huaping,项目名称:StabilityKPI,代码行数:70,代码来源:UiTestLib.py

示例8: InstallUninstallTest

# 需要导入模块: from uiautomator import Device [as 别名]
# 或者: from uiautomator.Device import swipe [as 别名]
class InstallUninstallTest(object):
    
    def __init__(self, serial=None):
        self.serial = serial 
        self.device=Device(self.serial)
        self.log_setting()
        
    def log_setting(self):
        logfilepath = os.path.abspath("C:\Temp")
        if not os.path.exists(logfilepath):
            os.mkdir(logfilepath)
        self.logger = logging.getLogger('mylogger')    
        self.logger.setLevel(logging.INFO) 
        #create handler for writting log into log file.
        fh = logging.FileHandler(os.path.join(logfilepath,"InstallSAPAnywhere.log")) 
        #create handler for writting log into console.
        ch = logging.StreamHandler() 
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') 
        fh.setFormatter(formatter) 
        ch.setFormatter(formatter) 
        self.logger.addHandler(fh)
        self.logger.addHandler(ch)   
   

    def check_device_attached(self):
        out=subprocess.Popen("adb devices",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()[0]
        match="List of devices attached"
        index=out.find(match)
        target_device_index=out.find(self.serial)
        if index<0:
            raise EnvironmentError("adb is not working.")
        elif target_device_index>0:
            self.logger.info("Device with serial %s attached"%self.serial)
        else:
            raise EnvironmentError("Device with serial %s is not attached"%self.serial)  
        
    def switch_network_to_corporate(self):
        try:
            self.swipe_down_notification_bar()
            self.device(text="WLAN").long_click()
            if not self.device(text="SAP-Corporate").sibling(text="Connected").exists:
                self.device(text="SAP-Corporate").click()
                self.device(text="Connect",className="android.widget.Button").click()
            if self.device(text="Notice").exists:
                self.device(text="connect",className="android.widget.Button").click()
            if self.device(text="SAP-Corporate").sibling(text="Connected").wait.exists(timeout=10000):
                self.logger.info("Network is switched to SAP-Corporate successfully")
            else:
                self.logger.error("Network is switched to SAP-Corporate timeout in 10s") 
        except:
            self.logger.error("Switch network to corporate failed with below %s"%traceback.format_exc()) 
     
    def check_app_installed(self):
        out=subprocess.Popen("adb shell pm list packages sap.sfa.container",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()[0]
        if len(out)>0:
            self.logger.info("SAP Anywhere is installed alreadlly.")
        else:
            self.logger.info("SAP Anywhere is not installed.")
        return len(out)>0
    
    def uninstall_app(self,appName):
        try:
            self.device.press("home")
            self.device.press("menu")
            self.device(text="Settings",className="android.widget.TextView").click()
            self.device(scrollable=True).scroll.to(text="Application manager")
            self.device(text="Application manager",className="android.widget.TextView").click()
            self.device(scrollable=True).scroll.to(text=appName)
            self.device(text=appName,className="android.widget.TextView").click()
            self.device(text="Uninstall").click()
            self.device(text="OK").click()
            if self.device(text="Uninstalled").wait.exists(timeout=10000)==True:
                self.logger.info("SAP Anywhere is uninstalled successfully.")    
                self.device(text="OK").click()
            else:
                self.logger.error("SAP Anywhere is uninstalled timeout in 10s.")
  
        except:
            self.logger.error("SAP Anywhere is uninstalled failed with below %s"%traceback.format_exc())      
              
    def install_app(self,appName):
        try:
            self.device(textContains=appName).click()
            self.device(text="Install").click()
            if self.device(text="Application installed").wait.exists(timeout=15000)==True:
                self.logger.info("%s is installed successfully."%appName)
                self.device(text="Done").click()
            else:
                self.logger.error("%s is installed timeout in 15s."%appName)                
        except:
            self.logger.error("%s is installed faield with below %s"%(traceback.format_exc(),appName))    
       

    def launch_chromedriver_servie(self):
        try:
            subprocess.Popen("start cmd /k C:\\temp\\chromedriver.exe",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
            self.logger.info("Launch chromedriver service successfully.")
        except:
            self.logger.error("Launch chromedriver service failed with below %s"%traceback.format_exc()) 
            
#.........这里部分代码省略.........
开发者ID:YuxinZhou,项目名称:uiautomatorSampleCodes,代码行数:103,代码来源:Samsung_Install_SAPAnywhere.py


注:本文中的uiautomator.Device.swipe方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。