當前位置: 首頁>>代碼示例>>Python>>正文


Python Device.press方法代碼示例

本文整理匯總了Python中uiautomator.Device.press方法的典型用法代碼示例。如果您正苦於以下問題:Python Device.press方法的具體用法?Python Device.press怎麽用?Python Device.press使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在uiautomator.Device的用法示例。


在下文中一共展示了Device.press方法的5個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: Mobile

# 需要導入模塊: from uiautomator import Device [as 別名]
# 或者: from uiautomator.Device import press [as 別名]
class Mobile():
    """
    """

    def __init__(self, android_serial = None):
#         logger.info("Importing Android library")
#         print "Importing Android library"
#         clm.message("Importing Android library")
        self.adb = ADB(android_serial)
        self.device = Device(android_serial)
        self.test_helper = TestHelper(android_serial)

    def set_serial(self, android_serial):
        """
        Set device serial
        """
        self.adb = ADB(android_serial)
        self.device = Device(android_serial)
        self.test_helper = TestHelper(android_serial)

    def get_info(self):
        """
        Retrieve the device info
        """
        return self.device.info

#Key Event Actions of the device
    """
    Turn on/off screen
    """
    def turn_on_screen(self):
        """
        Turn on screen
        """
        self.device.screen.on()

    def turn_off_screen(self):
        """
        Turn off screen
        """
        self.device.screen.off()

    def wakeup_the_device(self):
        """
        wakeup the device
        """
        self.device.wakeup()

    """
    Press hard/soft key
    """

    def press_key(self, *key):
        """
        press *key* keycode
        """
        self.device.press(*key)

    def press_home(self):
        """
        press home key
        """
        self.device.press.home()

    def press_back(self):
        """
        press back key
        """
        self.device.press.back()

    def press_left(self):
        """
        press left key
        """
        self.device.pres.left()

    def press_right(self):
        """
        press right key
        """
        self.device.press.right()

    def press_up(self):
        """
        press up key
        """
        self.device.press.up()

    def press_down(self):
        """
        press down key
        """
        self.device.press.down()

    def press_center(self):
        """
        press center key
        """
        self.device.press.center()

#.........這裏部分代碼省略.........
開發者ID:am01230123,項目名稱:parallelization,代碼行數:103,代碼來源:Mobile.py

示例2: AndroidDevice

# 需要導入模塊: from uiautomator import Device [as 別名]
# 或者: from uiautomator.Device import press [as 別名]

#.........這裏部分代碼省略.........
                shellcmd.append(arg)
                shellcmd.append(extra_key)
                shellcmd.append(str_value)
                
        if 'flags' in keys:
            shellcmd.append('-f')
            shellcmd.append(str(kwargs['flags']))

        if 'uri' in keys:
            shellcmd.append(kwargs['uri'])
        #sys.stderr.write(str(shellcmd))            
        self.d.server.adb.cmd(*shellcmd).communicate()
        return self

    def instrument(self, **kwargs):
        keys = kwargs.keys()
        shellcmd = ['shell', 'am', 'instrument', '-w', '-r']
        pkgname = kwargs.pop('packagename')
        for k, v in kwargs.items():
            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):
開發者ID:lucker6666,項目名稱:devicewrapper,代碼行數:70,代碼來源:android.py

示例3: UiTestLib

# 需要導入模塊: from uiautomator import Device [as 別名]
# 或者: from uiautomator.Device import press [as 別名]
class UiTestLib(object):
    """Ui Test Lib

    """

    def __init__(self, serial=None):
        """
        """
        logger.info("<p>Device=%s>" % serial, html=True)
        print "<p>Device=%s>" % serial
        self._result = ""
        self.starttime = 0
        self.d = Device(serial)
        self.adb = Adb(serial)
        self.debug = "True"

    def set_debugable(flag):
        self.debug = flag

    def set_serial(self, serial):
        """Specify given *serial* device to perform test.
        or export ANDROID_SERIAL=CXFS42343 if you have many devices connected but you don't use this
        interface

        When you need to use multiple devices, do not use this keyword to switch between devices in test execution.
        And set the serial to each library.
        Using different library name when importing this library according to
        http://robotframework.googlecode.com/hg/doc/userguide/RobotFrameworkUserGuide.html?r=2.8.5.

        Examples:
        | Setting | Value |  Value |  Value |
        | Library | UiTestLib | WITH NAME | Mobile1 |
        | Library | UiTestLib | WITH NAME | Mobile2 |

        And set the serial to each library.
        | Test Case        | Action             | Argument           |
        | Multiple Devices | Mobile1.Set Serial | device_1's serial  |
        |                  | Mobile2.Set Serial | device_2's serial  |
        """
        self.d = Device(serial)
        self.adb = Adb(serial)

    def logmsg(self, msg):
        if self.debug == "True":
            print msg

    def exe_adb_command(self, cmd):
        """ Execute adb *cmd*
         Examples:
        | Exe Adb Command | shell getprop  |
        """
        return self.adb.cmd(cmd).wait()

    def exe_adb_and_result(self, cmd):
        """Execute adb *cmd* and return lines of the command"""
        lproc = self.adb.cmd(cmd)
        lproc.poll()
        lines = lproc.stdout.readlines()
        return lines

    def get_device_info(self):
        """Get Device information
        return info dictionary
        """
        return self.d.info

    def light_screen(self):
        """Light screen by wakeup.

        Examples:
        | Action     |
        |Light screen|

        Use `Light screen` to light screen.
        """

        self.d.wakeup()
        self._result = self.d.press.home()

    def open_application(self, appname):
        """Open application by it name `appname`.

        Example:
        | Action           | Argument      |
        | Open application | "com.android.settings/com.android.settings.Settings" |
        """
        appname = "shell am start -n " + appname
        print "Open Application:", appname
        self._result = self.exe_adb_command(appname)

    def click_text(self, text, instance=0):
        """Click text label on screen
        instance=0 is default, change when you needed.

        Example:
        | Action     | Argument   |  Argument  |
        | Click Text | text | instance |
        """

        return self.d(text=text, instance=instance).click.wait()
#.........這裏部分代碼省略.........
開發者ID:huaping,項目名稱:StabilityKPI,代碼行數:103,代碼來源:UiTestLib.py

示例4: Mobile

# 需要導入模塊: from uiautomator import Device [as 別名]
# 或者: from uiautomator.Device import press [as 別名]
class Mobile():

    def __init__(self):
        pass

    def set_serial(self, android_serial):
        """
        Specify given *android_serial* device to perform test.

        You do not have to specify the device when there is only one device connects to the computer.

        When you need to use multiple devices, do not use this keyword to switch between devices in test execution.

        Using different library name when importing this library according to http://robotframework.googlecode.com/hg/doc/userguide/RobotFrameworkUserGuide.html?r=2.8.4#setting-custom-name-to-test-library.

        | ==Setting== | ==Value== |  ==Value== |  ==Value== | 
        | Library | Mobile | WITH NAME | Mobile1 |
        | Library | Mobile | WITH NAME | Mobile2 |

        And set the serial to each library.

        | Test Case        | Action             | Argument           |
        | Multiple Devices | Mobile1.Set Serial | device_1's serial  |
        |                  | Mobile2.Set Serial | device_2's serial  |

        """
        self.adb = ADB(android_serial)
        self.device = Device(android_serial)
        self.test_helper = TestHelper(self.adb)

    def get_device_info(self):
        """
        Retrieve the device info.

        The keyword will return a dictionary.

        You can log the information by using the log dictionary keyword in build in Collections library(http://robotframework.googlecode.com/hg/doc/libraries/Collections.html?r=2.8.4).

        Example:
        | ${device_info} | Get Device Info |
        | Log Dictionary | ${device_info}  |

        =>

        Dictionary size is 9 and it contains following items:\n
        currentPackageName: com.android.keyguard\n
        displayHeight: 1776\n
        displayRotation: 0\n
        displaySizeDpX: 360\n
        displaySizeDpY: 640\n
        displayWidth: 1080\n
        naturalOrientation: True\n
        productName: hammerhead\n
        sdkInt: 19\n

        Or get specific information of the device by giving the key.

        | ${device_info}  | Get Device Info | | |
        | ${product_name} | Get From Dictionary | ${device_info} | productName |

        =>

        ${product_name} = hammerhead

        """
        return self.device.info

#Key Event Actions of the device
    """
    Turn on/off screen
    """
    def turn_on_screen(self):
        """
        Turn on screen
        """
        self.device.screen.on()

    def turn_off_screen(self):
        """
        Turn off screen
        """
        self.device.screen.off()

    """
    Press hard/soft key
    """

    def press_key(self, *keys):
        """
        Press *key* keycode.

        You can find all keycode in http://developer.android.com/reference/android/view/KeyEvent.html

        """
        #not tested
        self.device.press(*keys)

    def press_home(self):
        """
        Press home key
#.........這裏部分代碼省略.........
開發者ID:am01230123,項目名稱:furry-ironman,代碼行數:103,代碼來源:Mobile.py

示例5: InstallUninstallTest

# 需要導入模塊: from uiautomator import Device [as 別名]
# 或者: from uiautomator.Device import press [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.press方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。