Exemplo n.º 1
0
class adb(object):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        self.instAdb=Adb()
        
        self.devSerialNoms= self.instAdb.devices().keys()
        self.devcount = len(self.devSerialNoms)
        self.devSerial = self.instAdb.device_serial()
        
        
    def getSerials(self):
        return self.devSerialNoms
        #return self.devSerialNoms
    
    def getDeviceCount(self):
        return self.devcount
    
    def getSerial(self):
        return self.devSerial
Exemplo n.º 2
0
    def test_serial(self):
        serial = "abcdef1234567890"
        adb = Adb(serial)
        self.assertEqual(adb.default_serial, serial)

        adb.devices = MagicMock()
        adb.devices.return_value = [serial, "123456"]
        self.assertEqual(adb.device_serial(), serial)
Exemplo n.º 3
0
    def test_serial(self):
        serial = "abcdef1234567890"
        adb = Adb(serial)
        self.assertEqual(adb.default_serial, serial)

        adb.devices = MagicMock()
        adb.devices.return_value = [serial, "123456"]
        self.assertEqual(adb.device_serial(), serial)
Exemplo n.º 4
0
 def test_forward_list(self):
     adb = Adb()
     os.name = 'posix'
     adb.raw_cmd = MagicMock()
     adb.raw_cmd.return_value.communicate.return_value = (b"014E05DE0F02000E    tcp:9008    tcp:9008\r\n489328DKFL7DF    tcp:9008    tcp:9008", b"")
     self.assertEqual(adb.forward_list(), [['014E05DE0F02000E', 'tcp:9008', 'tcp:9008'], ['489328DKFL7DF', 'tcp:9008', 'tcp:9008']])
     os.name = 'nt'
     self.assertEqual(adb.forward_list(), [])
Exemplo n.º 5
0
    def __init__(self):
        '''
        Constructor
        '''
        self.instAdb = Adb()

        self.devSerialNoms = self.instAdb.devices().keys()
        self.devcount = len(self.devSerialNoms)
        self.devSerial = self.instAdb.device_serial()
Exemplo n.º 6
0
 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'
Exemplo n.º 7
0
 def test_devices(self):
     adb = Adb()
     adb.raw_cmd = MagicMock()
     adb.raw_cmd.return_value.communicate.return_value = (
         b"List of devices attached \r\n014E05DE0F02000E\tdevice\r\n489328DKFL7DF\tdevice",
         b"")
     self.assertEqual(adb.devices(), {
         "014E05DE0F02000E": "device",
         "489328DKFL7DF": "device"
     })
     adb.raw_cmd.assert_called_once_with("devices")
     adb.raw_cmd.return_value.communicate.return_value = (
         b"List of devices attached \n\r014E05DE0F02000E\tdevice\n\r489328DKFL7DF\tdevice",
         b"")
     self.assertEqual(adb.devices(), {
         "014E05DE0F02000E": "device",
         "489328DKFL7DF": "device"
     })
     adb.raw_cmd.return_value.communicate.return_value = (
         b"List of devices attached \r014E05DE0F02000E\tdevice\r489328DKFL7DF\tdevice",
         b"")
     self.assertEqual(adb.devices(), {
         "014E05DE0F02000E": "device",
         "489328DKFL7DF": "device"
     })
     adb.raw_cmd.return_value.communicate.return_value = (
         b"List of devices attached \n014E05DE0F02000E\tdevice\n489328DKFL7DF\tdevice",
         b"")
     self.assertEqual(adb.devices(), {
         "014E05DE0F02000E": "device",
         "489328DKFL7DF": "device"
     })
     adb.raw_cmd.return_value.communicate.return_value = (b"not match", "")
     with self.assertRaises(EnvironmentError):
         adb.devices()
Exemplo n.º 8
0
    def test_adb_cmd(self):
        adb = Adb()
        adb.device_serial = MagicMock()
        adb.device_serial.return_value = "ANDROID_SERIAL"
        adb.raw_cmd = MagicMock()
        args = ["a", "b", "c"]
        adb.cmd(*args)
        adb.raw_cmd.assert_called_once_with("-s", "%s" % adb.device_serial(), *args)

        adb.device_serial.return_value = "ANDROID SERIAL"
        adb.raw_cmd = MagicMock()
        args = ["a", "b", "c"]
        adb.cmd(*args)
        adb.raw_cmd.assert_called_once_with("-s", "'%s'" % adb.device_serial(), *args)
Exemplo n.º 9
0
    def __init__(self,config=None):
        """

        :return:
        """

        self.config = config




        # dict of devices connected to the hub, key is the device_id
        self.connected_devices = {}

        # dict of active devices , key is alias
        self._devices = {}




        # device_ids available ( eg not actice)
        self.available_devices = []



        self.adb = Adb()
Exemplo n.º 10
0
 def test_adb_from_find(self):
     with patch.dict('os.environ', {}, clear=True):
         with patch("distutils.spawn.find_executable") as find_executable:
             find_executable.return_value = "/usr/bin/adb"
             with patch("os.path.realpath") as realpath:
                 realpath.return_value = "/home/user/android/platform-tools/adb"
                 self.assertEqual(realpath.return_value, Adb().adb())
                 find_executable.assert_called_once_with("adb")  # find_exectable should be called once
                 realpath.assert_called_once_with(find_executable.return_value)
                 realpath.return_value = find_executable.return_value
                 self.assertEqual(find_executable.return_value, Adb().adb())
             find_executable.return_value = None
             call_count = find_executable.call_count
             with self.assertRaises(EnvironmentError):
                 Adb().adb()
             self.assertEqual(call_count + 1, find_executable.call_count)
Exemplo n.º 11
0
    def initWifiADB(self):

        '''
            通过wifi方式建立adb连接,避免了通过usb连接adb繁琐的设置以及无法使用user版本
             环境:PC与车机同一个局域网
        adb.exe需要同一个进程调用,不然会被打断,所以统一用uiautomator方法初始化
        '''

        adb = Adb()
        try:
            line = adb.raw_cmd("connect", self.get_conf_value("deviceIPaddress").strip()+":5578").communicate()[0].decode("utf-8")
            if "connected to" in line:
                return True
            else:
                raise Exception('Connect to adb fail via wifi ')
        except IOError as e:
            return False
Exemplo n.º 12
0
 def __init__(self, serial=None, local_port=None):
     self.uiautomator_process = None
     self.adb = Adb(serial=serial)
     self.device_port = 9008
     if local_port:
         self.local_port = local_port
     else:
         try:  # first we will try to use the local port already adb forwarded
             for s, lp, rp in self.adb.forward_list():
                 if s == self.adb.device_serial(
                 ) and rp == 'tcp:%d' % self.device_port:
                     self.local_port = int(lp[4:])
                     break
             else:
                 self.local_port = next_local_port()
         except:
             self.local_port = next_local_port()
Exemplo n.º 13
0
 def test_adb_raw_cmd(self):
     import subprocess
     adb = Adb()
     adb.adb = MagicMock()
     adb.adb.return_value = "adb"
     args = ["a", "b", "c"]
     with patch("subprocess.Popen") as Popen:
         os.name = "posix"
         adb.raw_cmd(*args)
         Popen.assert_called_once_with(["%s %s" % (adb.adb(), " ".join(args))], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
     with patch("subprocess.Popen") as Popen:
         os.name = "nt"
         adb.raw_cmd(*args)
         Popen.assert_called_once_with([adb.adb()] + list(args), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 def check_current_activity(self, activity_name):
     ret = Adb().shell('dumpsys activity |grep mFocusedActivity')
     ret = str(ret).strip().replace("\n", "").replace("\r", "")
     self.logger.info("get current activity name: %s" % str(ret))
     if activity_name in str(ret):
         result = True
     else:
         result = False
     return result
Exemplo n.º 15
0
 def __init__(self):
     '''
     Constructor
     '''
     self.instAdb=Adb()
     
     self.devSerialNoms= self.instAdb.devices().keys()
     self.devcount = len(self.devSerialNoms)
     self.devSerial = self.instAdb.device_serial()
Exemplo n.º 16
0
 def test_adb_cmd(self):
     adb = Adb()
     adb.device_serial = MagicMock()
     adb.device_serial.return_value = "ANDROID_SERIAL"
     adb.raw_cmd = MagicMock()
     args = ["a", "b", "c"]
     adb.cmd(*args)
     adb.raw_cmd.assert_called_once_with("-s", "'%s'" % adb.device_serial(), *args)
Exemplo n.º 17
0
 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"
Exemplo n.º 18
0
    def dismiss_soft_keyboard(self):
        """
        Used to dismiss the soft keyboard on the screen

        """
        time.sleep(1)
        if "mInputShown=true" in \
                Adb(self._device.retrieve_serial_number()).cmd("shell dumpsys input_method").communicate()[
                    0].decode("utf-8"):
            self.d.press.back()
            time.sleep(1)
Exemplo n.º 19
0
 def test_adb_raw_cmd(self):
     import subprocess
     adb = Adb()
     adb.adb = MagicMock()
     adb.adb.return_value = "adb"
     args = ["a", "b", "c"]
     with patch("subprocess.Popen") as Popen:
         os.name = "posix"
         adb.raw_cmd(*args)
         Popen.assert_called_once_with(["%s %s" % (adb.adb(), " ".join(args))], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
     with patch("subprocess.Popen") as Popen:
         os.name = "nt"
         adb.raw_cmd(*args)
         Popen.assert_called_once_with([adb.adb()] + list(args), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Exemplo n.º 20
0
    def test_adb_from_env(self):
        home_dir = '/android/home'
        with patch.dict('os.environ', {'ANDROID_HOME': home_dir}):
            with patch('os.path.exists') as exists:
                exists.return_value = True

                os.name = "posix"  # linux
                adb_obj = Adb()
                adb_path = os.path.join(home_dir, "platform-tools", "adb")
                self.assertEqual(adb_obj.adb(), adb_path)
                exists.assert_called_once_with(adb_path)
                self.assertEqual(adb_obj.adb(), adb_path)
                exists.assert_called_once_with(adb_path) # the second call will return the __adb_cmd directly

                os.name = "nt"  # linux
                adb_obj = Adb()
                adb_path = os.path.join(home_dir, "platform-tools", "adb.exe")
                self.assertEqual(adb_obj.adb(), adb_path)

                exists.return_value = False
                with self.assertRaises(EnvironmentError):
                    Adb().adb()
Exemplo n.º 21
0
    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)
Exemplo n.º 22
0
    def test_forward_list(self):
        adb = Adb()
        adb.version = MagicMock()
        adb.version.return_value = ['1.0.31', '1', '0', '31']
        adb.raw_cmd = MagicMock()
        adb.raw_cmd.return_value.communicate.return_value = (b"014E05DE0F02000E    tcp:9008    tcp:9008\r\n489328DKFL7DF    tcp:9008    tcp:9008", b"")
        self.assertEqual(adb.forward_list(), [['014E05DE0F02000E', 'tcp:9008', 'tcp:9008'], ['489328DKFL7DF', 'tcp:9008', 'tcp:9008']])

        adb.version.return_value = ['1.0.29', '1', '0', '29']
        with self.assertRaises(EnvironmentError):
            adb.forward_list()
Exemplo n.º 23
0
 def test_devices(self):
     adb = Adb()
     adb.raw_cmd = MagicMock()
     adb.raw_cmd.return_value.communicate.return_value = (b"List of devices attached \r\n014E05DE0F02000E    device\r\n489328DKFL7DF    device", b"")
     self.assertEqual(adb.devices(), {"014E05DE0F02000E": "device", "489328DKFL7DF": "device"})
     adb.raw_cmd.assert_called_once_with("devices")
     adb.raw_cmd.return_value.communicate.return_value = (b"List of devices attached \n\r014E05DE0F02000E    device\n\r489328DKFL7DF    device", b"")
     self.assertEqual(adb.devices(), {"014E05DE0F02000E": "device", "489328DKFL7DF": "device"})
     adb.raw_cmd.return_value.communicate.return_value = (b"List of devices attached \r014E05DE0F02000E    device\r489328DKFL7DF    device", b"")
     self.assertEqual(adb.devices(), {"014E05DE0F02000E": "device", "489328DKFL7DF": "device"})
     adb.raw_cmd.return_value.communicate.return_value = (b"List of devices attached \n014E05DE0F02000E    device\n489328DKFL7DF    device", b"")
     self.assertEqual(adb.devices(), {"014E05DE0F02000E": "device", "489328DKFL7DF": "device"})
     adb.raw_cmd.return_value.communicate.return_value = (b"not match", "")
     with self.assertRaises(EnvironmentError):
         adb.devices()
Exemplo n.º 24
0
class adb(object):
    '''
    classdocs
    '''
    def __init__(self):
        '''
        Constructor
        '''
        self.instAdb = Adb()

        self.devSerialNoms = self.instAdb.devices().keys()
        self.devcount = len(self.devSerialNoms)
        self.devSerial = self.instAdb.device_serial()

    def getSerials(self):
        return self.devSerialNoms
        #return self.devSerialNoms

    def getDeviceCount(self):
        return self.devcount

    def getSerial(self):
        return self.devSerial
Exemplo n.º 25
0
    def __init__(self, **kwargs):

        adb_step.__init__(self, **kwargs)

        #  parse kwargs
        if "timeout" in kwargs:
            self.timeout = kwargs["timeout"]
        else:
            self.timeout = 10000
        if "serial" in kwargs:
            self.serial = kwargs["serial"]
        else:
            self.serial = None
        if "no_log" in kwargs:
            self.no_log = kwargs["no_log"]
        else:
            self.no_log = False

        #  constants for pass and error messages
        if self.serial:
            self._PASSM = "[ {} ] ".format(
                self.serial) + self.__class__.__name__ + " - [PASSED]"
            self._ERRORM = "[ {} ] ".format(
                self.serial) + self.__class__.__name__ + " - [FAILED]"
        else:
            self._PASSM = self.__class__.__name__ + " - [PASSED]"
            self._ERRORM = self.__class__.__name__ + " - [FAILED]"

        #  defaults pass and error messages
        self.passm = self._PASSM
        self.errorm = self._ERRORM

        #  replacing old uidevice available in testlib/external with standard
        #   uiautomator device class
        self.uidevice = Device(serial=self.serial)

        #  initialize adb connection with below to have backward compatibility
        self.adb_connection = Adb(serial=self.serial)

        #  Add Common ADB API to use instead of above hereafter
        self.adb_connection_common = connection_adb(**kwargs)

        if "version" in kwargs:
            self.version = kwargs["version"]
        else:
            self.version = self.adb_connection_common.get_prop(
                'ro.build.version.release')
Exemplo n.º 26
0
    def test_forward_list(self):
        adb = Adb()
        adb.version = MagicMock()
        adb.version.return_value = ['1.0.31', '1', '0', '31']
        adb.raw_cmd = MagicMock()
        adb.raw_cmd.return_value.communicate.return_value = (b"014E05DE0F02000E    tcp:9008    tcp:9008\r\n489328DKFL7DF    tcp:9008    tcp:9008", b"")
        self.assertEqual(adb.forward_list(), [['014E05DE0F02000E', 'tcp:9008', 'tcp:9008'], ['489328DKFL7DF', 'tcp:9008', 'tcp:9008']])

        adb.version.return_value = ['1.0.29', '1', '0', '29']
        with self.assertRaises(EnvironmentError):
            adb.forward_list()
Exemplo n.º 27
0
    def test_adb_from_env(self):
        home_dir = '/android/home'
        with patch.dict('os.environ', {'ANDROID_HOME': home_dir}):
            with patch('os.path.exists') as exists:
                exists.return_value = True

                os.name = "posix"  # linux
                adb_obj = Adb()
                adb_path = os.path.join(home_dir, "platform-tools", "adb")
                self.assertEqual(adb_obj.adb(), adb_path)
                exists.assert_called_once_with(adb_path)
                self.assertEqual(adb_obj.adb(), adb_path)
                exists.assert_called_once_with(adb_path) # the second call will return the __adb_cmd directly

                os.name = "nt"  # linux
                adb_obj = Adb()
                adb_path = os.path.join(home_dir, "platform-tools", "adb.exe")
                self.assertEqual(adb_obj.adb(), adb_path)

                exists.return_value = False
                with self.assertRaises(EnvironmentError):
                    Adb().adb()
Exemplo n.º 28
0
    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)
Exemplo n.º 29
0
class BaseClient(object):

    def __init__(self, device_id):
        self._device_id = device_id
        self._adb_commander = Adb(self._device_id)
        self._logcat_thread = threading.Thread(target=self._start_logcat)
        self._logcat_thread.start()
        self._device = Device(self._device_id)

    def open_app(self):
        self._device.screen.on()
        _package_name, _main_activity_name = utils.get_package_and_main_activity_name()
        os.system('adb -s %s shell am force-stop %s' % (self._device_id, _package_name))
        self._adb_commander.cmd('shell am start -W %s/%s' % (_package_name, _main_activity_name))

    def _start_logcat(self):
        log_file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'log'))
        self._adb_commander.cmd('logcat -c' % self._device_id)
        self._adb_commander.cmd('logcat> %s/%s.log' % (log_file_path, self._device_id))

    def stop_logcat(self):
        os.system('ps -e | grep "adb -s %s logcat" | xargs kill' % self._device_id)
Exemplo n.º 30
0
    def test_adb_cmd_server_host(self):
        adb = Adb(adb_server_host="localhost", adb_server_port=5037)
        adb.device_serial = MagicMock()
        adb.device_serial.return_value = "ANDROID_SERIAL"
        adb.raw_cmd = MagicMock()
        args = ["a", "b", "c"]
        adb.cmd(*args)
        adb.raw_cmd.assert_called_once_with("-H", "localhost", "-P", "5037", "-s", "%s" % adb.device_serial(), *args)

        adb = Adb(adb_server_host="localhost")
        adb.device_serial = MagicMock()
        adb.device_serial.return_value = "ANDROID_SERIAL"
        adb.raw_cmd = MagicMock()
        args = ["a", "b", "c"]
        adb.cmd(*args)
        adb.raw_cmd.assert_called_once_with("-H", "localhost", "-s", "%s" % adb.device_serial(), *args)
Exemplo n.º 31
0
def allDevices():
    devices = Adb().devices().keys()
    return devices
Exemplo n.º 32
0
 def __init__(self, device_id):
     self._device_id = device_id
     self._adb_commander = Adb(self._device_id)
     self._logcat_thread = threading.Thread(target=self._start_logcat)
     self._logcat_thread.start()
     self._device = Device(self._device_id)
Exemplo n.º 33
0
    def test_device_serial(self):
        with patch.dict('os.environ', {'ANDROID_SERIAL': "ABCDEF123456"}):
            adb = Adb()
            adb.devices = MagicMock()
            adb.devices.return_value = {"ABCDEF123456": "device"}
            self.assertEqual(adb.device_serial(), "ABCDEF123456")
        with patch.dict('os.environ', {'ANDROID_SERIAL': "ABCDEF123456"}):
            adb = Adb()
            adb.devices = MagicMock()
            adb.devices.return_value = {"ABCDEF123456": "device", "123456ABCDEF": "device"}
            self.assertEqual(adb.device_serial(), "ABCDEF123456")
        with patch.dict('os.environ', {'ANDROID_SERIAL': "HIJKLMN098765"}):
            adb = Adb()
            adb.devices = MagicMock()
            adb.devices.return_value = {"ABCDEF123456": "device", "123456ABCDEF": "device"}
            with self.assertRaises(EnvironmentError):
                adb.device_serial()
        with patch.dict('os.environ', {}, clear=True):
            adb = Adb()
            adb.devices = MagicMock()
            adb.devices.return_value = {"ABCDEF123456": "device", "123456ABCDEF": "device"}
            with self.assertRaises(EnvironmentError):
                adb.device_serial()
        with patch.dict('os.environ', {}, clear=True):
            adb = Adb()
            adb.devices = MagicMock()
            adb.devices.return_value = {"ABCDEF123456": "device"}
            print(adb.devices())
            self.assertEqual(adb.device_serial(), "ABCDEF123456")

        with self.assertRaises(EnvironmentError):
            adb = Adb()
            adb.devices = MagicMock()
            adb.devices.return_value = {}
            adb.device_serial()
Exemplo n.º 34
0
'''
Created on 2015. 10. 22.

@author: User
'''

import os, sys
from Libs import ClsActivity as CLS

from uiautomator import Device, Adb, AutomatorDevice
from Libs import SaveToLog as saveLog
from Libs import ModelInfo
import Libs.ClsKeyCode


instAdb=Adb()
devSerials= instAdb.devices().keys()
print(type(devSerials))
osType = sys.platform
sndLog = saveLog()

#sndLog = CLS("test", "test")

if len(devSerials) == 1:
    devSerials = instAdb.device_serial()
    mstrDevice = Device(devSerials)
    mstrInfo = mstrDevice.info
else:
    mstrDevSerial, slavDevSerial = devSerials
    mstrDevice = Device(mstrDevSerial)
    slvDevice = Device(slavDevSerial)
Exemplo n.º 35
0
    def test_adb_cmd_server_host(self):
        adb = Adb(adb_server_host="localhost", adb_server_port=5037)
        adb.device_serial = MagicMock()
        adb.device_serial.return_value = "ANDROID_SERIAL"
        adb.raw_cmd = MagicMock()
        args = ["a", "b", "c"]
        adb.cmd(*args)
        adb.raw_cmd.assert_called_once_with("-H", "localhost", "-P", "5037",
                                            "-s", "%s" % adb.device_serial(),
                                            *args)

        adb = Adb(adb_server_host="localhost")
        adb.device_serial = MagicMock()
        adb.device_serial.return_value = "ANDROID_SERIAL"
        adb.raw_cmd = MagicMock()
        args = ["a", "b", "c"]
        adb.cmd(*args)
        adb.raw_cmd.assert_called_once_with("-H", "localhost", "-s",
                                            "%s" % adb.device_serial(), *args)
Exemplo n.º 36
0
class UiHub(object):
    """
        represents a set of Device

    """

    def __init__(self,config=None):
        """

        :return:
        """

        self.config = config




        # dict of devices connected to the hub, key is the device_id
        self.connected_devices = {}

        # dict of active devices , key is alias
        self._devices = {}




        # device_ids available ( eg not actice)
        self.available_devices = []



        self.adb = Adb()




    def device_list(self):
        """

        :return: list : list of android connected device
        """
        self.connected_devices = self.adb.devices()
        return self.connected_devices



    def device(self,alias):
        """
            return the given connected device info
        :param alias:
        :return:
        """
        try:
            c = self.connected_devices
            assert c != {}
        except:
            self.device_list()
        return self.connected_devices[alias]



    def add_device(self,alias,serial=None,applications=None):
        """
            add a device , make it active

            if no serial is specified take a random device_it (not used ) amoung the connected devices


        :param allias:
        :param serial:
        :param applications:
        :return:
        """
        if not serial:
            # no serial specified: take a random one
            raise NotImplementedError


        self._devices[alias]= UiDevice(alias,serial=serial,applications=applications,config=self.config)
        return self._devices[alias]



    def iter_device(self):
        """
            iteration over active devices
        :return:
        """


    def find_device(self,**kwargs):
        """
Exemplo n.º 37
0
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()

    def long_click_text(self, text, instance=0):
        """
        Long Click text label on screen, *text* and *instance=0*

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

        return self.d(text=text, instance=instance).long_click()

    def long_click_ui(self, **selectors):
        """
        Long Click on **selectors**
        Selector supports below parameters. Refer to UiSelector java doc for detailed information.

            text, textContains, textMatches, textStartsWith
            className, classNameMatches
            description, descriptionContains, descriptionMatches, descriptionStartsWith
            checkable, checked, clickable, longClickable
            scrollable, enabled,focusable, focused, selected
            packageName, packageNameMatches
            resourceId, resourceIdMatches
            index, instance
        Example:
        | Action     | Argument   |  Argument  |  Argument  |
        | Long Click UI | text=XXXX | className=XXX.xxxx | resourceId=xxxxxx |
        """

        return self.d(**selectors).long_click()

    def text_display_on_screen_contains(self, text):
        """Verify text display on screen

        Example:
        | Action     | Argument   |
        |Text display on screen is| text |
        """

        if self.d(text=text).exists:
            self._result = True
            return True
        else:
            self._result = False
            return False

    def object_display_on_screen(self, obj, timeout=5000):
        """ Verify *obj* UiObject display on screen
        return to self._result

        Example:
        | Action     | Argument   |
        |Object display on screen | obj |
        """
        if obj.wait.exists(timeout):
            self._result = True
            return True
        else:
            self._result = False
            return False

    def assert_expectation(self, expect, actual):
        """
        Assert Expectation and actual value
        Example:
        | Action             |   args   |   args      |
        | Assert Expectation |   324324 |  ${actual}  |
        """
        if str(expect) != str(actual):
            raise AssertionError("Actual result is = %s, but expectation is: %s" % (str(actual), str(expect)))

    def assert_true(self, condition):
        """
        Assert True of *condition

        Example:
        |Assert True | condition |
        """
        if str(condition) != "True":  # because only string from robotframework
            raise AssertionError("Result is = %s" % str(condition))

    def assert_result_true(self):
        """
        Assert True of *self._result

        Example:
        |Assert True |
        """
        if self._result != True:
            raise AssertionError("Result is = %s" % str(self._result))

    def wait_for_ui_exists(self, timeout, **selectors):
        """
        Return True if
          Selector is to identify specific ui object in current window.

        # To seleted the object ,text is 'Clock' and its className is 'android.widget.TextView'
        wait_for_ui_exists(text='Clock', className='android.widget.TextView')

        Selector supports below parameters. Refer to UiSelector java doc for detailed information.

            text, textContains, textMatches, textStartsWith
            className, classNameMatches
            description, descriptionContains, descriptionMatches, descriptionStartsWith
            checkable, checked, clickable, longClickable
            scrollable, enabled,focusable, focused, selected
            packageName, packageNameMatches
            resourceId, resourceIdMatches
            index, instance

        Examples:
        | Action     | Argument   |  Argument  |  Argument  |  Argument  |
        |Wait For UI Exists | timeout | text=XXXX | className=XXX.xxxx | resourceId=xxxxxx |
        """
        self._result = self.d(**selectors).wait.exists(timeout=int(timeout))
        return self._result

    def wait_and_click(self, timeout, **selectors):
        """Wait for uiselector and click"""
        if self.d(**selectors).wait.exists(timeout=int(timeout)):
            self.d(**selectors).click()

    def assert_ui_exists(self, **selectors):
        """
        Assert UiObject appear on the screen

        Examples:
        | 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
        if rotation == "nature":
            self.d.orientation = "n"  # or "natural"
        elif rotation == "left":
            self.d.orientation = "l"  # or "left"
        elif rotation == "right":
            self.d.orientation = "r"  # or "right"
        elif rotation == "upsidedown":
            self.d.orientation = "upsidedown"  # or "upsidedown"
        else:
            self.d.rotation = "n"

    def take_screenshot(self, scale=None, quality=None):
        """
        Take a screenshot of device and log in the report with timestamp, scale for screenshot size and quality for screenshot quality
        default scale=1.0 quality=100

        Example:
        | Action     | Argument   |  Argument  |
        | Take Screenshot | 0.5 | 80 |
        """
        output_dir = BuiltIn().get_variable_value("${OUTPUTDIR}")
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime("%Y%m%d%H%M%S")
        screenshot_path = "%s%s%s.png" % (output_dir, os.sep, st)
        screenshot_name = "%s%s.png" % (os.sep, st)
        self.d.screenshot(screenshot_path, scale, quality)
        logger.info('\n<a href="%s">%s</a><br><img src="%s">' % (screenshot_path, st, screenshot_name), html=True)

    def open_notification(self):
        """
        Open notification of the phone
        """
        self.d.open.notification()

    def wait_window_update(self):
        """
        wait for window update
        """
        return self.d.wait.update()

    def wait_window_idle(self):
        """
        wait for window idle
        """
        return self.d.wait.idle()

    def remove_watchers(self):
        """
        Remove UI watchers
        """
        self.d.watchers.remove()

    def get_device(self):
        """
        Get device object, you can do any command using this
        """
        return self.d

    def click_id(self, id, instance=0):
        """
        Click *id* with *instance*=0
        """
        return self.d(resourceId=id, instance=instance).click.wait()

    def long_click_id(self, id, instance=0):
        """
        Long click *id* with *instance*=0
        """
        return self.d(resourceId=id, instance=0).long_click()

    def click_description(self, description, instance=0):
        """
        Click *description* with *instance*=0
        """
        return self.d(description=description, instance=instance).long_click()

    def click_class(self, className, instance=0):
        """
        Click *className* with *instance*=0
        """
        return self.d(className=className, instance=instance).long_click()

    def type_text(self, textStr, **selectors):
        """
        type text on selectors
        like text=EditName
        """
        self.d(**selectors).set_text(textStr)

    def press_key(self, key):
        """ Press Key of following value
            home
            back
            left
            right
            up
            down
            center
            menu
            search
            enter
            delete(or del)
            recent(recent apps)
            volume_up
            volume_down
            volume_mute
            camera
            power

            Examples:
            | Action     | Argument   |
            | Press Key | home |
            | Press Key | back |
            | Press Key | left |
            | Press Key | right |
            | Press Key | recent |
            | Press Key | volume_up |
            | Press Key | camera |
        """
        if key.isdigit():
            return self.d.press(int(key))
        return self.d.press(key)

    def phone_sleep(self, timeout):
        """
        android device sleep with timeout in ms, don't use for executor sleep,
        """
        return self.d.wait(int(timeout))

    def execute_command(self, cmd, block_parent_process=True):
        """
        Execute shell *cmd* command, with block_parent_process = True

        If block_parent_process = False, kill_command is needed to terminal the child process

        Example:
        | Execute Command | ping -c 5 127.0.0.1 |
        """
        if str(block_parent_process) == str(True):
            return subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
        else:
            return subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    def kill_command(self, process, timeout=0):
        """ Kill child *process* in timeout seconds
        Some bugs after process teminated
        """
        time.sleep(float(timeout))
        process.terminate()

    def wait_for_logcat(self, log, timeout=30):
        """ Wait log exists in given timeout, return True if have, otherwise will return False
        log is your want to search, log can be a regular expression
        time in seconds, default value is 30 seconds

        Example:
        | Wait For Logcat | .*ActivityManager.*cmp=com.sonyericsson.album/com.sonyericsson.album.Main.* |
        """
        start = time.time()
        while (time.time() - start) < int(timeout):
            log_proc = self.adb.cmd("logcat -d -v time")
            returncode = log_proc.poll()
            lines = log_proc.stdout.readlines()
            for line in lines:
                rlt = re.search(log, line.rstrip())
                if rlt is not None:
                    print rlt.group(0)
                    self._result = True
                    return True
            time.sleep(2)  # sleep 2s to wait
        self._result = False
        return False

    def clear_logcat(self):
        """
        Clear logcat, it's often used before you want to use *wait_for_logcat()*
        """
        print "Clear logcat before test"
        return self.exe_adb_command("logcat -c")

    def click_object(self, obj):
        """ Click UiObject *obj*

        Exmaple:
        | ${result}    | Get UI Object | text=XXX | className=xxxx |
        | Click Object |   ${result}   |
        """
        obj.click()

    def click_ui(self, **selectors):
        """
        Click selector

        click_selector(text="Home", resourceId = "android:id/title")
        for **selector, please refer *get_ui_object()*
        Selector supports below parameters. Refer to UiSelector java doc for detailed information.

            text, textContains, textMatches, textStartsWith
            className, classNameMatches
            description, descriptionContains, descriptionMatches, descriptionStartsWith
            checkable, checked, clickable, longClickable
            scrollable, enabled,focusable, focused, selected
            packageName, packageNameMatches
            resourceId, resourceIdMatches
            index, instance
        Operation for a UiObjects:
        click, clear_text, drag(obj).to(**selector), gesture, exists, set_text, long_click
        pinch.In(percent=100, steps=10), pinch.Out(percent=100, steps=100),.swipe.right(),
        .swipe.left(steps=10),.swipe("right", steps=20),.wait.gone(),.wait.exists()
        """
        print "selectors:", selectors
        return self.d(**selectors).click()

    def get_ui_object(self, **selectors):
        """
        Get UI object with *selectors*
        you can do anything on UiObject, like click(), long_click(),wait.exists(timeout)
        examples: get_ui_object(text="Home", resourceId = "android:id/title")

        Selector supports below parameters. Refer to UiSelector java doc for detailed information.

            text, textContains, textMatches, textStartsWith
            className, classNameMatches
            description, descriptionContains, descriptionMatches, descriptionStartsWith
            checkable, checked, clickable, longClickable
            scrollable, enabled,focusable, focused, selected
            packageName, packageNameMatches
            resourceId, resourceIdMatches
            index, instance
        Operation for a UiObjects:
        click, clear_text, drag(obj).to(**selector), gesture, exists, set_text, long_click
        pinch.In(percent=100, steps=10), pinch.Out(percent=100, steps=100),.swipe.right(),
        .swipe.left(steps=10),.swipe("right", steps=20),.wait.gone(),.wait.exists()

        Exmaple:
        | ${result}    | Get UI Object | text=XXX | className=xxxx |

        """
        self._result = self.d(**selectors)
        return self._result

    def wait_for_object_exists(self, obj, timeout=0):
        """
        Wait for UiObject *obj* exists in *timeout*= 0

        Example:
        | ${result}    | Get UI Object | text=XXX | className=xxxx |
        | Wait For Object Exists | ${result} | timeout |
        """
        self._result = obj.wait.exists(timeout=int(timeout))
        return self._result

    def wait_for_ui_gone(self, timeout=0, **selectors):
        """
        Wait for UiObject *obj* gone in *timeout*= 0

        Example:
        | ${result}    | Get UI Object | text=XXX | className=xxxx |
        | Wait For Object Gone | ${result} | timeout |

        """
        self._result = self.d(**selectors).wait.gone(timeout=int(timeout))
        return self._result

    def get_key_value(self, key, dictionary):
        """
        Get key value of dictionary
        """
        return dictionary(key)

    def get_tts(self, input_text, delete_file=False, **args):
        """
        Get TTS voice mp3 from Google
        get_tts(input_text='tunnel snakes rule apparently', args = {'language':'en','output':'outputto.mp3'})

        Robot Framework:
        Examples:
        | Action     | Argument   |  Argument  |  Argument  |  Argument  |
        | UiTestLib.Get TTS    |   Hello world    |   False   |    output=ooo.mp3   |   language=en |
        """
        print "Get text to speech: ", input_text
        downloaded = False
        if str(delete_file) == "True":
            if os.path.exists(args["output"]):
                os.remove(args["output"])
        if os.path.exists(args["output"]):
            if os.path.getsize(args["output"]) <= 0:
                os.remove(args["output"])
        if args["output"] is not None:
            if not os.path.exists(args["output"]):
                print "Generating mp3 file......", args["output"]
                downloaded = GoogleTTS.audio_extract(input_text, args)
            else:
                print "Have same local file"
                downloaded = True
        if not downloaded:
            print "Downloaded TTS from Google failed, trying to download from local FTP..."
            mp3file = open(args["output"], "w")
            mp3url = "ftp://cnbjlx9548/atautomation/Test-Content/Croft/" + args["output"]
            try:
                resp = urllib2.urlopen(mp3url, timeout=40)
                mp3file.write(resp.read())
                time.sleep(0.05)
            except Exception, e:
                print e
                return False
            mp3file.close()
        return True
Exemplo n.º 38
0
 def test_forward(self):
     adb = Adb()
     adb.cmd = MagicMock()
     adb.forward(90, 91)
     adb.cmd.assert_called_once_with("forward", "tcp:90", "tcp:91")
     adb.cmd.return_value.wait.assert_called_once_with()
Exemplo n.º 39
0
    def test_adb_cmd_server_host(self):
        adb = Adb(adb_server_host="localhost", adb_server_port=5037)
        adb.adb = MagicMock()
        adb.adb.return_value = "adb"
        adb.device_serial = MagicMock()
        adb.device_serial.return_value = "ANDROID_SERIAL"
        args = ["a", "b", "c"]
        with patch("subprocess.Popen") as Popen:
            os.name = "nt"
            adb.raw_cmd(*args)
            Popen.assert_called_once_with([adb.adb()] + args,
                                          shell=True,
                                          stdout=subprocess.PIPE,
                                          stderr=subprocess.PIPE)

        adb = Adb(adb_server_host="test.com", adb_server_port=1000)
        adb.adb = MagicMock()
        adb.adb.return_value = "adb"
        adb.device_serial = MagicMock()
        adb.device_serial.return_value = "ANDROID_SERIAL"
        args = ["a", "b", "c"]
        with patch("subprocess.Popen") as Popen:
            os.name = "posix"
            adb.raw_cmd(*args)
            Popen.assert_called_once_with([
                " ".join([adb.adb()] + ["-H", "test.com", "-P", "1000"] + args)
            ],
                                          shell=True,
                                          stdout=subprocess.PIPE,
                                          stderr=subprocess.PIPE)
Exemplo n.º 40
0
class AutomatorServer(uiautomator.AutomatorServer, object):
    """start and quit rpc server on device.
    """
    __jar_files = {
        "bundle.jar": "libs/bundle.jar",
        "uiautomator-stub.jar": "libs/uiautomator-stub.jar"
    }
    handlers = NotFoundHandler()  # handler UI Not Found exception

    def __init__(self, serial=None, local_port=None):
        self.uiautomator_process = None
        self.adb = Adb(serial=serial)
        self.device_port = 9008
        if local_port:
            self.local_port = local_port
        else:
            try:  # first we will try to use the local port already adb forwarded
                for s, lp, rp in self.adb.forward_list():
                    if s == self.adb.device_serial(
                    ) and rp == 'tcp:%d' % self.device_port:
                        self.local_port = int(lp[4:])
                        break
                else:
                    self.local_port = next_local_port()
            except:
                self.local_port = next_local_port()

    @property
    def jsonrpc(self):
        server = self
        ERROR_CODE_BASE = -32000

        def _JsonRPCMethod(url, method, timeout, restart=True):
            _method_obj = JsonRPCMethod(url, method, timeout)

            def wrapper(*args, **kwargs):
                URLError = urllib3.exceptions.HTTPError if os.name == "nt" else urllib2.URLError
                try:
                    return _method_obj(*args, **kwargs)
                except (URLError, socket.error, HTTPException) as e:
                    if restart:
                        server.stop()
                        server.start()
                        return _JsonRPCMethod(url, method, timeout,
                                              False)(*args, **kwargs)
                    else:
                        raise
                except JsonRPCError as e:
                    if e.code >= ERROR_CODE_BASE - 2:
                        server.stop()
                        server.start()
                        print "i am here & do something in this place will work!"
                        Exception_analyze.analysis_crash()
                        return _method_obj(*args, **kwargs)
                    raise

            return wrapper

        return JsonRPCClient(self.rpc_uri,
                             timeout=int(os.environ.get("JSONRPC_TIMEOUT",
                                                        90)),
                             method_class=_JsonRPCMethod)
Exemplo n.º 41
0
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()

    def long_click_text(self, text, instance=0):
        """
        Long Click text label on screen, *text* and *instance=0*

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

        return self.d(text=text, instance=instance).long_click()

    def long_click_ui(self, **selectors):
        """
        Long Click on **selectors**
        Selector supports below parameters. Refer to UiSelector java doc for detailed information.

            text, textContains, textMatches, textStartsWith
            className, classNameMatches
            description, descriptionContains, descriptionMatches, descriptionStartsWith
            checkable, checked, clickable, longClickable
            scrollable, enabled,focusable, focused, selected
            packageName, packageNameMatches
            resourceId, resourceIdMatches
            index, instance
        Example:
        | Action     | Argument   |  Argument  |  Argument  |
        | Long Click UI | text=XXXX | className=XXX.xxxx | resourceId=xxxxxx |
        """

        return self.d(**selectors).long_click()

    def text_display_on_screen_contains(self, text):
        """Verify text display on screen

        Example:
        | Action     | Argument   |
        |Text display on screen is| text |
        """

        if self.d(text=text).exists:
            self._result = True
            return True
        else:
            self._result = False
            return False

    def object_display_on_screen(self, obj, timeout=5000):
        """ Verify *obj* UiObject display on screen
        return to self._result

        Example:
        | Action     | Argument   |
        |Object display on screen | obj |
        """
        if obj.wait.exists(timeout):
            self._result = True
            return True
        else:
            self._result = False
            return False

    def assert_expectation(self, expect, actual):
        """
        Assert Expectation and actual value
        Example:
        | Action             |   args   |   args      |
        | Assert Expectation |   324324 |  ${actual}  |
        """
        if str(expect) != str(actual):
            raise AssertionError(
                'Actual result is = %s, but expectation is: %s' %
                (str(actual), str(expect)))

    def assert_true(self, condition):
        """
        Assert True of *condition

        Example:
        |Assert True | condition |
        """
        if str(condition) != 'True':  #because only string from robotframework
            raise AssertionError('Result is = %s' % str(condition))

    def assert_result_true(self):
        """
        Assert True of *self._result

        Example:
        |Assert True |
        """
        if self._result != True:
            raise AssertionError('Result is = %s' % str(self._result))

    def wait_for_ui_exists(self, timeout, **selectors):
        """
        Return True if
          Selector is to identify specific ui object in current window.

        # To seleted the object ,text is 'Clock' and its className is 'android.widget.TextView'
        wait_for_ui_exists(text='Clock', className='android.widget.TextView')

        Selector supports below parameters. Refer to UiSelector java doc for detailed information.

            text, textContains, textMatches, textStartsWith
            className, classNameMatches
            description, descriptionContains, descriptionMatches, descriptionStartsWith
            checkable, checked, clickable, longClickable
            scrollable, enabled,focusable, focused, selected
            packageName, packageNameMatches
            resourceId, resourceIdMatches
            index, instance

        Examples:
        | Action     | Argument   |  Argument  |  Argument  |  Argument  |
        |Wait For UI Exists | timeout | text=XXXX | className=XXX.xxxx | resourceId=xxxxxx |
        """
        self._result = self.d(**selectors).wait.exists(timeout=int(timeout))
        return self._result

    def wait_and_click(self, timeout, **selectors):
        """Wait for uiselector and click"""
        if self.d(**selectors).wait.exists(timeout=int(timeout)):
            self.d(**selectors).click()

    def assert_ui_exists(self, **selectors):
        """
        Assert UiObject appear on the screen

        Examples:
        | 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
        if rotation == "nature":
            self.d.orientation = "n"  # or "natural"
        elif rotation == "left":
            self.d.orientation = "l"  # or "left"
        elif rotation == "right":
            self.d.orientation = "r"  # or "right"
        elif rotation == "upsidedown":
            self.d.orientation = "upsidedown"  # or "upsidedown"
        else:
            self.d.rotation = "n"

    def take_screenshot(self, scale=None, quality=None):
        """
        Take a screenshot of device and log in the report with timestamp, scale for screenshot size and quality for screenshot quality
        default scale=1.0 quality=100

        Example:
        | Action     | Argument   |  Argument  |
        | Take Screenshot | 0.5 | 80 |
        """
        output_dir = BuiltIn().get_variable_value('${OUTPUTDIR}')
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d%H%M%S')
        screenshot_path = '%s%s%s.png' % (output_dir, os.sep, st)
        screenshot_name = '%s%s.png' % (os.sep, st)
        self.d.screenshot(screenshot_path, scale, quality)
        logger.info('\n<a href="%s">%s</a><br><img src="%s">' %
                    (screenshot_path, st, screenshot_name),
                    html=True)

    def open_notification(self):
        """
        Open notification of the phone
        """
        self.d.open.notification()

    def wait_window_update(self):
        """
        wait for window update
        """
        return self.d.wait.update()

    def wait_window_idle(self):
        """
        wait for window idle
        """
        return self.d.wait.idle()

    def remove_watchers(self):
        """
        Remove UI watchers
        """
        self.d.watchers.remove()

    def get_device(self):
        """
        Get device object, you can do any command using this
        """
        return self.d

    def click_id(self, id, instance=0):
        """
        Click *id* with *instance*=0
        """
        return self.d(resourceId=id, instance=instance).click.wait()

    def long_click_id(self, id, instance=0):
        """
        Long click *id* with *instance*=0
        """
        return self.d(resourceId=id, instance=0).long_click()

    def click_description(self, description, instance=0):
        """
        Click *description* with *instance*=0
        """
        return self.d(description=description, instance=instance).long_click()

    def click_class(self, className, instance=0):
        """
        Click *className* with *instance*=0
        """
        return self.d(className=className, instance=instance).long_click()

    def type_text(self, textStr, **selectors):
        """
        type text on selectors
        like text=EditName
        """
        self.d(**selectors).set_text(textStr)

    def press_key(self, key):
        """ Press Key of following value
            home
            back
            left
            right
            up
            down
            center
            menu
            search
            enter
            delete(or del)
            recent(recent apps)
            volume_up
            volume_down
            volume_mute
            camera
            power

            Examples:
            | Action     | Argument   |
            | Press Key | home |
            | Press Key | back |
            | Press Key | left |
            | Press Key | right |
            | Press Key | recent |
            | Press Key | volume_up |
            | Press Key | camera |
        """
        if key.isdigit():
            return self.d.press(int(key))
        return self.d.press(key)

    def phone_sleep(self, timeout):
        """
        android device sleep with timeout in ms, don't use for executor sleep,
        """
        return self.d.wait(int(timeout))

    def execute_command(self, cmd, block_parent_process=True):
        """
        Execute shell *cmd* command, with block_parent_process = True

        If block_parent_process = False, kill_command is needed to terminal the child process

        Example:
        | Execute Command | ping -c 5 127.0.0.1 |
        """
        if str(block_parent_process) == str(True):
            return subprocess.Popen(cmd,
                                    shell=True,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE).communicate()
        else:
            return subprocess.Popen(cmd,
                                    shell=True,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)

    def kill_command(self, process, timeout=0):
        """ Kill child *process* in timeout seconds
        Some bugs after process teminated
        """
        time.sleep(float(timeout))
        process.terminate()

    def wait_for_logcat(self, log, timeout=30):
        """ Wait log exists in given timeout, return True if have, otherwise will return False
        log is your want to search, log can be a regular expression
        time in seconds, default value is 30 seconds

        Example:
        | Wait For Logcat | .*ActivityManager.*cmp=com.sonyericsson.album/com.sonyericsson.album.Main.* |
        """
        start = time.time()
        while (time.time() - start) < int(timeout):
            log_proc = self.adb.cmd("logcat -d -v time")
            returncode = log_proc.poll()
            lines = log_proc.stdout.readlines()
            for line in lines:
                rlt = re.search(log, line.rstrip())
                if rlt is not None:
                    print rlt.group(0)
                    self._result = True
                    return True
            time.sleep(2)  #sleep 2s to wait
        self._result = False
        return False

    def clear_logcat(self):
        """
        Clear logcat, it's often used before you want to use *wait_for_logcat()*
        """
        print "Clear logcat before test"
        return self.exe_adb_command("logcat -c")

    def click_object(self, obj):
        """ Click UiObject *obj*

        Exmaple:
        | ${result}    | Get UI Object | text=XXX | className=xxxx |
        | Click Object |   ${result}   |
        """
        obj.click()

    def click_ui(self, **selectors):
        """
        Click selector

        click_selector(text="Home", resourceId = "android:id/title")
        for **selector, please refer *get_ui_object()*
        Selector supports below parameters. Refer to UiSelector java doc for detailed information.

            text, textContains, textMatches, textStartsWith
            className, classNameMatches
            description, descriptionContains, descriptionMatches, descriptionStartsWith
            checkable, checked, clickable, longClickable
            scrollable, enabled,focusable, focused, selected
            packageName, packageNameMatches
            resourceId, resourceIdMatches
            index, instance
        Operation for a UiObjects:
        click, clear_text, drag(obj).to(**selector), gesture, exists, set_text, long_click
        pinch.In(percent=100, steps=10), pinch.Out(percent=100, steps=100),.swipe.right(),
        .swipe.left(steps=10),.swipe("right", steps=20),.wait.gone(),.wait.exists()
        """
        print "selectors:", selectors
        return self.d(**selectors).click()

    def get_ui_object(self, **selectors):
        """
        Get UI object with *selectors*
        you can do anything on UiObject, like click(), long_click(),wait.exists(timeout)
        examples: get_ui_object(text="Home", resourceId = "android:id/title")

        Selector supports below parameters. Refer to UiSelector java doc for detailed information.

            text, textContains, textMatches, textStartsWith
            className, classNameMatches
            description, descriptionContains, descriptionMatches, descriptionStartsWith
            checkable, checked, clickable, longClickable
            scrollable, enabled,focusable, focused, selected
            packageName, packageNameMatches
            resourceId, resourceIdMatches
            index, instance
        Operation for a UiObjects:
        click, clear_text, drag(obj).to(**selector), gesture, exists, set_text, long_click
        pinch.In(percent=100, steps=10), pinch.Out(percent=100, steps=100),.swipe.right(),
        .swipe.left(steps=10),.swipe("right", steps=20),.wait.gone(),.wait.exists()

        Exmaple:
        | ${result}    | Get UI Object | text=XXX | className=xxxx |

        """
        self._result = self.d(**selectors)
        return self._result

    def wait_for_object_exists(self, obj, timeout=0):
        """
        Wait for UiObject *obj* exists in *timeout*= 0

        Example:
        | ${result}    | Get UI Object | text=XXX | className=xxxx |
        | Wait For Object Exists | ${result} | timeout |
        """
        self._result = obj.wait.exists(timeout=int(timeout))
        return self._result

    def wait_for_ui_gone(self, timeout=0, **selectors):
        """
        Wait for UiObject *obj* gone in *timeout*= 0

        Example:
        | ${result}    | Get UI Object | text=XXX | className=xxxx |
        | Wait For Object Gone | ${result} | timeout |

        """
        self._result = self.d(**selectors).wait.gone(timeout=int(timeout))
        return self._result

    def get_key_value(self, key, dictionary):
        """
        Get key value of dictionary
        """
        return dictionary(key)

    def get_tts(self, input_text, delete_file=False, **args):
        """
        Get TTS voice mp3 from Google
        get_tts(input_text='tunnel snakes rule apparently', args = {'language':'en','output':'outputto.mp3'})

        Robot Framework:
        Examples:
        | Action     | Argument   |  Argument  |  Argument  |  Argument  |
        | UiTestLib.Get TTS    |   Hello world    |   False   |    output=ooo.mp3   |   language=en |
        """
        print "Get text to speech: ", input_text
        downloaded = False
        if str(delete_file) == 'True':
            if os.path.exists(args['output']):
                os.remove(args['output'])
        if os.path.exists(args['output']):
            if os.path.getsize(args['output']) <= 0:
                os.remove(args['output'])
        if args['output'] is not None:
            if not os.path.exists(args['output']):
                print 'Generating mp3 file......', args['output']
                downloaded = GoogleTTS.audio_extract(input_text, args)
            else:
                print 'Have same local file'
                downloaded = True
        if not downloaded:
            print "Downloaded TTS from Google failed, trying to download from local FTP..."
            mp3file = open(args['output'], 'w')
            mp3url = 'ftp://cnbjlx9548/atautomation/Test-Content/Croft/' + args[
                'output']
            try:
                resp = urllib2.urlopen(mp3url, timeout=40)
                mp3file.write(resp.read())
                time.sleep(.05)
            except Exception, e:
                print e
                return False
            mp3file.close()
        return True
Exemplo n.º 42
0
 def test_forward(self):
     adb = Adb()
     adb.cmd = MagicMock()
     adb.forward(90, 91)
     adb.cmd.assert_called_once_with("forward", "tcp:90", "tcp:91")
     adb.cmd.return_value.wait.assert_called_once_with()
Exemplo n.º 43
0
    def test_device_serial(self):
        with patch.dict('os.environ', {'ANDROID_SERIAL': "ABCDEF123456"}):
            adb = Adb()
            adb.devices = MagicMock()
            adb.devices.return_value = {"ABCDEF123456": "device"}
            self.assertEqual(adb.device_serial(), "ABCDEF123456")
        with patch.dict('os.environ', {'ANDROID_SERIAL': "ABCDEF123456"}):
            adb = Adb()
            adb.devices = MagicMock()
            adb.devices.return_value = {
                "ABCDEF123456": "device",
                "123456ABCDEF": "device"
            }
            self.assertEqual(adb.device_serial(), "ABCDEF123456")
        with patch.dict('os.environ', {'ANDROID_SERIAL': "HIJKLMN098765"}):
            adb = Adb()
            adb.devices = MagicMock()
            adb.devices.return_value = {
                "ABCDEF123456": "device",
                "123456ABCDEF": "device"
            }
            with self.assertRaises(EnvironmentError):
                adb.device_serial()
        with patch.dict('os.environ', {}, clear=True):
            adb = Adb()
            adb.devices = MagicMock()
            adb.devices.return_value = {
                "ABCDEF123456": "device",
                "123456ABCDEF": "device"
            }
            with self.assertRaises(EnvironmentError):
                adb.device_serial()
        with patch.dict('os.environ', {}, clear=True):
            adb = Adb()
            adb.devices = MagicMock()
            adb.devices.return_value = {"ABCDEF123456": "device"}
            print(adb.devices())
            self.assertEqual(adb.device_serial(), "ABCDEF123456")

        with self.assertRaises(EnvironmentError):
            adb = Adb()
            adb.devices = MagicMock()
            adb.devices.return_value = {}
            adb.device_serial()
Exemplo n.º 44
0
    def test_adb_cmd_server_host(self):
        adb = Adb(adb_server_host="localhost", adb_server_port=5037)
        adb.adb = MagicMock()
        adb.adb.return_value = "adb"
        adb.device_serial = MagicMock()
        adb.device_serial.return_value = "ANDROID_SERIAL"
        args = ["a", "b", "c"]
        with patch("subprocess.Popen") as Popen:
            os.name = "nt"
            adb.raw_cmd(*args)
            Popen.assert_called_once_with(
                [adb.adb()] + args,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )

        adb = Adb(adb_server_host="test.com", adb_server_port=1000)
        adb.adb = MagicMock()
        adb.adb.return_value = "adb"
        adb.device_serial = MagicMock()
        adb.device_serial.return_value = "ANDROID_SERIAL"
        args = ["a", "b", "c"]
        with patch("subprocess.Popen") as Popen:
            os.name = "posix"
            adb.raw_cmd(*args)
            Popen.assert_called_once_with(
                [" ".join([adb.adb()] + ["-H", "test.com", "-P", "1000"] + args)],
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )
Exemplo n.º 45
0
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(self, 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" |
			"""
			if appname.find('/') > 0:
				appname = 'shell am start -n ' + appname
			else:
				appname = 'shell am start -a android.intent.action.MAIN -c android.intent.category.LAUNCHER ' + appname
			print 'Open Application:', appname
			self._result = self.exe_adb_command(appname)