@staticmethod
def sdbSetDate(devid):
print "set device date"
- HDATE = '`date "+%Y-%m-%d %H:%M"`'
+ HDATE = '`date "+%Y-%m-%d %H:%M:%S %Z"`'
date_cmd = '"date -s \''+ HDATE + '\'"'
SdbManager.sdbShell(devid, date_cmd)
-#!/usr/bin/python
-
-"""Usage:
- tct-config-device.py [--install [--deviceid <serial_no>]]
- tct-config-device.py --purge [--deviceid <serial_no>]
- tct-config-device.py --check [--deviceid <serial_no>][--procid <process_name>]
- tct-config-device.py --bhtest <profile>
-
-Options:
- -h, --help show this help message and exit
- --install Install tct resources to TIZEN device,it can be omitted
- --purge Clean up tct resources from TIZEN device
- --check Check test resource on device
- --bhtest Install tct behavior test
- --deviceid Set the device serial number
- --procid Set the check process name
-
-"""
-import os
-import sys
-import time
-import ConfigParser
-import threading
-import subprocess
-
-
-from optparse import OptionParser
-from devicemanager import DeviceManager
-from sdbmanager import SdbManager
-
-JOIN = os.path.join
-EXISTS = os.path.exists
-DIRNAME = os.path.dirname
-BASENAME = os.path.basename
-ABSPATH = os.path.abspath
-SPLIT = os.path.split
-
-CURENT_DIR = SPLIT(DIRNAME(ABSPATH(__file__)))[0]
-
-TOOLS_DIR = JOIN(CURENT_DIR, "tools")
-RESRC_DIR = JOIN(CURENT_DIR, "resource")
-PKGS_DIR = JOIN(CURENT_DIR, "package")
-
-DEVID = ""
-
-TIZENV = "tizen_6.0"
-
-DLOG_CLEAR = "dlogutil -c"
-DLOG_UTIL = "sdb -s %s shell dlogutil -v time"
-
-TCT_CONFIG_FILE = "/opt/tools/TCT_CONFIG"
-tct_parser = ConfigParser.ConfigParser()
-tct_parser.read(TCT_CONFIG_FILE)
-
-DEVICE_SUITE_TARGET_24 = tct_parser.get('DEVICE', 'DEVICE_SUITE_TARGET_24')
-DEVICE_SUITE_TARGET_30 = tct_parser.get('DEVICE', 'DEVICE_SUITE_TARGET_30')
-DEVICE_EXECUTION_MODE_30 = tct_parser.get('DEVICE', 'DEVICE_EXECUTION_MODE_30')
-
-if TIZENV.find('tizen_6.0') > -1:
- DEVICE_SUITE_TARGET = DEVICE_SUITE_TARGET_30
-else:
- DEVICE_SUITE_TARGET = DEVICE_SUITE_TARGET_24
-
-def LS(root, file_name, extension=None):
- import glob
-
- file_path = ""
- if extension:
- file_path = JOIN(root, file_name) + "*." + extension
- else:
- file_path = JOIN(root, file_name) + "*"
- files = glob.iglob(r'' + file_path + '')
- for f in files:
- return BASENAME(f)
-
-def get_device_arch():
- global DEV_ARCH
- #ARCHCMD = SDB_SERNO + " shell \"cat /etc/products.d/tizen.prod |grep \<arch\""
- arch_cmd = "cat /etc/config/model-config.xml | grep tizen.org/feature/platform.core.cpu.arch"
- #result example : <key name="tizen.org/feature/platform.core.cpu.arch" type="string">armv7</key>
- result = SdbManager.sdbShell(DEVID, arch_cmd)
- if result and len(result) > 0:
- arch_str = result.split('\n')[0]
- if arch_str and arch_str.find('armv') > -1:
- DEV_ARCH = "arm"
- print "info: [* Arch Type : arm *]"
- elif arch_str and arch_str.find("aarch64") > -1:
- DEV_ARCH = "aarch64"
- print "info: [* Arch Type : aarch64 *]"
- elif arch_str and arch_str.find('x86_64') > -1:
- DEV_ARCH = "ia64"
- print "info: [* Arch Type : ia64 *]"
- elif arch_str and (arch_str.find("i686") > -1 or arch_str.find("x86") > -1 or arch_str.find("i386") > -1):
- DEV_ARCH = "ia"
- print "info: [* Arch Type : ia *]"
- else:
- print "info: [* Arch Type : None *]"
- return False
- return True
- else:
- print "#ERROR#: Failed to get device cpu_arch type"
- return False
-
-
-def kill_process(process_name):
- proc_cmd = "ps aux | grep " + process_name + " | grep -v grep | awk '{print $2}'"
- result = SdbManager.sdbShell(DEVID, proc_cmd)
- if result and len(result) > 0:
- kill_cmd = "kill -9 " + str(result).strip() + " > /dev/null 2>&1"
- SdbManager.sdbShell(DEVID, kill_cmd)
- print "info: %s process has been killed" % process_name
- else:
- print "info: No process of %s activated" % process_name
-
-def remove_tinyweb():
- SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/server.pem > /dev/null 2>&1")
- SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/tinyweb > /dev/null 2>&1")
- SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/cgi-getcookie > /dev/null 2>&1")
- SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/cgi-getfield > /dev/null 2>&1")
- SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/libmongoose.so > /dev/null 2>&1")
- SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/echo.so > /dev/null 2>&1")
- SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/libssl.so > /dev/null 2>&1")
- SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/libcrypto.so > /dev/null 2>&1")
-
-def remove_stub():
- SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/testkit-stub")
-
-
-def uninstall_testconfig():
- if TIZENV.find('tizen_6.0') > -1:
- inst_path = RESRC_DIR + os.sep + 'tct-testconfig' + os.sep + 'inst.py'
- SdbManager.hostCommand("python %s -s %s -u" % (inst_path, DEVID))
- else:
- RPMPKG = LS(RESRC_DIR, "tct-testconfig")
- if not RPMPKG:
- sys.exit("#ERROR#: cannot found tct-testconfig.zip file in resource dir")
- uninst_cmd = JOIN(DEVICE_SUITE_TARGET, 'tct/opt/tct-testconfig/inst.sh') + ' -u'
- SdbManager.sdbShell(DEVID, uninst_cmd)
- rm_cmd = 'rm -f ' + JOIN(DEVICE_SUITE_TARGET, 'tct/', RPMPKG)
- SdbManager.sdbShell(DEVID, rm_cmd)
-
-
-def uninstall_behavior():
- print "info: Uninstall behavior tool."
- if TIZENV.find('tizen_6.0') > -1:
- pass
- else:
- uninst_cmd = JOIN(DEVICE_SUITE_TARGET, 'tct/opt/tct-behavior-tests/inst.sh') + ' -u'
- SdbManager.sdbShell(DEVID, uninst_cmd)
-
-
-def check_resource_dir():
- print "info: check resource directory."
- if os.path.exists(RESRC_DIR):
- SdbManager.sdbShell(DEVID, 'mkdir -p ' + JOIN(DEVICE_SUITE_TARGET, 'tct/'))
- SdbManager.sdbShell(DEVID, 'mkdir -p ' + JOIN(DEVICE_SUITE_TARGET, 'Documents/'))
- return True
- else:
- print "#WARNING#: The directory resource does not exists. Please copy test resources to %s " % RESRC_DIR
- return False
-
-def check_tinyweb():
- print "info: Check tinyweb."
- result = SdbManager.sdbShell(DEVID, "ls /opt/home/developer/ | grep tinyweb")
- if result and result.find('tinyweb'):
- remove_tinyweb()
- install_tinyweb()
- launch_tinyweb()
- else:
- install_tinyweb()
- launch_tinyweb()
-
-
-def port_manager():
- print "info: Check the tinyweb port"
- result = SdbManager.sdbShell('fuser -n tcp 80 8080 8081 8082 8083 8443')
- if result and len(result) > 0:
- check_port = SdbManager.sdbShell('su "netstat -nap |grep tinyweb"')
- if len(check_port) > 0:
- print "info: tinyweb on"
- else:
- print "info: Port is available"
-
-
-def launch_tinyweb():
- dpath_cmd = "printenv PATH"
- dpath = SdbManager.sdbShell(DEVID, dpath_cmd)
-
- launch_cmd = 'sdb -s ' + DEVID + ' shell ' + '"env LD_LIBRARY_PATH=/opt/home/developer PATH=' + dpath.strip() + \
- ':/opt/home/developer/ tinyweb -ssl_certificate /opt/home/developer/server.pem -document_root ' + \
- JOIN(DEVICE_SUITE_TARGET, 'tct') + ' -listening_ports 80,8080,8081,8082,8083,8443s; sleep 3s" 0> /dev/null'
-
- SdbManager.sdbCommand(launch_cmd, 10)
-
- check_tinyweb_cmd = '\"ps aux | grep tinyweb | grep -v grep\"'
- result = SdbManager.sdbShell(DEVID, check_tinyweb_cmd)
- if result and result.find('tinyweb') > -1:
- print "info: Active process tinyweb successfully."
- return True
- else:
- print "#ERROR#: Active process tinyweb failed."
- return False
-
-def install_tinyweb():
- print "info: Install tinyweb"
- SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, 'tinyweb', DEV_ARCH, 'tinyweb'), '/opt/home/developer/')
- SdbManager.sdbShell(DEVID, "chmod 777 /opt/home/developer/tinyweb")
-
- SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, 'tinyweb', DEV_ARCH, 'cgi-getcookie'), '/opt/home/developer/')
- SdbManager.sdbShell(DEVID, "chmod 777 /opt/home/developer/cgi-getcookie")
-
- SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, 'tinyweb', DEV_ARCH, 'cgi-getfield'), '/opt/home/developer/')
- SdbManager.sdbShell(DEVID, "chmod 777 /opt/home/developer/cgi-getfield")
-
- SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, 'tinyweb', DEV_ARCH, 'libmongoose.so'), '/opt/home/developer/')
- SdbManager.sdbShell(DEVID, "chmod 777 /opt/home/developer/libmongoose.so")
-
- SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, 'tinyweb', DEV_ARCH, 'echo.so'), '/opt/home/developer/')
- SdbManager.sdbShell(DEVID, "chmod 777 /opt/home/developer/echo.so")
-
- SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, 'tinyweb', DEV_ARCH, 'server.pem'), '/opt/home/developer/')
- SdbManager.sdbShell(DEVID, "chmod 777 /opt/home/developer/server.pem")
- if DEV_ARCH == "arm":
- SdbManager.sdbShell(DEVID, "ln -s /usr/lib/libssl.so.1.0.0 /opt/home/developer/libssl.so")
- SdbManager.sdbShell(DEVID, "ln -s /usr/lib/libcrypto.so.1.0.0 /opt/home/developer/libcrypto.so")
- elif DEV_ARCH == "ia":
- SdbManager.sdbShell(DEVID, "ln -s /usr/lib/libssl.so.1.0.0 /opt/home/developer/libssl.so")
- SdbManager.sdbShell(DEVID, "ln -s /usr/lib/libcrypto.so.1.0.0 /opt/home/developer/libcrypto.so")
- elif DEV_ARCH == "aarch64":
- SdbManager.sdbShell(DEVID, "ln -s /usr/lib64/libssl.so.1.0.0 /opt/home/developer/libssl.so")
- SdbManager.sdbShell(DEVID, "ln -s /usr/lib64/libcrypto.so.1.0.0 /opt/home/developer/libcrypto.so")
- elif DEV_ARCH == "ia64":
- SdbManager.sdbShell(DEVID, "ln -s /usr/lib64/libssl.so.1.0.0 /opt/home/developer/libssl.so")
- SdbManager.sdbShell(DEVID, "ln -s /usr/lib64/libcrypto.so.1.0.0 /opt/home/developer/libcrypto.so")
-
-
-def check_stub():
- print "info: Check testkit-stub."
- result = SdbManager.sdbShell(DEVID, "ls /opt/home/developer/ | grep testkit-stub")
- if result and len(result) > 0:
- print "info: testkit-stub has been installed on device."
- kill_process("testkit-stub")
- install_stub()
-
-
-def install_stub():
- print "info: Install testkit-stub."
- SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, 'testkit-stub', DEV_ARCH, 'testkit-stub'), '/opt/home/developer/testkit-stub')
- SdbManager.sdbShell(DEVID, "chmod a+x /opt/home/developer/testkit-stub")
- SdbManager.sdbShell(DEVID, "chsmack -e \"User\" /opt/home/developer/testkit-stub")
-
-
-def check_testconfig():
- result = SdbManager.sdbShell(DEVID, '"cat ' + JOIN(DEVICE_SUITE_TARGET, 'tct/opt/tct-testconfig/tct-testconfig.ini') + ' | grep tct"')
- if result and len(result) > 0 and result.find('No such file or directory') == -1:
- print "info: testconfig has already been installed on device."
- else:
- install_testconfig()
-
-
-def install_testconfig():
- print "info: Install testconfig."
- if TIZENV.find('tizen_6.0') > -1:
- instPath = RESRC_DIR + os.sep + 'tct-testconfig' + os.sep + 'inst.py'
- SdbManager.hostCommand("python %s -s %s" % (instPath, DEVID))
- else:
- conf_pkg = LS(RESRC_DIR, "tct-testconfig")
- SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, conf_pkg), JOIN(DEVICE_SUITE_TARGET, 'tct/'))
- SdbManager.sdbShell(DEVID, 'unzip -uo ' + JOIN(DEVICE_SUITE_TARGET, 'tct/') + conf_pkg + ' -d ' + JOIN(DEVICE_SUITE_TARGET, 'tct/'))
- SdbManager.sdbShell(DEVID, JOIN(DEVICE_SUITE_TARGET, 'tct/opt/tct-testconfig/inst.sh'))
-
- result = SdbManager.sdbShell(DEVID, 'cat ' + JOIN(DEVICE_SUITE_TARGET, 'tct/opt/tct-testconfig/tct-testconfig.ini') + ' | grep tct')
-
- if result and len(result) > 0:
- print "info: Install testconfig successfully."
- else:
- print "#ERROR#: Failed to install testconfig, please check %s" % RESRC_DIR
- return False
-
- return True
-
-def install_behavior(profile_name):
- print "info: Install behavior tool."
-
- if not profile_name in ['wearable', 'mobile', 'tv', 'ivi']:
- print "#WARNING#: Invalid device profile value %s" % profile_name
- return False
-
- if TIZENV.find('tizen_6.0') > -1:
- RPMPKG = "tct-behavior-tests-6.0.zip"
- opt_rpm_path = PKGS_DIR + "s" + os.sep + profile_name + os.sep + RPMPKG
- local_rpm_path = PKGS_DIR + os.sep + profile_name + os.sep + RPMPKG
-
- install_rpm = None
- install_dest = None
- install_cmd = None
- if os.path.exists(opt_rpm_path):
- install_rpm = opt_rpm_path
- install_dest = PKGS_DIR + "s" + os.sep + profile_name + os.sep
- install_cmd = PKGS_DIR + "s" + os.sep + profile_name + os.sep + \
- 'opt' + os.sep + "tct-behavior-tests" + os.sep + "inst.py"
- elif os.path.exists(local_rpm_path):
- install_rpm = local_rpm_path
- install_dest = PKGS_DIR + os.sep + profile_name + os.sep
- install_cmd = PKGS_DIR + os.sep + profile_name + os.sep + \
- 'opt' + os.sep + "tct-behavior-tests" + os.sep + "inst.py"
-
- SdbManager.hostCommand("rm -rf %s" % install_dest + "opt/tct-behavior-tests")
- SdbManager.hostCommand("unzip -uo %s -d %s" % (install_rpm, install_dest))
- SdbManager.hostCommand("python %s -s %s" % (install_cmd, DEVID))
-
- print "info: Check tizen-web-ui-fw. Please wait..."
- check_uifw = SdbManager.sdbShell(DEVID, "ls /usr/share/ | grep tizen-web-ui-fw")
- if check_uifw and len(check_uifw) > 0:
- print "info: tizen-web-ui-fw has been installed on device."
- else:
- SdbManager.sdbShell(DEVID, '"mkdir -p /usr/share/tizen-web-ui-fw/"')
- SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, "tizen-web-ui-fw"), '/usr/share/tizen-web-ui-fw/')
- else:
- pass
-
- return True
-
-
-def install_getCap():
- print "info: Install widget getCap."
- widgetCap = LS(RESRC_DIR, 'getCap', 'wgt')
- SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, widgetCap), JOIN(DEVICE_SUITE_TARGET, 'tct/') + widgetCap)
-
- if TIZENV.find('6.0') > -1:
- SdbManager.sdbShell(DEVID, "su - " + DEVICE_EXECUTION_MODE_30 + \
- " -c 'pkgcmd -i -t wgt -q -p " + JOIN(DEVICE_SUITE_TARGET, 'tct/') + widgetCap + '\'')
- SdbManager.sdbShell(DEVID, 'pkgcmd -i -t wgt -q -p ' + JOIN(DEVICE_SUITE_TARGET, 'tct/') + widgetCap)
-
-
-def install_ngetCap():
- print "info: Install widget ngetCap."
- getcap_pkg = LS(RESRC_DIR, 'getCap', 'tpk')
- SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, getcap_pkg), JOIN(DEVICE_SUITE_TARGET, 'tct/') + getcap_pkg)
-
- if TIZENV.find('tizen_6.0') > -1:
- SdbManager.sdbShell(DEVID, "su - " + DEVICE_EXECUTION_MODE_30 + \
- " -c 'pkgcmd -ipt tpk -p " + JOIN(DEVICE_SUITE_TARGET, 'tct/') + getcap_pkg + '\'')
- else:
- SdbManager.sdbShell(DEVID, "pkgcmd -iqt tpk -p" + JOIN(DEVICE_SUITE_TARGET, 'tct/') + getcap_pkg)
-
-def uninstall_getCap():
- print "info: Uninstall widget getCap."
- wgt_id = getCap_appid()
- if wgt_id:
- uninst_cmd = ""
- if TIZENV.find('tizen_6.0') > -1:
- uninst_cmd = "su - " + DEVICE_EXECUTION_MODE_30 + \
- " -c 'pkgcmd -qun " + wgt_id.split('.')[0] + '\''
- elif TIZENV.find('tizen_2.4') > -1:
- uninst_cmd = "pkgcmd -u -q -t wgt -q -p " + wgt_id + '\''
- SdbManager.sdbShell(DEVID, uninst_cmd)
-
- else:
- print "info: getCap is not installed. No need to uninstall"
-
- SdbManager.sdbShell(DEVID, "rm -rf " + JOIN(DEVICE_SUITE_TARGET, "Documents/tct"))
- SdbManager.sdbShell(DEVID, "rm -rf " + JOIN(DEVICE_SUITE_TARGET, "tct/getCap.wgt"))
- SdbManager.sdbShell(DEVID, "rm -rf " + JOIN(DEVICE_SUITE_TARGET, "tct/getCap.tpk"))
-
-
-def uninstall_ngetCap():
- print "info: Uninstall widget ngetCap."
-
-def getCap_appid():
- widgetid_cmd = ""
- if TIZENV.find('tizen_6.0') > -1:
- widgetid_cmd = "su - " + DEVICE_EXECUTION_MODE_30 + \
- " -c \"app_launcher -l | grep getCapabilities\""
- else:
- widgetid_cmd = "wrt-launcher -l | grep getCapabilities"
-
- widgetids = SdbManager.sdbShell(DEVID, widgetid_cmd)
- if widgetids and widgetids.find('getCapabilities') > -1:
- items = widgetids.split()
- return items[len(items) - 1].strip("'")
- else:
- return None
-
-def check_getCap():
- print "info: Check getCap widget. Please wait..."
- if getCap_appid():
- print "info: widget getCap has already been installed on device."
- else:
- install_getCap()
- launch_getCap()
-
-
-def check_ngetCap():
- print "info: Check ngetCap widget. Please wait..."
- if getCap_appid():
- print "info: widget ngetCap has already been installed on device."
- else:
- install_ngetCap()
- launch_ngetCap()
-
-
-def launch_getCap():
- wgt_id = getCap_appid()
- if wgt_id:
- launchResult = None
- if TIZENV.find('tizen_6.0') > -1:
- launchResult = SdbManager.sdbShell(DEVID, 'su - ' + \
- DEVICE_EXECUTION_MODE_30 + ' -c \"app_launcher -s ' + wgt_id + '\"')
- else:
- launchResult = SdbManager.sdbShell(DEVID, '\"wrt-launcher -s ' + wgt_id + '\"')
-
- if launchResult.find('launched') > -1:
- fcheck_retry = 20
-
- while fcheck_retry > 0:
- build = SdbManager.sdbShell(DEVID, "cat " + JOIN(DEVICE_SUITE_TARGET, "Documents/tct/buildinfo.xml") + " | grep buildinfos")
- capa = SdbManager.sdbShell(DEVID, "cat " + JOIN(DEVICE_SUITE_TARGET, "Documents/tct/capability.xml") + " | grep capabilities")
- if not build or not capa:
- time.sleep(2)
- fcheck_retry -= 1
- else:
- break
- if fcheck_retry == 0:
- print "#ERROR#: getCap get buildinfo, capability of device failed!"
- return False
+#!/usr/bin/python\r
+\r
+"""Usage:\r
+ tct-config-device.py [--install [--deviceid <serial_no>]]\r
+ tct-config-device.py --purge [--deviceid <serial_no>]\r
+ tct-config-device.py --check [--deviceid <serial_no>][--procid <process_name>]\r
+ tct-config-device.py --bhtest <profile>\r
+\r
+Options:\r
+ -h, --help show this help message and exit\r
+ --install Install tct resources to TIZEN device,it can be omitted\r
+ --purge Clean up tct resources from TIZEN device\r
+ --check Check test resource on device\r
+ --bhtest Install tct behavior test\r
+ --deviceid Set the device serial number\r
+ --procid Set the check process name\r
+\r
+"""\r
+import os\r
+import sys\r
+import time\r
+import ConfigParser\r
+import threading\r
+import subprocess\r
+\r
+\r
+from optparse import OptionParser\r
+from devicemanager import DeviceManager\r
+from sdbmanager import SdbManager\r
+\r
+JOIN = os.path.join\r
+EXISTS = os.path.exists\r
+DIRNAME = os.path.dirname\r
+BASENAME = os.path.basename\r
+ABSPATH = os.path.abspath\r
+SPLIT = os.path.split\r
+\r
+CURENT_DIR = SPLIT(DIRNAME(ABSPATH(__file__)))[0]\r
+\r
+TOOLS_DIR = JOIN(CURENT_DIR, "tools")\r
+RESRC_DIR = JOIN(CURENT_DIR, "resource")\r
+PKGS_DIR = JOIN(CURENT_DIR, "package")\r
+\r
+DEVID = ""\r
+\r
+TIZENV = "tizen_6.5"\r
+\r
+DLOG_CLEAR = "dlogutil -c"\r
+DLOG_UTIL = "sdb -s %s shell dlogutil -v time"\r
+\r
+TCT_CONFIG_FILE = "/opt/tools/TCT_CONFIG"\r
+tct_parser = ConfigParser.ConfigParser()\r
+tct_parser.read(TCT_CONFIG_FILE)\r
+\r
+DEVICE_SUITE_TARGET_24 = tct_parser.get('DEVICE', 'DEVICE_SUITE_TARGET_24')\r
+DEVICE_SUITE_TARGET_30 = tct_parser.get('DEVICE', 'DEVICE_SUITE_TARGET_30')\r
+DEVICE_EXECUTION_MODE_30 = tct_parser.get('DEVICE', 'DEVICE_EXECUTION_MODE_30')\r
+\r
+if TIZENV.find('tizen_6.5') > -1:\r
+ DEVICE_SUITE_TARGET = DEVICE_SUITE_TARGET_30\r
+else:\r
+ DEVICE_SUITE_TARGET = DEVICE_SUITE_TARGET_24\r
+\r
+def LS(root, file_name, extension=None):\r
+ import glob\r
+\r
+ file_path = ""\r
+ if extension:\r
+ file_path = JOIN(root, file_name) + "*." + extension\r
+ else:\r
+ file_path = JOIN(root, file_name) + "*"\r
+ files = glob.iglob(r'' + file_path + '')\r
+ for f in files:\r
+ return BASENAME(f)\r
+\r
+def get_device_arch():\r
+ global DEV_ARCH\r
+ #ARCHCMD = SDB_SERNO + " shell \"cat /etc/products.d/tizen.prod |grep \<arch\""\r
+ arch_cmd = "cat /etc/config/model-config.xml | grep tizen.org/feature/platform.core.cpu.arch"\r
+ #result example : <key name="tizen.org/feature/platform.core.cpu.arch" type="string">armv7</key>\r
+ result = SdbManager.sdbShell(DEVID, arch_cmd)\r
+ if result and len(result) > 0:\r
+ arch_str = result.split('\n')[0]\r
+ if arch_str and arch_str.find('armv') > -1:\r
+ DEV_ARCH = "arm"\r
+ print "info: [* Arch Type : arm *]"\r
+ elif arch_str and arch_str.find("aarch64") > -1:\r
+ DEV_ARCH = "aarch64"\r
+ print "info: [* Arch Type : aarch64 *]"\r
+ elif arch_str and arch_str.find('x86_64') > -1:\r
+ DEV_ARCH = "ia64"\r
+ print "info: [* Arch Type : ia64 *]"\r
+ elif arch_str and (arch_str.find("i686") > -1 or arch_str.find("x86") > -1 or arch_str.find("i386") > -1):\r
+ DEV_ARCH = "ia"\r
+ print "info: [* Arch Type : ia *]"\r
+ else:\r
+ print "info: [* Arch Type : None *]"\r
+ return False\r
+ return True\r
+ else:\r
+ print "#ERROR#: Failed to get device cpu_arch type"\r
+ return False\r
+\r
+\r
+def kill_process(process_name):\r
+ proc_cmd = "ps aux | grep " + process_name + " | grep -v grep | awk '{print $2}'"\r
+ result = SdbManager.sdbShell(DEVID, proc_cmd)\r
+ if result and len(result) > 0:\r
+ kill_cmd = "kill -9 " + str(result).strip() + " > /dev/null 2>&1"\r
+ SdbManager.sdbShell(DEVID, kill_cmd)\r
+ print "info: %s process has been killed" % process_name\r
+ else:\r
+ print "info: No process of %s activated" % process_name\r
+\r
+def remove_tinyweb():\r
+ SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/server.pem > /dev/null 2>&1")\r
+ SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/tinyweb > /dev/null 2>&1")\r
+ SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/cgi-getcookie > /dev/null 2>&1")\r
+ SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/cgi-getfield > /dev/null 2>&1")\r
+ SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/libmongoose.so > /dev/null 2>&1")\r
+ SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/echo.so > /dev/null 2>&1")\r
+ SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/libssl.so > /dev/null 2>&1")\r
+ SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/libcrypto.so > /dev/null 2>&1")\r
+\r
+def remove_stub():\r
+ SdbManager.sdbShell(DEVID, "rm -f /opt/home/developer/testkit-stub")\r
+\r
+\r
+def uninstall_testconfig():\r
+ if TIZENV.find('tizen_6.5') > -1:\r
+ inst_path = RESRC_DIR + os.sep + 'tct-testconfig' + os.sep + 'inst.py'\r
+ SdbManager.hostCommand("python %s -s %s -u" % (inst_path, DEVID))\r
+ else:\r
+ RPMPKG = LS(RESRC_DIR, "tct-testconfig")\r
+ if not RPMPKG:\r
+ sys.exit("#ERROR#: cannot found tct-testconfig.zip file in resource dir")\r
+ uninst_cmd = JOIN(DEVICE_SUITE_TARGET, 'tct/opt/tct-testconfig/inst.sh') + ' -u'\r
+ SdbManager.sdbShell(DEVID, uninst_cmd)\r
+ rm_cmd = 'rm -f ' + JOIN(DEVICE_SUITE_TARGET, 'tct/', RPMPKG)\r
+ SdbManager.sdbShell(DEVID, rm_cmd)\r
+\r
+\r
+def uninstall_behavior():\r
+ print "info: Uninstall behavior tool."\r
+ if TIZENV.find('tizen_6.5') > -1:\r
+ pass\r
+ else:\r
+ uninst_cmd = JOIN(DEVICE_SUITE_TARGET, 'tct/opt/tct-behavior-tests/inst.sh') + ' -u'\r
+ SdbManager.sdbShell(DEVID, uninst_cmd)\r
+\r
+\r
+def check_resource_dir():\r
+ print "info: check resource directory."\r
+ if os.path.exists(RESRC_DIR):\r
+ SdbManager.sdbShell(DEVID, 'mkdir -p ' + JOIN(DEVICE_SUITE_TARGET, 'tct/'))\r
+ SdbManager.sdbShell(DEVID, 'mkdir -p ' + JOIN(DEVICE_SUITE_TARGET, 'Documents/'))\r
+ return True\r
+ else:\r
+ print "#WARNING#: The directory resource does not exists. Please copy test resources to %s " % RESRC_DIR\r
+ return False\r
+\r
+def check_tinyweb():\r
+ print "info: Check tinyweb."\r
+ result = SdbManager.sdbShell(DEVID, "ls /opt/home/developer/ | grep tinyweb")\r
+ if result and result.find('tinyweb'):\r
+ remove_tinyweb()\r
+ install_tinyweb()\r
+ launch_tinyweb()\r
+ else:\r
+ install_tinyweb()\r
+ launch_tinyweb()\r
+\r
+\r
+def port_manager():\r
+ print "info: Check the tinyweb port"\r
+ result = SdbManager.sdbShell('fuser -n tcp 80 8080 8081 8082 8083 8443')\r
+ if result and len(result) > 0:\r
+ check_port = SdbManager.sdbShell('su "netstat -nap |grep tinyweb"')\r
+ if len(check_port) > 0:\r
+ print "info: tinyweb on"\r
+ else:\r
+ print "info: Port is available"\r
+\r
+\r
+def launch_tinyweb():\r
+ dpath_cmd = "printenv PATH"\r
+ dpath = SdbManager.sdbShell(DEVID, dpath_cmd)\r
+\r
+ launch_cmd = 'sdb -s ' + DEVID + ' shell ' + '"env LD_LIBRARY_PATH=/opt/home/developer PATH=' + dpath.strip() + \\r
+ ':/opt/home/developer/ tinyweb -ssl_certificate /opt/home/developer/server.pem -document_root ' + \\r
+ JOIN(DEVICE_SUITE_TARGET, 'tct') + ' -listening_ports 80,8080,8081,8082,8083,8443s; sleep 3s" 0> /dev/null'\r
+\r
+ SdbManager.sdbCommand(launch_cmd, 10)\r
+\r
+ check_tinyweb_cmd = '\"ps aux | grep tinyweb | grep -v grep\"'\r
+ result = SdbManager.sdbShell(DEVID, check_tinyweb_cmd)\r
+ if result and result.find('tinyweb') > -1:\r
+ print "info: Active process tinyweb successfully."\r
+ return True\r
+ else:\r
+ print "#ERROR#: Active process tinyweb failed."\r
+ return False\r
+\r
+def install_tinyweb():\r
+ print "info: Install tinyweb"\r
+ SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, 'tinyweb', DEV_ARCH, 'tinyweb'), '/opt/home/developer/')\r
+ SdbManager.sdbShell(DEVID, "chmod 777 /opt/home/developer/tinyweb")\r
+\r
+ SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, 'tinyweb', DEV_ARCH, 'cgi-getcookie'), '/opt/home/developer/')\r
+ SdbManager.sdbShell(DEVID, "chmod 777 /opt/home/developer/cgi-getcookie")\r
+\r
+ SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, 'tinyweb', DEV_ARCH, 'cgi-getfield'), '/opt/home/developer/')\r
+ SdbManager.sdbShell(DEVID, "chmod 777 /opt/home/developer/cgi-getfield")\r
+\r
+ SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, 'tinyweb', DEV_ARCH, 'libmongoose.so'), '/opt/home/developer/')\r
+ SdbManager.sdbShell(DEVID, "chmod 777 /opt/home/developer/libmongoose.so")\r
+\r
+ SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, 'tinyweb', DEV_ARCH, 'echo.so'), '/opt/home/developer/')\r
+ SdbManager.sdbShell(DEVID, "chmod 777 /opt/home/developer/echo.so")\r
+\r
+ SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, 'tinyweb', DEV_ARCH, 'server.pem'), '/opt/home/developer/')\r
+ SdbManager.sdbShell(DEVID, "chmod 777 /opt/home/developer/server.pem")\r
+ if DEV_ARCH == "arm":\r
+ SdbManager.sdbShell(DEVID, "ln -s /usr/lib/libssl.so.1.0.0 /opt/home/developer/libssl.so")\r
+ SdbManager.sdbShell(DEVID, "ln -s /usr/lib/libcrypto.so.1.0.0 /opt/home/developer/libcrypto.so")\r
+ elif DEV_ARCH == "ia":\r
+ SdbManager.sdbShell(DEVID, "ln -s /usr/lib/libssl.so.1.0.0 /opt/home/developer/libssl.so")\r
+ SdbManager.sdbShell(DEVID, "ln -s /usr/lib/libcrypto.so.1.0.0 /opt/home/developer/libcrypto.so")\r
+ elif DEV_ARCH == "aarch64":\r
+ SdbManager.sdbShell(DEVID, "ln -s /usr/lib64/libssl.so.1.0.0 /opt/home/developer/libssl.so")\r
+ SdbManager.sdbShell(DEVID, "ln -s /usr/lib64/libcrypto.so.1.0.0 /opt/home/developer/libcrypto.so")\r
+ elif DEV_ARCH == "ia64":\r
+ SdbManager.sdbShell(DEVID, "ln -s /usr/lib64/libssl.so.1.0.0 /opt/home/developer/libssl.so")\r
+ SdbManager.sdbShell(DEVID, "ln -s /usr/lib64/libcrypto.so.1.0.0 /opt/home/developer/libcrypto.so")\r
+\r
+\r
+def check_stub():\r
+ print "info: Check testkit-stub."\r
+ result = SdbManager.sdbShell(DEVID, "ls /opt/home/developer/ | grep testkit-stub")\r
+ if result and len(result) > 0:\r
+ print "info: testkit-stub has been installed on device."\r
+ kill_process("testkit-stub")\r
+ install_stub()\r
+\r
+\r
+def install_stub():\r
+ print "info: Install testkit-stub."\r
+ SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, 'testkit-stub', DEV_ARCH, 'testkit-stub'), '/opt/home/developer/testkit-stub')\r
+ SdbManager.sdbShell(DEVID, "chmod a+x /opt/home/developer/testkit-stub")\r
+ SdbManager.sdbShell(DEVID, "chsmack -e \"User\" /opt/home/developer/testkit-stub")\r
+\r
+\r
+def check_testconfig():\r
+ result = SdbManager.sdbShell(DEVID, '"cat ' + JOIN(DEVICE_SUITE_TARGET, 'tct/opt/tct-testconfig/tct-testconfig.ini') + ' | grep tct"')\r
+ if result and len(result) > 0 and result.find('No such file or directory') == -1:\r
+ print "info: testconfig has already been installed on device."\r
+ else:\r
+ install_testconfig()\r
+\r
+\r
+def install_testconfig():\r
+ print "info: Install testconfig."\r
+ if TIZENV.find('tizen_6.5') > -1:\r
+ instPath = RESRC_DIR + os.sep + 'tct-testconfig' + os.sep + 'inst.py'\r
+ SdbManager.hostCommand("python %s -s %s" % (instPath, DEVID))\r
+ else:\r
+ conf_pkg = LS(RESRC_DIR, "tct-testconfig")\r
+ SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, conf_pkg), JOIN(DEVICE_SUITE_TARGET, 'tct/'))\r
+ SdbManager.sdbShell(DEVID, 'unzip -uo ' + JOIN(DEVICE_SUITE_TARGET, 'tct/') + conf_pkg + ' -d ' + JOIN(DEVICE_SUITE_TARGET, 'tct/'))\r
+ SdbManager.sdbShell(DEVID, JOIN(DEVICE_SUITE_TARGET, 'tct/opt/tct-testconfig/inst.sh'))\r
+\r
+ result = SdbManager.sdbShell(DEVID, 'cat ' + JOIN(DEVICE_SUITE_TARGET, 'tct/opt/tct-testconfig/tct-testconfig.ini') + ' | grep tct')\r
+\r
+ if result and len(result) > 0:\r
+ print "info: Install testconfig successfully."\r
+ else:\r
+ print "#ERROR#: Failed to install testconfig, please check %s" % RESRC_DIR\r
+ return False\r
+\r
+ return True\r
+\r
+def install_behavior(profile_name):\r
+ print "info: Install behavior tool."\r
+\r
+ if not profile_name in ['wearable', 'mobile', 'tv', 'ivi']:\r
+ print "#WARNING#: Invalid device profile value %s" % profile_name\r
+ return False\r
+\r
+ if TIZENV.find('tizen_6.5') > -1:\r
+ RPMPKG = "tct-behavior-tests-6.5.zip"\r
+ opt_rpm_path = PKGS_DIR + "s" + os.sep + profile_name + os.sep + RPMPKG\r
+ local_rpm_path = PKGS_DIR + os.sep + profile_name + os.sep + RPMPKG\r
+\r
+ install_rpm = None\r
+ install_dest = None\r
+ install_cmd = None\r
+ if os.path.exists(opt_rpm_path):\r
+ install_rpm = opt_rpm_path\r
+ install_dest = PKGS_DIR + "s" + os.sep + profile_name + os.sep\r
+ install_cmd = PKGS_DIR + "s" + os.sep + profile_name + os.sep + \\r
+ 'opt' + os.sep + "tct-behavior-tests" + os.sep + "inst.py"\r
+ elif os.path.exists(local_rpm_path):\r
+ install_rpm = local_rpm_path\r
+ install_dest = PKGS_DIR + os.sep + profile_name + os.sep\r
+ install_cmd = PKGS_DIR + os.sep + profile_name + os.sep + \\r
+ 'opt' + os.sep + "tct-behavior-tests" + os.sep + "inst.py"\r
+\r
+ SdbManager.hostCommand("rm -rf %s" % install_dest + "opt/tct-behavior-tests")\r
+ SdbManager.hostCommand("unzip -uo %s -d %s" % (install_rpm, install_dest))\r
+ SdbManager.hostCommand("python %s -s %s" % (install_cmd, DEVID))\r
+\r
+ print "info: Check tizen-web-ui-fw. Please wait..."\r
+ check_uifw = SdbManager.sdbShell(DEVID, "ls /usr/share/ | grep tizen-web-ui-fw")\r
+ if check_uifw and len(check_uifw) > 0:\r
+ print "info: tizen-web-ui-fw has been installed on device."\r
+ else:\r
+ SdbManager.sdbShell(DEVID, '"mkdir -p /usr/share/tizen-web-ui-fw/"')\r
+ SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, "tizen-web-ui-fw"), '/usr/share/tizen-web-ui-fw/')\r
+ else:\r
+ pass\r
+\r
+ return True\r
+\r
+\r
+\r
+def update_tctconf_file():\r
+ print "Updating TCT_CONFIG file"\r
+ tct_config_old = "/opt/tools/TCT_CONFIG"\r
+ tct_config_new = "/opt/tools/shell/tmp/%s/TCT_CONFIG"%DEVID\r
+\r
+ if os.path.exists(tct_config_new):\r
+ os.remove(tct_config_new)\r
+\r
+ config_content = ""\r
+ with open(tct_config_old, 'r') as f:\r
+ config_content = f.readlines()\r
+ f_new = open(tct_config_new, 'w')\r
+\r
+ tmp = ""\r
+ for line in config_content:\r
+ if line.find("DEVICE_PHYSICAL_STORAGE_30")!=-1:\r
+ tmp = getDevPhysicalStorage()\r
+ if tmp is None:\r
+ f_new.write(line)\r
+ else:\r
+ f_new.write("DEVICE_PHYSICAL_STORAGE_30="+tmp.strip()+"\n")\r
+ elif line.find("DEVICE_ADMIN_USER_APPS_ROOT_30")!=-1:\r
+ tmp = getDevAdminUserAppsRoot()\r
+ if tmp is None:\r
+ f_new.write(line)\r
+ else:\r
+ f_new.write("DEVICE_ADMIN_USER_APPS_ROOT_30="+tmp.strip()+"\n")\r
+ elif line.find("DEVICE_STORAGE_30")!=-1:
+ tmp = getDevStorage()
+ if tmp is None:
+ f_new.write(line)
else:
- print "info: Launch getCap successfully"
- return True
- else:
- print "#ERROR#: Launch getCap got failed"
- return False
- else:
- print "#ERROR#: Widget getCap cannot be found. Please check whether the widget is installed successfully"
- return False
-
-def launch_ngetCap():
- launch_result = None
- if TIZENV.find('tizen_6.0') > -1:
- launch_result = SdbManager.sdbShell(DEVID, 'su - ' + \
- DEVICE_EXECUTION_MODE_30 + ' -c \"launch_app org.example.getcap\"')
- else:
- launch_result = SdbManager.sdbShell(DEVID, '\"launch_app org.example.getcap\"')
-
- if "launched" in launch_result:
- return True
- else:
- return False
-
-def getStorage_appid():
- widgetid_cmd = "su - " + DEVICE_EXECUTION_MODE_30 + \
- " -c \"app_launcher -l | grep InternalStorageSetting\""
- widgetids = SdbManager.sdbShell(DEVID, widgetid_cmd)
- if widgetids and widgetids.find('InternalStorageSetting') > -1:
- items = widgetids.split()
- return items[len(items)-1].strip("'")
- else:
+ f_new.write("DEVICE_STORAGE_30="+tmp.strip()+"\n")
+ else:\r
+ f_new.write(line)\r
+ f_new.close()\r
+\r
+def getDevPhysicalStorage():\r
+ devphysicalstorage_cmd = "tzplatform-get -u owner TZ_USER_CONTENT"\r
+ print devphysicalstorage_cmd\r
+ ret = SdbManager.sdbShell(DEVID, devphysicalstorage_cmd)\r
+ print ret\r
+ if ret is None:\r
+ print "Cannot get info from cmd : %s" %devphysicalstorage_cmd\r
+ return None\r
+ else:\r
+ ret = ret.replace('/opt/usr/','/')\r
+ print "DEVICE_PHYSICAL_STORAGE_30 : %s" %(ret.split('=')[1])\r
+ return ret.split('=')[1]\r
+\r
+def getDevAdminUserAppsRoot():\r
+ devadminuserappsroot_cmd = "tzplatform-get TZ_SYS_RW_APP"\r
+ ret = SdbManager.sdbShell(DEVID, devadminuserappsroot_cmd)\r
+ if ret is None:\r
+ print "Cannot get info from cmd : %s" %devadminuserappsroot_cmd\r
+ return None\r
+ else:\r
+ print "DEVCIE_ADMIN_USER_APPS_ROOT_30 : %s" %(ret.split('=')[1])\r
+ return ret.split('=')[1]\r
+\r
+def getDevStorage():
+ devstorage_cmd = "tzplatform-get -u owner TZ_USER_CONTENT"
+ print devstorage_cmd
+ ret = SdbManager.sdbShell(DEVID, devstorage_cmd)
+ print ret
+ if ret is None:
+ print "Cannot get info from cmd : %s" %devstorage_cmd
return None
-
-def check_storage():
- print "info: Check InternalStorageSetting widget. Please wait..."
- if getStorage_appid():
- print "info: widget InternalStorageSetting has already been installed on device."
- else:
- install_storage()
- launch_storage()
-
-def install_storage():
- print "info: Install widget InternalStorageSetting"
- widget = LS(RESRC_DIR, 'InternalStorageSetting', 'wgt')
- SdbManager.sdbPush(DEVID, JOIN(RESRC_DIR, widget), JOIN(DEVICE_SUITE_TARGET, 'tct/') + widget)
-
- SdbManager.sdbShell(DEVID, "su - " + DEVICE_EXECUTION_MODE_30 + \
- " -c 'pkgcmd -i -t wgt -q -p " + JOIN(DEVICE_SUITE_TARGET, 'tct/') + widget + '\'')
-
-def launch_storage():
- wgt_id = getStorage_appid()
- if wgt_id:
- launch_result = SdbManager.sdbShell(DEVID, 'su - ' + \
- DEVICE_EXECUTION_MODE_30 + ' -c \"app_launcher -s ' + wgt_id + '\"')
-
- if launch_result.find('launched') > -1:
- print "info: Launch InternalStorageSetting successfully"
- return True
- else:
- print "#ERROR#: InternalStorageSetting launch failed"
- return False
- else:
- print "#ERROR#: Widget InternalStorageSetting cannot be found"
- return False
-
-def uninstall_storage():
- print "info: Uninstall widget InternalStorageSetting"
- wgt_id = getStorage_appid()
- if wgt_id:
- uninst_cmd = "su - " + DEVICE_EXECUTION_MODE_30 + \
- " -c 'pkgcmd -qun " + wgt_id.split('.')[0] + '\''
- SdbManager.sdbShell(DEVID, uninst_cmd)
else:
- print "info: InternalStorageSetting is not installed"
-
-def push_tctconf_file():
- local = TCT_CONFIG_FILE
- remote = DEVICE_SUITE_TARGET_30
- if not SdbManager.sdbPush(DEVID, local, remote):
- print "#ERROR#: TCT_CONFIG file push failed"
- return False
- return True
-
-def find_ngetCap():
- getcap_tpk = LS(RESRC_DIR, 'getCap', 'tpk')
- if getcap_tpk:
- return True
- else:
- return False
-
-def debug_trace(cmd, logfile):
- global debug_flag, metux
-
- wbuffile = file(logfile, "a+")
- exit_code = None
- proc = subprocess.Popen(args=cmd,
- shell=True,
- stdout=wbuffile,
- stderr=None)
- while True:
- exit_code = proc.poll()
- if exit_code is not None:
- break
- time.sleep(0.6)
- metux.acquire()
- proc_flag = debug_flag
- metux.release()
- if not proc_flag:
- break
- wbuffile.close()
- SdbManager.killall(proc.pid)
-
-
-def start_debug(dlog_file):
- global debug_flag, metux, dlog_thread
- debug_flag = True
- metux = threading.Lock()
- clear_cmd = DLOG_CLEAR
- SdbManager.sdbShell(DEVID, clear_cmd)
-
- dlog_cmd = DLOG_UTIL % DEVID
- dlog_thread = threading.Thread(target=debug_trace, args=(dlog_cmd, dlog_file))
- dlog_thread.setDaemon(True)
- dlog_thread.start()
-
-
-def stop_debug():
- global debug_flag, metux
- metux.acquire()
- debug_flag = False
- metux.release()
- dlog_thread.join()
-
-
-def runProcess():
- if options.purge:
- print "[ Uninstall test resource on device. Please wait...]"
- uninstall_testconfig()
- uninstall_behavior()
- uninstall_getCap()
- remove_tinyweb()
- kill_process("tinyweb")
- kill_process("testkit-stub")
- remove_stub()
- if TIZENV.find('6.0') > -1:
- uninstall_storage()
- print "Clean the tct packages in device successfully."
-
- elif options.check:
- check_resource_dir()
- print "[ Check test resource on device. Please wait...]"
- if options.process == 'tinyweb':
- check_tinyweb()
- elif options.process == 'testkit-stub':
- check_stub()
- elif options.process == 'testconfig':
- check_testconfig()
- elif options.process == 'getCap':
- check_getCap()
- elif options.process == 'ngetCap':
- if find_ngetCap():
- check_ngetCap()
- else:
- check_getCap()
- elif options.process == 'storage':
- check_storage()
- else:
- check_tinyweb()
- check_stub()
- check_testconfig()
- if find_ngetCap():
- check_ngetCap()
- else:
- check_getCap()
- if TIZENV.find('6.0') > -1:
- check_storage()
-
- print "Check finished."
-
- elif options.bhtest:
- check_resource_dir()
- if TIZENV.find('6.0') > -1:
- uninstall_storage()
- install_storage()
- launch_storage()
-
- uninstall_behavior()
- print "[ Install tct behavior tool on device. Please wait...]"
- install_behavior(options.bhtest)
- print "Installation of tct behavior on device completed."
-
- else:
- check_resource_dir()
- print "[ Clean old test resource on device. Please wait...]"
- if options.process == 'tinyweb':
- kill_process("tinyweb")
- remove_tinyweb()
- elif options.process == 'testkit-stub':
- kill_process("testkit-stub")
- remove_stub()
- elif options.process == 'testconfig':
- uninstall_testconfig()
- elif options.process == 'getCap':
- uninstall_getCap()
- pass
- elif options.process == 'ngetCap':
- uninstall_ngetCap()
- elif options.process == 'storage':
- uninstall_storage()
- else:
- remove_tinyweb()
- kill_process("testkit-stub")
- remove_stub()
- uninstall_testconfig()
- uninstall_getCap()
- uninstall_ngetCap()
- if TIZENV.find('6.0') > -1:
- uninstall_storage()
-
- print "Clean the tct packages in device successfully."
- print "[ Install test resource on device. Please wait...]"
- if options.process == 'tinyweb':
- install_tinyweb()
- launch_tinyweb()
- elif options.process == 'testkit-stub':
- install_stub()
- elif options.process == 'testconfig':
- install_testconfig()
- elif options.process == 'getCap':
- install_getCap()
- launch_getCap()
- elif options.process == 'ngetCap':
- if find_ngetCap():
- install_ngetCap()
- launch_ngetCap()
- else:
- install_getCap()
- launch_getCap()
- elif options.process == 'storage':
- install_storage()
- launch_storage()
- else:
- install_testconfig()
- install_stub()
- install_tinyweb()
- launch_tinyweb()
- if find_ngetCap():
- install_ngetCap()
- launch_ngetCap()
- else:
- install_getCap()
- launch_getCap()
-
- if TIZENV.find('6.0') > -1:
- install_storage()
- launch_storage()
-
- print "All of installation process on device completed."
-
-
-if __name__ == "__main__":
-
- parser = OptionParser()
- parser.add_option(
- "--install", dest="install", action="store_true", default=False,
- help="Install tct resources to TIZEN device,it can be omitted")
- parser.add_option(
- "--purge", dest="purge", action="store_true", default=False,
- help="Clean up tct resources from TIZEN device")
- parser.add_option(
- "--check", dest="check", action="store_true", default=False,
- help="Check test resource on device")
- parser.add_option(
- "--deviceid", dest="deviceid", action="store",
- help="Set the device serial number")
- parser.add_option(
- "--procid", dest="process", action="store",
- help="Set the process id for checking")
- parser.add_option(
- "--bhtest", dest="bhtest", action="store",
- help="Install behavior test tool to device")
-
- (options, args) = parser.parse_args()
-
- devinst = DeviceManager.getInstance()
- if options.deviceid:
- if devinst.isDeviceAvailable(options.deviceid):
- DEVID = options.deviceid
- else:
- sys.exit("#ERROR#: The '%s' device Id exists error" % options.deviceid)
- else:
- if devinst.getDeviceSize() > 1 or devinst.getDeviceSize() == 0:
- sys.exit("#ERROR#: %s devices connected or device not connected" % str(devinst.getDeviceSize()))
- else:
- DEVID = devinst.getSdbDeviceList()[0].getDeviceId()
-
- print "[========== start tct-config-device : %s ==========]" % DEVID
- dev_temp_dir = '/opt/tools/shell/tmp/%s/' % DEVID
- if not os.path.isdir(dev_temp_dir):
- os.mkdir(dev_temp_dir)
- DLOG_SAVE_PATH = '/opt/tools/shell/tmp/%s/conf_dev_%s.dlog'
- if options.process is None:
- DLOG_SAVE_PATH = DLOG_SAVE_PATH % (DEVID, 'all')
- else:
- DLOG_SAVE_PATH = DLOG_SAVE_PATH % (DEVID, options.process)
-
- #start_debug(DLOG_SAVE_PATH)
-
- if not SdbManager.sdbRootOn(DEVID):
- sys.exit(-1)
-
- SdbManager.sdbSetDate(DEVID)
-
- if not get_device_arch() or not push_tctconf_file():
- sys.exit(0)
-
- runProcess()
- #stop_debug()
- print "[========== end tct-config-device : %s ==========]" % DEVID
+ print "DEVICE_STORAGE_30 : %s" %(ret.split('=')[1])
+ return ret.split('=')[1]
+
+def push_tctconf_file():\r
+ updated_tct_conf_local = "/opt/tools/shell/tmp/%s/TCT_CONFIG"%DEVID\r
+ remote = DEVICE_SUITE_TARGET_30\r
+ if not SdbManager.sdbPush(DEVID, updated_tct_conf_local, remote):\r
+ print "#ERROR#: TCT_CONFIG file push failed"\r
+ return False\r
+ return True\r
+\r
+\r
+def debug_trace(cmd, logfile):\r
+ global debug_flag, metux\r
+\r
+ wbuffile = file(logfile, "a+")\r
+ exit_code = None\r
+ proc = subprocess.Popen(args=cmd,\r
+ shell=True,\r
+ stdout=wbuffile,\r
+ stderr=None)\r
+ while True:\r
+ exit_code = proc.poll()\r
+ if exit_code is not None:\r
+ break\r
+ time.sleep(0.6)\r
+ metux.acquire()\r
+ proc_flag = debug_flag\r
+ metux.release()\r
+ if not proc_flag:\r
+ break\r
+ wbuffile.close()\r
+ SdbManager.killall(proc.pid)\r
+\r
+\r
+def start_debug(dlog_file):\r
+ global debug_flag, metux, dlog_thread\r
+ debug_flag = True\r
+ metux = threading.Lock()\r
+ clear_cmd = DLOG_CLEAR\r
+ SdbManager.sdbShell(DEVID, clear_cmd)\r
+\r
+ dlog_cmd = DLOG_UTIL % DEVID\r
+ dlog_thread = threading.Thread(target=debug_trace, args=(dlog_cmd, dlog_file))\r
+ dlog_thread.setDaemon(True)\r
+ dlog_thread.start()\r
+\r
+\r
+def stop_debug():\r
+ global debug_flag, metux\r
+ metux.acquire()\r
+ debug_flag = False\r
+ metux.release()\r
+ dlog_thread.join()\r
+\r
+\r
+def runProcess():\r
+ if options.purge:\r
+ print "[ Uninstall test resource on device. Please wait...]"\r
+ uninstall_testconfig()\r
+ uninstall_behavior()\r
+ remove_tinyweb()\r
+ kill_process("tinyweb")\r
+ kill_process("testkit-stub")\r
+ remove_stub()\r
+ print "Clean the tct packages in device successfully."\r
+\r
+ elif options.check:\r
+ check_resource_dir()\r
+ print "[ Check test resource on device. Please wait...]"\r
+ if options.process == 'tinyweb':\r
+ check_tinyweb()\r
+ elif options.process == 'testkit-stub':\r
+ check_stub()\r
+ elif options.process == 'testconfig':\r
+ check_testconfig()\r
+ else:\r
+ check_tinyweb()\r
+ check_stub()\r
+ check_testconfig()\r
+\r
+ print "Check finished."\r
+\r
+ elif options.bhtest:\r
+ check_resource_dir()\r
+\r
+ uninstall_behavior()\r
+ print "[ Install tct behavior tool on device. Please wait...]"\r
+ install_behavior(options.bhtest)\r
+ print "Installation of tct behavior on device completed."\r
+\r
+ else:\r
+ check_resource_dir()\r
+ print "[ Clean old test resource on device. Please wait...]"\r
+ if options.process == 'tinyweb':\r
+ kill_process("tinyweb")\r
+ remove_tinyweb()\r
+ elif options.process == 'testkit-stub':\r
+ kill_process("testkit-stub")\r
+ remove_stub()\r
+ elif options.process == 'testconfig':\r
+ uninstall_testconfig()\r
+ else:\r
+ remove_tinyweb()\r
+ kill_process("testkit-stub")\r
+ remove_stub()\r
+ uninstall_testconfig()\r
+\r
+ print "Clean the tct packages in device successfully."\r
+ print "[ Install test resource on device. Please wait...]"\r
+ if options.process == 'tinyweb':\r
+ install_tinyweb()\r
+ launch_tinyweb()\r
+ elif options.process == 'testkit-stub':\r
+ install_stub()\r
+ elif options.process == 'testconfig':\r
+ install_testconfig()\r
+ else:\r
+ install_testconfig()\r
+ install_stub()\r
+ install_tinyweb()\r
+ launch_tinyweb()\r
+\r
+\r
+ print "All of installation process on device completed."\r
+\r
+\r
+if __name__ == "__main__":\r
+\r
+ parser = OptionParser()\r
+ parser.add_option(\r
+ "--install", dest="install", action="store_true", default=False,\r
+ help="Install tct resources to TIZEN device,it can be omitted")\r
+ parser.add_option(\r
+ "--purge", dest="purge", action="store_true", default=False,\r
+ help="Clean up tct resources from TIZEN device")\r
+ parser.add_option(\r
+ "--check", dest="check", action="store_true", default=False,\r
+ help="Check test resource on device")\r
+ parser.add_option(\r
+ "--deviceid", dest="deviceid", action="store",\r
+ help="Set the device serial number")\r
+ parser.add_option(\r
+ "--procid", dest="process", action="store",\r
+ help="Set the process id for checking")\r
+ parser.add_option(\r
+ "--bhtest", dest="bhtest", action="store",\r
+ help="Install behavior test tool to device")\r
+\r
+ (options, args) = parser.parse_args()\r
+\r
+ devinst = DeviceManager.getInstance()\r
+ if options.deviceid:\r
+ if devinst.isDeviceAvailable(options.deviceid):\r
+ DEVID = options.deviceid\r
+ else:\r
+ sys.exit("#ERROR#: The '%s' device Id exists error" % options.deviceid)\r
+ else:\r
+ if devinst.getDeviceSize() > 1 or devinst.getDeviceSize() == 0:\r
+ sys.exit("#ERROR#: %s devices connected or device not connected" % str(devinst.getDeviceSize()))\r
+ else:\r
+ DEVID = devinst.getSdbDeviceList()[0].getDeviceId()\r
+\r
+ print "[========== start tct-config-device : %s ==========]" % DEVID\r
+ dev_temp_dir = '/opt/tools/shell/tmp/%s/' % DEVID\r
+ if not os.path.isdir(dev_temp_dir):\r
+ os.makedirs(dev_temp_dir)
+ DLOG_SAVE_PATH = '/opt/tools/shell/tmp/%s/conf_dev_%s.dlog'\r
+ if options.process is None:\r
+ DLOG_SAVE_PATH = DLOG_SAVE_PATH % (DEVID, 'all')\r
+ else:\r
+ DLOG_SAVE_PATH = DLOG_SAVE_PATH % (DEVID, options.process)\r
+\r
+ #start_debug(DLOG_SAVE_PATH)\r
+\r
+ if not SdbManager.sdbRootOn(DEVID):\r
+ sys.exit(-1)\r
+\r
+ SdbManager.sdbSetDate(DEVID)\r
+\r
+ update_tctconf_file()\r
+ if not get_device_arch() or not push_tctconf_file():\r
+ sys.exit(0)\r
+\r
+ runProcess()\r
+ #stop_debug()\r
+ print "[========== end tct-config-device : %s ==========]" % DEVID\r
+\r
DEVICE_ADMIN_USER_30=owner
DEVICE_ADMIN_USER_APPS_ROOT_30=/opt/usr/globalapps
DEVICE_OTHER_USER_APPS_ROOT_30=/opt/usr/home/owner/apps_rw
+DEVICE_STORAGE_30=/home/owner/media
+++ /dev/null
-#!/usr/bin/python
-
-import sys
-
-from tctmonkey.monkeywrapper import MonkeyWrapper
-from tctmonkey.devicemanager import DeviceManager
-from tctmonkey.monkeyworker import RandomExecutor
-from tctmonkey.monkeyworker import ReplayExecutor
-
-
-def main():
- wrapper = MonkeyWrapper()
- wrapper.parse_options(sys.argv)
-
- dmi = DeviceManager.getInstance()
-
- mExecutor = []
- for dev in dmi.getSdbDeviceList():
- th = None
- if wrapper.is_py_install():
- wrapper.python_install(dev.getDeviceId())
- if wrapper.is_random_mode():
- th = RandomExecutor(dev.getDeviceId(), wrapper)
- elif wrapper.is_replay_mode():
- th = ReplayExecutor(dev.getDeviceId(), wrapper)
-
- mExecutor.append(th)
-
- for thread in mExecutor:
- if thread:
- thread.start()
-
- for thread in mExecutor:
- if thread:
- thread.join()
-
-if __name__ == "__main__":
- main()
+++ /dev/null
-
-import os
-
-class Constants:
- LIB_DIR = "/opt/tools/dev_event/lib/"
- AGENT_PATH = "/opt/tools/dev_event/tctmonkey/fmbttizen-agent.py"
- UINPUT_AGENT_PATH = "/opt/tools/dev_event/tctmonkey/fmbtuinput.py"
- DUMP_DIR_PATH = "/opt/share/crash/dump/"
- RESULT_DIR = "/opt/monkey/result/"
- RECORD_FILE_NAME = "record_file"
- SDB_LS = "sdb -s %s shell ls -al"
- SDB_PUSH = "sdb -s %s push"
- SDB_SHELL = "sdb -s %s shell"
- SDB_ROOT_ON = "sdb -s %s root on"
- SDB_DEVICES = "sdb devices"
- SDB_START_SERVER = "sdb start-server"
- SDB_KILL_SERVER = "sdb kill-server"
- SDB_CONNECT = "sdb connect %s"
- SDB_PULL = "sdb -s %s pull"
- SDB_CAT_CONFIG = " cat %s"
- FILE_FOUND_SCRIPT = "[ -f %s ] && echo \"Found\" || echo \"Not Found\""
-
- @staticmethod
- def checkFileExists(aPath):
- if os.path.exists(aPath):
- return True
- else:
- return False
+++ /dev/null
-
-from sdbmanager import SdbManager
-
-class DeviceManager(object):
- INSTANCE = None
- devices = []
-
- def __init__(self):
- if DeviceManager.INSTANCE is not None:
- raise Exception ("DeviceManager instance already exists")
-
- @classmethod
- def getInstance(cls):
- if cls.INSTANCE is None:
- cls.INSTANCE = DeviceManager()
- if len(cls.INSTANCE.devices) < 1:
- cls.INSTANCE.loadDeviceList()
- return cls.INSTANCE
-
- def _updateConnDevice(self, connDevices):
- self._resetDevices()
-
- for dev in connDevices:
- self.devices.append(dev)
-
- def _resetDevices(self):
- listSize = len(self.devices)
- del self.devices[0:listSize]
-
- def getDeviceSize(self):
- return len(self.devices)
-
- def getSdbDeviceList(self):
- return self.devices
-
- def loadDeviceList(self):
- connDevices = []
- sdbOutLog = SdbManager.sdbDevices()
- devicesInfo = sdbOutLog.replace("List of devices attached", "")
- devList = devicesInfo.split('\n')
-
- for dev in devList:
- if len(dev) > 1:
- devInfoItem = dev.split('\t')
- devId = devInfoItem[0].rstrip()
- devType = devInfoItem[1].rstrip()
- devName = devInfoItem[2].rstrip()
- if not (devType == "unknown" or devType == "offline" \
- or devId == "unknown" or devId == "offline"):
- connDevices.append(SdbDevice(devId, devName, devType))
-
- if len(connDevices) > 0:
- self._updateConnDevice(connDevices)
- return True
- else:
- self._resetDevices()
- return False
-
-
-class SdbDevice:
- def __init__(self, devId, devName, devType):
- self.devId = devId
- self.devName = devName
- self.devType = devType
-
- def _printDevInfo(self):
- pass
-
- def getDeviceId(self):
- return self.devId
-
- def getDeviceName(self):
- return self.devName
-
- def getDeviceType(self):
- return self.devType
+++ /dev/null
-# fMBT, free Model Based Testing tool
-# Copyright (c) 2013, Intel Corporation.
-#
-# This program is free software; you can redistribute it and/or modify it
-# under the terms and conditions of the GNU Lesser General Public License,
-# version 2.1, as published by the Free Software Foundation.
-#
-# This program is distributed in the hope it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
-# more details.
-#
-# You should have received a copy of the GNU Lesser General Public License along with
-# this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
-
-import base64
-import cPickle
-import ctypes
-import fcntl
-import glob
-import os
-import platform
-import re
-import shlex
-import shutil
-import string
-import struct
-import subprocess
-import sys
-import termios
-import time
-import zlib
-
-import fmbtuinput
-
-fmbtuinput.refreshDeviceInfo()
-
-if "--debug" in sys.argv:
- g_debug = True
-else:
- g_debug = False
-
-try:
- _opt_keyboard = [a.split("=")[1] \
- for a in sys.argv if a.startswith("--keyboard=")][0]
-except IndexError:
- _opt_keyboard = None
-
-try:
- _opt_touch = [a.split("=")[1] \
- for a in sys.argv if a.startswith("--touch=")][0]
-except IndexError:
- _opt_touch = None
-
-try:
- _opt_mouse = [a.split("=")[1] \
- for a in sys.argv if a.startswith("--mouse=")][0]
-except IndexError:
- _opt_mouse = None
-
-keyboard_device = None
-touch_device = None
-mouse_device = None
-
-
-def openKeyboardDevice(keyboardSpec=None):
- keyboard_device = None
- if keyboardSpec == None:
- try:
- keyboard_device = openKeyboardDevice("sysrq")
- except IndexError:
- keyboard_device = openKeyboardDevice("virtual")
- elif keyboardSpec in (None, "virtual"):
- keyboard_device = fmbtuinput.Keyboard().create()
- elif keyboardSpec.startswith("file:"):
- keyboard_device = fmbtuinput.Keyboard().open(keyboardSpec.split(":",1)[1])
- elif keyboardSpec == "sysrq":
- keyboard_device = fmbtuinput.Keyboard().open(
- "/dev/input/" + re.findall(
- '[ =](event[0-9]+)\s',
- [i for i in devices.split("\n\n") if "sysrq" in i.lower()][0])[0])
- elif keyboardSpec == "disabled":
- keyboard_device = None
- return keyboard_device
-
-
-def openTouchDevice(touchSpec=None, fallback=None):
- touch_device = None
- if touchSpec == None:
- if fallback != None:
- return openTouchDevice(fallback)
- else:
- pass # will return None
- elif touchSpec.startswith("virtual"):
- inputResolution=re.findall("virtual:([0-9]*)x([0-9]*)", touchSpec)
- if inputResolution:
- maxX = int(inputResolution[0][0])
- maxY = int(inputResolution[0][1])
- else:
- maxX, maxY = None, None
- touch_device = fmbtuinput.Touch().create(maxX=maxX, maxY=maxY)
- elif touchSpec.startswith("file:") or touchSpec.startswith("name:"):
- touch_device = fmbtuinput.Touch().open(touchSpec.split(":",1)[1])
- elif touchSpec == "disabled":
- pass # will return None
- else:
- raise ValueError('invalid touch device "%s"' % (touchSpec,))
- return touch_device
-
-
-def openMouseDevice(mouseSpec=None, fallback=None):
- mouse_device = None
- if mouseSpec == None:
- if fallback != None:
- return openMouseDevice(fallback)
- else:
- pass # will return None
- elif mouseSpec.startswith("virtual:"):
- abs_or_rel = mouseSpec.split(":",1)[1]
- if abs_or_rel == "abs":
- absoluteMove = True
- elif abs_or_rel == "rel":
- absoluteMove = False
- else:
- raise ValueError('invalid mouse "%s"' % (mouseSpec,))
- mouse_device = fmbtuinput.Mouse(absoluteMove=absoluteMove).create()
- elif mouseSpec.startswith("file:") or mouseSpec.startswith("name:"):
- mouse_device = fmbtuinput.Mouse().open(mouseSpec.split(":",1)[1])
- elif mouseSpec == "disabled":
- pass # will return None
- else:
- raise ValueError('invalid mouse device "%s"' % (mouseSpec,))
- return mouse_device
-
-
-def debug(msg):
- if g_debug:
- sys.stdout.write("debug: %s\n" % (msg,))
- sys.stdout.flush()
-
-
-def error(msg, exitstatus=1):
- sys.stdout.write("fmbttizen-agent: %s\n" % (msg,))
- sys.stdout.flush()
- sys.exit(exitstatus)
-
-
-iAmRoot = (os.getuid() == 0)
-
-try:
- libc = ctypes.CDLL("libc.so.6")
- libX11 = ctypes.CDLL("libX11.so.6")
- libXtst = ctypes.CDLL("libXtst.so.6")
- g_Xavailable = True
- g_keyb = None # no need for virtual keyboard
-except OSError:
- g_Xavailable = False
-
-if g_Xavailable:
- class XImage(ctypes.Structure):
- _fields_ = [
- ('width' , ctypes.c_int),
- ('height' , ctypes.c_int),
- ('xoffset' , ctypes.c_int),
- ('format' , ctypes.c_int),
- ('data' , ctypes.c_void_p),
- ('byte_order' , ctypes.c_int),
- ('bitmap_unit' , ctypes.c_int),
- ('bitmap_bit_order' , ctypes.c_int),
- ('bitmap_pad' , ctypes.c_int),
- ('depth' , ctypes.c_int),
- ('bytes_per_line' , ctypes.c_int),
- ('bits_per_pixel' , ctypes.c_int)]
-
- libc.write.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_size_t]
- libX11.XAllPlanes.restype = ctypes.c_ulong
- libX11.XGetImage.restype = ctypes.POINTER(XImage)
- libX11.XRootWindow.restype = ctypes.c_uint32
- libX11.XOpenDisplay.restype = ctypes.c_void_p
- libX11.XDefaultScreen.restype = ctypes.c_int
- libX11.XGetKeyboardMapping.restype = ctypes.POINTER(ctypes.c_uint32)
-
- # X11 constants, see Xlib.h
-
- X_CurrentTime = ctypes.c_ulong(0)
- X_False = ctypes.c_int(0)
- X_NULL = ctypes.c_void_p(0)
- X_True = ctypes.c_int(1)
- X_ZPixmap = ctypes.c_int(2)
- NoSymbol = 0
-
-# InputKeys contains key names known to input devices, see
-# linux/input.h or http://www.usb.org/developers/hidpage. The order is
-# significant, because keyCode = InputKeys.index(keyName).
-InputKeys = [
- "RESERVED", "ESC","1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
- "MINUS", "EQUAL", "BACKSPACE", "TAB",
- "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P",
- "LEFTBRACE", "RIGHTBRACE", "ENTER", "LEFTCTRL",
- "A", "S", "D", "F", "G", "H", "J", "K", "L",
- "SEMICOLON", "APOSTROPHE", "GRAVE", "LEFTSHIFT", "BACKSLASH",
- "Z", "X", "C", "V", "B", "N", "M",
- "COMMA", "DOT", "SLASH", "RIGHTSHIFT", "KPASTERISK", "LEFTALT",
- "SPACE", "CAPSLOCK",
- "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10",
- "NUMLOCK", "SCROLLLOCK",
- "KP7", "KP8", "KP9", "KPMINUS",
- "KP4", "KP5", "KP6", "KPPLUS",
- "KP1", "KP2", "KP3", "KP0", "KPDOT",
- "undefined0",
- "ZENKAKUHANKAKU", "102ND", "F11", "F12", "RO",
- "KATAKANA", "HIRAGANA", "HENKAN", "KATAKANAHIRAGANA", "MUHENKAN",
- "KPJPCOMMA", "KPENTER", "RIGHTCTRL", "KPSLASH", "SYSRQ", "RIGHTALT",
- "LINEFEED", "HOME", "UP", "PAGEUP", "LEFT", "RIGHT", "END", "DOWN",
- "PAGEDOWN", "INSERT", "DELETE", "MACRO",
- "MUTE", "VOLUMEDOWN", "VOLUMEUP",
- "POWER",
- "KPEQUAL", "KPPLUSMINUS", "PAUSE", "SCALE", "KPCOMMA", "HANGEUL",
- "HANGUEL", "HANJA", "YEN", "LEFTMETA", "RIGHTMETA", "COMPOSE"]
-
-_inputKeyNameToCode={}
-for c, n in enumerate(InputKeys):
- _inputKeyNameToCode[n] = c
-
-# See struct input_event in /usr/include/linux/input.h
-if platform.architecture()[0] == "32bit":
- _input_event = 'IIHHi'
-else:
- _input_event = 'QQHHi'
-
-# Event and keycodes are in input.h, too.
-_EV_KEY = 0x01
-_EV_ABS = 0x03
-_ABS_X = 0x00
-_ABS_Y = 0x01
-_ABS_MT_SLOT = 0x2f
-_ABS_MT_POSITION_X = 0x35
-_ABS_MT_POSITION_Y = 0x36
-_ABS_MT_TRACKING_ID = 0x39
-
-_BTN_MOUSE = 0x110
-
-# Set input device names (in /proc/bus/input/devices)
-# for pressing hardware keys.
-try:
- cpuinfo = file("/proc/cpuinfo").read()
-except:
- cpuinfo = ""
-
-def readDeviceInfo():
- global devices
- try:
- devices = file("/proc/bus/input/devices").read()
- except:
- devices = ""
-
-readDeviceInfo()
-kbInputDevFd = None
-
-if iAmRoot:
- debug("hardware detection uses generic defaults")
- # Unknown platform, guessing best possible defaults for devices
- _d = devices.split("\n\n")
- try:
- power_devname = re.findall('Name=\"([^"]*)\"', [i for i in _d if "power" in i.lower()][0])[0]
- except IndexError:
- power_devname = "gpio-keys"
-
- touch_device = None
- try:
- touch_device_f = "file:/dev/input/" + re.findall('[ =](event[0-9]+)\s', [i for i in _d if "touch" in i.lower()][0])[0]
- except IndexError:
- touch_device_f = None
- touch_device = openTouchDevice(_opt_touch, touch_device_f)
-
- mouse_device = None
- try:
- mouse_device_f = "file:/dev/input/" + re.findall('[ =](event[0-9]+)\s', [i for i in _d if "Mouse" in i][0])[0]
- except IndexError:
- mouse_device_f = None
- mouse_device = openMouseDevice(_opt_mouse, mouse_device_f)
-
- keyboard_device = openKeyboardDevice(_opt_keyboard)
-
- hwKeyDevice = {
- "POWER": power_devname,
- "VOLUMEUP": "gpio-keys",
- "VOLUMEDOWN": "gpio-keys",
- "HOME": "gpio-keys"
- }
-
- if isinstance(mouse_device, fmbtuinput.Mouse):
- time.sleep(1)
- mouse_device.move(-4096, -4096)
- mouse_device.setXY(0, 0)
-
- del _d
-
-if iAmRoot and g_debug:
- debug("touch device: %s" % (touch_device,))
- debug("mouse device: %s" % (mouse_device,))
- debug("keyb device: %s" % (keyboard_device,))
-
-if iAmRoot and _opt_keyboard and "keyboard_device" not in globals():
- # Use forced keyboard with any hardware type
- keyboard_device = openKeyboardDevice(_opt_keyboard)
-
-if "touch_device" in globals() and touch_device:
- mtInputDevFd = touch_device._fd
-
-if "keyboard_device" in globals() and keyboard_device:
- kbInputDevFd = keyboard_device._fd
-
-
-# Read input devices
-deviceToEventFile = {}
-for _l in devices.splitlines():
- if _l.startswith('N: Name="'): _device = _l.split('"')[1]
- elif _l.startswith("H: Handlers=") and "event" in _l:
- try: deviceToEventFile[_device] = "/dev/input/" + re.findall("(event[0-9]+)", _l)[0]
- except Exception, e: pass
-
-screenWidth = None
-screenHeight = None
-
-# Connect to X server, get root window size for screenshots
-display = None
-if g_Xavailable:
- def resetXConnection():
- global display, current_screen, root_window, X_AllPlanes
- if display != None:
- libX11.XCloseDisplay(display)
- display = libX11.XOpenDisplay(X_NULL)
- if display == 0 or display == None:
- error("cannot connect to X server")
- current_screen = libX11.XDefaultScreen(display)
- root_window = libX11.XRootWindow(display, current_screen)
- X_AllPlanes = libX11.XAllPlanes()
- resetXConnection()
-
- ref = ctypes.byref
- __rw = ctypes.c_uint(0)
- __x = ctypes.c_int(0)
- __y = ctypes.c_int(0)
- root_width = ctypes.c_uint(0)
- root_height = ctypes.c_uint(0)
- __bwidth = ctypes.c_uint(0)
- root_depth = ctypes.c_uint(0)
-
- libX11.XGetGeometry(display, root_window, ref(__rw), ref(__x), ref(__y),
- ref(root_width), ref(root_height), ref(__bwidth),
- ref(root_depth))
-
- cMinKeycode = ctypes.c_int(0)
- cMaxKeycode = ctypes.c_int(0)
- cKeysymsPerKeycode = ctypes.c_int(0)
- libX11.XDisplayKeycodes(display, ref(cMinKeycode), ref(cMaxKeycode))
- keysyms = libX11.XGetKeyboardMapping(display,
- cMinKeycode,
- (cMaxKeycode.value - cMinKeycode.value) + 1,
- ref(cKeysymsPerKeycode))
- shiftModifier = libX11.XKeysymToKeycode(display, libX11.XStringToKeysym("Shift_R"))
-
- screenWidth = root_width.value
- screenHeight = root_height.value
-
-def read_cmd():
- return sys.stdin.readline().strip()
-
-def _encode(obj):
- return base64.b64encode(cPickle.dumps(obj))
-
-def _decode(string):
- return cPickle.loads(base64.b64decode(string))
-
-def write_response(ok, value):
- if ok: p = "FMBTAGENT OK "
- else: p = "FMBTAGENT ERROR "
- if not g_debug:
- response = "%s%s\n" % (p, _encode(value))
- else:
- response = "%s%s\n" % (p, value)
- sys.stdout.write(response)
- sys.stdout.flush()
-
-def sendHwTap(x, y, button):
- try:
- if touch_device:
- touch_device.tap(x, y)
- else:
- mouse_device.tap(x, y, button)
- return True, None
- except Exception, e:
- return False, str(e)
-
-def sendHwMove(x, y):
- try:
- if touch_device:
- touch_device.move(x, y)
- else:
- mouse_device.move(x, y)
- return True, None
- except Exception, e:
- return False, str(e)
-
-def sendRelMove(x, y):
- try:
- mouse_device.setXY(0,0)
- mouse_device.move(x, y)
- mouse_device.setXY(0,0)
- return True, None
- except Exception, e:
- return False, str(e)
-
-def sendHwFingerDown(x, y, button):
- try:
- if touch_device:
- touch_device.pressFinger(button, x, y)
- else:
- mouse_device.move(x, y)
- mouse_device.press(button)
- return True, None
- except Exception, e:
- return False, str(e)
-
-def sendHwFingerUp(x, y, button):
- try:
- if touch_device:
- touch_device.releaseFinger(button)
- else:
- mouse_device.move(x, y)
- mouse_device.release(button)
- return True, None
- except Exception, e:
- return False, str(e)
-
-def sendHwKey(keyName, delayBeforePress, delayBeforeRelease):
- keyName = keyName.upper()
- if keyName.startswith("KEY_"):
- keyName = keyName.lstrip("KEY_")
- fd = None
- closeFd = False
- try:
- # Explicit IO device defined for the key?
- inputDevice = deviceToEventFile[hwKeyDevice[keyName]]
- except:
- # Fall back to giving input with keyboard - given that there is one
- if not kbInputDevFd:
- return False, 'No input device for key "%s"' % (keyName,)
- fd = kbInputDevFd
- try: keyCode = _inputKeyNameToCode[keyName]
- except KeyError:
- try: keyCode = fmbtuinput.toKeyCode(keyName)
- except ValueError: return False, 'No keycode for key "%s"' % (keyName,)
- try:
- if not fd:
- fd = os.open(inputDevice, os.O_WRONLY | os.O_NONBLOCK)
- closeFd = True
- except: return False, 'Unable to open input device "%s" for writing' % (inputDevice,)
- if delayBeforePress > 0: time.sleep(delayBeforePress)
- if delayBeforePress >= 0:
- if os.write(fd, struct.pack(_input_event, int(time.time()), 0, _EV_KEY, keyCode, 1)) > 0:
- os.write(fd, struct.pack(_input_event, 0, 0, 0, 0, 0))
- if delayBeforeRelease > 0: time.sleep(delayBeforeRelease)
- if delayBeforeRelease >= 0:
- if os.write(fd, struct.pack(_input_event, int(time.time()), 0, _EV_KEY, keyCode, 0)) > 0:
- os.write(fd, struct.pack(_input_event, 0, 0, 0, 0, 0))
- if closeFd:
- os.close(fd)
- return True, None
-
-def specialCharToXString(c):
- c2s = {'\n': "Return",
- ' ': "space", '!': "exclam", '"': "quotedbl",
- '#': "numbersign", '$': "dollar", '%': "percent",
- '&': "ampersand", "'": "apostrophe",
- '(': "parenleft", ')': "parenright", '*': "asterisk",
- '+': "plus", '-': "minus", '.': "period", '/': "slash",
- ':': "colon", ';': "semicolon", '<': "less", '=': "equal",
- '>': "greater", '?': "question", '@': "at",
- '_': "underscore"}
- return c2s.get(c, c)
-
-def specialCharToUsKeys(c):
- # character -> ([modifier, [modifier...]] keycode)
- c2s = {'\n': ("KEY_ENTER",),
- ' ': ("KEY_SPACE",),
- '`': ("KEY_GRAVE",), '~': ("KEY_LEFTSHIFT", "KEY_GRAVE"),
- '!': ("KEY_LEFTSHIFT", "KEY_1"),
- '@': ("KEY_LEFTSHIFT", "KEY_2"),
- '#': ("KEY_LEFTSHIFT", "KEY_3"),
- '$': ("KEY_LEFTSHIFT", "KEY_4"),
- '%': ("KEY_LEFTSHIFT", "KEY_5"),
- '^': ("KEY_LEFTSHIFT", "KEY_6"),
- '&': ("KEY_LEFTSHIFT", "KEY_7"),
- '*': ("KEY_LEFTSHIFT", "KEY_8"),
- '(': ("KEY_LEFTSHIFT", "KEY_9"),
- ')': ("KEY_LEFTSHIFT", "KEY_0"),
- '-': ("KEY_MINUS",), '_': ("KEY_LEFTSHIFT", "KEY_MINUS"),
- '=': ("KEY_EQUAL",), '+': ("KEY_LEFTSHIFT", "KEY_EQUAL"),
- '\t': ("KEY_TAB",),
- '[': ("KEY_LEFTBRACE",), '{': ("KEY_LEFTSHIFT", "KEY_LEFTBRACE"),
- ']': ("KEY_RIGHTBRACE",), '}': ("KEY_LEFTSHIFT", "KEY_RIGHTBRACE"),
- ';': ("KEY_SEMICOLON",), ':': ("KEY_LEFTSHIFT", "KEY_SEMICOLON"),
- "'": ("KEY_APOSTROPHE",), '"': ("KEY_LEFTSHIFT", "KEY_APOSTROPHE"),
- '\\': ("KEY_BACKSLASH",), '|': ("KEY_LEFTSHIFT", "KEY_BACKSLASH"),
- ',': ("KEY_COMMA",), '<': ("KEY_LEFTSHIFT", "KEY_COMMA"),
- '.': ("KEY_DOT",), '>': ("KEY_LEFTSHIFT", "KEY_DOT"),
- '/': ("KEY_SLASH",), '?': ("KEY_LEFTSHIFT", "KEY_SLASH"),
- }
- return c2s.get(c, c)
-
-mtEvents = {} # slot -> (tracking_id, x, y)
-
-def inputEventSend(inputDevFd, eventType, event, param):
- t = time.time()
- tsec = int(t)
- tusec = int(1000000*(t-tsec))
- os.write(inputDevFd, struct.pack(_input_event,
- tsec, tusec, eventType, event, param))
-
-def mtEventSend(eventType, event, param):
- """multitouch device event"""
- return inputEventSend(mtInputDevFd, eventType, event, param)
-
-def mtGestureStart(x, y):
- mtGestureStart.trackingId += 1
- trackingId = mtGestureStart.trackingId
-
- for freeSlot in xrange(16):
- if not freeSlot in mtEvents: break
- else: raise ValueError("No free multitouch event slots available")
-
- mtEvents[freeSlot] = [trackingId, x, y]
-
- mtEventSend(_EV_ABS, _ABS_MT_SLOT, freeSlot)
- mtEventSend(_EV_ABS, _ABS_MT_TRACKING_ID, trackingId)
- mtEventSend(_EV_ABS, _ABS_MT_POSITION_X, x)
- mtEventSend(_EV_ABS, _ABS_MT_POSITION_Y, y)
- mtEventSend(_EV_ABS, _ABS_X, x)
- mtEventSend(_EV_ABS, _ABS_Y, y)
- mtEventSend(0, 0, 0) # SYNC
- return freeSlot
-mtGestureStart.trackingId = 0
-
-def mtGestureMove(slot, x, y):
- if x == mtEvents[slot][1] and y == mtEvents[slot][2]: return
- mtEventSend(_EV_ABS, _ABS_MT_SLOT, slot)
- mtEventSend(_EV_ABS, _ABS_MT_TRACKING_ID, mtEvents[slot][0])
- if x != mtEvents[slot][1] and 0 <= x <= root_width:
- mtEventSend(_EV_ABS, _ABS_MT_POSITION_X, x)
- mtEvents[slot][1] = x
- if y != mtEvents[slot][2] and 0 <= y <= root_height:
- mtEventSend(_EV_ABS, _ABS_MT_POSITION_Y, y)
- mtEvents[slot][2] = y
- if 0 <= x <= root_width:
- mtEventSend(_EV_ABS, _ABS_X, x)
- if 0 <= y <= root_height:
- mtEventSend(_EV_ABS, _ABS_Y, y)
- mtEventSend(0, 0, 0)
-
-def mtGestureEnd(slot):
- mtEventSend(_EV_ABS, _ABS_MT_SLOT, slot)
- mtEventSend(_EV_ABS, _ABS_MT_TRACKING_ID, -1)
- mtEventSend(0, 0, 0) # SYNC
- del mtEvents[slot]
-
-def mtLinearGesture(listOfStartEndPoints, duration, movePoints, sleepBeforeMove=0, sleepAfterMove=0):
- # listOfStartEndPoints: [ [(finger1startX, finger1startY), (finger1endX, finger1endY)],
- # [(finger2startX, finger2startY), (finger2endX, finger2endY)], ...]
- startPoints = [startEnd[0] for startEnd in listOfStartEndPoints]
- xDist = [startEnd[1][0] - startEnd[0][0] for startEnd in listOfStartEndPoints]
- yDist = [startEnd[1][1] - startEnd[0][1] for startEnd in listOfStartEndPoints]
- movePointsF = float(movePoints)
- fingers = []
- for (x, y) in startPoints:
- fingers.append(mtGestureStart(x, y))
-
- if sleepBeforeMove > 0: time.sleep(sleepBeforeMove)
-
- if movePoints > 0:
- intermediateSleep = float(duration) / movePoints
- for i in xrange(1, movePoints + 1):
- if intermediateSleep > 0:
- time.sleep(intermediateSleep)
- for fingerIndex, finger in enumerate(fingers):
- mtGestureMove(finger,
- startPoints[fingerIndex][0] + int(xDist[fingerIndex]*i/movePointsF),
- startPoints[fingerIndex][1] + int(yDist[fingerIndex]*i/movePointsF))
-
- if sleepAfterMove > 0: time.sleep(sleepAfterMove)
-
- for finger in fingers:
- mtGestureEnd(finger)
- return True, None
-
-def typeCharX(origChar):
- modifiers = []
- c = specialCharToXString(origChar)
- keysym = libX11.XStringToKeysym(c)
- if keysym == NoSymbol:
- return False
- keycode = libX11.XKeysymToKeycode(display, keysym)
-
- first = (keycode - cMinKeycode.value) * cKeysymsPerKeycode.value
-
- try:
- if chr(keysyms[first + 1]) == origChar:
- modifiers.append(shiftModifier)
- except ValueError: pass
-
- for m in modifiers:
- libXtst.XTestFakeKeyEvent(display, m, X_True, X_CurrentTime)
-
- libXtst.XTestFakeKeyEvent(display, keycode, X_True, X_CurrentTime)
- libXtst.XTestFakeKeyEvent(display, keycode, X_False, X_CurrentTime)
-
- for m in modifiers[::-1]:
- libXtst.XTestFakeKeyEvent(display, m, X_False, X_CurrentTime)
- return True
-
-def typeCharHw(origChar):
- for c in origChar:
- modifiers = []
- keyCode = None
- c = specialCharToUsKeys(c)
- if isinstance(c, tuple):
- modifiers = c[:-1]
- keyCode = c[-1]
- elif c in string.uppercase:
- modifiers = ["KEY_LEFTSHIFT"]
- keyCode = "KEY_" + c
- elif c in string.lowercase or c in string.digits:
- keyCode = "KEY_" + c.upper()
- else:
- # do not know how to type the character
- pass
- if keyCode:
- for m in modifiers:
- keyboard_device.press(m)
- keyboard_device.tap(keyCode)
- for m in modifiers[::-1]:
- keyboard_device.release(m)
- return True
-
-if g_Xavailable:
- typeChar = typeCharX
-else:
- typeChar = typeCharHw
-
-def typeSequence(s, delayBetweenChars=0):
- skipped = []
- for c in s:
- if not typeChar(c):
- skipped.append(c)
- if delayBetweenChars != 0:
- time.sleep(delayBetweenChars)
- if skipped: return False, skipped
- else: return True, skipped
-
-def takeScreenshotOnX():
- image_p = libX11.XGetImage(display, root_window,
- 0, 0, root_width, root_height,
- X_AllPlanes, X_ZPixmap)
- image = image_p[0]
- # FMBTRAWX11 image format header:
- # FMBTRAWX11 [width] [height] [color depth] [bits per pixel]<linefeed>
- # Binary data
- rawfmbt_header = "FMBTRAWX11 %d %d %d %d\n" % (
- image.width, image.height, root_depth.value, image.bits_per_pixel)
- rawfmbt_data = ctypes.string_at(image.data, image.height * image.bytes_per_line)
- compressed_image = rawfmbt_header + zlib.compress(rawfmbt_data, 3)
- libX11.XDestroyImage(image_p)
- return True, compressed_image
-
-def westonTakeScreenshotRoot(retry=2):
- if westonTakeScreenshotRoot.ssFilenames == None:
- westonTakeScreenshotRoot.ssFilenames = findWestonScreenshotFilenames()
- if not westonTakeScreenshotRoot.ssFilenames:
- return False, "cannot find weston screenshot directory"
- try:
- for ssFilename in westonTakeScreenshotRoot.ssFilenames:
- if os.access(ssFilename, os.R_OK):
- os.remove(ssFilename)
- keyboard_device.press("KEY_LEFTMETA")
- keyboard_device.tap("s")
- keyboard_device.release("KEY_LEFTMETA")
- time.sleep(0.5)
- # find which screenshot file got created?
- for ssFilename in westonTakeScreenshotRoot.ssFilenames:
- if os.access(ssFilename, os.R_OK):
- break
- else:
- if retry > 0:
- return westonTakeScreenshotRoot(retry-1)
- else:
- return False, "weston did not create any of files %s" % (
- westonTakeScreenshotRoot.ssFilenames,)
- # wait for the screenshot writer to finish
- writerPid = fuser(ssFilename)
- if writerPid != None:
- time.sleep(0.1)
- while fuser(ssFilename, [writerPid]) != None:
- time.sleep(0.1)
- shutil.move(ssFilename, "/tmp/screenshot.png")
- os.chmod("/tmp/screenshot.png", 0666)
- except Exception, e:
- return False, str(e)
- return True, None
-westonTakeScreenshotRoot.ssFilenames = None
-
-def takeScreenshotOnWeston():
- if iAmRoot:
- rv, status = westonTakeScreenshotRoot()
- else:
- rv, status = subAgentCommand("root", "tizen", "ss weston-root")
- if rv == False:
- return rv, status
- return True, file("/tmp/screenshot.png").read()
-
-def fuser(filename, usualSuspects=None):
- """Returns the pid of a user of given file, or None"""
- filepath = os.path.realpath(filename)
- if not os.access(filepath, os.R_OK):
- raise ValueError('No such file: "%s"' % (filename,))
- if usualSuspects == None:
- procFds = glob.glob("/proc/[1-9][0-9][0-9]*/fd/*")
- else:
- procFds = []
- for pid in usualSuspects:
- procFds.extend(glob.glob("/proc/%s/fd/*" % (pid,)))
- for symlink in procFds:
- try:
- if os.path.realpath(symlink) == filepath:
- return int(symlink.split('/')[2])
- except OSError:
- pass
-
-def findWestonScreenshotFilenames():
- # find weston cwd
- dirs = []
- for exe in glob.glob("/proc/[1-9][0-9][0-9]*/exe"):
- try:
- if os.path.realpath(exe) == "/usr/bin/weston":
- dirs.append(os.path.realpath(os.path.dirname(exe) + "/cwd"))
- except OSError:
- pass
- return [d + "/wayland-screenshot.png" for d in sorted(set(dirs))]
-
-if g_Xavailable:
- takeScreenshot = takeScreenshotOnX
-else:
- takeScreenshot = takeScreenshotOnWeston
-
-def shellSOE(command, asyncStatus, asyncOut, asyncError, usePty):
- if usePty:
- command = '''python -c "import pty; pty.spawn(%s)" ''' % (repr(shlex.split(command)),),
- if (asyncStatus, asyncOut, asyncError) != (None, None, None):
- # prepare for decoupled asynchronous execution
- if asyncStatus == None: asyncStatus = "/dev/null"
- if asyncOut == None: asyncOut = "/dev/null"
- if asyncError == None: asyncError = "/dev/null"
- try:
- stdinFile = file("/dev/null", "r")
- stdoutFile = file(asyncOut, "a+")
- stderrFile = file(asyncError, "a+", 0)
- statusFile = file(asyncStatus, "a+")
- except IOError, e:
- return False, (None, None, e)
- try:
- if os.fork() > 0:
- # parent returns after successful fork, there no
- # direct visibility to async child process beyond this
- # point.
- stdinFile.close()
- stdoutFile.close()
- stderrFile.close()
- statusFile.close()
- return True, (0, None, None) # async parent finishes here
- except OSError, e:
- return False, (None, None, e)
- os.setsid()
- else:
- stdinFile = subprocess.PIPE
- stdoutFile = subprocess.PIPE
- stderrFile = subprocess.PIPE
- try:
- p = subprocess.Popen(command, shell=True,
- stdin=stdinFile,
- stdout=stdoutFile,
- stderr=stderrFile,
- close_fds=True)
- except Exception, e:
- return False, (None, None, e)
- if asyncStatus == None and asyncOut == None and asyncError == None:
- # synchronous execution, read stdout and stderr
- out, err = p.communicate()
- else:
- # asynchronous execution, store status to file
- statusFile.write(str(p.wait()) + "\n")
- statusFile.close()
- out, err = None, None
- sys.exit(0) # async child finishes here
- return True, (p.returncode, out, err)
-
-def waitOutput(nonblockingFd, acceptedOutputs, timeout, pollInterval=0.1):
- start = time.time()
- endTime = start + timeout
- s = ""
- try: s += nonblockingFd.read()
- except IOError: pass
- foundOutputs = [ao for ao in acceptedOutputs if ao in s]
- while len(foundOutputs) == 0 and time.time() < endTime:
- time.sleep(pollInterval)
- try: s += nonblockingFd.read()
- except IOError: pass
- foundOutputs = [ao for ao in acceptedOutputs if ao in s]
- return foundOutputs, s
-
-_subAgents = {}
-def openSubAgent(username, password):
- p = subprocess.Popen('''python -c 'import pty; pty.spawn(["su", "-c", "python /tmp/fmbttizen-agent.py --sub-agent", "-", "%s"])' ''' % (username,),
- shell=True,
- stdin=subprocess.PIPE,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE)
-
- # Read in non-blocking mode to ensure agent starts correctly
- fl = fcntl.fcntl(p.stdout.fileno(), fcntl.F_GETFL)
- fcntl.fcntl(p.stdout.fileno(), fcntl.F_SETFL, fl | os.O_NONBLOCK)
-
- output2 = ""
- seenPrompts, output1 = waitOutput(p.stdout, ["Password:", "FMBTAGENT"], 5.0)
- if "Password:" in seenPrompts:
- p.stdin.write(password + "\r")
- output1 = ""
- seenPrompts, output2 = waitOutput(p.stdout, ["FMBTAGENT"], 5.0)
-
- if not "FMBTAGENT" in seenPrompts:
- p.terminate()
- return (None, 'fMBT agent with username "%s" does not answer.' % (username,),
- output1 + output2)
-
- # Agent is alive, continue in blocking mode
- fcntl.fcntl(p.stdout.fileno(), fcntl.F_SETFL, fl)
-
- return p, "", ""
-
-def subAgentCommand(username, password, cmd):
- if not username in _subAgents:
- process, output, error = openSubAgent(username, password)
- if process == None:
- return None, (-1, output, error)
- else:
- _subAgents[username] = process
- p = _subAgents[username]
- p.stdin.write(cmd + "\r")
- p.stdin.flush()
- answer = p.stdout.readline().rstrip()
- if answer.startswith("FMBTAGENT OK "):
- return True, _decode(answer[len("FMBTAGENT OK "):])
- else:
- return False, _decode(answer[len("FMBTAGENT ERROR "):])
-
-def closeSubAgents():
- for username in _subAgents:
- subAgentCommand(username, None, "quit")
-
-if __name__ == "__main__":
- try:
- origTermAttrs = termios.tcgetattr(sys.stdin.fileno())
- hasTerminal = True
- except termios.error:
- origTermAttrs = None
- hasTerminal = False
- if hasTerminal and not "--keep-echo" in sys.argv and not "--debug" in sys.argv:
- # Disable terminal echo
- newTermAttrs = origTermAttrs
- newTermAttrs[3] = origTermAttrs[3] & ~termios.ECHO
- termios.tcsetattr(sys.stdin.fileno(), termios.TCSANOW, newTermAttrs)
-
- if "--no-x" in sys.argv:
- debug("X disabled")
- g_Xavailable = False
-
- platformInfo = {}
- platformInfo["input devices"] = fmbtuinput._g_deviceNames.keys()
-
- # Send version number, enter main loop
- write_response(True, platformInfo)
- cmd = read_cmd()
- while cmd:
- if cmd.startswith("bl "): # set display backlight time
- if iAmRoot:
- timeout = int(cmd[3:].strip())
- try:
- file("/opt/var/kdb/db/setting/lcd_backlight_normal","wb").write(struct.pack("ii",0x29,timeout))
- write_response(True, None)
- except Exception, e: write_response(False, e)
- else:
- write_response(*subAgentCommand("root", "tizen", cmd))
- elif cmd.startswith("er "): # event recorder
- if iAmRoot:
- cmd, arg = cmd.split(" ", 1)
- if arg.startswith("start "):
- filterOpts = _decode(arg.split()[1])
- if touch_device:
- filterOpts["touchScreen"] = touch_device
- fmbtuinput.startQueueingEvents(filterOpts)
- write_response(True, None)
- elif arg == "stop":
- events = fmbtuinput.stopQueueingEvents()
- write_response(True, None)
- elif arg == "fetch":
- events = fmbtuinput.fetchQueuedEvents()
- write_response(True, events)
- else:
- write_response(*subAgentCommand("root", "tizen", cmd))
- elif cmd.startswith("gd"): # get display status
- try:
- p = subprocess.Popen(['/usr/bin/xset', 'q'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- out, err = p.communicate()
- if "Monitor is Off" in out: write_response(True, "Off")
- elif "Monitor is On" in out: write_response(True, "On")
- else: write_response(False, err)
- except Exception, e: write_response(False, e)
- elif cmd.startswith("tm "): # touch move(x, y)
- xs, ys = cmd[3:].strip().split()
- if g_Xavailable:
- libXtst.XTestFakeMotionEvent(display, current_screen, int(xs), int(ys), X_CurrentTime)
- libX11.XFlush(display)
- else:
- if iAmRoot: rv, msg = sendHwMove(int(xs), int(ys))
- else: rv, msg = subAgentCommand("root", "tizen", cmd)
- write_response(True, None)
- elif cmd.startswith("tr "): # relative move(x, y)
- xd, yd = cmd[3:].strip().split()
- if iAmRoot: rv, msg = sendRelMove(int(xd), int(yd))
- else: rv, msg = subAgentCommand("root", "tizen", cmd)
- write_response(True, None)
- elif cmd.startswith("tt "): # touch tap(x, y, button)
- x, y, button = [int(i) for i in cmd[3:].strip().split()]
- if g_Xavailable:
- libXtst.XTestFakeMotionEvent(display, current_screen, x, y, X_CurrentTime)
- libXtst.XTestFakeButtonEvent(display, button, X_True, X_CurrentTime)
- libXtst.XTestFakeButtonEvent(display, button, X_False, X_CurrentTime)
- libX11.XFlush(display)
- rv, msg = True, None
- else:
- if iAmRoot: rv, msg = sendHwTap(x, y, button-1)
- else: rv, msg = subAgentCommand("root", "tizen", cmd)
- write_response(rv, msg)
- elif cmd.startswith("td "): # touch down(x, y, button)
- xs, ys, button = cmd[3:].strip().split()
- button = int(button)
- if g_Xavailable:
- libXtst.XTestFakeMotionEvent(display, current_screen, int(xs), int(ys), X_CurrentTime)
- libXtst.XTestFakeButtonEvent(display, button, X_True, X_CurrentTime)
- libX11.XFlush(display)
- else:
- if iAmRoot: rv, msg = sendHwFingerDown(int(xs), int(ys), button-1)
- else: rv, msg = subAgentCommand("root", "tizen", cmd)
- write_response(True, None)
- elif cmd.startswith("tu "): # touch up(x, y, button)
- xs, ys, button = cmd[3:].strip().split()
- button = int(button)
- if g_Xavailable:
- libXtst.XTestFakeMotionEvent(display, current_screen, int(xs), int(ys), X_CurrentTime)
- libXtst.XTestFakeButtonEvent(display, button, X_False, X_CurrentTime)
- libX11.XFlush(display)
- else:
- if iAmRoot: rv, msg = sendHwFingerUp(int(xs), int(ys), button-1)
- else: rv, msg = subAgentCommand("root", "tizen", cmd)
- write_response(True, None)
- elif cmd.startswith("kd "): # hw key down
- if iAmRoot: rv, msg = sendHwKey(cmd[3:], 0, -1)
- else: rv, msg = subAgentCommand("root", "tizen", cmd)
- write_response(rv, msg)
- elif cmd.startswith("kn"): # list input key names
- if "hwKeyDevice" in globals():
- hk = hwKeyDevice.keys()
- else:
- hk = []
- if "keyboard_device" in globals():
- ik = InputKeys
- else:
- ik = []
- write_response(True, sorted(ik + hk))
- elif cmd.startswith("kp "): # hw key press
- if iAmRoot: rv, msg = sendHwKey(cmd[3:], 0, 0)
- else: rv, msg = subAgentCommand("root", "tizen", cmd)
- write_response(rv, msg)
- elif cmd.startswith("ku "): # hw key up
- if iAmRoot: rv, msg = sendHwKey(cmd[3:], -1, 0)
- else: rv, msg = subAgentCommand("root", "tizen", cmd)
- write_response(rv, msg)
- elif cmd.startswith("kt "): # send x events
- if g_Xavailable:
- rv, skippedSymbols = typeSequence(_decode(cmd[3:]))
- libX11.XFlush(display)
- elif iAmRoot:
- rv, skippedSymbols = typeSequence(_decode(cmd[3:]),
- delayBetweenChars=0.05)
- else:
- rv, skippedSymbols = subAgentCommand("root", "tizen", cmd)
- write_response(rv, skippedSymbols)
- elif cmd.startswith("ml "): # send multitouch linear gesture
- if iAmRoot:
- rv, _ = mtLinearGesture(*_decode(cmd[3:]))
- else:
- rv, _ = subAgentCommand("root", "tizen", cmd)
- write_response(rv, _)
- elif cmd.startswith("ss"): # save screenshot
- if "R" in cmd.split() and g_Xavailable:
- resetXConnection()
- if "weston-root" in cmd.split(): # do Weston root part only
- write_response(*westonTakeScreenshotRoot())
- else:
- rv, compressedImage = takeScreenshot()
- write_response(rv, compressedImage)
- elif cmd.startswith("sd "): # set screen dimensions (width and height)
- _sw, _sh = cmd[3:].split()
- screenWidth, screenHeight = int(_sw), int(_sh)
- if iAmRoot:
- if touch_device:
- touch_device.setScreenSize((screenWidth, screenHeight))
- rv, msg = True, None
- else:
- rv, msg = True, "no touch device"
- else:
- rv, msg = subAgentCommand("root", "tizen", cmd)
- write_response(rv, msg)
- elif cmd.startswith("sa "): # set screenshot rotation angle (degrees)
- if iAmRoot:
- if touch_device:
- _sa = int(cmd[3:])
- # compensate it with opposite rotation
- touch_device.setScreenAngle(-_sa)
- rv, msg = True, None
- else:
- rv, msg = True, "no touch device"
- else:
- rv, msg = subAgentCommand("root", "tizen", cmd)
- write_response(rv, msg)
- elif cmd.startswith("es "): # execute shell
- shellCmd, username, password, asyncStatus, asyncOut, asyncError, usePty = _decode(cmd[3:])
- if username == "":
- rv, soe = shellSOE(shellCmd, asyncStatus, asyncOut, asyncError, usePty)
- else:
- rv, soe = subAgentCommand(username, password,
- "es " + _encode((shellCmd, "", "", asyncStatus, asyncOut, asyncError, usePty)))
- write_response(rv, soe)
- elif cmd.startswith("quit"): # quit
- write_response(rv, True)
- break
- else:
- write_response(False, 'Unknown command: "%s"' % (cmd,))
- cmd = read_cmd()
-
- closeSubAgents()
-
- if g_Xavailable:
- libX11.XCloseDisplay(display)
-
- if hasTerminal:
- termios.tcsetattr(sys.stdin.fileno(), termios.TCSANOW, origTermAttrs)
+++ /dev/null
-# fMBT, free Model Based Testing tool
-# Copyright (c) 2013, Intel Corporation.
-#
-# This program is free software; you can redistribute it and/or modify it
-# under the terms and conditions of the GNU Lesser General Public License,
-# version 2.1, as published by the Free Software Foundation.
-#
-# This program is distributed in the hope it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
-# License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St - Fifth Floor, Boston, MA
-# 02110-1301 USA.
-
-# pylint: disable = C0103, C0111, R0913
-
-"""
-This library offers Python interface for Linux uinput system.
-
-Mouse, Touch and Keyboard classes can be used for
-creating new mouse, touch and keyboard devices and synthesizing user
-inputs through those devices.
-"""
-
-cmdline_usage = """
-Usage: python fmbtuinput.py -p <list-of-input-device-files>
-
-Example: python fmbtuinput.py -p /dev/input/event*
-"""
-
-import array
-import glob
-import os
-import platform
-import re
-import struct
-import thread
-import time
-import Queue
-
-if os.name != "nt":
- import fcntl
-else:
- class fcntl:
- def __getattr__(self, attr):
- raise NotImplementedError("%s not available on Windows" % (attr,))
-
-# See /usr/include/linux/input.h
-eventTypes = {
- "EV_SYN": 0x00,
- "EV_KEY": 0x01,
- "EV_REL": 0x02,
- "EV_ABS": 0x03,
- "EV_MSC": 0x04,
- "EV_SW": 0x05,
- "EV_LED": 0x11,
- "EV_SND": 0x12,
- "EV_REP": 0x14,
- "EV_FF": 0x15,
- "EV_PWR": 0x16,
- "EV_FF_STATUS": 0x17,
- "EV_MAX": 0x1f,
- }
-
-keyCodes = {
- "KEY_RESERVED": 0,
- "KEY_ESC": 1,
- "KEY_1": 2,
- "KEY_2": 3,
- "KEY_3": 4,
- "KEY_4": 5,
- "KEY_5": 6,
- "KEY_6": 7,
- "KEY_7": 8,
- "KEY_8": 9,
- "KEY_9": 10,
- "KEY_0": 11,
- "KEY_MINUS": 12,
- "KEY_EQUAL": 13,
- "KEY_BACKSPACE": 14,
- "KEY_TAB": 15,
- "KEY_Q": 16,
- "KEY_W": 17,
- "KEY_E": 18,
- "KEY_R": 19,
- "KEY_T": 20,
- "KEY_Y": 21,
- "KEY_U": 22,
- "KEY_I": 23,
- "KEY_O": 24,
- "KEY_P": 25,
- "KEY_LEFTBRACE": 26,
- "KEY_RIGHTBRACE": 27,
- "KEY_ENTER": 28,
- "KEY_LEFTCTRL": 29,
- "KEY_A": 30,
- "KEY_S": 31,
- "KEY_D": 32,
- "KEY_F": 33,
- "KEY_G": 34,
- "KEY_H": 35,
- "KEY_J": 36,
- "KEY_K": 37,
- "KEY_L": 38,
- "KEY_SEMICOLON": 39,
- "KEY_APOSTROPHE": 40,
- "KEY_GRAVE": 41,
- "KEY_LEFTSHIFT": 42,
- "KEY_BACKSLASH": 43,
- "KEY_Z": 44,
- "KEY_X": 45,
- "KEY_C": 46,
- "KEY_V": 47,
- "KEY_B": 48,
- "KEY_N": 49,
- "KEY_M": 50,
- "KEY_COMMA": 51,
- "KEY_DOT": 52,
- "KEY_SLASH": 53,
- "KEY_RIGHTSHIFT": 54,
- "KEY_KPASTERISK": 55,
- "KEY_LEFTALT": 56,
- "KEY_SPACE": 57,
- "KEY_CAPSLOCK": 58,
- "KEY_F1": 59,
- "KEY_F2": 60,
- "KEY_F3": 61,
- "KEY_F4": 62,
- "KEY_F5": 63,
- "KEY_F6": 64,
- "KEY_F7": 65,
- "KEY_F8": 66,
- "KEY_F9": 67,
- "KEY_F10": 68,
- "KEY_NUMLOCK": 69,
- "KEY_SCROLLLOCK": 70,
- "KEY_KP7": 71,
- "KEY_KP8": 72,
- "KEY_KP9": 73,
- "KEY_KPMINUS": 74,
- "KEY_KP4": 75,
- "KEY_KP5": 76,
- "KEY_KP6": 77,
- "KEY_KPPLUS": 78,
- "KEY_KP1": 79,
- "KEY_KP2": 80,
- "KEY_KP3": 81,
- "KEY_KP0": 82,
- "KEY_KPDOT": 83,
-
- "KEY_ZENKAKUHANKAKU": 85,
- "KEY_102ND": 86,
- "KEY_F11": 87,
- "KEY_F12": 88,
- "KEY_RO": 89,
- "KEY_KATAKANA": 90,
- "KEY_HIRAGANA": 91,
- "KEY_HENKAN": 92,
- "KEY_KATAKANAHIRAGANA": 93,
- "KEY_MUHENKAN": 94,
- "KEY_KPJPCOMMA": 95,
- "KEY_KPENTER": 96,
- "KEY_RIGHTCTRL": 97,
- "KEY_KPSLASH": 98,
- "KEY_SYSRQ": 99,
- "KEY_RIGHTALT": 100,
- "KEY_LINEFEED": 101,
- "KEY_HOME": 102,
- "KEY_UP": 103,
- "KEY_PAGEUP": 104,
- "KEY_LEFT": 105,
- "KEY_RIGHT": 106,
- "KEY_END": 107,
- "KEY_DOWN": 108,
- "KEY_PAGEDOWN": 109,
- "KEY_INSERT": 110,
- "KEY_DELETE": 111,
- "KEY_MACRO": 112,
- "KEY_MUTE": 113,
- "KEY_VOLUMEDOWN": 114,
- "KEY_VOLUMEUP": 115,
- "KEY_POWER": 116,
- "KEY_KPEQUAL": 117,
- "KEY_KPPLUSMINUS": 118,
- "KEY_PAUSE": 119,
- "KEY_SCALE": 120,
-
- "KEY_KPCOMMA": 121,
- "KEY_HANGEUL": 122,
- "KEY_HANJA": 123,
- "KEY_YEN": 124,
- "KEY_LEFTMETA": 125,
- "KEY_RIGHTMETA": 126,
- "KEY_COMPOSE": 127,
-
- "KEY_STOP": 128,
- "KEY_AGAIN": 129,
- "KEY_PROPS": 130,
- "KEY_UNDO": 131,
- "KEY_FRONT": 132,
- "KEY_COPY": 133,
- "KEY_OPEN": 134,
- "KEY_PASTE": 135,
- "KEY_FIND": 136,
- "KEY_CUT": 137,
- "KEY_HELP": 138,
- "KEY_MENU": 139,
- "KEY_CALC": 140,
- "KEY_SETUP": 141,
- "KEY_SLEEP": 142,
- "KEY_WAKEUP": 143,
- "KEY_FILE": 144,
- "KEY_SENDFILE": 145,
- "KEY_DELETEFILE": 146,
- "KEY_XFER": 147,
- "KEY_PROG1": 148,
- "KEY_PROG2": 149,
- "KEY_WWW": 150,
- "KEY_MSDOS": 151,
- "KEY_COFFEE": 152,
- "KEY_DIRECTION": 153,
- "KEY_CYCLEWINDOWS": 154,
- "KEY_MAIL": 155,
- "KEY_BOOKMARKS": 156,
- "KEY_COMPUTER": 157,
- "KEY_BACK": 158,
- "KEY_FORWARD": 159,
- "KEY_CLOSECD": 160,
- "KEY_EJECTCD": 161,
- "KEY_EJECTCLOSECD": 162,
- "KEY_NEXTSONG": 163,
- "KEY_PLAYPAUSE": 164,
- "KEY_PREVIOUSSONG": 165,
- "KEY_STOPCD": 166,
- "KEY_RECORD": 167,
- "KEY_REWIND": 168,
- "KEY_PHONE": 169,
- "KEY_ISO": 170,
- "KEY_CONFIG": 171,
- "KEY_HOMEPAGE": 172,
- "KEY_REFRESH": 173,
- "KEY_EXIT": 174,
- "KEY_MOVE": 175,
- "KEY_EDIT": 176,
- "KEY_SCROLLUP": 177,
- "KEY_SCROLLDOWN": 178,
- "KEY_KPLEFTPAREN": 179,
- "KEY_KPRIGHTPAREN": 180,
- "KEY_NEW": 181,
- "KEY_REDO": 182,
-
- "KEY_F13": 183,
- "KEY_F14": 184,
- "KEY_F15": 185,
- "KEY_F16": 186,
- "KEY_F17": 187,
- "KEY_F18": 188,
- "KEY_F19": 189,
- "KEY_F20": 190,
- "KEY_F21": 191,
- "KEY_F22": 192,
- "KEY_F23": 193,
- "KEY_F24": 194,
-
- "KEY_PLAYCD": 200,
- "KEY_PAUSECD": 201,
- "KEY_PROG3": 202,
- "KEY_PROG4": 203,
- "KEY_DASHBOARD": 204,
- "KEY_SUSPEND": 205,
- "KEY_CLOSE": 206,
- "KEY_PLAY": 207,
- "KEY_FASTFORWARD": 208,
- "KEY_BASSBOOST": 209,
- "KEY_PRINT": 210,
- "KEY_HP": 211,
- "KEY_CAMERA": 212,
- "KEY_SOUND": 213,
- "KEY_QUESTION": 214,
- "KEY_EMAIL": 215,
- "KEY_CHAT": 216,
- "KEY_SEARCH": 217,
- "KEY_CONNECT": 218,
- "KEY_FINANCE": 219,
- "KEY_SPORT": 220,
- "KEY_SHOP": 221,
- "KEY_ALTERASE": 222,
- "KEY_CANCEL": 223,
- "KEY_BRIGHTNESSDOWN": 224,
- "KEY_BRIGHTNESSUP": 225,
- "KEY_MEDIA": 226,
-
- "KEY_SWITCHVIDEOMODE": 227,
-
- "KEY_KBDILLUMTOGGLE": 228,
- "KEY_KBDILLUMDOWN": 229,
- "KEY_KBDILLUMUP": 230,
-
- "KEY_SEND": 231,
- "KEY_REPLY": 232,
- "KEY_FORWARDMAIL": 233,
- "KEY_SAVE": 234,
- "KEY_DOCUMENTS": 235,
-
- "KEY_BATTERY": 236,
-
- "KEY_BLUETOOTH": 237,
- "KEY_WLAN": 238,
- "KEY_UWB": 239,
-
- "KEY_UNKNOWN": 240,
-
- "KEY_VIDEO_NEXT": 241,
- "KEY_VIDEO_PREV": 242,
- "KEY_BRIGHTNESS_CYCLE": 243,
- "KEY_BRIGHTNESS_ZERO": 244,
- "KEY_DISPLAY_OFF": 245,
-
- "KEY_WIMAX": 246,
- "KEY_RFKILL": 247,
-
- "KEY_MICMUTE": 248,
-
- "BTN_MISC": 0x100,
- "BTN_0": 0x100,
- "BTN_1": 0x101,
- "BTN_2": 0x102,
- "BTN_3": 0x103,
- "BTN_4": 0x104,
- "BTN_5": 0x105,
- "BTN_6": 0x106,
- "BTN_7": 0x107,
- "BTN_8": 0x108,
- "BTN_9": 0x109,
-
- "BTN_MOUSE": 0x110,
- "BTN_LEFT": 0x110,
- "BTN_RIGHT": 0x111,
- "BTN_MIDDLE": 0x112,
- "BTN_SIDE": 0x113,
- "BTN_EXTRA": 0x114,
- "BTN_FORWARD": 0x115,
- "BTN_BACK": 0x116,
- "BTN_TASK": 0x117,
-
- "BTN_JOYSTICK": 0x120,
- "BTN_TRIGGER": 0x120,
- "BTN_THUMB": 0x121,
- "BTN_THUMB2": 0x122,
- "BTN_TOP": 0x123,
- "BTN_TOP2": 0x124,
- "BTN_PINKIE": 0x125,
- "BTN_BASE": 0x126,
- "BTN_BASE2": 0x127,
- "BTN_BASE3": 0x128,
- "BTN_BASE4": 0x129,
- "BTN_BASE5": 0x12a,
- "BTN_BASE6": 0x12b,
- "BTN_DEAD": 0x12f,
-
- "BTN_GAMEPAD": 0x130,
- "BTN_A": 0x130,
- "BTN_B": 0x131,
- "BTN_C": 0x132,
- "BTN_X": 0x133,
- "BTN_Y": 0x134,
- "BTN_Z": 0x135,
- "BTN_TL": 0x136,
- "BTN_TR": 0x137,
- "BTN_TL2": 0x138,
- "BTN_TR2": 0x139,
- "BTN_SELECT": 0x13a,
- "BTN_START": 0x13b,
- "BTN_MODE": 0x13c,
- "BTN_THUMBL": 0x13d,
- "BTN_THUMBR": 0x13e,
-
- "BTN_DIGI": 0x140,
- "BTN_TOOL_PEN": 0x140,
- "BTN_TOOL_RUBBER": 0x141,
- "BTN_TOOL_BRUSH": 0x142,
- "BTN_TOOL_PENCIL": 0x143,
- "BTN_TOOL_AIRBRUSH": 0x144,
- "BTN_TOOL_FINGER": 0x145,
- "BTN_TOOL_MOUSE": 0x146,
- "BTN_TOOL_LENS": 0x147,
- "BTN_TOOL_QUINTTAP": 0x148,
- "BTN_TOUCH": 0x14a,
- "BTN_STYLUS": 0x14b,
- "BTN_STYLUS2": 0x14c,
- "BTN_TOOL_DOUBLETAP": 0x14d,
- "BTN_TOOL_TRIPLETAP": 0x14e,
- "BTN_TOOL_QUADTAP": 0x14f,
-
- "BTN_WHEEL": 0x150,
- "BTN_GEAR_DOWN": 0x150,
- "BTN_GEAR_UP": 0x151,
- }
-
-relCodes = {
- "REL_X": 0x00,
- "REL_Y": 0x01,
- "REL_Z": 0x02,
- "REL_RX": 0x03,
- "REL_RY": 0x04,
- "REL_RZ": 0x05,
- "REL_HWHEEL": 0x06,
- "REL_DIAL": 0x07,
- "REL_WHEEL": 0x08,
- "REL_MISC": 0x09,
- "REL_MAX": 0x0f,
- }
-
-absCodes = {
- "ABS_X": 0x00,
- "ABS_Y": 0x01,
- "ABS_Z": 0x02,
- "ABS_RX": 0x03,
- "ABS_RY": 0x04,
- "ABS_RZ": 0x05,
- "ABS_THROTTLE": 0x06,
- "ABS_RUDDER": 0x07,
- "ABS_WHEEL": 0x08,
- "ABS_GAS": 0x09,
- "ABS_BRAKE": 0x0a,
- "ABS_HAT0X": 0x10,
- "ABS_HAT0Y": 0x11,
- "ABS_HAT1X": 0x12,
- "ABS_HAT1Y": 0x13,
- "ABS_HAT2X": 0x14,
- "ABS_HAT2Y": 0x15,
- "ABS_HAT3X": 0x16,
- "ABS_HAT3Y": 0x17,
- "ABS_PRESSURE": 0x18,
- "ABS_DISTANCE": 0x19,
- "ABS_TILT_X": 0x1a,
- "ABS_TILT_Y": 0x1b,
- "ABS_TOOL_WIDTH": 0x1c,
-
- "ABS_VOLUME": 0x20,
-
- "ABS_MISC": 0x28,
-
- "ABS_MT_SLOT": 0x2f,
- "ABS_MT_TOUCH_MAJOR": 0x30,
- "ABS_MT_TOUCH_MINOR": 0x31,
- "ABS_MT_WIDTH_MAJOR": 0x32,
- "ABS_MT_WIDTH_MINOR": 0x33,
- "ABS_MT_ORIENTATION": 0x34,
- "ABS_MT_POSITION_X": 0x35,
- "ABS_MT_POSITION_Y": 0x36,
- "ABS_MT_TOOL_TYPE": 0x37,
- "ABS_MT_BLOB_ID": 0x38,
- "ABS_MT_TRACKING_ID": 0x39,
- "ABS_MT_PRESSURE": 0x3a,
- "ABS_MT_DISTANCE": 0x3b,
-
- "ABS_MAX": 0x3f,
- }
-
-mscCodes = {
- "MSC_SERIAL": 0x00,
- "MSC_PULSELED": 0x01,
- "MSC_GESTURE": 0x02,
- "MSC_RAW": 0x03,
- "MSC_SCAN": 0x04,
- "MSC_TIMESTAMP": 0x05,
- "MSC_MAX": 0x07,
- "MSC_CNT": 0x08,
-}
-
-abs_count = absCodes['ABS_MAX'] + 1
-
-event_codetables = {
- eventTypes["EV_SYN"]: {},
- eventTypes["EV_KEY"]: keyCodes,
- eventTypes["EV_REL"]: relCodes,
- eventTypes["EV_ABS"]: absCodes,
-}
-
-BUS_PCI = 0x01
-BUS_ISAPNP = 0x02
-BUS_USB = 0x03
-BUS_HIL = 0x04
-BUS_BLUETOOTH = 0x05
-BUS_VIRTUAL = 0x06
-
-# See struct input_event in /usr/include/linux/input.h
-if platform.architecture()[0] == "32bit":
- struct_timeval = "II"
-else:
- struct_timeval = "QQ"
-
-struct_input_event = struct_timeval + 'HHi'
-sizeof_input_event = struct.calcsize(struct_input_event)
-
-struct_input_id = 'HHHH'
-struct_uinput_user_dev = ('80s' +
- struct_input_id +
- 'i' +
- str(abs_count) + 'i' +
- str(abs_count) + 'i' +
- str(abs_count) + 'i' +
- str(abs_count) + 'i')
-sizeof_uinput_user_dev = struct.calcsize(struct_uinput_user_dev)
-
-struct_input_absinfo = 'iiii'
-
-# asm-generic/ioctl.h:
-IOC_NRBITS = 8
-IOC_TYPEBITS = 8
-IOC_SIZEBITS = 14
-IOC_DIRBITS = 2
-
-IOC_NRSHIFT = 0
-IOC_TYPESHIFT = IOC_NRSHIFT + IOC_NRBITS
-IOC_SIZESHIFT = IOC_TYPESHIFT + IOC_TYPEBITS
-IOC_DIRSHIFT = IOC_SIZESHIFT + IOC_SIZEBITS
-
-IOC_NONE = 0
-IOC_WRITE = 1
-IOC_READ = 2
-
-def IOC(dir_, type_, nr, size):
- return ((dir_ << IOC_DIRSHIFT) |
- (type_ << IOC_TYPESHIFT) |
- (nr << IOC_NRSHIFT) |
- (size << IOC_SIZESHIFT))
-def IO(type_, nr):
- return IOC(IOC_NONE, type_, nr, 0)
-def IOR(type_, nr, size):
- return IOC(IOC_READ, type_, nr, struct.calcsize(size))
-def IOW(type_, nr, size):
- return IOC(IOC_WRITE, type_, nr, struct.calcsize(size))
-def EVIOCGABS(abs):
- return IOR(ord('E'), 0x40 + (abs), struct_input_absinfo)
-
-UINPUT_IOCTL_BASE = ord('U')
-UI_DEV_CREATE = IO(UINPUT_IOCTL_BASE, 1)
-UI_DEV_DESTROY = IO(UINPUT_IOCTL_BASE, 2)
-
-UI_SET_EVBIT = IOW(UINPUT_IOCTL_BASE, 100, 'i')
-UI_SET_KEYBIT = IOW(UINPUT_IOCTL_BASE, 101, 'i')
-UI_SET_RELBIT = IOW(UINPUT_IOCTL_BASE, 102, 'i')
-UI_SET_ABSBIT = IOW(UINPUT_IOCTL_BASE, 103, 'i')
-
-# inverse lookup tables for event/key/rel/abs codes
-eventTypesInv = {}
-keyCodesInv = {}
-relCodesInv = {}
-absCodesInv = {}
-for d in ["eventTypes", "keyCodes",
- "relCodes", "absCodes"]:
- globals()[d + "Inv"] = dict([(v, k) for k, v in globals()[d].iteritems()])
-
-def toKeyCode(keyCodeOrName):
- if isinstance(keyCodeOrName, int):
- return keyCodeOrName
- elif keyCodeOrName in keyCodes:
- return keyCodes[keyCodeOrName]
- elif keyCodeOrName.upper() in keyCodes:
- return keyCodes[keyCodeOrName.upper(keyCodeOrName)]
- elif ("KEY_" + keyCodeOrName.upper()) in keyCodes:
- return keyCodes["KEY_" + keyCodeOrName.upper()]
- else:
- raise ValueError('Invalid keycode "%s"' % (keyCodeOrName,))
-
-def toKeyName(keyCode):
- if keyCode in keyCodesInv:
- return keyCodesInv[keyCode]
- else:
- raise ValueError('Invalid keycode "%s"' % (keyCode,))
-
-def toButtonCode(buttonCodeOrName):
- if isinstance(buttonCodeOrName, str):
- buttonCode = toKeyCode(buttonCodeOrName)
- elif buttonCodeOrName < 0xf:
- buttonCode = keyCodes["BTN_MOUSE"] + buttonCodeOrName
- else:
- buttonCode = buttonCodeOrName
- return buttonCode
-
-def refreshDeviceInfo():
- global _g_devices
- global _g_deviceNames
- global _g_filenames
- _g_devices = file("/proc/bus/input/devices").read().split("\n\n")
- _g_deviceNames = {}
- _g_filenames = {}
- for d in _g_devices:
- if d.strip() == "":
- continue
- _name = [line.split('"')[1] for line in d.split('\n')
- if line.startswith('N: ')][0]
- _g_deviceNames[_name] = ("/dev/input/" +
- re.findall('[ =](event[0-9]+)\s', d)[0])
- _g_filenames[_g_deviceNames[_name]] = _name
-
-def toEventFilename(deviceName):
- return _g_deviceNames[deviceName]
-
-def toEventDeviceName(filename):
- return _g_filenames[filename]
-
-class InputDevice(object):
- def __init__(self):
- if not "_g_devices" in globals():
- refreshDeviceInfo()
- self._fd = -1
- self._filename = None
- self._uidev = None
- self._created = False
- self._opened = False
- self._name = None
-
- def __del__(self):
- if self._created:
- self.destroy()
-
- def __str__(self):
- return "%s(name=%s, filename=%s, created=%s, opened=%s, fd=%s)" % (
- self.__class__.__name__,
- repr(self._name),
- repr(self._filename),
- repr(self._created),
- repr(self._opened),
- repr(self._fd))
-
- def startCreating(self, name, vendor, product, version,
- absmin=None, absmax=None):
- if self._fd > 0:
- raise InputDeviceError("InputDevice is already open")
- self._fd = os.open("/dev/uinput", os.O_WRONLY | os.O_NONBLOCK)
- if absmin == None:
- absmin = [0 for _ in xrange(abs_count)]
- if absmax == None:
- absmax = [0 for _ in xrange(abs_count)]
- absfuzz = [0 for _ in xrange(abs_count)]
- absflat = [0 for _ in xrange(abs_count)]
- self._name = name
- self._uidev = struct.pack(struct_uinput_user_dev,
- name, # name
- BUS_USB, # id.bus_type
- vendor, # id.vendor
- product, # id.product
- version, # id.version
- 0, # ff_effects_max
- # TODO: why absmin + absmax gives
- # error for touch?
- *(absmax + absmin + absfuzz + absflat)
- )
-
- def finishCreating(self):
- if self._fd < 1:
- raise InputDeviceError("startCreating() not called")
- bytes_written = os.write(self._fd, self._uidev)
- if bytes_written != sizeof_uinput_user_dev:
- raise InputDeviceError(
- "Writing to /dev/uinput failed, wrote %s/%s bytes"
- % (bytes_written, sizeof_uinput_user_dev))
- rv = fcntl.ioctl(self._fd, UI_DEV_CREATE)
- if rv != 0:
- raise InputDeviceError(
- "Creating device failed, ioctl UI_DEV_CREATE returned %s"
- % (rv,))
- self._created = True
- return True
-
- def destroy(self):
- if self._created:
- fcntl.ioctl(self._fd, UI_DEV_DESTROY)
- self._created = False
- self.close()
-
- def open(self, filename):
- if self._fd > 0:
- raise InputDeviceError("InputDevice is already open")
- if not filename.startswith("/dev/input"):
- filename = toEventFilename(filename)
- self._fd = os.open(filename, os.O_WRONLY | os.O_NONBLOCK)
- self._filename = filename
- self._created = False
- self._name = toEventDeviceName(self._filename)
- return self
-
- def close(self):
- if self._fd > 0:
- os.close(self._fd)
- self._fd = -1
-
- def filename(self):
- return self._filename
-
- def addCap(self, capBit, capCodeOrName, capCode2Name):
- if self._fd < 1:
- raise InputDeviceError("startCreating() not called")
- if self._created or self._opened:
- raise InputDeviceError("Cannot add capabilities after creation")
- if isinstance(capCodeOrName, int):
- capCode = capCodeOrName
- elif capCodeOrName in capCode2Name:
- capCode = capCode2Name[capCodeOrName]
- else:
- raise InputDeviceError('Unknown name "%s"' % (capCodeOrName,))
- return fcntl.ioctl(self._fd, capBit, capCode)
-
- def addEvent(self, eventCodeOrName):
- return self.addCap(UI_SET_EVBIT, eventCodeOrName, eventTypes)
-
- def addKey(self, keyCodeOrName):
- return self.addCap(UI_SET_KEYBIT, keyCodeOrName, keyCodes)
-
- def addRel(self, relCodeOrName):
- return self.addCap(UI_SET_RELBIT, relCodeOrName, relCodes)
-
- def addAbs(self, absCodeOrName):
- return self.addCap(UI_SET_ABSBIT, absCodeOrName, absCodes)
-
- def send(self, type_, code, value):
- if self._fd < 1:
- raise InputDeviceError("InputDevice is not open")
- if isinstance(type_, str):
- typeCode = eventTypes[type_]
- else:
- typeCode = type_
- if isinstance(code, str):
- codeCode = event_codetables[typeCode][code]
- else:
- codeCode = code
- return sendInputEvent(self._fd, typeCode, codeCode, value)
-
- def sync(self):
- if self._fd < 1:
- raise InputDeviceError("InputDevice is not open")
- return sendInputSync(self._fd)
-
-class InputDeviceError(Exception):
- pass
-
-class Mouse(InputDevice):
- def __init__(self, absoluteMove=False):
- """
- Parameters:
-
- absoluteMove (boolean, optional)
- force move(x,y) to send absolute coordinates instead
- of standard relative movement. This helps avoiding
- mouse pointer drift in some occasions. The default
- is False.
- """
- InputDevice.__init__(self)
- self._x = 0
- self._y = 0
- self._sendAbs = absoluteMove
-
- def create(self, name="Virtual fMBT Mouse",
- vendor=0xf4b7, product=0x4053, version=1):
-
- self.startCreating(name, vendor, product, version)
- self.addEvent("EV_KEY")
- self.addEvent("EV_REL")
- if self._sendAbs:
- self.addEvent("EV_ABS")
- self.addEvent("EV_SYN")
- self.addRel("REL_X")
- self.addRel("REL_Y")
- self.addRel("REL_HWHEEL")
- self.addRel("REL_WHEEL")
- self.addKey("BTN_LEFT")
- self.addKey("BTN_RIGHT")
- self.addKey("BTN_MIDDLE")
- self.addKey("BTN_SIDE")
- self.addKey("BTN_EXTRA")
- self.addKey("BTN_FORWARD")
- self.addKey("BTN_BACK")
- self.addKey("BTN_TASK")
- if self._sendAbs:
- self.addAbs("ABS_X")
- self.addAbs("ABS_Y")
- self.finishCreating()
- return self
-
- def move(self, x, y):
- """
- Move mouse cursor to coordinates x, y.
- """
- if self._sendAbs:
- self.send("EV_ABS", "ABS_X", x)
- self.send("EV_ABS", "ABS_Y", y)
- else:
- deltaX = x - self._x
- deltaY = y - self._y
- self.send("EV_REL", "REL_X", deltaX)
- self.send("EV_REL", "REL_Y", deltaY)
- self.sync()
- self.setXY(x, y)
-
- def moveRel(self, deltaX, deltaY):
- self.send("EV_REL", "REL_X", deltaX)
- self.send("EV_REL", "REL_Y", deltaY)
- self.sync()
- self.setXY(self._x + deltaX, self._y + deltaY)
-
- def press(self, button):
- buttonCode = toButtonCode(button)
- self.send("EV_KEY", buttonCode, 1)
- self.sync()
-
- def release(self, button):
- buttonCode = toButtonCode(button)
- self.send("EV_KEY", buttonCode, 0)
- self.sync()
-
- def setXY(self, x, y):
- """
- Resets relative mouse position to (x, y), does not synthesize
- event. Example: disable possible mouse pointer drift:
-
- mouse.moveRel(-4096, -4096) # move to the top-left corner
- mouse.setXY(0, 0) # set current pointer coordinates to 0, 0
-
- After this, mouse.move(x, y) will synthesize relative mouse
- move event which will drive cursor to coordinates x, y.
- """
- self._x = x
- self._y = y
-
- def xy(self):
- return (self._x, self._y)
-
- def tap(self, x, y, button):
- self.move(x, y)
- self.press(button)
- self.release(button)
-
-class Touch(InputDevice):
- """
- Simulates touchpanel and touchpad
- """
- def __init__(self, maxX = None, maxY = None,
- screenWidth = None, screenHeight = None, screenAngle = None):
- InputDevice.__init__(self)
- self._maxX = maxX
- self._maxY = maxY
- self._screenW = screenWidth
- self._screenH = screenHeight
- self._screenA = screenAngle
- self._maxPressure = None
- self._multiTouch = True
- self._mtTrackingId = 0
- self._mtTracking = {}
- self._hoover = (0, 0)
-
- def create(self, name="Virtual fMBT Touch",
- vendor=0xf4b7, product=0x70c5, version=1,
- maxX=0xffff, maxY=0xffff, maxPressure=None,
- multiTouch = True):
- if maxX != None:
- self._maxX = maxX
- else:
- self._maxX = 0xffff
- if maxY != None:
- self._maxY = maxY
- else:
- self._maxY = 0xffff
- absmin = [0 for _ in xrange(abs_count)]
- absmax = [0 for _ in xrange(abs_count)]
- absmax[absCodes["ABS_X"]] = self._maxX
- absmax[absCodes["ABS_Y"]] = self._maxY
- if maxPressure != None:
- self._maxPressure = maxPressure
- absmax[absCodes["ABS_PRESSURE"]] = self._maxPressure
- absmax[absCodes["ABS_MT_SLOT"]] = 16
- absmax[absCodes["ABS_MT_TRACKING_ID"]] = 0x0fffffff
- absmax[absCodes["ABS_MT_POSITION_X"]] = self._maxX
- absmax[absCodes["ABS_MT_POSITION_Y"]] = self._maxY
- self._multiTouch = multiTouch
-
- self.startCreating(name, vendor, product, version,
- absmin=absmin, absmax=absmax)
- self.addEvent("EV_KEY")
- self.addEvent("EV_ABS")
- self.addEvent("EV_SYN")
- self.addKey("BTN_TOUCH")
- self.addAbs("ABS_X")
- self.addAbs("ABS_Y")
- if self._maxPressure != None:
- self.addAbs("ABS_PRESSURE")
- if self._multiTouch:
- self.addAbs("ABS_MT_SLOT")
- self.addAbs("ABS_MT_TRACKING_ID")
- self.addAbs("ABS_MT_POSITION_X")
- self.addAbs("ABS_MT_POSITION_Y")
- self.finishCreating()
- return self
-
- def open(self, filename):
- InputDevice.open(self, filename)
- # detect touch device capabilities and max values
- # nfo is struct input_absinfo
- nfo = array.array('i', range(6))
- fcntl.ioctl(self._fd, EVIOCGABS(absCodes["ABS_X"]), nfo, 1)
- self._maxX = nfo[2]
- fcntl.ioctl(self._fd, EVIOCGABS(absCodes["ABS_Y"]), nfo, 1)
- self._maxY = nfo[2]
- return self
-
- def setScreenSize(self, (width, height)):
- self._screenW, self._screenH = (width, height)
-
- def setScreenAngle(self, angle):
- self._screenA = angle
-
- def _angleXY(self, x, y, angle=None):
- """return x, y in screen without rotation"""
- if angle == None:
- angle = self._screenA
- sw, sh = self._screenW, self._screenH
- if angle:
- while angle < 0:
- angle += 360
- while angle > 360:
- angle -= 360
- if angle == 90:
- ax = self._screenH - y
- ay = x
- sw, sh = self._screenH, self._screenW
- elif angle == 180:
- ax = self._screenH - x
- ay = self._screenW - y
- elif angle == 270:
- ax = y
- ay = self._screenW - x
- sw, sh = self._screenH, self._screenW
- else:
- raise ValueError('Illegal screen rotation angle %s' %
- (self._screenA,))
- else:
- ax, ay = x, y
- return (sw, sh, ax, ay)
-
- def _tXY(self, x, y):
- """convert x, y to touch screen coordinates"""
- if self._screenW and self._maxX and self._screenH and self._maxY:
- w, h, x, y = self._angleXY(x, y)
- x = int((self._maxX * x) / w)
- y = int((self._maxY * y) / h)
- return (x, y)
- else:
- return (x, y)
-
- def absToScreenXY(self, absX, absY):
- if self._screenW and self._maxX and self._screenH and self._maxY:
- x = int(self._screenW * absX / self._maxX)
- y = int(self._screenH * absY / self._maxY)
- if self._screenA:
- _, _, x, y = self._angleXY(x, y, -self._screenA)
- return (x, y)
- else:
- return (absX, absY)
-
- def _startTracking(self, finger, x, y):
- self._mtTrackingId += 1
- usedSlots = set([self._mtTracking[fngr][0]
- for fngr in self._mtTracking])
- for freeSlot in xrange(16):
- if not freeSlot in usedSlots:
- break
- else:
- raise ValueError("No free slots for multitouch")
- self._mtTracking[finger] = [freeSlot, self._mtTrackingId, x, y]
- self._sendSlot(finger)
- self.send("EV_ABS", "ABS_MT_TRACKING_ID", self._mtTrackingId)
- tx, ty = self._tXY(x, y)
- self.send("EV_ABS", "ABS_MT_POSITION_X", tx)
- self.send("EV_ABS", "ABS_MT_POSITION_Y", ty)
- return self._mtTrackingId
-
- def _stopTracking(self, finger):
- self._sendSlot(finger)
- self.send("EV_ABS", "ABS_MT_TRACKING_ID", -1)
- del self._mtTracking[finger]
-
- def _sendSlot(self, finger):
- slot = self._mtTracking[finger][0]
- self.send("EV_ABS", "ABS_MT_SLOT", slot)
-
- def tap(self, x, y, pressure=None):
- self.pressFinger(-1, x, y, pressure)
- self.releaseFinger(-1)
-
- # Compatibility API to allow using a Touch almost like a Mouse
- def move(self, x, y):
- if len(self._mtTracking.keys()) == 0:
- self._hoover = (x, y)
- else:
- finger = sorted(self._mtTracking.keys())[0]
- return self.moveFinger(finger, x, y)
-
- def press(self, finger):
- return self.pressFinger(finger, *self._hoover)
-
- def release(self, finger):
- return self.releaseFinger(finger)
- # end of compatibility API
-
- # Multi-touch API
- def pressFinger(self, finger, x, y, pressure=None):
- """Add a finger to current multitouch gesture. If multitouch gesture
- is not started, it starts automatically.
- """
- if self._multiTouch and not finger in self._mtTracking:
- self._startTracking(finger, x, y)
- if pressure != None and self._maxPressure != None:
- self.send("EV_ABS", "ABS_PRESSURE", pressure)
- self.send("EV_KEY", "BTN_TOUCH", 1)
- tx, ty = self._tXY(x, y)
- self.send("EV_ABS", "ABS_X", tx)
- self.send("EV_ABS", "ABS_Y", ty)
- self.sync()
-
- def releaseFinger(self, finger):
- """Remove a finger from current multitouch gesture. When last finger
- is raised from the screen, multitouch gesture ends."""
- if self._multiTouch:
- self._stopTracking(finger)
- self.send("EV_KEY", "BTN_TOUCH", 0)
- for fngr in self._mtTracking:
- # still some finger pressed, non-multitouch reader gets
- # coordinates from one of those
- tx, ty = self._tXY(self._mtTracking[fngr][2],
- self._mtTracking[fngr][3])
- self.send("EV_ABS", "ABS_X", tx)
- self.send("EV_ABS", "ABS_Y", ty)
- break # only one coordinates will be sent.
- self.sync()
-
- def moveFinger(self, finger, x, y):
- """Move a finger in current multitouch gesture"""
- self._sendSlot(finger)
- tx, ty = self._tXY(x, y)
- if self._multiTouch:
- self.send("EV_ABS", "ABS_MT_POSITION_X", tx)
- self.send("EV_ABS", "ABS_MT_POSITION_Y", ty)
- self.send("EV_ABS", "ABS_X", tx)
- self.send("EV_ABS", "ABS_Y", ty)
- self._mtTracking[finger][2] = x # last X
- self._mtTracking[finger][3] = y # last Y
- self.sync()
-
-class Keyboard(InputDevice):
- def __init__(self):
- InputDevice.__init__(self)
-
- def create(self, name="Virtual fMBT Keyboard",
- vendor=0xf4b7, product=0x4ebd, version=1):
- self.startCreating(name, vendor, product, version)
- self.addEvent("EV_KEY")
- self.addEvent("EV_SYN")
- for keyName in keyCodes:
- if keyName.startswith("KEY_"):
- self.addKey(keyCodes[keyName])
- self.finishCreating()
- return self
-
- def press(self, keyCodeOrName):
- # TODO: there should be different MSC_SCAN matrix location for each key
- self.send("EV_MSC", mscCodes["MSC_SCAN"], 458793)
- self.send("EV_KEY", toKeyCode(keyCodeOrName), 1)
- self.sync()
-
- def release(self, keyCodeOrName):
- # TODO: there should be different MSC_SCAN matrix location for each key
- self.send("EV_MSC", mscCodes["MSC_SCAN"], 458793)
- self.send("EV_KEY", toKeyCode(keyCodeOrName), 0)
- self.sync()
-
- def tap(self, keyCodeOrName):
- keyCode = toKeyCode(keyCodeOrName)
- self.press(keyCode)
- self.release(keyCode)
-
-def sendInputSync(devFd):
- return sendInputEvent(devFd, 0, 0, 0)
-
-def sendInputEvent(devFd, type_, code, value):
- t = time.time()
- t_sec = int(t)
- t_usec = int(1000000*(t-t_sec))
- rv = os.write(devFd,
- struct.pack(struct_input_event,
- t_sec, t_usec,
- type_,
- code,
- value))
- return rv == sizeof_input_event
-
-def eventToString(inputEvent):
- tim, tus, typ, cod, val = struct.unpack(struct_input_event, inputEvent)
- styp = eventTypesInv.get(typ, "?")
- if styp == "EV_KEY":
- scod = keyCodesInv.get(cod, "?")
- elif styp == "EV_REL":
- scod = relCodesInv.get(cod, "?")
- elif styp == "EV_ABS":
- scod = absCodesInv.get(cod, "?")
- else:
- scod = "N/A"
- if typ == 0:
- return styp
- else:
- return "%8s.%s type: %4s (%5s), code: %5s (%15s) value: %8s" % \
- (tim, str(tus).zfill(6), typ, styp, cod, scod, val)
-
-def queueEventsFromFile(filename, queue, lock, filterOpts):
- if isinstance(filterOpts, dict) and "type" in filterOpts:
- allowedTypes = set()
- for t in filterOpts["type"]:
- if isinstance(t, str):
- allowedTypes.add(eventTypes[t])
- else:
- allowedTypes.add(t)
- else:
- allowedTypes = set(eventTypes.values())
- if ("touchScreen" in filterOpts and
- filename == filterOpts["touchScreen"].filename()):
- touchScreen = filterOpts["touchScreen"]
- absXCodes = set([absCodes["ABS_X"], absCodes["ABS_MT_POSITION_X"]])
- absYCodes = set([absCodes["ABS_Y"], absCodes["ABS_MT_POSITION_Y"]])
- absType = eventTypes["EV_ABS"]
- else:
- touchScreen = None
- fd = os.open(filename, os.O_RDONLY)
- try:
- while 1:
- eventData = os.read(fd, sizeof_input_event)
- if not lock.locked():
- return
- if not eventData:
- break
- (ts, tus, typ, cod, val) = struct.unpack(struct_input_event, eventData)
- if touchScreen and typ == absType:
- if cod in absXCodes:
- val, _ = touchScreen.absToScreenXY(val, 0)
- elif cod in absYCodes:
- _, val = touchScreen.absToScreenXY(0, val)
- if typ in allowedTypes:
- queue.put((ts, tus, typ, cod, val))
- finally:
- os.close(fd)
-
-# _g_recQL dictionary contains events being actively recorded
-# - key: filename, like "/dev/input/event0"
-# - value: (eventQueue, lock)
-# A thread is filling eventQueue with events from filename.
-# Once the lock is released, the thread will quit without writing
-# anything to the eventQueue anymore.
-_g_recQL = {}
-_g_unfetchedEvents = []
-def queueEventsFromFiles(listOfFilenames, filterOpts):
- global _g_recQL
- for filename in listOfFilenames:
- q = Queue.Queue()
- l = thread.allocate_lock()
- l.acquire()
- if filename in _g_recQL:
- # previous reader thread should quit
- _g_recQL[filename][1].release()
- thread.start_new_thread(
- queueEventsFromFile, (filename, q, l, filterOpts))
- _g_recQL[filename] = (q, l)
-
-def startQueueingEvents(filterOpts):
- refreshDeviceInfo()
- if len(_g_recQL) > 0:
- # already queueing, restart
- stopQueueingEvents()
- if "device" in filterOpts:
- deviceFiles = []
- for n in filterOpts["device"]:
- if n in _g_deviceNames:
- deviceFiles.append(_g_deviceNames[n])
- elif os.access(n, os.R_OK):
- deviceFiles.append(n)
- del filterOpts["device"]
- else:
- deviceFiles = glob.glob("/dev/input/event[0-9]*")
- queueEventsFromFiles(deviceFiles, filterOpts)
-
-def stopQueueingEvents():
- global _g_recQL
- global _g_unfetchedEvents
- for filename in _g_recQL:
- _g_recQL[filename][1].release()
- _g_unfetchedEvents = fetchQueuedEvents()
- _g_recQL = {}
-
-def fetchQueuedEvents():
- global _g_unfetchedEvents
- if len(_g_recQL) == 0: # no active recording
- rv = _g_unfetchedEvents
- _g_unfetchedEvents = []
- return rv
- else: # events are being recorded
- events = []
- for filename in _g_recQL:
- events.extend(fetchQueuedEventsFromFile(filename))
- return events
-
-def fetchQueuedEventsFromFile(filename):
- events = []
- q = _g_recQL[filename][0]
- deviceName = toEventDeviceName(filename)
- while 1:
- try:
- ts, tus, typ, cod, val = q.get_nowait()
- events.append((deviceName, ts + tus/1000000.0, typ, cod, val))
- except Queue.Empty:
- break
- return events
-
-def printEventsFromFile(filename):
- fd = os.open(filename, os.O_RDONLY)
-
- sdev = filename.split("/")[-1]
-
- try:
- while 1:
- inputEvent = os.read(fd, sizeof_input_event)
- if not inputEvent:
- break
- print sdev, eventToString(inputEvent)
- finally:
- os.close(fd)
-
-if __name__ == "__main__":
- import getopt
- import sys
-
- opt_print_devices = []
-
- opts, remainder = getopt.getopt(
- sys.argv[1:], 'hp',
- ['help', 'print'])
- for opt, arg in opts:
- if opt in ['-h', '--help']:
- print cmdline_usage
- sys.exit(0)
- elif opt in ['-p', '--print']:
- if not remainder:
- print cmdline_usage
- opt_print_devices = remainder
-
- if opt_print_devices:
- for deviceFilename in opt_print_devices:
- thread.start_new_thread(printEventsFromFile, (deviceFilename,))
- raw_input("Press ENTER to stop printing...\n")
+++ /dev/null
-import time
-
-class _USE_DEFAULTS:
- pass
-
-
-def int_coords((x,y), (width, height)):
- if 0 <= x <= 1 and type(x) == float:
- x = x * width
- if 0 <= y <= 1 and type(y) == float:
- y = y * height
- return (int(round(x)), int(round(y)))
-
-
-class GUITestConnection(object):
-
- def send_tap(self, x, y):
- return self.send_touchdown(x, y) and self.send_touchup(x, y)
-
- def send_press(self, keyname):
- return self.send_keydown(keyname) and self.send_keyup(keyname)
-
- def send_keydown(self, keyname):
- print ("send keydown(%s) needed but not implemented." % (keyname,))
-
- def send_keyup(self, keyname):
- print ("send keyup(%s) needed but not implemented." % (keyname,))
-
- def send_touchdown(self, x, y):
- print ("send touchdown(%d, %d) needed but not implemented" % (x, y))
-
- def send_touchup(self, x, y):
- print ("send touchup(%d, %d) needed but not implemented" % (x, y))
-
- def send_touchmove(self, x, y):
- print ("send touchmove(%d, %d) needed but not implemented" % (x, y))
-
-
-class GUITestInterface(object):
- def __init__(self):
- self._conn = None
- self.tap_defaults = {}
- self.longtap_holdtime = 2.0
-
- def setConnection(self, conn):
- self._conn = conn
-
- def screen_size(Self):
- return 720, 1280
-
- def pressKey(self, keyname, long=False, hold=0.0, modifiers=None):
- extra_params = {}
- if modifiers != None:
- extra_params['modifiers'] = modifiers
- if hold > 0.0:
- try:
- assert self.existing_connection().\
- send_keydown(keyname, **extra_params)
- time.sleep(hold)
- assert self.existing_connection().\
- send_keyup(keyname, **extra_params)
- except AssertionError:
- return False
- return True
- return self.existing_connection().send_press(keyname, **extra_params)
-
- def tap(self, (x, y), long=_USE_DEFAULTS, hold=_USE_DEFAULTS,\
- count=_USE_DEFAULTS, delay_between_taps=_USE_DEFAULTS,
- button=_USE_DEFAULTS):
- if long == _USE_DEFAULTS:
- long = self.tap_defaults.get("long", False)
- if hold == _USE_DEFAULTS:
- hold = self.tap_defaults.get("hold", 0.0)
- if count == _USE_DEFAULTS:
- count = self.tap_defaults.get("count", 1)
- if delay_between_taps == _USE_DEFAULTS:
- delay_between_taps = \
- self.tap_defaults.get("delay_between_taps", 0.5)
- if button == _USE_DEFAULTS:
- button = self.tap_defaults.get("button", None)
-
- x, y = self.int_coords((x,y))
- count = int(count)
- if long and hold == 0.0:
- hold = self.longtap_holdtime
- extra_params = {}
- if button != None:
- extra_params['button'] = button
- while count > 0:
- if hold > 0.0:
- try:
- assert self.existing_connection().\
- send_touchdown(x,y, **extra_params)
- time.sleep(hold)
- assert self.existing_connection().\
- send_touchup(x,y, **extra_params)
- except AssertionError:
- return False
- else:
- if delay_between_taps:
- time.sleep(delay_between_taps)
- if not self.existing_connection().send_tap(x, y, **extra_params):
- return False
- count = int(count) - 1
- return True
-
- def down_scroll(self, (x1, y1), (x2, y2)):
- x1, y1 = self.int_coords((x1, y1))
- x2, y2 = self.int_coords((x2, y2))
-
- self.existing_connection().send_touchdown(x1, y1)
- ytemp = y1 - y2
- yidx = 0
-
- while ytemp - yidx > 0:
- self.existing_connection().send_touchmove(x1, y1 - yidx)
- yidx += 5
-
- self.existing_connection().send_touchup(x2, y2)
-
- def up_scroll(self, (x1, y1), (x2, y2)):
- x1, y1 = self.int_coords((x1, y1))
- x2, y2 = self.int_coords((x2, y2))
-
- self.existing_connection().send_touchdown(x1, y1)
- ytemp = y2 - y1
- yidx = 0
-
- while ytemp - yidx > 0:
- self.existing_connection().send_touchmove(x1, y2 + yidx)
- yidx += 5
-
- self.existing_connection().send_touchup(x2, y2)
-
-
- def drag(self, (x1, y1), (x2, y2), delay_between_moves=0.01,\
- delay_before_moves=0, delay_after_moves=0, move_points=10,\
- button=_USE_DEFAULTS):
- x1, y1 = self.int_coords((x1, y1))
- x2, y2 = self.int_coords((x2, y2))
-
- extra_args = {}
- if button != _USE_DEFAULTS:
- extra_args["button"] = button
-
- if delay_before_moves >= 0:
- time.sleep(delay_before_moves)
- else:
- time.sleep(delay_between_moves)
- for i in xrange(0, move_points):
- nx = x1 + int(round(((x2 - x1) / float(move_points+1)) * (i+1)))
- ny = y1 + int(round(((y2 - y2) / float(move_points+1)) * (i+1)))
- if not self.existing_connection().\
- send_touchmove(nx, ny, **extra_args):
- return False
- time.sleep(delay_between_moves)
- if delay_after_moves > 0:
- self.existing_connection().send_touchmove(x2, y2, **extra_args)
- time.sleep(delay_after_moves)
- if delay_after_moves >= 0:
- if self.existing_connection().send_touchup(x2, y2, **extra_args):
- return True
- else:
- return False
- else:
- return True
-
-
-
- def existing_connection(self):
- if self._conn:
- return self._conn
- else:
- print ("not connected")
-
- def int_coords(self, (x, y)):
- width, height = self.screen_size()
- return int_coords((x,y), (width, height))
-
+++ /dev/null
-
-import os
-import time
-import subprocess
-import cPickle
-import base64
-import Queue
-import thread
-
-import monkey_gti
-
-from constants import Constants
-
-
-def _file_to_queue(f, out_queue):
- line = f.readline()
- while line != "":
- out_queue.put(line)
- line = f.readline()
- f.close()
-
-
-def _encode(obj):
- return base64.b64encode(cPickle.dumps(obj))
-
-
-def _decode(string):
- return cPickle.loads(base64.b64decode(string))
-
-
-def _run(cmd, expected_exitstatus=None):
- if type(cmd) == str:
- shell = True
- else:
- shell = False
-
- try:
- proc = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE,\
- stderr=subprocess.PIPE, close_fds=True)
- if expected_exitstatus != None:
- out, err = proc.communicate()
- else:
- out, err = ('', None)
- except Exception, ex:
- class fakeProcess(object):
- pass
- p = fakeProcess
- p.returncode = 127
- out, err = ('', ex)
-
- exit_status = proc.returncode
-
- if (expected_exitstatus != None and
- exit_status != expected_exitstatus and
- exit_status not in expected_exitstatus):
- msg = "Executing %s failed. Exit status: %s, expected %s" % \
- (cmd, exit_status, expected_exitstatus)
- raise FMBTTizenError(msg)
-
- return exit_status, out, err
-
-
-class Device(monkey_gti.GUITestInterface):
-
- def __init__(self, serial_number=None, debug_agentfile=None, \
- keyboard_device=None, touch_device=None, \
- mouse_device=None, **kwargs):
-
- monkey_gti.GUITestInterface.__init__(self, **kwargs)
- c = TizenDeviceConnection(serial_number=serial_number,\
- debug_agentfile=debug_agentfile,\
- keyboard_device=keyboard_device,\
- touch_device=touch_device,\
- mouse_device=mouse_device)
- self.setConnection(c)
- c.gti = self
-
- def connect(self):
- if hasattr(self, "_conn"):
- self._conn.open()
- return True
- else:
- return False
-
- def disconnect(self):
- if hasattr(self, "_conn"):
- self._conn.close()
- return True
- else:
- return False
-
- def pressPower(self, **pressKeyKwArgs):
- return self.pressKey("POWER", **pressKeyKwArgs)
-
- def pressBack(self, **pressKeyKwArgs):
- return self.pressKey("BACK", **pressKeyKwArgs)
-
- def pressMenu(self, **pressKeyKwArgs):
- return self.pressKey("MENU", **pressKeyKwArgs)
-
- def pressVolumeDown(self, **pressKeyKwArgs):
- return self.pressKey("VOLUMEDOWN", **pressKeyKwArgs)
-
- def pressVolumeUp(self, **pressKeyKwArgs):
- return self.pressKey("VOLUMEUP", **pressKeyKwArgs)
-
- def key_names(self):
- return self._conn.key_names()
-
-
-class TizenDeviceConnection(monkey_gti.GUITestConnection):
-
- def __init__(self, serial_number=None, debug_agentfile=None, \
- keyboard_device=None, touch_device=None, mouse_device=None):
- if serial_number == None:
- self.serial_number = "unknown"
- else:
- self.serial_number = serial_number
-
- self.sdb_shell = None
- self.agent_needs_resolution = True
- self.touch_device = touch_device
- self.keyboard_device = keyboard_device
- self.debug_agentfile = debug_agentfile
- self.mouse_device = mouse_device
- self.open()
-
- def open(self):
- if self.serial_number == "unknown":
- raise TizenDeviceNotFoundError("Tizen device not found.")
-
- self.close()
-
- agent_fname = "fmbttizen-agent.py"
- agent_uinput_fname = "fmbtuinput.py"
-
- agent_fname_path = Constants.AGENT_PATH
- uinput_fname_path = Constants.UINPUT_AGENT_PATH
- remote_upload_path = "/tmp/"
-
- remote_agent_fname = remote_upload_path + agent_fname
-
- upload_files = [(agent_fname_path, remote_upload_path), \
- (uinput_fname_path, remote_upload_path)]
-
- for src, dst in upload_files:
- upload_cmd = ["sdb", "-s", self.serial_number, "push", src, dst]
- status, out, err = _run(upload_cmd, range(256))
- if status == 127:
- raise TizenConnectionError("Executing sdb -s %s push failed." + \
- "Check your Tizen SDK installation." % \
- self.serial_number)
- elif status != 0:
- if "device not found" in err:
- raise TizenDeviceNotFoundError(\
- 'Tizen device "%s" not found.'% \
- self.serial_number)
- else:
- raise TizenConnectionError('Executing "%s" failed: %s' % \
- (' '.join(upload_cmd), err + " " + out))
-
- self.agent_args = []
- if self.keyboard_device:
- self.agent_args.append("--keyboard=%s" % (self.keyboard_device,))
- if self.touch_device:
- self.agent_args.append("--touch=%s" % (self.touch_device,))
- if self.mouse_device:
- self.agent_args.append("--mouse=%s" % (self.mouse_device,))
-
- remote_shellcmd = ["sdb", "-s", self.serial_number, "shell"]
- try:
- self.sdb_shell = subprocess.Popen(remote_shellcmd,\
- shell=False,
- stdin=subprocess.PIPE,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- close_fds=True)
- except OSError:
- raise TizenConnectionError("Executing %s failed" % \
- " ".join(remote_shellcmd),)
-
- self.sdbshell_errqueue = Queue.Queue()
- thread.start_new_thread(_file_to_queue, (self.sdb_shell.stderr, \
- self.sdbshell_errqueue))
- self.sdb_shell.stdin.write("\r")
- try:
- ok, self.platform_info = self._agent_cmd(\
- "python %s %s; exit" % \
- (remote_agent_fname, " ".join(self.agent_args)))
- except IOError, msg:
- raise TizenConnectionError(\
- ('Connecting to a Tizen device/emulator failed. Error: %s'
- '\nTry "sdb -s %s shell python %s --debug".') % \
- (msg, self.serial_number, remote_agent_fname))
-
- return ok
-
- def key_names(self):
- return self._agent_cmd("kn")[1]
-
- def send_keydown(self, keyname):
- print 'keydown %s' % keyname
- return self._agent_cmd("kd %s" % (keyname,))[0]
-
- def send_keyup(self, keyname):
- print 'keyup %s' % keyname
- return self._agent_cmd("ku %s" % (keyname,))[0]
-
- def send_press(self, keyname, modifiers=()):
- print 'send_press %s' % keyname
- rv = True
- for m in modifiers:
- rv = rv and self.send_keydown(m)
- rv = rv and self._agent_cmd("kp %s" % (keyname,))[0]
- for m in modifiers[::-1]:
- rv = rv and self.send_keyup(m)
- return rv
-
- def send_touchdown(self, x, y):
- print 'touchdown %s %s' % (x, y)
- return self._agent_cmd("td %s %s 1" % (x, y))[0]
-
- def send_touchup(self, x, y):
- print 'touchup %s %s' % (x, y)
- return self._agent_cmd("tu %s %s 1" % (x, y))[0]
-
- def send_tap(self, x, y):
- print 'tap %s %s' % (x, y)
- return self._agent_cmd("tt %s %s 1" % (x, y))[0]
-
- def send_touchmove(self, x, y):
- print 'touchmove %s %s' % (x, y)
- return self._agent_cmd("tm %s %s" % (x, y))[0]
-
- def _report_errors_inqueue(self):
- while True:
- try:
- l = self._sdbshell_errqueue.get_nowait()
- except Queue.Empty:
- return
- if self.debug_agentfile:
- self.debug_agentfile.write("<2 %s" % (l,))
-
- def _agent_cmd(self, cmd, retry=3):
- if cmd[:2] in ["tt", "td", "tm", "tu", "er"]:
- if self.agent_needs_resolution:
- self._agent_cmd("sd %s %s" % self.gti.screen_size())
- self.agent_needs_resolution = False
-
- if self.sdb_shell == None:
- return False, "disconnected"
-
- if self.debug_agentfile:
- self.debug_agentfile.write(">0 %s\n" % (cmd,))
- try:
- if len(cmd) > 0:
- self.sdb_shell.stdin.write("%s%s" % (cmd, '\n'))
- self.sdb_shell.stdin.flush()
- except IOError, msg:
- if retry > 0:
- time.sleep(2)
- self._report_errors_inqueue()
- print ("Error when sending command %s : %s" % (cmd, msg))
- self.open()
- self._agent_cmd(cmd, retry=retry - 1)
- return self._agent_answer()
-
- def _agent_answer(self):
- error_line_prefix = "FMBTAGENT ERROR "
- ok_line_prefix = "FMBTAGENT OK "
- l = self.sdb_shell.stdout.readline()
- output = []
- while True:
- if self.debug_agentfile:
- if len(l) > 72:
- self.debug_agentfile.write("<1 %s...\n" % (l[:72],))
- else:
- self.debug_agentfile.write("<1 %s\n" % (l,))
- if l.startswith(ok_line_prefix):
- return True, _decode(l[len(ok_line_prefix):])
- elif l.startswith(error_line_prefix):
- return False, _decode(l[len(error_line_prefix):])
- else:
- output.append(l)
- pass
- l = self.sdb_shell.stdout.readline()
- if l == "":
- raise IOError("Agent connection lost : %s" % \
- ("\n".join(output)))
- break
- l = l.strip()
-
- def close(self):
- if hasattr(self, "sdb_Shell") and self.sdb_shell != None:
- try:
- self._agent_cmd("quit", retry=0)
- except:
- pass
- try:
- self.sdb_shell.stdin.close()
- except:
- pass
- try:
- self.sdb_shell.stdout.close()
- except:
- pass
- try:
- self.sdb_shell.stderr.close()
- except:
- pass
- self._report_errors_inqueue()
- self.sdb_shell = None
-
-
-class FMBTTizenError(Exception):
- pass
-
-
-class TizenConnectionError(FMBTTizenError):
- pass
-
-
-class TizenDeviceNotFoundError(TizenConnectionError):
- pass
+++ /dev/null
-
-import os
-import threading
-import random
-
-from monkey_tizen import Device
-from sdbmanager import SdbManager
-from constants import Constants
-
-
-class RandomExecutor(threading.Thread):
- def __init__(self, _devid, _wrap):
- self.monkey_dev = Device(_devid, _wrap.get_debug_file(), \
- _wrap.get_key_dev(), _wrap.get_touch_dev(), \
- _wrap.get_mouse_dev())
- self.devid = _devid
- self.monkey_dev.connect()
- self.random_count = int(_wrap.get_random_count())
- self.result_path = _wrap.get_result_dirpath(_devid)
- self.back_count = _wrap.get_back_count()
-
- if _wrap.get_record_file():
- self.rec_file = open(_wrap.get_record_file(), 'w')
- else:
- self.rec_file = open(\
- os.path.join(self.result_path, \
- Constants.RECORD_FILE_NAME), 'w')
- threading.Thread.__init__(self)
-
- def run(self):
- for idx in range(self.random_count):
- x = random.uniform(0.0, 1.0)
- y = random.uniform(0.0, 1.0)
-
- self.rec_file.write("tap %s %s\n" % (x, y))
- self.monkey_dev.tap((x, y))
-
- if self.back_count and idx >= int(self.back_count):
- if idx % int(self.back_count) == 0:
- self.rec_file.write("pressBack\n")
- self.monkey_dev.pressBack()
-
- SdbManager.exportDumpFiles(self.devid, \
- os.path.join(self.result_path, 'random'))
- self.monkey_dev.disconnect()
- self.rec_file.close()
-
-
-class ReplayExecutor(threading.Thread):
- def __init__(self, _devid, _wrap):
- self.monkey_dev = Device(_devid, _wrap.get_debug_file(), \
- _wrap.get_key_dev(), _wrap.get_touch_dev(), \
- _wrap.get_mouse_dev())
- self.devid = _devid
- self.monkey_dev.connect()
- self.replay_filepath = _wrap.get_replay_file()
- self.replay_file = None
-
- self.result_path = _wrap.get_result_dirpath(_devid)
-
- if self.replay_filepath:
- self.replay_file = open(self.replay_filepath, 'r')
-
- threading.Thread.__init__(self)
-
- def run(self):
- while True:
- line = self.replay_file.readline()
- if not line:
- break
- msg = line.split()
- if msg[0].find('tap') > -1:
- self.monkey_dev.tap((float(msg[1]), float(msg[2])))
- elif msg[0].find('pressBack') > -1:
- self.monkey_dev.pressBack()
-
- self.replay_file.close()
- self.monkey_dev.disconnect()
- SdbManager.exportDumpFiles(self.devid, \
- os.path.join(self.result_path, 'replay'))
+++ /dev/null
-
-import os
-import datetime
-
-from optparse import *
-from constants import Constants
-
-
-def varnarg(option, opt_str, value, parser):
- """ parser srg"""
- value = []
- import re
- for arg in parser.rargs:
- if re.search('^--.+', arg) or re.search('^-[\D]', arg):
- break
- value.append(arg)
-
- del parser.rargs[:len(value)]
- setattr(parser.values, option.dest, value)
-
-
-class MonkeyWrapper:
- def __init__(self):
- self.options = None
- self.USAGE = "\n\""
-
- def print_usage(self):
- print self.USAGE
-
- def parse_options(self, argv):
- option_list = [
- make_option("--py-install", dest="python_install", \
- action="store_true", default=False, help=""),
- make_option("--random", dest="random_count", action="callback", \
- callback=varnarg, help=""),
- make_option("--record", dest="record_file", action="callback", \
- callback=varnarg, help=""),
- make_option("--debug", dest="debug_file", action="callback", \
- callback=varnarg, help=""),
- make_option("--replay", dest="replay_file", action="callback", \
- callback=varnarg, help=""),
- make_option("--key-dev", dest="key_device", action="callback", \
- callback=varnarg, help=""),
- make_option("--touch-dev", dest="touch_device", \
- action="callback", callback=varnarg, help=""),
- make_option("--mouse_dev", dest="mouse_device", \
- action="callback", callback=varnarg, help=""),
- make_option("--output", dest="result_dir", action="callback", \
- callback=varnarg, help=""),
- make_option("--back-key", dest="back_count", action="callback", \
- callback=varnarg, help="")
- ]
-
- # detect non-params
- if len(argv) == 1:
- pass
- argv.append("--help")
-
- PARSERS = OptionParser(option_list=option_list, usage=self.USAGE)
- (self.options, args) = PARSERS.parse_args()
-
- def is_py_install(self):
- return self.options.python_install
-
- def python_install(self, _devid):
- os.system('sdb -s %s root on' % _devid)
- curr_path = Constants.LIB_DIR
- os.system('sdb -s %s push %s %s' % (_devid, os.path.join(curr_path, 'libpython-2.7.1-1.7.armv7l.rpm'), '/tmp/'))
- os.system('sdb -s %s push %s %s' % (_devid, os.path.join(curr_path, 'python-2.7.1-1.4.armv7l.rpm'), '/tmp/'))
- os.system('sdb -s %s push %s %s' % (_devid, os.path.join(curr_path, 'python-base-2.7.1-1.7.armv7l.rpm'), '/tmp/'))
- os.system('sdb -s %s shell rpm -ivh /tmp/libpython-2.7.1-1.7.armv7l.rpm' % _devid)
- os.system('sdb -s %s shell rpm -ivh /tmp/python-base-2.7.1-1.7.armv7l.rpm' % _devid)
- os.system('sdb -s %s shell rpm -ivh /tmp/python-2.7.1-1.4.armv7l.rpm' % _devid)
-
- def get_replay_file(self):
- if self.options.replay_file:
- return self.options.replay_file[0]
- else:
- return None
-
- def get_record_file(self):
- if self.options.record_file:
- return self.options.record_file[0]
- else:
- return None
-
- def get_random_count(self):
- return self.options.random_count[0]
-
- def get_back_count(self):
- if self.options.back_count:
- return self.options.back_count[0]
- else:
- return None
-
- def get_debug_file(self):
- if self.options.debug_file:
- return self.options.debug_file[0]
- else:
- return None
-
- def get_key_dev(self):
- if self.options.key_device:
- return self.options.key_device[0]
- else:
- return None
-
- def get_touch_dev(self):
- if self.options.touch_device:
- return str(self.options.touch_device[0])
- else:
- return None
-
- def get_mouse_dev(self):
- if self.options.mouse_device:
- self.options.mouse_device[0]
- else:
- return None
-
- def is_random_mode(self):
- if self.options.random_count and self.options.random_count[0] > 0:
- return True
- else:
- return False
-
- def is_replay_mode(self):
- if self.options.replay_file:
- return True
- else:
- return False
-
- def get_result_dirpath(self, _devid):
- curr_time = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
- result_path = os.path.join(Constants.RESULT_DIR, _devid, curr_time)
- if not os.path.exists(result_path):
- os.makedirs(result_path)
-
- return result_path
+++ /dev/null
-
-import os
-import time
-import subprocess
-
-from constants import Constants
-
-class SdbManager:
-
- @staticmethod
- def sdbCommand(command, timeout=90):
- #LOGGER.debug("sdbCommand : %s" % command)
- proc = subprocess.Popen(command,
- shell=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE)
- time_out = 0
- while time_out < timeout:
- exit_code = proc.poll()
- if exit_code is not None:
- break
- time_out += 0.5
- time.sleep(0.5)
- if exit_code is None:
- pass
- #LOGGER.error("sdb time out,kill subprocess...")
- #killall(proc.pid)
-
- return exit_code, proc.stdout, proc.stderr
-
-
- @staticmethod
- def sdbDevices():
- dev_cmd = "sdb devices"
- start_server_cmd = "sdb start-server"
- SdbManager.sdbCommand(start_server_cmd, 8)
- exit_code, re_stdout, re_stderr = SdbManager.sdbCommand(dev_cmd, 5)
-
- return re_stdout.read()
-
-
- @staticmethod
- def checkDirExist(_devid, _dirname):
- existed = True
- lscmd = Constants.SDB_LS % _devid + " " + _dirname
- exit_code, std_out, std_err = SdbManager.sdbCommand(lscmd)
- out_log = std_out.read()
- if out_log and out_log.find("No such file or directory") > -1:
- existed = False
- return existed
-
- @staticmethod
- def sdbShell(deviceId, cmd):
- shell_cmd = Constants.SDB_SHELL % deviceId + " " + cmd
- exit_code, re_stdout, re_stderr = SdbManager.sdbCommand(shell_cmd)
-
- if exit_code is None:
- return False
- else:
- outLog = re_stdout.read()
- if outLog and outLog.find('command not found') > -1:
- return False
-
- return outLog
-
- @staticmethod
- def exportDumpFiles(_devid, _resultDir):
- dumpPath = os.path.join(_resultDir, "dump")
- if not os.path.exists(dumpPath):
- os.makedirs(dumpPath)
- remote = Constants.DUMP_DIR_PATH
- SdbManager.sdbPull(_devid, remote, dumpPath)
- SdbManager.sdbShell(_devid, 'rm -rf ' + remote)
-
-
- @staticmethod
- def sdbPull(_devid, remote, local):
- rmtFileCheck_cmd = Constants.SDB_SHELL % _devid + " " \
- + Constants.FILE_FOUND_SCRIPT % remote
- exit_code, re_stdout, re_stderr = \
- SdbManager.sdbCommand(rmtFileCheck_cmd)
-
- if exit_code is None:
- return False
-
- pull_cmd = Constants.SDB_PULL % _devid + " " + remote + " " + local
- exit_code, re_stdout, re_stderr = SdbManager.sdbCommand(pull_cmd)
-
- if exit_code is None:
- return False
-
- if Constants.checkFileExists(local) is False:
- return False
- else:
- pass
-
- return True
-
-
-
-TIZENV=tizen_web_2.3,tizen_native_2.3,tizen_web_2.3.1,tizen_native_2.3.1,tizen_web_2.3.2,tizen_native_2.3.2,tizen_web_2.4,tizen_native_2.4,tizen_web_3.0,tizen_native_3.0,tizen_csharp_3.0,tizen_web_4.0,tizen_native_4.0,tizen_csharp_4.0,tizen_web_5.0,tizen_native_5.0,tizen_csharp_5.0,tizen_web_5.5,tizen_native_5.5,tizen_csharp_5.5,tizen_web_6.0,tizen_native_6.0,tizen_csharp_6.0
-PROFILE=mobile,wearable,tv,common_iot
+TIZENV=tizen_web_2.3,tizen_native_2.3,tizen_web_2.3.1,tizen_native_2.3.1,tizen_web_2.3.2,tizen_native_2.3.2,tizen_web_2.4,tizen_native_2.4,tizen_web_3.0,tizen_native_3.0,tizen_csharp_3.0,tizen_web_4.0,tizen_native_4.0,tizen_csharp_4.0,tizen_web_5.0,tizen_native_5.0,tizen_csharp_5.0,tizen_web_5.5,tizen_native_5.5,tizen_csharp_5.5,tizen_web_6.0,tizen_native_6.0,tizen_csharp_6.0,tizen_web_6.5,tizen_native_6.5,tizen_csharp_6.5
+PROFILE=mobile,wearable,tv,tizeniot
+++ /dev/null
-[TCTSHELL]
-WRT_LAUNCHR_CMD = WRTLauncher
-TCT_SHELL_HOME = /opt/tools/shell/
-TCT_PLAN_FOLDER = /opt/tools/shell/plan/
-
-[DISTRIBUTE_MODE]
-DEVICE_EXCEPTIONS =
-#Devices to ignore for distribute mode.
-#example:
-# example_device1
-# example_device2
- DEVICE1
- DEVICE2
-# 0000d81400006200
-
-[Device]
-DEVICE_TMP_FOLDER = /tmp/
-DEVICE_TESTS_FILE = /opt/usr/media/tct/opt/%s/tests.xml
-DEVICE_CAPABILITY_PATH = /opt/usr/media/Documents/tct/capability.xml
-DEVICE_BUILD_INFO_PATH = /opt/usr/media/Documents/tct/buildinfo.xml
-DEVICE_DEFAULT_CONF_PATH = /opt/usr/media/tct/opt/tct-testconfig/tct-testconfig.ini
-DEVICE_DEFAULT_ISON_CONF_PATH = /opt/usr/media/tct/preconfigure.json
-DEVICE_PORT_JSON_CONF_PATH = /opt/usr/media/tct/portconfigure.json
-DEVICE_PRECONFIGURE_FILE_PATH = /opt/usr/media/Documents/tct/pre_configure.conf
-
-
+++ /dev/null
-[public_version]
-version=TCT_2.4
-[internal_version]
-version=TCT_2.4
-[public_shell_version]
-version=TCTSHELL_3.1.0-20160418
+++ /dev/null
-tct-shell (1.0.16) unstable; urgency=low
-
- * Packaged for Ubuntu
-
- -- Ed Bartosh <eduard.bartosh@intel.com> Mon, 06 May 2013 14:37:15 +0300
+++ /dev/null
-Source: tct-shell
-Section: utils
-Priority: standard
-Maintainer: Lei Yang <lei.a.yang@intel.com>
-Build-Depends: debhelper (>= 8.0.0), python-setuptools
-Standards-Version: 3.9.4
-
-Package: tct-shell
-Architecture: all
-Depends: ${shlibs:Depends}, ${misc:Depends}, ${python:Depends}
-Description: Console tool for Tizen Compliance Test
- This tool provides an alternative way to execute TCT with testkit-lite
- when testkit-manager is not available
+++ /dev/null
-Format: http://dep.debian.net/deps/dep5
-Source: https://github.com/testkit/testkit-manager
-
-Files: *
-Copyright: 2012-2013 Intel Corp.
-License: GPL-2.0
-
-Files: debian/*
-Copyright: 2012-2013 Intel Corp.
-License: GPL-2.0
-
-License: GPL-2.0
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 2 of the License
- .
- This package is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
- .
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- .
- On Debian systems, the complete text of the GNU General
- Public License version 3 can be found in "/usr/share/common-licenses/GPL-3".
+++ /dev/null
-README
-CONFIG
+++ /dev/null
-tct-shell_1.0.16_all.deb utils standard
+++ /dev/null
-#!/bin/sh
-
-# Set permissions
-chmod -R ugo+rwx /opt/tools/shell
-
-#DEBHELPER#
+++ /dev/null
-#!/usr/bin/make -f
-
-%:
- dh $@
+++ /dev/null
-PKG_NAME := tct-shell
-SPECFILE = $(addsuffix .spec, $(PKG_NAME))
-PKG_VERSION := $(shell grep '^Version: ' $(SPECFILE)|awk '{print $$2}')
-
-TARBALL := $(PKG_NAME)_$(PKG_VERSION).tar.gz
-
-dsc: tarball
- $(eval MD5=$(shell md5sum $(TARBALL) | sed "s/ / $(shell stat -c '%s' $(TARBALL)) /"))
- @sed -i 's/^Version:.*/Version: $(PKG_VERSION)/' $(PKG_NAME).dsc
- @sed -i 's/ [a-f0-9]\+ [0-9]\+ $(PKG_NAME).*tar.*/ $(MD5)/' $(PKG_NAME).dsc
-
-tarball:
- @cd "$$(git rev-parse --show-toplevel)" \
- && git archive --prefix $(PKG_NAME)-$(PKG_VERSION)/ HEAD \
- | gzip > "$(CURDIR)/$(TARBALL)"
-
-clean:
- @rm -f $(PKG_NAME)*.tar.gz
-
-all: clean tarball dsc
+++ /dev/null
-Source: tct-shell
-Section: utils
-Priority: standard
-Maintainer: Shaofeng <shaofeng.tang@intel.com>
-Build-Depends: debhelper (>= 8.0.0), python-setuptools, python-support, tree
-Standards-Version: 3.9.2
-Homepage: https://github.com/testkit/
-Version: 1.0.1
-Files:
- f64f26693160cf59cdae21e8961cf986 15593 tct-shell_1.0.1.tar.gz
-
+++ /dev/null
-Summary: TCT-Shell
-Name: tct-shell
-Version: 1.0.15
-Release: 1
-License: GPLv2
-Group: Applications/System
-Source: %name-%version.tar.gz
-BuildRoot: %_tmppath/%name-%version-buildroot
-Requires: python
-
-
-%description
-TCT-Shell is a wrapper pf testkit-lite. provide an alternative way to execute TCT with testkit-lite when testkit-manager is not available
-Provide the following functions:
-1. List available test packages.
-2. Install/remove test packages on target device according to user's option
-3. Trigger testing in 3 ways: through test plan, through package, rerun failed test cases.
-4. Show test result summary in visual way.
-
-%prep
-%setup -q
-
-%build
-./autogen
-./configure
-make
-
-%install
-[ "\$RPM_BUILD_ROOT" != "/" ] && rm -rf "\$RPM_BUILD_ROOT"
-make install DESTDIR=$RPM_BUILD_ROOT
-
-%clean
-
-%post
-# Set permissions
-chmod ugo+rwx /opt/tools/shell
-
-%files
-/usr/lib/python2.7/dist-packages/tctshell/*
-/opt/tools/shell
-/opt/tools/shell/plan
-/opt/tools/shell/style
-/opt/tools/tct-shell
-/opt/tools/tct-plan-generator
-
-%post
-chmod -R 777 /opt/tools/shell
-
-%changelog
+++ /dev/null
-#!/usr/bin/python
-
-from glob import glob
-
-from setuptools import setup, find_packages
-
-setup(
- name = "tct-shell",
- description = "Console tool for Tizen Compliance Test",
- author = "Cathy Shen",
- author_email = "daniel.tao@intel.com",
- version = "1.0.16",
- include_package_data = True,
- data_files = [('/opt/tools/shell/plan', glob('plan/*')),
- ('/opt/tools/shell/', ['CONFIG', 'LICENSE', 'VERSION']),
- ('/opt/tools/shell/style', glob('style/*')),
- ('/opt/tools/', ['tct-shell', 'tct-plan-generator'])],
- packages = find_packages(),
-)
+++ /dev/null
-globals = com.arne.GlobalLogics$ServerLifeCycle\r
-\r
-server.host = 182.254.132.122\r
-server.port = 8080\r
-\r
-platform.imgUrlPattern = http://182.254.132.122/imgStorage/%s\r
-platform.servlet.imgStorage = {"class":"com.arne.basedevss.base.sfs.local.LocalSFS", "args":{"dir":"/home/leader21/sltLeader21/leader21/imgStorage"}}\r
-platform.bookUrlPattern = http://182.254.132.122/bookStorage/%s\r
-platform.servlet.bookStorage = {"class":"com.arne.basedevss.base.sfs.local.LocalSFS", "args":{"dir":"/home/leader21/sltLeader21/leader21/bookStorage"}}\r
-platform.bookImgUrlPattern = http://182.254.132.122/bookImgStorage/%s\r
-platform.servlet.bookImgStorage = {"class":"com.arne.basedevss.base.sfs.local.LocalSFS", "args":{"dir":"/home/leader21/sltLeader21/leader21/bookImgStorage"}}\r
-platform.appUrlPattern = http://182.254.132.122/appStorage/%s\r
-platform.servlet.appStorage = {"class":"com.arne.basedevss.base.sfs.local.LocalSFS", "args":{"dir":"/home/leader21/sltLeader21/leader21/appStorage"}}\r
-platform.appTestUrlPattern = http://182.254.132.122/appTestStorage/%s\r
-platform.servlet.appTestStorage = {"class":"com.arne.basedevss.base.sfs.local.LocalSFS", "args":{"dir":"/home/leader21/sltLeader21/leader21/appTestStorage"}}\r
-platform.docUrlPattern = http://182.254.132.122/docStorage/%s\r
-platform.servlet.docStorage = {"class":"com.arne.basedevss.base.sfs.local.LocalSFS", "args":{"dir":"/home/leader21/sltLeader21/leader21/docStorage"}}\r
-\r
-platform.ysbookImgUrlPattern = http://182.254.132.122/bookImgStorage/%s\r
-platform.servlet.ysbookImgStorage = {"class":"com.arne.basedevss.base.sfs.local.LocalSFS", "args":{"dir":"/home/leader21/sltLeader21/leader21/bookImgStorage"}}\r
-\r
-platform.servlet.xmlStorage = {"class":"com.arne.basedevss.base.sfs.local.LocalSFS", "args":{"dir":"/home/leader21/sltLeader21/leader21/xml/"}}\r
-platform.attachmentPattern = http://182.254.132.122/Attachments/%s\r
-\r
-platform.ysbookImgUrlPattern.small.flag = 0\r
-platform.ysbookImgUrlPattern.small.width=110\r
-platform.ysbookImgUrlPattern.small = http://182.254.132.122/bookImgStorage/small/%s\r
-platform.servlet.ysbookImgStorage.small = {"class":"com.arne.basedevss.base.sfs.local.LocalSFS", "args":{"dir":"/home/leader21/sltLeader21/leader21/bookImgStorage/small"}}\r
-\r
-platform.servlet.qrCodeStorage = {"class":"com.arne.basedevss.base.sfs.local.LocalSFS", "args":{"dir":"/home/leader21/sltLeader21/leader21/qrCode/"}}\r
-platform.servlet.qrCodeStr = /home/leader21/sltLeader21/leader21/qrCode/\r
-platform.qrCodePattern = http://182.254.132.122/qrCode/%s\r
-platform.servlet.qrCode.width = 300\r
-platform.servlet.qrCode.height = 300\r
-\r
-platform.xmlStr = /home/leader21/sltLeader21/leader21/xml/\r
-platform.appStr = /home/leader21/sltLeader21/leader21/appStorage/\r
-\r
-platform.test.device.ids = /home/leader21/sltLeader21/leader21/device/ids.txt\r
-\r
-platform.join_act_count = 10\r
-platform.act_fillgolden.join_begin = 2014-02-10 00:00:00\r
-platform.act_fillgolden.join_end = 2014-02-28 23:59:59\r
-\r
-YL.merchantName = LEADER21\r
-YL.merchantId = 802310048992658\r
-YL.password = 61dear86420\r
-YL.private.p12 = /home/leader21/sltLeader21/leader21/PAY.YL/up_61dear_p12.p12\r
-YL.head.cer = /home/leader21/sltLeader21/leader21/PAY.YL/yl8001.cer\r
-YL.merchant_public_cer = /home/leader21/sltLeader21/leader21/PAY.YL/up_61dear_cer.cer\r
-YL.sendUrl = http://mobilepay.unionpaysecure.com/qzjy/MerOrderAction/deal.action\r
-YL.backEndUrl = http://182.254.132.122:8080/order/yl_back\r
-\r
-\r
-ZFB.partner = 2088701185025742\r
-ZFB.private_key = MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMym9J2yZ1K1/Lq+9V4UqDylZ7JygEk24d9vtFmPbNCGywU5JiQddfif8/lN8XcdpgvoNl1ujiXzpT6w5n2GYEKycg3B8zHcdoU8tWzWVL6GGbeZ/4dLY2U2XMPWtBJ+256ZP9qxN0iyBP8/qex57Ua43goWBRML5TPa/wQaCE2HAgMBAAECgYEAkiYAtsV7CBQy4eIRNBiodHbi8QrYFnD9KSWKtBK68MfyIE7JsCzh3KXOA5HoCNrBg+tXN64GEZBHx9dpIuddwbzZwoKv4DBWKRaIZDgfCyhWfopAYpxcGODngREIsdaBL7MSpElxfl2opMTESTIGSfXi4ZJFNb1kys7NlxjKEfECQQDo1kN+ka1s/Tk/oZHFysaM653oqdi6hTjpqSZJqlK7VAShQoKlR6aDy2phB3HWI2Qc5NJbNbEwqZ0+ISyhldATAkEA4QLmeWj2ZKcMwNitwq9i6Y9h4TZ0jG70B/+JgaayPFplwIjOiLn5rlLF+GRUsDJya/GQGCeAYsMIHUkbJDSDPQJBAOHCh1Uc+VQ5P54kEgz/bX9MIiNrNFq+PA3L1fUNcgRzFb4qmDScAae+v5nvNwCT9klR0Wlg6Tqu62lHj1fpxAMCQHY79OlVGyuWj+ABu4RybnI18oPJ/oIQh1BwmUu0UTHfeloqSQSVXLqaKga0ib+wMmnAHCxlDVRYETp6QLXMli0CQAOaSMnMfTrWwgdSSZVz9YKMqtCa1hzkUekTBQWFryNCLl+z54BMMhBSrj8XcGXkyD9ROzR+8HtS2ofuMn69XC8=\r
-ZFB.seller_id = 2088701185025742\r
-ZFB.log_path = /home/leader21/sltLeader21/leader21/\r
-ZFB.it_b_pay = 30 m\r
-ZFB.show_url = http://182.254.132.122/\r
-ZFB.backEndUrl = http://182.254.132.122:8080/order/zfb_back\r
-ZFB.ali_public_key = MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB\r
-\r
-YB.pay_urlprefix=https://ok.yeepay.com/payapi\r
-YB.paytest_merchantaccount = YB01000000675\r
-YB.paytest_merchant_publickey = MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCPGXEFfLsmUVlBzb/4LjH+512G4fjVX9exKfM6ZET+JYNpGoNGTx6Qa1Q9vT4wMKR+fWTyGtjzP2T8AjTbAX4MuhzjxEfoWGzSz4On24F6cdYbcl9ZW92Ejic3w6B9QNkQ6QccOBviBjWlfm59jlfnDzxvibhMjuG/K+MJzfnLZwIDAQAB\r
-YB.paytest_merchant_privatekey = MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAI8ZcQV8uyZRWUHNv/guMf7nXYbh+NVf17Ep8zpkRP4lg2kag0ZPHpBrVD29PjAwpH59ZPIa2PM/ZPwCNNsBfgy6HOPER+hYbNLPg6fbgXpx1htyX1lb3YSOJzfDoH1A2RDpBxw4G+IGNaV+bn2OV+cPPG+JuEyO4b8r4wnN+ctnAgMBAAECgYA8fB92l0svnhDhLIto5nXBbZ/tpFQeNH2h575kPv+egNKzuT4lmMmtd4BK/FNt4RGWWYAyiUCMSI5xqqkWrOHO8yrECuG3HOJOJuDFIZ6IA+4deVujzKGGuShV93Stm0Kkgz4L6Gy3FTiDzSV2Sb4WdSlObbtol8jvYHvdK1if6QJBAMza32yMWd2UzJ8kZLnBZTqO27zxpW523NRC7kP/osJqHqjaa3eTlPSUwHIE79kUtajLnnjSB4ZNNqQBp1OfUtUCQQCy04OOSaeTCMqdw9Z+b9eImkols/b//fH5wm8miK1SYGux4vghIObneOgHA0hZL3z3SRwK1E0Uw9IgZo77t+tLAkAVJvhw7eENlyK1v/1CjOyV6lBYJx9s04sjw7F0hf3ZUznNN5hnJW74/i8M1uOpJ5FGV5gKY61xOaHNt3n+kXHtAkEAqL8ljlh8tCgAot1Rg+BgP/xwaaGoPCrTcz8CChfBjlGEbsliIkjc+6LBORTk6ZwBTYyE1Mc/sY+TspV06Z3FfwJAKQA7ilH5VL7i7hwBF2q83pT5dco/vND1/RanOFgHMmuMrgWckvmWNs0wJh7nqomQVFkoxNRqWngH9/+qGHoD1w==\r
-YB.paytest_yibao_publickey = MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDD/yQOpBS2bulX2a+sHLXJPkAfMhF5dgmpc9+wGxOWqzvuxCgjy1Kyb9SwXVqHJtl1S+PA6ZSXdOosRgjVBhKonYU+7CLj0gvDk50mfhzFEM5bSEeM7Vu9G2gwy4yVJKV7lKg6KvGDzwdJpodvT8DS04OaBwcp6zvf6heqYNDyTQIDAQAB\r
-YB.user_id_card = 355533056614185\r
-YB.server_mac_addr = 14-DA-E9-F0-7C-47\r
-YB.server_ip_addr = 210.73.207.184\r
-YB.userua = bkb\r
-YB.callbackurl = http://182.254.132.122:8080/order/yb_back\r
-YB.fcallbackurl = http://182.254.132.122/close.html\r
-\r
-Exam.question.count = 7\r
-platform.servlet.questionStorage = {"class":"com.arne.basedevss.base.sfs.local.LocalSFS", "args":{"dir":"/home/leader21/sltLeader21/leader21/"}}\r
-platform.questionPattern = http://182.254.132.122/%s\r
-platform.questionPatternStr = http://182.254.132.122/\r
-\r
-platform.activity.db = mysql/127.0.0.1/leader21/root/ledi!@#qwe\r
-platform.admin.db = mysql/127.0.0.1/leader21/root/ledi!@#qwe\r
-platform.apps.db = mysql/127.0.0.1/leader21/root/ledi!@#qwe\r
-platform.books.db = mysql/127.0.0.1/leader21/root/ledi!@#qwe\r
-platform.examinations.db = mysql/127.0.0.1/leader21/root/ledi!@#qwe\r
-platform.history.db = mysql/127.0.0.1/leader21/root/ledi!@#qwe\r
-platform.user.db = mysql/127.0.0.1/leader21/root/ledi!@#qwe\r
-platform.user_books.db = mysql/127.0.0.1/leader21/root/ledi!@#qwe\r
-platform.user_increase.db = mysql/127.0.0.1/leader21/root/ledi!@#qwe\r
-platform.user_wealth.db = mysql/127.0.0.1/leader21/root/ledi!@#qwe\r
-platform.api.db = mysql/127.0.0.1/leader21/root/ledi!@#qwe\r
-\r
-servlet.activity.class =com.arne.platform.activity.ActivityServlet\r
-servlet.activity.path = /activity/*\r
-servlet.admin.class =com.arne.platform.admin.AdminServlet\r
-servlet.admin.path = /admin/*\r
-servlet.apps.class =com.arne.platform.apps.AppsServlet\r
-servlet.apps.path = /apps/*,/a/*\r
-servlet.books.class =com.arne.platform.books.BooksServlet\r
-servlet.books.path = /books/*\r
-servlet.history.class =com.arne.platform.history.HistoryServlet\r
-servlet.history.path = /history/*\r
-servlet.user.class =com.arne.platform.user.UserServlet\r
-servlet.user.path = /user/*\r
-servlet.userbooks.class =com.arne.platform.user_books.User_booksServlet\r
-servlet.userbooks.path = /userbooks/*\r
-servlet.user_increase.class =com.arne.platform.user_increase.User_increaseServlet\r
-servlet.user_increase.path = /user_increase/*\r
-servlet.userwealth.class =com.arne.platform.user_wealth.User_wealthServlet\r
-servlet.userwealth.path = /userwealth/*\r
-servlet.solutionapi.class =com.arne.platform.solutionapi.SolutionApiServlet\r
-servlet.solutionapi.path = /solutionapi/*\r
-servlet.exam.class =com.arne.platform.exam.ExamServlet\r
-servlet.exam.path = /exam/*\r
-servlet.order.class =com.arne.platform.order.OrderServlet\r
-servlet.order.path = /order/*\r
+++ /dev/null
-#!/usr/bin/python
-
-import sys
-from tctshell.scenario_options import ScenarioGeneratorOptions
-from tctshell.scenario_runner import ScenarioRunner
-
-
-def main():
- wrapper = ScenarioGeneratorOptions()
- wrapper.parse_options(sys.argv)
- output = wrapper.get_output()
- runner = ScenarioRunner()
- runner.load_local_repo(wrapper.get_planlist_args(), \
- wrapper.get_plansrc_folder(), wrapper.get_scen_name(), \
- wrapper.getPlanList(), wrapper.getDeviceList())
-
- runner.to_xml(output)
-
-if __name__ == "__main__":
- main()
from tctshell.environment_manager import EnvironmentManager
from tctshell.devicemanager import DevBaseManager
from tctshell.sdbmanager import SdbManager
-
+from tctshell.constants import Constants
def main():
#time check
try:
start_time = timeit.default_timer()
+ Constants.GlobalProfile = ""
+
devbaseMgr = DevBaseManager()
devbaseMgr.start()
wrapper = ShellWrapper(devmgr)
wrapper.parse_options(sys.argv)
+ timeout = wrapper.get_tc_timeout()
+ Constants.set_default_timeout(timeout)
+ if wrapper.get_tizenV().find("native") > -1:
+ if timeout is None:
+ timeout = "60"
+ File_Dir = "/opt/tools/shell/tmp/"
+ f = open(os.path.join(File_Dir, 'TC_Timeout.txt'), 'w')
+ f.write(timeout)
+ f.close()
+ if Constants.isDistMode():
+ devmgr.loadDeviceList()
+ devices = devmgr.getSdbDeviceList()
+ for dev in devices:
+ if not SdbManager.sdbPush(dev.getDeviceId(),File_Dir+"TC_Timeout.txt","/tmp/"):
+ LOGGER.error("Not able to push file in device")
+ raise
+ else:
+ if not SdbManager.sdbPush(wrapper.get_deviceId(),File_Dir+"TC_Timeout.txt","/tmp/"):
+ LOGGER.error("Not able to push file in device")
+ raise
+
isPreconSet = wrapper.is_enable_preconf_func()
devmgr.setDbuteDevIds(wrapper.getDbuteDevIds())
raise
env_manager = EnvironmentManager(plans, isPreconSet, \
- wrapper.get_tracking_dump(), devmgr)
+ devmgr)
env_manager.setup()
MRP_i = MultiRunnPlan.getInstance()
for counter, plan in enumerate(MRP_i.getPlanDict().values()):
th = None
+ run_timeout = 1440 #Time in min after which tct-shell exits
if Constants.isDistMode():
th = AutoPlanExecutor(plan, counter + 1, isPreconSet, \
- env_manager, wrapper.get_run_timeout(), devmgr)
+ env_manager, run_timeout, devmgr)
else:
th = PlanExecutor(plan, counter + 1, isPreconSet, devmgr)
TCT_HOME = "/opt/tct/"
+ GlobalProfile = ""
+
SUITE_TEST_EXPECTED_TIME = 7
TCT_PLAN_FOLDER = "/opt/tools/shell/plan/"
- TCT_SCEN_FOLDER = "/opt/tools/shell/scen/"
-
STYLE_FOLDER = "/opt/tools/shell/style/"
DEVICE_HEALTH_CMD = "/opt/tct/%s/scripts/tct-config-device.py"
TCT_LOG_FOLDER = "/opt/tools/shell/tmp/logs"
DEFAULT_TIZENV = ""
+
+ DEFAULT_TIMEOUT = ""
#SDB Command
SDB_PUSH = "sdb -s %s push"
LOCAL_CAPABILITY_PATH = "/opt/tools/shell/tmp/%s/device_capability.xml"
LOCAL_BUILD_INFO_PATH = "/opt/tools/shell/tmp/%s/buildinfo.xml"
LOCAL_SHELL_TEMP_PATH = "/opt/tools/shell/tmp/%s/"
+ SOURCE_XML_PATH = "/opt/tct/%s/resource"
+
+ DEVICE_MODEL_CONFIG_PATH = "/etc/config/model-config.xml"
+ DEVICE_INFO_INI_PATH = "/etc/info.ini"
+ DEVICE_CPU_INFO_PATH = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"
+ EMUL_CPU_INFO_PATH = "/proc/cpuinfo"
#Testkit-Lite
LITE_CMD1 = "testkit-lite1.0"
UNINSTALL_ZIP_24 = "inst.sh -u"
UNINSTALL_ZIP_W3 = "inst.py -u"
- #Scenario Generator
- DEFAULT_SCEN_NAME = "Scen_Full_test"
-
#Plan Generator
ALL_PROFILES = ['mobile', 'wearable', 'tv']
DEFAULT_MATCH_REGEX = "*.zip"
#Running Mode
RUNNING_MODE_PLAN = "plan"
- RUNNING_MODE_SCEN = "scenario"
RUNNING_MODE_RERUN = "rerun"
RUNNING_MODE_SUITES = "suites"
RUNNING_MODE_PROFILE = "profile"
RERUNING_MODE = False
- SCENARIO_MODE = False
DISTRIBUTE_MODE = False
#PRECONFIGURE
PRE_CONF_HOST_JSON = "/opt/tools/shell/tmp/%s/preconfigure.json"
PRE_CONF_HOST_XML = "/opt/tools/shell/tmp/%s/tests.xml"
PORT_CONF_HOST_JSON = "/opt/tools/shell/tmp/%s/portconfigure.json"
- NAT_CONF_HOST_TXT = "/opt/tools/shell/tmp/%s/TC_Config.txt"
+ NAT_CONF_HOST_TXT = "/opt/tools/shell/tmp/%s/TCT_Preconditions.txt"
NAT_CONF_DEVICE_TXT = "/opt/usr/home/owner/share/"
#Waiting Time
return os.path.join(Constants.DEVICE_SUITE_TARGET_24, "Documents/tct/capability.xml")
@staticmethod
+ def getDEVICE_XML_PATH(_tizenV):
+ if _tizenV and float(_tizenV.split('_')[-1]) >= 3.0:
+ return os.path.join(Constants.DEVICE_SUITE_TARGET_30, "Documents/tct/")
+ else:
+ return os.path.join(Constants.DEVICE_SUITE_TARGET_24, "Documents/tct/")
+
+ @staticmethod
def getPRE_CONF_DEVICE_INI(_tizenV):
if _tizenV and float(_tizenV.split('_')[-1]) >= 3.0:
return os.path.join(Constants.DEVICE_SUITE_TARGET_30, "tct/opt/tct-testconfig/tct-testconfig.ini")
@staticmethod
def getNAT_CONF_DEVICE_TXT(_tizenV):
if _tizenV and float(_tizenV.split('_')[-1]) >= 3.0:
- return os.path.join(Constants.DEVICE_SUITE_TARGET_30, "tct/opt/tct-testconfig/TC_Config.txt")
+ return os.path.join(Constants.DEVICE_SUITE_TARGET_30, "tct/opt/tct-testconfig/TCT_Preconditions.txt")
else:
- return os.path.join(Constants.DEVICE_SUITE_TARGET_24, "tct/opt/tct-testconfig/TC_Config.txt")
+ return os.path.join(Constants.DEVICE_SUITE_TARGET_24, "tct/opt/tct-testconfig/TCT_Preconditions.txt")
@staticmethod
def setLogLevel(lvl):
Constants.RERUNING_MODE = isRerun
@staticmethod
- def setScenMode(isScen):
- Constants.SCENARIO_MODE = isScen
-
- @staticmethod
def setDistMode(isDist):
Constants.DISTRIBUTE_MODE = isDist
return Constants.DISTRIBUTE_MODE
@staticmethod
- def isScenMode():
- return Constants.SCENARIO_MODE
-
- @staticmethod
def checkBuildIds(devs):
check = True
if len(devs) == 0:
Constants.DEFAULT_TIZENV = _tizenV
@staticmethod
+ def set_default_timeout(_timeout):
+ Constants.DEFAULT_TIMEOUT = _timeout
+
+ @staticmethod
def get_tct_binaryV():
tct_binV = ""
ver_path = '/opt/tct/%s/VERSION' % Constants.DEFAULT_TIZENV
LOGGER.debug("No need to reboot. Waking up other devices")
break
'''
- LOGGER.info("Wait for the connected devices to be reconnected [%s:%s]" % \
- (str(timeout), str(Constants.NO_WORKERS_TIMEOUT)))
- time.sleep(10)
+ #LOGGER.info("Wait for the connected devices to be reconnected [%s:%s]" % \
+ #(str(timeout), str(Constants.NO_WORKERS_TIMEOUT)))
+ #time.sleep(10)
timeout += 10
if timeout >= Constants.NO_WORKERS_TIMEOUT:
- LOGGER.error("The reboot times for all the devices have been exceeded")
+ LOGGER.error("All devices are not available")
while not self.suite_q.empty():
self.suites[None].insert(0, (self.suite_q.get(True)))
self._auto_test_inhost(self.suites[None])
if not self.devmgr.isDeviceAvailable(self.deviceId) and \
not is_reboot_timeout:
#reboot
- LOGGER.error("Please reboot device : %s" % self.deviceId)
+ #LOGGER.error("Please reboot device : %s" % self.deviceId)
#scheduling purpose: waiting for UsbMonitor to release lock.
try:
self.rebootLock.get(block=True, timeout=60)
elif is_reboot_timeout:
self.killThread()
- LOGGER.error("%s is reboot timeout" % self.deviceId)
+ #LOGGER.error("%s is reboot timeout" % self.deviceId)
break
else:
if self.isRebooting():
class EnvironmentManager:
- def __init__(self, plans, isPreconSet, dump_name, devmgr):
+ def __init__(self, plans, isPreconSet, devmgr):
self.plans = plans
self.dev_plans = {}
self.env_threads = []
self.netstat_monitors = []
self.dump_monitors = []
self.dev_recovery_locks = {}
- self.dump_name = dump_name
self.devmgr = devmgr
self.orgPlans()
self.load_devices()
from .logmanager import LOGGER
from .shellplanner import *
-
def _verifyPlan(planfile, tizenVersion):
xml_tree = ElementTree.parse(planfile)
xml_root = xml_tree.getroot()
return set_autocnt, set_manualcnt, tcCheck
-def _parsTestScenario(scen_name, file_path, stubPort, skip_package, \
- skip_count, skip_tc):
- LOGGER.debug("parsing Test Scenario : " + file_path)
- plans = []
- xml_tree = ElementTree.parse(file_path)
- xml_root = xml_tree.getroot()
- for xml_plan in xml_root.findall('plan'):
- plan_file_path = xml_plan.find("path").text
- plan_name = xml_plan.get("name")
- plan_deviceId = xml_plan.find("device").get("id")
- plan_tizenVersion = xml_plan.find("version").text
- plans.append(_parsTestPlan(plan_file_path, plan_name, plan_deviceId, \
- None, plan_tizenVersion, None, stubPort, skip_package, \
- skip_count, skip_tc, scen_name)[0])
- return plans
-
-
# return : TctShellSuite []
def _parsTestPlan(file_path, plan_name, deviceId, executeType, tizenVersion, \
- resultFolder, stubPort, skip_package, skip_count, skip_tc, devmgr, \
- scen_name=None, make_ne_package=None, pre_test=None, post_test=None):
+ resultFolder, stubPort, skip_package, skip_tc, devmgr, \
+ pre_test=None, post_test=None):
suites = []
profile = ""
if not _verifyPlan(file_path, tizenVersion):
xml_root = xml_tree.getroot()
if xml_root.get('profile') is not None:
profile = xml_root.get('profile')
+ Constants.GlobalProfile = xml_root.get('profile')
if not executeType:
executeType = ExecuteType.createExecuteType(\
continue
packName = xml_suite.get("name")
+ package_name = xml_suite.find("pkg_name").text
+ LOGGER.info("package_name is " + str(package_name))
+ if Constants.GlobalProfile == "":
+ package_list = package_name.split('/')
+ Constants.GlobalProfile = package_list[0]
+ LOGGER.info("GlobalProfile is " + str(Constants.GlobalProfile))
+
if skip_package and str(skip_package).find(packName) > -1:
LOGGER.info("[skip package : %s]" % packName)
else:
- is_make_ne = 0
- if make_ne_package and str(make_ne_package).find(suite_name) > -1:
- issue_num = _pars_issue_num(make_ne_package[0], suite_name)
- is_make_ne = int(issue_num)
-
suite = TctShellSuite(packName, None, \
xml_suite.find("auto_tcn").text, \
xml_suite.find("manual_tcn").text, \
xml_suite.find("pkg_name").text, \
xml_suite.get("launcher"), xml_suite.get("category"), \
- tizenVersion, skip_count, skip_tc, devmgr, \
+ tizenVersion, skip_tc, devmgr, \
pre_test=pre_test, \
- post_test=post_test, \
- is_make_ne=is_make_ne)
+ post_test=post_test)
suites.append(suite)
plan = TctShellPlan(plan_name, devmgr, deviceId, profile, executeType, \
- suites, tizenVersion, resultFolder, stubPort, scen_name)
+ suites, tizenVersion, resultFolder, stubPort)
if Constants.isDistMode():
if not plan.setup_distribute():
def _parsTestProfile(path_suites, deviceId, executeType, tizenV, profile, \
- resultFolder, stubPort, skip_package, skip_count, skip_tc, devmgr, \
- distribute_count, make_ne_package=None, pre_test=None, post_test=None):
+ resultFolder, stubPort, skip_package, skip_tc, devmgr, \
+ distribute_count, pre_test=None, post_test=None):
suites = []
LOGGER.debug("Preparing Test Suite ")
suite_profile = os.path.basename(os.path.dirname(path_suites[0]))
+ Constants.GlobalProfile = suite_profile
+
for counter, suite_path in enumerate(path_suites):
counter = counter + 1
suite_profile = os.path.basename(os.path.dirname(suite_path))
elif auto_num == 0 and manual_num == 0:
pass
else:
- is_make_ne = 0
- if make_ne_package and str(make_ne_package).find(suite_name) > -1:
- issue_num = _pars_issue_num(make_ne_package[0], suite_name)
- is_make_ne = int(issue_num)
-
suite = TctShellSuite(suite_name, None, auto_num, manual_num, \
suite_pkg_name, suite_launcher, suite_category, \
- suite_tizenVer, skip_count, skip_tc, devmgr, \
+ suite_tizenVer, skip_tc, devmgr, \
pre_test=pre_test, \
- post_test=post_test, \
- is_make_ne=is_make_ne)
+ post_test=post_test)
if not distribute_count:
suites.append(suite)
def _parsTestSuite(path_suites, deviceId, executeType, tizenVersion, tc_name, \
- resultFolder, stubPort, devmgr, skip_count=None, skip_tc=None, \
- pre_test=None, post_test=None, make_ne_package=None):
+ resultFolder, stubPort, devmgr, skip_tc=None, \
+ pre_test=None, post_test=None):
#type(suites) -> list
suites = []
LOGGER.debug("Preparing Test Suite ")
suite_profile = os.path.basename(os.path.dirname(path_suites[0]))
for suite_path in path_suites:
+ suite_profile = os.path.basename(os.path.dirname(suite_path))
suite_zipname = os.path.basename(suite_path)
suite_name = _geneSuiteName(suite_zipname, tizenVersion)
auto_num, manual_num, suite_launcher, suite_category, tc_exist, s_name\
suite_pkg_name = os.path.join(suite_profile, \
os.path.basename(suite_path))
- is_make_ne = 0
- if make_ne_package and str(make_ne_package).find(suite_name) > -1:
- issue_num = _pars_issue_num(make_ne_package[0], suite_name)
- is_make_ne = int(issue_num)
-
suite = TctShellSuite(suite_name, tc_name, auto_num, manual_num, \
suite_pkg_name, suite_launcher, suite_category, \
- suite_tizenVer, skip_count, skip_tc, devmgr, \
+ suite_tizenVer, skip_tc, devmgr, \
pre_test=pre_test, \
- post_test=post_test, \
- is_make_ne=is_make_ne)
+ post_test=post_test)
suites.append(suite)
Constants.clean_unzip_file()
temp_plan_name = "temp_plan_name"
- plan = TctShellPlan(temp_plan_name, devmgr, deviceId, suite_profile, executeType, \
+ if (Constants.GlobalProfile is None) or (Constants.GlobalProfile == ""):
+ Constants.GlobalProfile = suite_profile
+ plan = TctShellPlan(temp_plan_name, devmgr, deviceId, Constants.GlobalProfile, executeType, \
suites, tizenVersion, resultFolder, stubPort)
if Constants.isDistMode():
def _parsAutoPlan(planFile, plan_name, executeType, tizenVer, \
- resultFolderPath, stubPort, skip_package, skip_count, skip_tc, \
- devmgr, pre_test=None, post_test=None, make_ne_package=None):
+ resultFolderPath, stubPort, skip_package, skip_tc, \
+ devmgr, pre_test=None, post_test=None):
if not _verifyPlan(planFile, tizenVer):
LOGGER.warning("Please check the plan xml file: %s" % planFile)
return None
xml_root = xml_tree.getroot()
if xml_root.get('profile') is not None:
profile = xml_root.get('profile')
+ Constants.GlobalProfile = profile
if not executeType:
executeType = ExecuteType.createExecuteType(\
if skip_package and str(skip_package).find(suite_name) > -1:
LOGGER.error("[skip package : %s]" % suite_name)
else:
- is_make_ne = 0
- if make_ne_package and str(make_ne_package).find(suite_name) > -1:
- issue_num = _pars_issue_num(make_ne_package[0], suite_name)
- is_make_ne = int(issue_num)
-
suite = TctShellSuite(suite_name, None, \
xml_suite.find("auto_tcn").text, xml_suite.find("manual_tcn").text,\
xml_suite.find("pkg_name").text, xml_suite.get("launcher"), \
- xml_suite.get("category"), tizenVer, skip_count, skip_tc, \
- devmgr, pre_test=pre_test, post_test=post_test, is_make_ne=is_make_ne)
+ xml_suite.get("category"), tizenVer, skip_tc, \
+ devmgr, pre_test=pre_test, post_test=post_test)
suite.setExpectedTime(etime)
if suite.suite_pkg_name is None:
return planList
-def _parsResultForRerun(wrapper, skip_package, skip_count, skip_tc, devmgr, \
- distribute_count, pre_test=None, post_test=None, make_ne_package=None):
+def _parsResultForRerun(wrapper, skip_package, skip_tc, devmgr, \
+ distribute_count, pre_test=None, post_test=None):
result = wrapper.get_result_for_rerun()
rerun_plan_creator = ResultSummary()
rerun_data = rerun_plan_creator.prepareRerun(result)
plan_name = intention_info[0]
executeType = ExecuteType.createExecuteType(intention_info[1])
profile = intention_info[2]
+ Constants.GlobalProfile = profile
tizenVer = intention_info[3]
deviceId = intention_info[4]
- scen_resultFolderPath = intention_info[6]
if len(suites_path) < 1:
LOGGER.debug("No unpassed results to rerun in plan: [%s]" \
continue
if devmgr.getDevice(deviceId) is None:
- if len(rerun_data) > 1:
- LOGGER.error("Required devices not connected. " + \
- "Check what devices were used for the scenario.")
-
LOGGER.warning("WARNING: \
Device used for the test is not connected: \
device id: %s" % deviceId)
if skip_package and str(skip_package).find(suite_name) > -1:
LOGGER.error("[skip package : %s]" % suite_name)
else:
- is_make_ne = 0
- if make_ne_package and \
- str(make_ne_package).find(suite_name) > -1:
- issue_num = _pars_issue_num(make_ne_package[0], \
- suite_name)
- is_make_ne = int(issue_num)
-
suite = TctShellSuite(suite_name, None, auto_num, manual_num, \
suite_pkg_name, suite_launcher, suite_category, \
- tizenVer, skip_count, skip_tc, devmgr, \
+ tizenVer, skip_tc, devmgr, \
pre_test=pre_test, \
- post_test=post_test, \
- is_make_ne=is_make_ne)
+ post_test=post_test)
if not distribute_count:
suites.append(suite)
suites.append(suite)
plan = TctShellPlan(plan_name, devmgr, deviceId, profile, executeType, suites,\
- tizenVer, resultFolderPath, wrapper.get_stubPort())
- plan.setScenResultFolderPath(scen_resultFolderPath)
+ tizenVer, resultFolderPath, wrapper.get_default_stubPort())
plan.setRerunning(True)
plans.append(plan)
return False
-def _pars_issue_num(_make_ne_package, _suite_name):
- ne_pack_list = _make_ne_package.split(',')
- for _pn in ne_pack_list:
- if _pn.find(_suite_name) > -1:
- return _pn.split(':')[1]
- return 0
-
-
class IntentionGenerator:
# return : bool
@staticmethod
def genIntentionData(wrapper, devmgr):
skip_package = wrapper.get_skip_package()
- skip_count = wrapper.get_skip_count()
skip_tc = wrapper.get_skip_tc()
- make_ne_package = wrapper.get_make_ne()
pre_test = wrapper.get_pre_test()
post_test = wrapper.get_post_test()
distribute_count = wrapper.get_distribute_count()
if wrapper.get_running_mode() == Constants.RUNNING_MODE_RERUN:
- return _parsResultForRerun(wrapper, skip_package, skip_count, \
- skip_tc, devmgr, distribute_count, \
- make_ne_package=make_ne_package)
+ return _parsResultForRerun(wrapper, skip_package, \
+ skip_tc, devmgr, distribute_count)
intention_type = wrapper.getIntentionType()
deviceId = None
suites = wrapper.get_suites()
tizenVer = wrapper.get_tizenV()
resultFolderPath = wrapper.get_resultFolderPath()
- stubPort = wrapper.get_stubPort()
+ stubPort = wrapper.get_default_stubPort()
if intention_type == -1:
return None
intention_type == IntentionType.TestProfile or \
intention_type == IntentionType.TestSuite) and \
not Constants.isDistMode():
- if not wrapper.is_make_summary_mode():
- if not devmgr.isDeviceAvailable(deviceId):
- LOGGER.error("Device [%s] is not connected" % deviceId)
- LOGGER.error("Required devices not connected properly")
- return None
-
- if intention_type == IntentionType.TestScenario:
- scenFile = wrapper.get_scenfile()
- scenName = wrapper.get_scen_name()
- plans = _parsTestScenario(scenName, scenFile, stubPort, \
- skip_package, skip_count, skip_tc)
- elif intention_type == IntentionType.TestPlan:
+ if not devmgr.isDeviceAvailable(deviceId):
+ LOGGER.error("Device [%s] is not connected" % deviceId)
+ LOGGER.error("Required devices not connected properly")
+ return None
+
+ if intention_type == IntentionType.TestPlan:
name = wrapper.get_plan_name()
planFile = wrapper.get_planfile()
plans = _parsTestPlan(planFile, name, deviceId, executeType, \
tizenVer, resultFolderPath, stubPort, skip_package, \
- skip_count, skip_tc, devmgr, make_ne_package=make_ne_package, \
- pre_test=pre_test, post_test=post_test)
+ skip_tc, devmgr,pre_test=pre_test, \
+ post_test=post_test)
elif intention_type == IntentionType.TestCase:
plans = _parsTestCase(suites, deviceId, executeType, tizenVer, \
tcId, resultFolderPath, stubPort, devmgr)
elif intention_type == IntentionType.TestSuite:
+ if(Constants.GlobalProfile == None) or (Constants.GlobalProfile == ""):
+ profile = wrapper.get_profile()
+ Constants.GlobalProfile = profile
plans = _parsTestSuite(suites, deviceId, executeType, tizenVer, \
- None, resultFolderPath, stubPort, devmgr, skip_count, \
- skip_tc, make_ne_package=make_ne_package, pre_test=pre_test, post_test=post_test)
+ None, resultFolderPath, stubPort, devmgr, \
+ skip_tc, pre_test=pre_test, post_test=post_test)
elif intention_type == IntentionType.AutoPlan:
name = wrapper.get_plan_name()
autoFile = wrapper.get_autoplanfile()
plans = _parsAutoPlan(autoFile, name, executeType, tizenVer, \
- resultFolderPath, stubPort, skip_package, skip_count, \
- skip_tc, devmgr, make_ne_package=make_ne_package, pre_test=pre_test, post_test=post_test)
+ resultFolderPath, stubPort, skip_package, \
+ skip_tc, devmgr, pre_test=pre_test, post_test=post_test)
elif intention_type == IntentionType.TestProfile:
profile_suites = wrapper.get_profile_suites()
if not profile_suites:
return None
profile = wrapper.get_profile()
+ Constants.GlobalProfile = profile
plans = _parsTestProfile(profile_suites, deviceId, executeType, \
tizenVer, profile, resultFolderPath, stubPort, \
- skip_package, skip_count, skip_tc, devmgr, distribute_count, \
- make_ne_package=make_ne_package, pre_test=pre_test, post_test=post_test)
-
+ skip_package, skip_tc, devmgr, distribute_count, \
+ pre_test=pre_test, post_test=post_test)
return plans
def genSummary(self, plans):
summary_file = None
- #browser = 'firefox'
- if Constants.RERUNING_MODE and Constants.SCENARIO_MODE:
- summary = ResultSummary(plans=plans)
- summary_file = summary.rerun_genSummaryForScen()
- summary.updateScenStatus()
- elif len(plans) > 1:
- LOGGER.debug("generate Summary for Scenario")
- summary = ResultSummary(plans=plans)
- summary.makeMergedFolder()
- summary_file = summary.genSummaryForScen()
- summary.genScenStatus()
- elif len(plans) == 1:
+ if len(plans) == 1:
summary_file = os.path.join(\
plans[0].getResultFolderPath(), 'summary.xml')
if summary_file is not None:
if not os.path.isfile(summary_file):
LOGGER.warning("Summary file [%s] does not exist" % summary_file)
- '''
- else:
- try:
- url_path = urlparse.urljoin('file:', \
- urllib.pathname2url(summary_file))
- webbrowser.get(browser).open(url_path, new=2)
- except Exception, e:
- LOGGER.error("[ Error: opening summary file with \
- %s failed, error: %s ]\n" %(browser, e))
- pass
- '''
def print_result_summaries(self):
resultFolderPaths = []
tizenV = None
if self.plans:
- scen_resultFolderPath = None
for plan in self.plans:
if tizenV is None:
tizenV = plan.getTizenVersion()
- if plan.scen_resultFolderPath is None or \
- not os.path.isdir(plan.scen_resultFolderPath):
- resultFolderPath = plan.getResultFolderPath()
- summary_xml = os.path.join(resultFolderPath, 'summary.xml')
- self.print_result_summary(summary_xml)
- resultFolderPaths.append(\
- (plan.getPlanName(), resultFolderPath))
- elif plan.scen_resultFolderPath != scen_resultFolderPath:
- resultFolderPath = plan.getScenResultFolderPath()
- scen_resultFolderPath = resultFolderPath
- summary_xml = os.path.join(resultFolderPath, 'summary.xml')
- self.print_result_summary(summary_xml)
- resultFolderPaths.append(\
- (plan.getScenName(), resultFolderPath))
+ resultFolderPath = plan.getResultFolderPath()
+ summary_xml = os.path.join(resultFolderPath, 'summary.xml')
+ self.print_result_summary(summary_xml)
+ resultFolderPaths.append(\
+ (plan.getPlanName(), resultFolderPath))
distribute = " --distribute" if Constants.isDistMode() else ""
rerun_command = "tct-shell --tizen-version {0} --rerun-fail %s {1}".\
from xml.etree import ElementTree
import os
+import sys
import glob
import shutil
import errno
headplan = plans[0]
self.head_profile = headplan.getProfile()
self.head_deviceid = headplan.getDeviceId()
- self.scenid = headplan.getScenName()
- self.scen_resultFolder = headplan.getScenResultFolderPath()
- if len(plans) > 1:
- for plan in plans[1:]:
- plan.setScenResultFolderPath(self.scen_resultFolder)
self.env = self.ResEnvironment()
self.summary = self.ResSummary()
tree.write(os.path.join(plan.getResultFolderPath(), \
"plan_status.xml"), encoding="UTF-8")
- def genScenStatus(self):
- root = ElementTree.Element('scen_status')
- ele_set(root, 'scenario_name', self.scenid)
- for plan in self.plans:
- plan_root = ElementTree.Element('plan')
- ele_set(plan_root, 'name', plan.getPlanName())
- ele_set(plan_root, 'result_folder', plan.getResultFolderPath())
- ele_set(plan_root, 'has_unpass_tc', str(plan.getUnpass()))
- device = ElementTree.Element('device')
- ele_set(device, 'device_id', plan.getDeviceId())
- ele_set(device, 'build_id', plan.getBuildId())
- plan_root.append(device)
- root.append(plan_root)
- Constants.indent(root)
- tree = ElementTree.ElementTree()
- tree._setroot(root)
- tree.write(os.path.join(self.scen_resultFolder, \
- "scenario_status.xml"), encoding="UTF-8")
- LOGGER.info("SENARIO_STATUS TO XML: writing into %s" \
- % os.path.join(self.scen_resultFolder, "scenario_status.xml"))
-
- def updateScenStatus(self):
- scenstat = os.path.join(self.scen_resultFolder, 'scenario_status.xml')
- if not os.path.isfile(scenstat):
- LOGGER.error("scenario_status.xml should be present in \
- [%s]. Not Found" % self.scen_resultFolder)
- raise
- xml_tree = ElementTree.parse(scenstat)
- root = xml_tree.getroot()
- for plan in root.findall('plan'):
- for rerun_plan in self.plans:
- if plan.get('name') == rerun_plan.getPlanName():
- ele_set(plan, 'has_unpass_tc', str(rerun_plan.getUnpass()))
-
- tree = ElementTree.ElementTree()
- tree._setroot(root)
- tree.write(scenstat, encoding="UTF-8")
- LOGGER.info("UPDATING SENARIO_STATUS TO XML: writing into %s" \
- % scenstat)
-
def prepareRerun(self, result):
suiteFiles = {}
suitePkgs = {}
- scen_resultFolderPath = None
if os.path.isdir(result):
if os.path.isfile(os.path.join(result, "plan_status.xml")):
suiteFiles = self.prepareRerun_Plan(result)
- elif os.path.isfile(os.path.join(result, "scenario_status.xml")):
- suiteFiles = self.prepareRerun_Scen(result)
- Constants.setScenMode(True)
- Constants.setDistMode(False)
- scen_resultFolderPath = result
elif os.path.isfile(result):
suiteFiles = self.prepareRerun_Suite(result)
else:
raise
suitePkgs[planFolder] = [[plan_name, executeType, profile, \
tizenVersion, device_id, build_id, \
- scen_resultFolderPath], suite_pkgs]
+ ], suite_pkgs]
return suitePkgs
def prepareRerun_Suite(self, result):
suiteFiles[result] = {}
os.chdir(result)
for suite in glob.glob("*.xml"):
- if 'auto' in suite or 'manual' in suite or 'rerun' in suite \
+ if 'auto.' in suite or 'manual.' in suite or 'rerun' in suite \
or 'status.xml' in suite or suite == 'summary.xml':
continue
suiteFile = os.path.abspath(suite)
suiteFiles[result][suiteFile[:-4]] = suiteFile
return self.genRerunFile(suiteFiles)
- def prepareRerun_Scen(self, result):
- suiteFiles = {}
- planResultFolders = []
- scen_status = os.path.join(result, "scenario_status.xml")
- xml_tree = ElementTree.parse(os.path.join(scen_status))
- xml_root = xml_tree.getroot()
- for xml_plan in xml_root.findall('plan'):
- if xml_plan.get('has_unpass_tc') == "True":
- planResultFolders.append(xml_plan.get('result_folder'))
-
- for planResult in planResultFolders:
- suiteFiles.update(self.prepareRerun_Plan(planResult))
-
- return suiteFiles
-
def genRerunFile(self, rerun_suiteFiles):
if not bool(rerun_suiteFiles):
LOGGER.debug("No suite results exist...")
xml_root = xml_tree.getroot()
if self.env.isNull:
self.env.parse(ele_find(xml_root, 'environment'))
+ if self.env.device_id=="None" and self.plans:
+ LOGGER.debug("%s has inaccurate device_id information" % suiteFile)
+ self.env.device_id = self.plans[0].getDeviceId()
+ LOGGER.debug("Updated device_id : %s" % self.env.device_id)
+ dev_buildinfo = Constants.LOCAL_BUILD_INFO_PATH % self.env.device_id
+ if os.path.exists(dev_buildinfo):
+ xml_infotree = ElementTree.parse(dev_buildinfo)
+ xml_inforoot = xml_infotree.getroot()
+ for buildinfo in xml_inforoot.findall('buildinfo'):
+ if buildinfo.get('name')=='model' and self.env.device_model=="":
+ self.env.device_model = buildinfo.find('value').text
+ elif buildinfo.get('name')=='manufacturer' and self.env.manufacturer=="":
+ self.env.manufacturer = buildinfo.find('value').text
+ elif buildinfo.get('name')=='buildVersion' and self.env.build_id=="":
+ self.env.build_id = buildinfo.find('value').text
if self.env.tct_profile is None:
self.env.tct_profile = self.profile
if self.summary.isNull:
self.suites = []
if self.env.isNull:
self.env.parse(ele_find(xml_root1, 'environment'))
+ if self.env.device_id=="None" and self.plans:
+ LOGGER.debug("%s has inaccurate device_id information" % suiteFile)
+ self.env.device_id = self.plans[0].getDeviceId()
+ LOGGER.debug("Updated device_id : %s" % self.env.device_id)
+ dev_buildinfo = Constants.LOCAL_BUILD_INFO_PATH % self.env.device_id
+ if os.path.exists(dev_buildinfo):
+ xml_infotree = ElementTree.parse(dev_buildinfo)
+ xml_inforoot = xml_infotree.getroot()
+ for buildinfo in xml_inforoot.findall('buildinfo'):
+ if buildinfo.get('name')=='model' and self.env.device_model=="":
+ self.env.device_model = buildinfo.find('value').text
+ elif buildinfo.get('name')=='manufacturer' and self.env.manufacturer=="":
+ self.env.manufacturer = buildinfo.find('value').text
+ elif buildinfo.get('name')=='buildVersion' and self.env.build_id=="":
+ self.env.build_id = buildinfo.find('value').text
if self.env.tct_profile is None:
self.env.tct_profile = self.profile
decl1 = ElementTree.PI('xml-stylesheet', \
'type="text/xsl" href="./style/testresult.xsl"')
decl1.tail = "\n"
- '''
- decl2 = ElementTree.PI('xml-stylesheet', \
- 'type="text/xsl" href="testresult.xsl"')
- decl2.tail = "\n"
- '''
decl_root.append(decl1)
#decl_root.append(decl2)
root = ElementTree.Element('test_definition')
suiteFiles[plan_resultFolder][suiteFile[:-4]] = []
return suiteFiles
- def _rerun_findResultSuites_scen(self):
- suiteFiles = {}
- scen_resultFolder = self.scen_resultFolder
- suiteFiles[scen_resultFolder] = {}
- os.chdir(scen_resultFolder)
- for suiteFile in glob.glob("*.xml"):
- if 'auto.xml' in suiteFile or 'manual.xml' in suiteFile \
- or 'rerun.xml' in suiteFile or 'status.xml' \
- in suiteFile or suiteFile == 'summary.xml':
- continue
- suiteFiles[scen_resultFolder][suiteFile[:-4]] = []
- return suiteFiles
-
- def _not_in_use_rerun_findResultSuites_scen(self, scen_status):
- suiteFiles = {}
- xml_scenstat = ElementTree.parse(scen_status)
- root = xml_scenstat.getroot()
- for plan in root.findall('plan'):
- plan_resultFolder = plan.get('result_folder')
- suiteFiles[plan_resultFolder] = []
- os.chdir(plan_resultFolder)
- for suiteFile in glob.glob("*.xml"):
- if 'auto.xml' in suiteFile or 'manual.xml' in suiteFile \
- or 'rerun.xml' in suiteFile or 'status.xml' \
- in suiteFile or suiteFile == 'summary.xml':
- continue
- suiteFiles[plan_resultFolder].append(suiteFile)
- return suiteFiles
-
- #return folderPath
- def makeMergedFolder(self):
- #create mergeFolder
- if Constants.RERUNING_MODE and Constants.SCENARIO_MODE:
- if not os.path.isdir(self.scen_resultFolder):
- LOGGER.warning("RERUN: cannot find original result folder : \
- [%s]" % self.scen_resultFolder)
- else:
- os.mkdir(self.scen_resultFolder, mode=0o777)
- return
-
- def suiteCopyFiles(self):
- self.suites = []
- self.suiteFiles = self._findResultSuites()
- suiteResults_scen = []
- for planFolder, plan in self.suiteFiles.items():
- for suite_am in plan.keys():
- resultFile = suite_am + ".xml"
- if not os.path.isfile(resultFile):
- continue
- dest = os.path.join(self.scen_resultFolder, \
- os.path.basename(resultFile))
- if os.path.isfile(dest):
- self.mergeSuiteResults(dest, resultFile)
- continue
- copyfiledir(resultFile, dest)
- suiteResults_scen.append(dest)
- return suiteResults_scen
-
- def _rerunReplaceResults(self, suiteFiles):
- updated_check = []
- for planFolder, plan in suiteFiles.items():
- for suite_am in plan.keys():
- resultFile = suite_am + ".xml"
- if not os.path.isfile(resultFile):
- continue
- dest = os.path.join(self.scen_resultFolder, \
- os.path.basename(resultFile))
- if os.path.isfile(dest):
- if suite_am in updated_check:
- self.mergeSuiteResults(dest, resultFile)
- else:
- self.mergeRerunResults(dest, resultFile)
- updated_check.append(suite_am)
- else:
- LOGGER.warning("The original result xml does not exist \
- in the scenario file. File: [%s]" % dest)
-
- def genSummaryForScen(self):
- self.deviceid = self.head_deviceid
- self.profile = self.head_profile
- self.planid = self.scenid
- suiteFiles = self.suiteCopyFiles()
- self.suites = []
- self.parse(suiteFiles)
- dest = os.path.join(self.scen_resultFolder, 'summary.xml')
- self.summary_to_xml(dest)
- return dest
-
- def rerun_genSummaryForScen(self):
- self._rerunReplaceResults(self._findResultSuites())
- suiteFiles = self._rerun_findResultSuites_scen()
- for scenFolder, scen in suiteFiles.items():
- suiteResults_scen = []
- for suite_am in scen.keys():
- suiteResults_scen.append(suite_am + ".xml")
- self.suites = []
- self.parse(suiteResults_scen)
- dest = os.path.join(self.scen_resultFolder, 'summary.xml')
- self.summary_to_xml(dest)
- return dest
-
def mergeRerunResults(self, src1, src2):
self.mergeSuiteResults(src1, src2, priority="PASS")
self.name = None
self.support = None
self.typ = None
+ self.val = None
def parse(self, cap):
self.name = cap.get('name')
self.support = cap.get('support')
self.typ = cap.get('type')
+ if self.typ!='boolean':
+ self.val = cap.find('value').text
def to_xml(self):
cap = ElementTree.Element('capability')
ele_set(cap, 'name', self.name)
ele_set(cap, 'support', self.support)
ele_set(cap, 'type', self.typ)
+ if self.typ!='boolean':
+ val = ElementTree.SubElement(cap, 'value')
+ val.text = self.val
return cap
class ResSuite:
+++ /dev/null
-#!/usr/bin/python
-
-import os
-import re
-import sys, traceback
-import glob
-from constants import Constants
-from xml.etree import ElementTree
-import xml.etree.ElementTree as etree
-from Tkinter import *
-import tkMessageBox
-from optparse import *
-from devicemanager import DeviceManager
-from logmanager import LOGGER
-
-def vanarg(option, opt_str, value, parser):
- value = []
- for arg in parser.rargs:
- if re.search('^--.+', arg) or re.search('^-[\D]', arg):
- break
- value.append(arg)
- del parser.rargs[:len(value)]
- setattr(parser.values, option.dest, value)
-
-def printPlans_Devices(option, opt_str, value, parser):
- printPlanList()
- printDeviceList()
- sys.exit(1)
-
-def printPlanList():
- print "\nAvaiable Plans:...\n"
- folder = Constants.TCT_PLAN_FOLDER
- os.chdir(folder)
- for files in glob.glob("*.xml"):
- print files[:-4]
-
-def printDeviceList():
- print "\nConnected Devices:...\n"
- dmi = DeviceManager.getInstance()
- dmi.loadDeviceList()
- devices = dmi.getSdbDeviceList()
- for dev in devices:
- dev._printDevInfo()
- if len(devices) < 1:
- print "No Connected Devices"
-
-class ScenarioGeneratorOptions:
- def __init__(self):
- self._j = os.path.join
- self._e = os.path.exists
- self._d = os.path.dirname
- self._b = os.path.basename
- self._abspath = os.path.abspath
- self.options = None
- self.running_mode = None
- self.USAGE = ""
-
- def parse_options(self, argv):
- option_list = [
- make_option("--folderpath", "-f", dest = "plansrcfolder", \
- action="callback", callback=vanarg, \
- help="Specify the plan source directory"),
- make_option("-o", "--output", dest="testscen_file", \
- action="callback", callback=vanarg, \
- help="Specify the generating testscen in a XML file."),
- make_option("-d", "--default", dest="default", \
- action="store_true", help="Default setting"),
- make_option("-p", "--plan", dest="plan", action="callback", \
- callback=vanarg, help="Make list of sets that match a \
- plan with a device and tizen version : \
- [plan_file],[device],[tizenversion]"),
- make_option("--list", dest="lst", action="callback", \
- callback=printPlans_Devices, help="List all existing \
- plans and connected devices")
- ]
- if len(argv) == 1:
- argv.append("-h")
- PARSERS = OptionParser(option_list=option_list, usage=self.USAGE)
-
- (self.options, args) = PARSERS.parse_args()
-
- if self.options.default is not None:
- if self.options.plansrcfolder is not None or \
- self.options.testscen_file is not None or \
- self.options.plan is not None:
- sys.exit("options: conflict")
-
- def get_scen_name(self):
- if (self.options.testscen_file is not None) and \
- (self.options.testscen_file[0] is not None):
- name, ext = os.path.splitext(self.options.testscen_file[0])
- return name.split("/")[-1]
- else:
- return Constants.DEFAULT_SCEN_NAME
-
- def get_plansrc_folder(self):
- if (self.options.plansrcfolder is not None) and \
- (self.options.plansrcfolder[0] is not None):
- return self.options.plansrcfolder[0]
- else:
- return Constants.TCT_PLAN_FOLDER
-
- def get_output(self):
- if (self.options.testscen_file is not None) and \
- (self.options.testscen_file[0] is not None):
- d = os.path.abspath(os.path.dirname(self.options.testscen_file[0]))
- if not os.path.exists(d):
- os.makedirs(d)
- return os.path.abspath(self.options.testscen_file[0])
- else:
- d = os.path.abspath(Constants.TCT_SCEN_FOLDER)
- if not os.path.exists(d):
- os.makedirs(d)
- return Constants.TCT_SCEN_FOLDER + "generated_scen.xml"
-
- def get_planlist_args(self):
- if self.options.plan is not None:
- plans = []
- dmi = DeviceManager.getInstance()
- dmi.loadDeviceList()
- for plan in self.options.plan:
- if len(plan.split(',')) != 3:
- sys.exit("[--plan]: Wrong format. See --help for correct \
- format")
- plan_name = plan.split(',')[0]
- dev_id = plan.split(',')[1]
- tizenVer = plan.split(',')[2]
- dev = dmi.getDevice(dev_id)
- if dev is None:
- sys.exit("Device: [%s] is not connected" % dev_id)
- if not os.path.isfile(os.path.join(self.get_plansrc_folder(),\
- "%s.xml" % plan_name)):
- sys.exit("Plan: [%s] does not exist in the plan source \
- folder : [%s]" % (plan_name, \
- self.get_plansrc_folder()))
- self.check_tizen_version(tizenVer)
- plans.append([plan_name, [dev.devName, dev.devId, \
- dev.devType], tizenVer])
- return plans
-
- def check_tizen_version(self, tizenversion):
- VER_PATTERN = "^tizen_web_\d.\d|^tizen_native_\d.\d|^tizen_csharp_\d.\d"
- pa = re.compile(VER_PATTERN, re.I)
- ma = pa.match(tizenversion)
- if ma is None:
- LOGGER.error("A required \"/opt/tct/" + tizenversion + "\" could \
- not be found.")
- sys.exit("Invalid Tizen version. Tizen version must be in the form\
- of tizen_(web|native|csharp)_#.#")
-
- def getPlanList(self):
- folder = self.get_plansrc_folder()
- os.chdir(folder)
- planList = []
- for files in glob.glob("*.xml"):
- planList.append(files[:-4])
- return planList
-
- def getDeviceList(self):
- deviceList = []
- dmi = DeviceManager.getInstance()
- dmi.loadDeviceList()
- devices = dmi.getSdbDeviceList()
- for dev in devices:
- deviceList.append([dev.devName, dev.devId, dev.devType])
- if len(deviceList) < 1:
- print "No Device Attached"
- sys.exit("Exit: No Connected Devices")
- return deviceList
+++ /dev/null
-#!/usr/bin/python
-
-from constants import Constants
-from xml.etree import ElementTree
-from tctshell.gui.main_window import MainWindow
-import os,os.path
-import sys
-from logmanager import LOGGER
-
-class ScenPlan:
-
- def __init__(self, folder, name, device, version):
- self.name = name
- self.device = device
- self.version = version
- self.folder = folder
-
- def to_xml(self):
- plan = ElementTree.Element('plan')
- plan.set('name', self.name)
- device = ElementTree.Element('device')
- device.set('name', self.device[0])
- device.set('id', self.device[1])
- device.set('type', self.device[2])
- plan.append(device)
- version = ElementTree.Element('version')
- version.text = self.version
- plan.append(version)
- path = ElementTree.Element('path')
- name = "#".join(self.name.split("#")[:-1])
- path.text = os.path.join(self.folder, "%s.xml" %name)
- plan.append(path)
- return plan
-
-class ScenarioRunner:
-
- def __init__(self):
- self.plans = {}
- self.scen_name = Constants.DEFAULT_SCEN_NAME
-
- def load_local_repo(self, planlist_args, path, scen_name, plan_list, dev_list):
- self.scen_name = scen_name
- count = 0
- if planlist_args is None:
- scenario = self.getPlanInfo(plan_list, dev_list)
- else:
- scenario = planlist_args
- for plans in scenario:
- count += 1
- plan = ScenPlan(path, plans[0], plans[1], plans[2])
- plan.name += "#%d" % count
- self.plans[plan.name] = plan
-
- def getPlanInfo(self, planList, deviceList):
- mw = MainWindow("Scenario Generator")
- mw.getActionFrame()
- mw.importData(planList, deviceList, os.listdir("/opt/tct/"))
- mw.run()
- scenData = mw.getScenData()
- if len(scenData) < 1:
- LOGGER.error("No correct scenario data given.\nExiting...")
- raise
- return mw.getScenData()
-
- def to_xml(self, xml_name):
- root = ElementTree.Element('ns3:testscenario')
- root.set('name', self.scen_name)
- root.set('xmlns', '')
- root.set('xmlns:ns3', 'http://www.example.org/plan/')
-
- for plan_name in self.plans:
- plan = self.plans[plan_name]
- root.append(plan.to_xml())
- Constants.indent(root)
- tree = ElementTree.ElementTree()
- tree._setroot(root)
- if os.path.basename(xml_name) == "generated_scen.xml":
- i = 0
- while os.path.isfile(xml_name):
- i += 1
- if xml_name[-5] == "]":
- xml_name = "[".join(xml_name.split("[")[:-1])+"[%d].xml" % i
- else:
- xml_name = xml_name[:-4]+"[%d].xml" % i
- LOGGER.info("generating scenario to %s" % xml_name)
- tree.write(xml_name, xml_declaration=True, encoding="utf-8")
-
#PARAM resultFolderPath = '/opt/tct/tizen_web_2.4/shell/result/'
#PARAM stubPort = 8000
def __init__(self, name, devmgr, deviceId, profile, executeType, suites, \
- tizenVer, resultFolderPath, stubPort=8000, scen_name=None):
+ tizenVer, resultFolderPath, stubPort=8000):
self.suites = []
self.name = name
self.devmgr = devmgr
self.profile = profile
self.executeType = executeType
self.unpass = None
- self.scen_name = scen_name
for suite in suites:
LOGGER.info("List: suite's name = %s" % str(suite.getSuiteName()))
self.suites.append(suite)
self.tizenVer = tizenVer
self.resultFolderPath = resultFolderPath
self.expectedTime = 0
- self.scen_resultFolderPath = None
self.stubPort = stubPort
self.planLock = Lock()
if self.resultFolderPath is None:
def getDevTctTmpPath(self):
return Constants.getDEVICE_SUITE_TARGET(self.tizenVer) + "tmp/"
- def getScenName(self):
- return self.scen_name
-
- def setScenResultFolderPath(self, path):
- self.scen_resultFolderPath = path
-
- def getScenResultFolderPath(self):
- self.acquire()
- if not self.scen_resultFolderPath and self.getScenName():
- folderName = "scenario_" + self.getScenName() + '_' \
- + datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S.%f')
- self.scen_resultFolderPath = Constants.RESULT_FOLDER \
- % (self.tizenVer, self.getBuildId(), folderName)
- self.release()
- return self.scen_resultFolderPath
-
def setup_distribute(self):
self.devmgr.loadDeviceList()
runningDevs = self.devmgr.getSdbDeviceList()
connection_suite = None
for suite in suites:
suite_name = suite.getSuiteName()
- if suite_name == 'tct-connection-native-utc':
- connection_suite = suite
- continue
autoCount = int(suite.getAutoNum())
category = suite.category
suite.setExpectedTime(etime)
sorted_suites.append(suite)
sorted_suites.sort(key=lambda x: x.expectedTime, reverse=True)
- if connection_suite:
- sorted_suites.append(connection_suite)
self.suites = sorted_suites
#PARAM category = 'Compliance'
#PARAM tizenV = 'tizen_web_2.4'
def __init__(self, suiteName, tcName, auto_num, manual_num, \
- suite_pkg_name, launcher, category, tizenV, skip_count, skip_tc, \
- devmgr, pre_test, post_test, is_make_ne=0):
+ suite_pkg_name, launcher, category, tizenV, skip_tc, \
+ devmgr, pre_test, post_test):
self.suiteName = suiteName
self.tcName = tcName
self.auto_num = auto_num
self.runErrorStatus = False
self.noAuto = False
self.noManual = False
- self.skip_count = skip_count
self.skip_tc = skip_tc
self.devmgr = devmgr
self.pre_test = pre_test
self.post_test = post_test
- self.is_make_ne = is_make_ne
def _liteCommand(self, deviceId, resultFolder, extype, \
tcName, isRerun, stubPort, isSkip=None, reverse_tests=None):
if isSkip:
lcmd += 'None' + " "
- elif self.is_make_ne != 0:
- lcmd += 'NE:{}_{}'.format(str(self.is_make_ne), \
- str(deviceId)) + " "
else:
lcmd += str(deviceId) + " "
lcmd += str(tc)
lcmd += " "
+ if self.tizenV and (self.tizenV.find("web") > -1 or self.tizenV.find("csharp") > -1):
+ timeout = Constants.DEFAULT_TIMEOUT
+ if timeout is not None:
+ lcmd += "--tc-timeout" + " "
+ lcmd += timeout + " "
+
if self.tizenV and (self.tizenV.find("web") > -1 or self.tizenV.find('csharp') > -1):
lcmd += Constants.EXT_TYPE_PARAM + " "
lcmd += Constants.COMM_TYPE_PARAM + " "
isPass = True
if deviceId:
- isPass = SdbManager.hostLiteCommand(exCmd, self.skip_count)
+ isPass = SdbManager.hostLiteCommand(exCmd)
else:
SdbManager.hostRecLiteCommand(exCmd)
return None
from .logmanager import LOGGER
-#show all available suites
-def show_available_suites(option, opt_str, value, parser):
- LOGGER.info("Test Suites:...\n")
- repos = Constants.ALL_PROFILES
- repos.append('common')
- repos.append('common-iot')
- os.chdir(Constants.TCT_HOME)
- versions = sorted(glob.glob("tizen_*"))
- for ver in versions:
- LOGGER.info("version : %s" % ver)
- for tp in repos:
- LOGGER.info(" profile : %s" % tp)
- if not os.path.isdir(Constants.SUITES_REPOSITORY % (ver) + tp):
- continue
- os.chdir(Constants.SUITES_REPOSITORY % (ver) + tp)
- zips = sorted(glob.glob("*.zip"))
- for files in zips:
- #without ".zip"
- LOGGER.info(" %s" % files[:-4])
- sys.exit(1)
-
-
-def show_result_files():
- os.chdir(Constants.TCT_HOME)
- LOGGER.info("\n *Result Folder Absolute Path*")
- versions = sorted(glob.glob("tizen_*"))
- for ver in versions:
- if not os.path.isdir("/opt/tct/%s/shell/result/" % ver):
- continue
- os.chdir("/opt/tct/%s/shell/result/" % ver)
- buildids = sorted(glob.glob("*"))
- for buildid in buildids:
- if buildid == "latest" or buildid == "Untitled Folder":
- continue
- os.chdir(Constants.RESULT_REPO % (ver, buildid))
- results = sorted(glob.glob("*"))
- for result in results:
- os.chdir(Constants.RESULT_REPO % (ver, buildid))
- if not os.path.isdir(os.path.abspath(result)):
- continue
- LOGGER.info(" %s" % os.path.abspath(result))
-
- LOGGER.info('')
- sys.exit(1)
-
-
-def print_planfolder(option, opt_str, value, parser):
- LOGGER.info("Shell plan folder path : \'%s\'" % Constants.TCT_PLAN_FOLDER)
- ret = os.system("tree %s" % Constants.TCT_PLAN_FOLDER)
- if ret:
- LOGGER.error("The program \'tree\' is currently not installed. \
-You can install it by typing : apt-get install tree")
- sys.exit(1)
-
-
-def print_resultfolder(option, opt_str, value, parser):
- os.chdir(Constants.TCT_HOME)
- for tizenV in glob.glob("tizen_*"):
- resultFolder = (Constants.RESULT_REPO % (tizenV, ""))[:-1]
- if os.path.isdir(resultFolder):
- ret = os.system("tree -L 3 %s" % resultFolder)
- if ret:
- LOGGER.error("The program \'tree\' is currently not installed. \
-You can install it by typing : apt-get install tree")
-
- show_result_files()
- sys.exit(1)
-
-
-def invoke_sdb_devices(option, opt_str, value, parser):
- os.system(Constants.SDB_DEVICES)
- sys.exit(1)
-
-
-# version option
-def print_version(option, opt_str, value, parser):
- LOGGER.info("TCTSHELL Version : %s " % Constants.TCT_VERSION)
- sys.exit(0)
-
-
def varnarg(option, opt_str, value, parser):
""" parser srg"""
value = []
class IntentionType:
- TestScenario = 0
TestPlan = 1
TestSuite = 2
TestCase = 3
self.options = None
self.USAGE = "\n\
run examples: \n\
- tct-shell --scenario <smoewhere>/scenario.xml\n\
tct-shell --testplan <somewhere>/testplan.xml\n\
tct-shell --test package1 package2 ... packageN\n\
tct-shell --test package1 --id caps_screenSizeNormal\n\
tct-shell --rerun-fail '<somewhere>/result_folder/\n\
\n\
- show examples: \n\
- tct-shell --help\n\
- tct-shell --plan-list\n\
- tct-shell --result-list\n\
- tct-shell --device-lite\n\
- tct-shell --all-suites\n\
- \n\
Note: \n\
1) Proxy settings should be disabled when execute webapi packages\n\
2) run command 'tct-shell', it might not be able to locate related module, \n\
def parse_options(self, argv):
option_list = [
- make_option("--scenario", "-s", dest="scenario_file", \
- action="callback", callback=varnarg, \
- help="Specify the scenario.xml as the test plan."),
make_option("--testplan", "-p", dest="testplan_file", \
action="callback", callback=varnarg, \
help="Specify the testplan.xml as the test plan."),
make_option("--tizen-version", dest="tizenversion", \
action="callback", callback=varnarg, \
help="Specify the name of tizen-version. The tizen-version is defined in the local repository. and its path is '/opt/tct/'"),
- make_option("--stub-port", dest="stubport", action="callback", \
- callback=varnarg, help="Specify a port number. Network port used by the testkit-stub"),
make_option("--deviceid", "-d", dest="deviceid", \
action="callback", callback=varnarg, \
help="Set sdb device serial information."),
make_option("--output", "-o", dest="resultfile", \
action="callback", callback=varnarg,
help="Specify the output file for result XML. If more than one test xml file provided, results will be merged into this outputfile"),
- make_option("--timeout", dest="run_timeout", action="callback", \
- callback=varnarg, help="Set the end time of test (unit : minute"),
make_option("--skip-package", dest="skip_package", action="callback", \
callback=varnarg, help="Specify the package names for exclude from the test"),
- make_option("--make-ne", dest="make_ne", action="callback", \
- callback=varnarg, help="Spectify the package names for make NE of results"),
- make_option("--skip-count", dest="skip_count", action="callback", \
- callback=varnarg, help="Specify the fail/block/na count. The test is terminated when the same skip-count value and fail/block/na count on the result"),
make_option("--skip-tc", dest="skip_tc", action="callback", \
callback=varnarg, help="Specify the testcase id for exclude from the test"),
- make_option("--version", dest="version_info", action="callback", \
- callback=print_version, help="Show version information"),
- make_option("--all-suites", dest="show_suites", \
- action="callback", callback=show_available_suites,
- help="Show all available test-suites in the local repository \'/opt/tct/\'"),
- make_option("--plan-list", dest="show_plan_folder", \
- action="callback", callback=print_planfolder,
- help="List all existed plans in the Plan directory. The plan directory is defined in the configuration file named CONFIG, and its path is :'/opt/tools/shell/CONFIG'"),
- make_option("--result-list", dest="show_all_result", \
- action="callback", callback=print_resultfolder,
- help="List all history results in the result directory. and its path is :'/opt/tct/{tizen-version}/shell/result/'"),
- make_option("--device-list", dest="show_all_device", \
- action="callback", callback=invoke_sdb_devices, \
- help="List all connected devices. just same with 'sdb devices'"),
make_option("--log", "-l", dest="loglevel", action="callback", callback=varnarg,
help="Set Log level. Logs that are less severe than the level will be ignored. Log levels (in descending severity order): [CRITICAL, ERROR, WARNING, NOTSET, INFO, DEBUG]"),
- make_option("--make-summary", dest="makesummary",\
- action="callback", callback=varnarg, help="Specify the result folder. When the test is not abnomally terminated. you can create summary file use to this option"),
- make_option("--tracking-dump", dest="trackingdump", action="callback", callback=varnarg,
- help="Specify the file(dump) names expected (for distribute run mode). After tracking the file(dump) generated by test and exits the tct-shell tool"),
make_option("--pre-test", dest="pre_test", action="callback", \
callback=varnarg, help="Before running suite, run a given script before installing testsuite."),
make_option("--post-test", dest="post_test", action="callback", \
- callback=varnarg, help="After running suite, run a given script before uninstalling testsuite.")
+ callback=varnarg, help="After running suite, run a given script before uninstalling testsuite."),
+ make_option("--tc-timeout", dest="tc_timeout", action="callback", \
+ callback=varnarg, help="Specify the timeout for TC")
]
# detect non-params
if len(argv) == 1:
argv.append("--help")
+ Constants.GlobalProfile = ""
+
PARSERS = OptionParser(option_list=option_list, usage=self.USAGE)
(self.options, args) = PARSERS.parse_args()
if self.is_testplan_mode():
conflicts = ["--testplan"]
- if self.options.scenario_file is not None:
- conflicts.append("--scenario")
if self.options.fail_result_xml is not None:
conflicts.append("--rerun-fail")
if self.options.profile is not None:
self.conflict_exit(conflicts)
self.running_mode = Constants.RUNNING_MODE_PLAN
- elif self.is_scenario_mode():
- conflicts = ["--scenario"]
- if self.options.dist_mode is not None:
- conflicts.append("--distribute")
- if self.options.fail_result_xml is not None:
- conflicts.append("--rerun-fail")
- if self.options.profile is not None:
- conflicts.append("--profile")
- if self.options.suites is not None:
- conflicts.append("--test")
- if self.options.testcase_id is not None:
- conflicts.append("--id")
- if self.options.deviceid is not None:
- conflicts.append("--deviceid")
- if self.options.makesummary is not None:
- conflicts.append("--make-summary")
- self.conflict_exit(conflicts)
- self.running_mode = Constants.RUNNING_MODE_SCEN
- Constants.setScenMode(True)
-
elif self.is_fail_rerun_mode():
conflicts = ["--rerun-fail"]
if self.options.profile is not None:
conflicts.append("--test")
if self.options.testcase_id is not None:
conflicts.append("--id")
- if self.options.makesummary is not None:
- conflicts.append("--make-summary")
self.conflict_exit(conflicts)
self.running_mode = Constants.RUNNING_MODE_RERUN
Constants.setRerunMode(True)
- elif self.is_profile_mode():
- conflicts = ["--profile"]
- if self.options.suites is not None:
- conflicts.append("--test")
- if self.options.testcase_id is not None:
- conflicts.append("--id")
- self.conflict_exit(conflicts)
- self.running_mode = Constants.RUNNING_MODE_PROFILE
elif self.is_suite_mode():
- conflicts = ["--test"]
- if self.options.profile is not None:
- conflicts.append("--profile")
self.running_mode = Constants.RUNNING_MODE_SUITES
+ elif self.is_profile_mode():
+ self.running_mode = Constants.RUNNING_MODE_PROFILE
if self.options.all_tc and self.options.only_manual:
conflicts = ["--all", "--manual"]
self.check_args_number()
self.check_args_exist()
- if not self.options.tizenversion and not self.is_scenario_mode() and not self.is_fail_rerun_mode():
+ if not self.options.tizenversion and not self.is_fail_rerun_mode():
LOGGER.error("The default tizen version could not be set.")
conflicts = ["--tizen-version"]
conflicts.append(None)
if self.running_mode == Constants.RUNNING_MODE_PLAN and len(self.options.testplan_file) > 0:
if not Constants.checkFileExists(self.options.testplan_file[0]):
opt = "--testplan"
- elif self.running_mode == Constants.RUNNING_MODE_SCEN and len(self.options.scenario_file) > 0:
- if not Constants.checkFileExists(self.options.scenario_file[0]):
- opt = "--scenario"
elif self.running_mode == Constants.RUNNING_MODE_RERUN and len(self.options.fail_result_xml) > 0:
if not Constants.checkFileExists(self.options.fail_result_xml[0]):
opt = "--rerun-fail"
if not self.check_tizen_version():
opt = "--tizen-version"
- if self.options.stubport and len(self.options.stubport) > 0:
- if not self.check_stub_port():
- opt = "--stub-port"
-
- if self.options.run_timeout and len(self.options.run_timeout) > 0:
- if not self.check_run_timeout():
- opt = "--timeout"
-
if self.options.skip_package and len(self.options.skip_package) > 0:
if not self.check_skip_package():
opt = "--skip-package"
- if self.options.skip_count and len(self.options.skip_count) > 0:
- if not self.check_skip_count():
- opt = "--skip-count"
-
if self.options.skip_tc and len(self.options.skip_tc) > 0:
if not self.check_skip_tc():
opt = "--skip-tc"
- if self.options.makesummary and len(self.options.makesummary) > 0:
- if not self.check_makesummary():
- opt = "--make-summary"
-
- if self.options.trackingdump and len(self.options.trackingdump) > 0:
- if not self.check_tracking_dump():
- opt = "--tracking-dump"
- if self.options.make_ne and len(self.options.make_ne) > 0:
- if not self.check_make_ne():
- opt = "--make-ne"
if self.options.pre_test and len(self.options.pre_test) > 0:
if not self.check_pre_test():
opt = "--pre-test"
opt = ""
if self.running_mode == Constants.RUNNING_MODE_PLAN and len(self.options.testplan_file) < 1:
opt = "--testplan"
- elif self.running_mode == Constants.RUNNING_MODE_SCEN and len(self.options.scenario_file) < 1:
- opt = "--scenario"
elif self.running_mode == Constants.RUNNING_MODE_RERUN and len(self.options.fail_result_xml) < 1:
opt = "--rerun-fail"
elif self.running_mode == Constants.RUNNING_MODE_PROFILE and len(self.options.profile) < 1:
opt = "--id"
elif self.options.tizenversion is not None and len(self.options.tizenversion) < 1:
opt = "--tizen-version"
- elif self.options.stubport is not None and len(self.options.stubport) < 1:
- opt = "--stub-port"
- elif self.options.run_timeout is not None and len(self.options.run_timeout) < 1:
- opt = "--timeout"
elif self.options.skip_package is not None and len(self.options.skip_package) < 1:
opt = "--skip-package"
- elif self.options.skip_count is not None and len(self.options.skip_count) < 1:
- opt = "--skip-count"
elif self.options.skip_tc is not None and len(self.options.skip_tc) < 1:
opt = "--skip-tc"
- elif self.options.makesummary is not None and len(self.options.makesummary) < 1:
- opt = "--make-summary"
- elif self.options.trackingdump is not None and len(self.options.trackingdump) < 1:
- opt = "--tracking-dump"
- elif self.options.make_ne is not None and len(self.options.make_ne) < 1:
- opt = "--make-ne"
if len(opt) > 0:
os.system("tct-shell -h")
Constants.set_default_tizenV(tizenversion)
return True
- def check_stub_port(self):
- port = self.options.stubport[0]
- portLen = len(port)
- return port.isdigit() and (portLen > 3 and portLen < 6)
-
- def check_run_timeout(self):
- timeout = self.options.run_timeout[0]
- timeoutLen = len(timeout)
- return timeout.isdigit() and timeoutLen > 0
-
def check_skip_package(self):
packages = self.options.skip_package[0]
packLen = len(packages)
return packLen > 0
- def check_skip_count(self):
- count = self.options.skip_count[0]
- countLen = len(count)
- return count.isdigit() and countLen > 0
-
def check_skip_tc(self):
tc = self.options.skip_tc[0]
tcLen = len(tc)
return tcLen > 0
- def check_tracking_dump(self):
- dump_names = self.options.trackingdump[0]
- dump_names_len = len(dump_names)
- return dump_names_len > 0
-
- def check_makesummary(self):
- return os.path.exists(self.options.makesummary[0])
-
- def check_make_ne(self):
- packages = self.options.make_ne[0]
- packLen = len(packages)
- return packLen > 0
-
def check_pre_test(self):
script = self.options.pre_test[0]
return os.path.isfile(script)
script = self.options.post_test[0]
return os.path.isfile(script)
+ def get_tc_timeout(self):
+ if self.options.tc_timeout is not None:
+ return self.options.tc_timeout[0]
+ else:
+ return None
+
def getIntentionType(self):
- if self.options.scenario_file is not None:
- return IntentionType.TestScenario
- elif self.options.testplan_file is not None:
+ if self.options.testplan_file is not None:
return IntentionType.TestPlan
elif self.options.testcase_id is not None:
return IntentionType.TestCase
return IntentionType.TestProfile
return -1
- def get_scenfile(self):
- return self.options.scenario_file[0]
-
def get_planfile(self):
if self.is_testplan_mode():
return self.options.testplan_file[0]
def get_profile(self):
- return self.options.profile[0]
+ if self.options.profile is not None:
+ return self.options.profile[0]
+ else:
+ return None
def get_result_for_rerun(self):
return self.options.fail_result_xml[0]
plan_name = os.path.basename(self.get_planfile())[:-4]
return plan_name
- def get_scen_name(self):
- if self.is_scenario_mode():
- return os.path.basename(self.get_scenfile())[:-4]
-
- def get_stubPort(self):
- if self.options.stubport is None:
- return '8000'
- else:
- return self.options.stubport[0]
-
- def get_run_timeout(self):
- if self.options.run_timeout is None:
- return 1440 #24 hour
- else:
- return self.options.run_timeout[0]
-
- def get_makesummarydir(self):
- return self.options.makesummary[0]
+ def get_default_stubPort(self):
+ return '8000'
def get_resultFolderPath(self):
if (self.options.resultfile is not None) and (self.options.resultfile[0] is not None):
return self.options.deviceid[0]
LOGGER.error("Error! [%s] device is not connected" % self.options.deviceid[0])
raise
- elif not self.is_scenario_mode() and not self.is_make_summary_mode():
+ else:
if len(devices) < 1:
LOGGER.error("No device is connected")
raise Exception('Device connection is required')
if (self.options.tizenversion is not None) and (self.options.tizenversion[0] is not None):
return self.options.tizenversion[0]
+ def getChoosenProfile(self,suite_name):
+ suite_repo = Constants.SUITES_REPOSITORY % self.get_tizenV()
+ LOGGER.info("Select profiles for [%s] :" % suite_name)
+ for profile in os.listdir(suite_repo):
+ if profile=="common" or profile=="pkg_infos":
+ continue
+ else:
+ LOGGER.info(" - %s" % profile)
+ suite_temp_profile = None
+ while not suite_temp_profile in os.listdir(suite_repo):
+ suite_temp_profile = input("\nChoose profile: ")
+ if (Constants.GlobalProfile is None) or (Constants.GlobalProfile == ""):
+ Constants.GlobalProfile = suite_temp_profile
+
def _chooseProfile(self, path_suites):
suite_profiles = {}
for suite_path in path_suites:
for suiteName, suiteProfile in suite_profiles.items():
suite_name = "-".join(suiteName[:-4].split("-")[:-1])
if len(suiteProfile) == 1:
+ if ("common" in suiteProfile) and (self.get_profile() is None):
+ self.getChoosenProfile(suite_name)
suite_profiles[suiteName] = suiteProfile[0]
continue
LOGGER.info("Multiple profiles for [%s] :" % suite_name)
+ if "common" in suiteProfile:
+ self.getChoosenProfile(suite_name)
for profile_i in suiteProfile:
LOGGER.info(" - %s" % profile_i)
suite_profile = None
suites = []
filtered_suites = []
suite_repo = Constants.SUITES_REPOSITORY % self.get_tizenV()
+ sel_profile = None
+ if self.options.profile is not None:
+ sel_profile = self.get_profile()
+ suite_profiles = {}
if self.options.suites:
- for suite_name in self.options.suites:
- for profiles in os.listdir(suite_repo):
- if profiles == "pkg_infos":
- continue
- for package in glob.glob(suite_repo + profiles + "/*.zip"):
- if package.find(suite_name) > -1:
- suites.append(package)
+ if sel_profile is None:
+ for suite_name in self.options.suites:
+ for profiles in os.listdir(suite_repo):
+ if profiles == "pkg_infos":
+ continue
+ for package in glob.glob(suite_repo + profiles + "/*.zip"):
+ if package.find(suite_name) > -1:
+ suites.append(package)
+ if (len(suites) < 1):
+ LOGGER.error("Error! [%s] suite does not exists" % suite_name)
+ else:
+ if os.path.exists(os.path.join(suite_repo, sel_profile)):
+ for suite_name in self.options.suites:
+ for package in glob.glob(suite_repo + sel_profile + "/*.zip"):
+ if package.find(suite_name) > -1:
+ suites.append(package)
+ if os.path.exists(os.path.join(suite_repo, "common")):
+ for suite_name in self.options.suites:
+ for package in glob.glob(suite_repo + "common/*.zip"):
+ if package.find(suite_name) > -1:
+ suites.append(package)
if (len(suites) < 1):
- LOGGER.error("Error! [%s] suite does not exists" % suite_name)
+ LOGGER.error("Error! [%s] suite does not exists in [%s] profile" % (suite_name, sel_profile))
suite_profiles = self._chooseProfile(suites)
+
check_profile = None
multiProfiles = False
for suiteName, suiteProfile in suite_profiles.items():
tc_id = self.options.testcase_id[0]
return tc_id
- def get_inst_suites(self):
- suites = []
- if self.options.instsuites:
- for suite_str in self.options.instsuites:
- suite_str_array = suite_str.split(" ")
- for suite_name in suite_str_array:
- suites.append(suite_name)
- return suites
-
- def get_uninst_suites(self):
- suites = []
- if self.options.uninstsuites:
- for suite_str in self.options.uninstsuites:
- suite_str_array = suite_str.split(" ")
- for suite_name in suite_str_array:
- suites.append(suite_name)
- return suites
-
def get_running_mode(self):
return self.running_mode
if self.options.skip_package is not None:
return self.options.skip_package
- def get_skip_count(self):
- if (self.options.skip_count is not None) and (self.options.skip_count[0] is not None):
- return self.options.skip_count[0]
-
def get_skip_tc(self):
if self.options.skip_tc is not None:
return self.options.skip_tc
- def get_tracking_dump(self):
- if (self.options.trackingdump is not None) and (self.options.trackingdump[0] is not None):
- return self.options.trackingdump[0]
-
- def get_make_ne(self):
- if self.options.make_ne is not None:
- return self.options.make_ne
-
def get_pre_test(self):
if self.options.pre_test is not None:
return self.options.pre_test[0]
def is_testplan_mode(self):
return self.options.testplan_file is not None
- def is_scenario_mode(self):
- return self.options.scenario_file is not None
-
def is_profile_mode(self):
return self.options.profile
def is_enable_preconf_func(self):
return self.options.disable_preconfigure
- def is_update_portconf_func(self):
- return self.options.stubport is not None
-
def is_suite_mode(self):
return self.options.suites is not None
def is_fail_rerun_mode(self):
return self.options.fail_result_xml is not None
- def is_make_summary_mode(self):
- return self.options.makesummary is not None
-
def is_dist_mode(self):
return self.options.dist_mode is not None
if executor.name == 'ResultManager':
continue
plan = executor.plan
- scenFolder = plan.getScenResultFolderPath()
planFolder = plan.getResultFolderPath()
- if not scenFolder in logs:
- logs[scenFolder] = {}
- if not planFolder in logs[scenFolder]:
- logs[scenFolder][planFolder] = []
- logs[scenFolder][planFolder].append(\
+ if not planFolder in logs:
+ logs[planFolder] = []
+ logs[planFolder].append(\
os.path.join(Constants.TCT_LOG_FOLDER, 'MainProcess.log'))
- logs[scenFolder][planFolder].append(\
+ logs[planFolder].append(\
os.path.join(Constants.TCT_LOG_FOLDER, 'critical.log'))
- logs[scenFolder][planFolder].append(\
+ logs[planFolder].append(\
os.path.join(Constants.TCT_LOG_FOLDER, 'debug.log'))
- logs[scenFolder][planFolder].append(\
+ logs[planFolder].append(\
os.path.join(Constants.TCT_LOG_FOLDER, 'error.log'))
- logs[scenFolder][planFolder].append(\
+ logs[planFolder].append(\
os.path.join(Constants.TCT_LOG_FOLDER, 'info.log'))
- logs[scenFolder][planFolder].append(\
+ logs[planFolder].append(\
os.path.join(Constants.TCT_LOG_FOLDER, 'warning.log'))
if hasattr(executor, 'all_dev_threads'):
for autoPlanExecutor in executor.all_dev_threads:
- logs[scenFolder][planFolder].append(\
+ logs[planFolder].append(\
os.path.join(Constants.TCT_LOG_FOLDER, '%s.log' % \
autoPlanExecutor.name))
- logs[scenFolder][planFolder].append(\
+ logs[planFolder].append(\
os.path.join(Constants.TCT_LOG_FOLDER, 'E_%s.log' % \
autoPlanExecutor.name))
- for scenFolder, plan_logs in logs.items():
- for planFolder, thread_logs in plan_logs.items():
- for src_logs in thread_logs:
- Constants.move_log_file(src_logs, planFolder)
- if scenFolder is not None and os.path.isdir(scenFolder):
- Constants.move_log_file(src_logs, scenFolder)
- #Constants.move_log_file(os.path.join(Constants.TCT_LOG_FOLDER, 'ResultManager.log'), planFolder)
- #Constants.move_log_file(os.path.join(Constants.TCT_LOG_FOLDER, 'MainThread.log'), planFolder)
- if scenFolder is not None and os.path.isdir(scenFolder):
- pass
- #Constants.move_log_file(os.path.join(Constants.TCT_LOG_FOLDER, 'ResultManager.log'), scenFolder)
- #Constants.move_log_file(os.path.join(Constants.TCT_LOG_FOLDER, 'MainThread.log'), scenFolder)
-
+ for planFolder, thread_logs in logs.items():
+ for src_logs in thread_logs:
+ Constants.move_log_file(src_logs, planFolder)
def getDbuteDevIds(self):
return self.options.dbutedevid
from .sdbmanager import SdbManager
from .logmanager import LOGGER
from .constants import Constants
+from .getcapabilities import GetCap
class TestEnvironment(Process):
if self.isPreconSet:
self._reset_health_res_indevice()
+ self._getDeviceCapability()
+
if not self._isHealthCheckPassed():
self.queue.put('Fail_Healthcheck')
return
self.queue.put('Fail_Preconfig')
return
- if not self._extractDeviceCapability():
- self.queue.put('Fail_ExtractDeviceCapability')
+ if not self._checkDeviceCapability():
+ self.queue.put('Fail_CheckDeviceCapability')
return
#SdbManager.resetDumpFiles(self.deviceId)
values.append(v.split(","))
return values
+ def _extractFiles(self):
+ shell_tmp_dir = Constants.LOCAL_SHELL_TEMP_PATH % self.deviceId
+ model_config = os.path.join(shell_tmp_dir, 'model-config.xml')
+ info_ini = os.path.join(shell_tmp_dir, 'info.ini')
+ cpu_max_freq = os.path.join(shell_tmp_dir, 'cpuinfo_max_freq')
+ cpu_info = os.path.join(shell_tmp_dir, 'cpuinfo')
+
+ if os.path.exists(model_config):
+ os.remove(model_config)
+ if os.path.exists(info_ini):
+ os.remove(info_ini)
+ if os.path.exists(cpu_max_freq):
+ os.remove(cpu_max_freq)
+ if os.path.exists(cpu_info):
+ os.remove(cpu_info)
+
+ SdbManager.sdbPull(self.deviceId, Constants.DEVICE_MODEL_CONFIG_PATH, shell_tmp_dir)
+ SdbManager.sdbPull(self.deviceId, Constants.DEVICE_INFO_INI_PATH, shell_tmp_dir)
+ SdbManager.sdbPull(self.deviceId, Constants.DEVICE_CPU_INFO_PATH, shell_tmp_dir)
+ SdbManager.sdbPull(self.deviceId, Constants.EMUL_CPU_INFO_PATH, shell_tmp_dir)
+
+
+ def _getDeviceCapability(self):
+ buil_file = Constants.LOCAL_BUILD_INFO_PATH % self.deviceId
+ LOGGER.debug('buildinfo path : %s' % buil_file)
+ if os.path.exists(buil_file):
+ os.remove(buil_file)
+
+ capa_file = Constants.LOCAL_CAPABILITY_PATH % self.deviceId
+ LOGGER.debug('capability path : %s' % capa_file)
+ if os.path.exists(capa_file):
+ os.remove(capa_file)
+
+ self._extractFiles()
+
+ getCap = GetCap(self.tizenVer, self.deviceId)
+ getCap.run()
+
+ return True
+
def _isHealthCheckPassed(self):
healtlist = self._read_health_check_ini()
+
+ counter = 0
+ counter_loop = 0
+ if Constants.GlobalProfile == "tizeniot" or Constants.GlobalProfile == "":
+ counter = len(healtlist) - 1
+ else:
+ counter = len(healtlist)
+
+ LOGGER.info("value of counter is " + str(counter))
+ LOGGER.info("value of GlobalProfile is " + str(Constants.GlobalProfile))
+
if not healtlist:
return False
for l in healtlist:
+ counter_loop = counter_loop + 1
+ if counter_loop > counter:
+ break
+
if self.tizenVer.find("native") > -1 and l[1].find("tinyweb") > -1:
continue
- getcap = ""
- if self.tizenVer.find("native") > -1 and l[1].find("getCap") > -1:
- getcap = "ngetCap"
- else:
- getcap = l[1].strip()
+ proc = l[1].strip()
command = "python " + \
(Constants.DEVICE_HEALTH_CMD % self.tizenVer) \
+ " " + "--deviceid " + self.deviceId \
- + " --check" + " --procid=" + getcap
+ + " --check" + " --procid=" + proc
try:
outLog, errLog = SdbManager.sdbCommand(command, 180)
except Exception as ex:
LOGGER.info(str(outLog))
if str(outLog).find('#ERROR#') > -1 or \
str(outLog).find('#WARNING#') > -1:
- LOGGER.error(l[0].strip() + ": fail")
- return False
+ LOGGER.warning(l[0].strip() + ": fail")
else:
LOGGER.info(l[0].strip() + ": pass")
LOGGER.info("Return From isHealthCheckPassed, return value : True")
return True
- def _extractDeviceCapability(self):
+ def _checkDeviceCapability(self):
capa_file = Constants.LOCAL_CAPABILITY_PATH % self.deviceId
LOGGER.debug('capability path : %s' % capa_file)
- if os.path.exists(capa_file):
- os.remove(capa_file)
-
- if not SdbManager.getCapabilityBack(self.deviceId, self.tizenVer):
- LOGGER.error('Fail to extract the capability.xml from device : ' \
- + Constants.getDEVICE_CAPABILITY_PATH(self.tizenVer))
+ if not os.path.exists(capa_file):
return False
return True
% Constants.PORT_CONF_HOST_JSON % self.deviceId)
return False
- SdbManager.sdbPull(self.deviceId, \
- Constants.getDEVICE_BUILD_INFO_PATH(self.tizenVer), \
- Constants.LOCAL_BUILD_INFO_PATH % self.deviceId)
if Constants.checkFileExists(Constants.LOCAL_BUILD_INFO_PATH % \
- self.deviceId) is False:
+ self.deviceId) is False:
LOGGER.error("The %s file does not exist. [ Preconfig Check]" \
% Constants.LOCAL_BUILD_INFO_PATH % self.deviceId)
return False
CURRENT_TARGET_LITE_PATH = ""
CURRENT_SOURCE_LITE_PATH = ""
- #monkey
- SOURCE_MONKEY_PATH = sep + "dev_event"
- TARGET_MONKEY_PATH = sep + "dev_event"
-
#shell
SOURCE_SHELL_PATH = sep + "shell"
TARGET_SHELL_PATH = sep + "shell"
os.system('kill -9 ' + result[x+1])
'''
try:
- '''
+
if(self.checkInstalledSdb()):
print("sdb install is not required")
return
print("sdb install")
- '''
+
if (str(osInfo[0]).find("64") != -1):
self.cpFile(
self.CURRENT_SOURCE_BASE_PATH + \
return p.stdout.readline()
def checkInstalledSdb(self):
- cmd = "sdb"
+ cmd = ["sdb", "version"]
installedVer = ""
try:
output = str(self.get_cmd_result(cmd).split('\n')[0])
if output.find('Smart Development Bridge') > -1:
- installedVer = output.split(' ')[3]
+ installedVer = output.split(' ')[4]
else:
raise
except:
osInfo = self.getCurrentOSBit()
if (str(osInfo[0]).find("32") != -1):
- cmd = "sdb/sdb-32"
+ cmd = ["sdb/sdb-32", "version"]
else:
- cmd = "sdb/sdb-64"
+ cmd = ["sdb/sdb-64", "version"]
toolVer = ""
try:
output = str(self.get_cmd_result(cmd).split('\n')[0])
if output.find('Smart Development Bridge') > -1:
- toolVer = output.split(' ')[3]
+ toolVer = output.split(' ')[4]
else:
raise
except:
if(int(installedSplit[i]) < int(toolSplit[i])):
break
if(hit==3):
- print("Same version sdb is already installed : " + installedVer)
+ print("Same version of sdb is already installed : " + installedVer)
return True
return False
def cpOtherFiles(self):
tct_mgr = "tct-mgr"
tct_shell = "tct-shell"
- tct_monkey = "tct-monkey"
testkit_lite1 = "testkit-lite1.0"
testkit_lite2 = "testkit-lite2.0"
tct_config = "TCT_CONFIG"
self.sep + tct_shell, self.CURRENT_TARGET_BASE_PATH + \
self.sep + tct_shell)
self.cpFile(self.CURRENT_SOURCE_BASE_PATH + self.SOURCE_SCRIPT_PATH + \
- self.sep + tct_monkey, self.CURRENT_TARGET_BASE_PATH + \
- self.sep + tct_monkey)
- self.cpFile(self.CURRENT_SOURCE_BASE_PATH + self.SOURCE_SCRIPT_PATH + \
self.sep + testkit_lite1, self.CURRENT_TARGET_BASE_PATH + \
self.sep + testkit_lite1)
self.cpFile(self.CURRENT_SOURCE_BASE_PATH + self.SOURCE_SCRIPT_PATH + \
def cpOtherFilesToBinDir(self):
tct_mgr = "tct-mgr"
tct_shell = "tct-shell"
- tct_monkey = "tct-monkey"
testkit_lite1 = "testkit-lite1.0"
testkit_lite2 = "testkit-lite2.0"
self.SOURCE_SCRIPT_PATH + self.sep + \
tct_shell, "/usr/bin/" + tct_shell)
self.cpFile(self.CURRENT_SOURCE_BASE_PATH + \
- self.SOURCE_SCRIPT_PATH + self.sep + \
- tct_monkey, "/usr/bin/" + tct_monkey)
- self.cpFile(self.CURRENT_SOURCE_BASE_PATH + \
self.SOURCE_SCRIPT_PATH + self.sep + testkit_lite1,\
"/usr/bin/" + testkit_lite1)
self.cpFile(self.CURRENT_SOURCE_BASE_PATH + \
try:
os.system("chmod -R 777 /usr/bin/" + tct_mgr)
os.system("chmod -R 777 /usr/bin/" + tct_shell)
- os.system("chmod -R 777 /usr/bin/" + tct_monkey)
os.system("chmod -R 777 /usr/bin/" + testkit_lite1)
os.system("chmod -R 777 /usr/bin/" + testkit_lite2)
os.system("chmod -R 777 /usr/bin/sdb")
if (platform.system() != "Windows"):
os.chmod(r, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
- def cpMonkey(self):
- self.cpDir(self.CURRENT_SOURCE_BASE_PATH + self.SOURCE_MONKEY_PATH, \
- self.CURRENT_TARGET_BASE_PATH + self.TARGET_MONKEY_PATH, \
- "monkey")
- for r, d, f in os.walk(self.CURRENT_TARGET_BASE_PATH + \
- self.TARGET_MONKEY_PATH):
- if (platform.system() != "Windows"):
- os.chmod(r, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
-
def cpPlugin(self):
self.cpDir(self.CURRENT_SOURCE_BASE_PATH + self.SOURCE_PLUGIN_PATH,
self.CURRENT_TARGET_BASE_PATH + self.TARGET_PLUGIN_PATH, \
self.setCurrentPath()
self.cpShell()
self.cpManager()
- self.cpMonkey()
self.cpOtherFiles()
self.cpTestKitLite()
self.cpPlugin()
+++ /dev/null
-#!/bin/bash
-
-python /opt/tools/dev_event/tct-monkey "${@}"
device_file = DEVICE_SUITE_TARGET_30 + '/Documents/tct/buildinfo.xml'
elif _tizenV and _tizenV.find("5.5") > -1:
device_file = DEVICE_SUITE_TARGET_30 + '/Documents/tct/buildinfo.xml'
+ elif _tizenV and _tizenV.find("6.0") > -1:
+ device_file = DEVICE_SUITE_TARGET_30 + '/Documents/tct/buildinfo.xml'
+ elif _tizenV and _tizenV.find("6.5") > -1:
+ device_file = DEVICE_SUITE_TARGET_30 + '/Documents/tct/buildinfo.xml'
else:
device_file = DEVICE_SUITE_TARGET_24 + '/Documents/tct/buildinfo.xml'
root.insert(0, get_summary(start_time, end_time))
root.insert(0, self.__get_environment())
# add XSL support to testkit-lite
- declaration_text = """<?xml version="1.0" encoding="UTF-8"?>
- <?xml-stylesheet type="text/xsl" href="testresult.xsl"?>\n"""
+ declaration_text = """<?xml version="1.0" encoding="UTF-8"?>\n"""
#LOGGER.info("\nmergefile: %s ]" % mergefile)
try:
with open(mergefile, 'w') as output:
<?xml version="1.0" encoding="UTF-8"?>\r
-<?xml-stylesheet type="text/xsl" href="testresult.xsl"?>\r
<test_definition name="http://tempuri.org" type=""\r
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
xsi:noNamespaceSchemaLocation="test_definition.xsd">\r
# help="setting test user")
make_option("--tizen-version", dest="tizenversion", action="callback", callback=varnarg, help="set tizen version infomation"),
make_option("--skip-tc", dest="skip_tc", action="callback", callback=varnarg, help ="Specify the testcase id for exclude from the test"),
- make_option("--stub-port", dest="stubport", action="callback", callback=varnarg, help = "set testkit-stub port number")
+ make_option("--stub-port", dest="stubport", action="callback", callback=varnarg, help = "set testkit-stub port number"),
+ make_option("--tc-timeout", dest="tc_timeout", action="callback", callback=varnarg, help ="Specify the timeout for one TC"),
]
OPTION_LIST.extend([
self.test_prefix = options.test_prefix
if options.device_serial:
self.deviceid = options.device_serial
+ if options.tc_timeout:
+ self.tc_timeout = options.tc_timeout[0]
+ else:
+ self.tc_timeout = None
if options.worker:
self.worker_name = options.worker
else:
self.worker_name = None
+ LOGGER.info("TIMEOUT : "+str(self.tc_timeout))
#if options.targetplatform:
self.targetplatform = os.environ.get("targetplatform",'')
#modify the wdurl value, yangx.zhou@intel.com, 2014.09.18
root.insert(0, get_summary(start_time, end_time))
root.insert(0, self.__get_environment())
# add XSL support to testkit-lite
- declaration_text = """<?xml version="1.0" encoding="UTF-8"?>
- <?xml-stylesheet type="text/xsl" href="testresult.xsl"?>\n"""
+ declaration_text = """<?xml version="1.0" encoding="UTF-8"?>\n"""
try:
with open(mergefile, 'w') as output:
output.write(declaration_text)
case_detail_tmp.setdefault("purpose", tcase.get('purpose'))
case_detail_tmp.setdefault("order", str(case_order))
case_detail_tmp.setdefault("onload_delay", "3")
+ if self.tc_timeout is not None:
+ case_detail_tmp.setdefault("timeout", self.tc_timeout)
if parameters["location"] != '':
case_detail_tmp.setdefault("location", parameters["location"])
else:
tc_entry = tc_entry.replace(DEVICE_EXECUTION_MODE_30_STR,DEVICE_EXECUTION_MODE_30)
case_detail_tmp["entry"] = self.test_prefix + tc_entry
+ #if case_detail_tmp["timeout"] is None:
if tcase.find(
- 'description/test_script_entry').get('timeout'):
+ 'description/test_script_entry').get('timeout'):
case_detail_tmp["timeout"] = tcase.find(
'description/test_script_entry'
).get('timeout')
<?xml version="1.0" encoding="UTF-8"?>
-<?xml-stylesheet type="text/xsl" href="testresult.xsl"?>
<test_definition xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="http://tempuri.org" type="" xsi:noNamespaceSchemaLocation="test_definition.xsd">
<environment device_id="generic/sdk/generic:4.0.4/MR1/302030:eng/test-keys" device_model="unknown" device_name="MR8" firmware_version="4.0.4" host="zhongqing-dev.sh.intel.com (Linux - 2.6.38.6-26.rc1.fc15.i686)" os_version="4.0.4" resolution="1280*800" screen_size="250*150" cts_version="2.3.0-3">
<other> Here is a Long String for testing ~~~~~~~~~~~~~~~~~~~