标签:
Return Type |
Methods |
Comment |
void |
broadcastIntent (string uri, string action, string data, string mimetype, iterable categories dictionary extras, component component, iterable flags)Broadcasts an Intent to this device, as if the Intent were coming from an application. | |
void |
drag (tuple start, tuple end, float duration, integer steps)Simulates a drag gesture (touch, hold, and move) on this device‘s screen. | |
object |
getProperty (string key)Given the name of a system environment variable, returns its value for this device.The available variable names are listed in the detailed description of this method. | |
object |
getSystemProperty (string key). The API equivalent of adb shell getprop <key>. This is provided foruse by platform developers. | |
void |
installPackage (string path)Installs the Android application or test package contained in packageFile onto this device.If the application or test package is already installed, it is replaced. | Obsolete,返回值是Boolean |
dictionary |
instrument (string className, dictionary args)Runs the specified component under Android instrumentation, and returns the results in a dictionary whose exact format is dictated by the component being run. The component must already be present on this device. | |
void |
press (string name, dictionary type)Sends the key event specified by type to the key specified by keycode. | |
void |
reboot (string into)Reboots this device into the bootloader specified by bootloadType. | |
void |
removePackage (string package)Deletes the specified package from this device, including its data and cache. | Obsolete,返回值是Boolean |
object |
shell (string cmd)Executes an adb shell command and returns the result, if any. | |
void |
startActivity (string uri, string action, string data, string mimetype, iterable categories dictionary extras, component component, flags)Starts an Activity on this device by sending an Intent constructed from the supplied arguments. | |
takeSnapshot()Captures the entire screen buffer of this device, yielding a MonkeyImage object containinga screen capture of the current display. | ||
void |
touch (integer x, integer y, integer type)Sends a touch event specified by type to the screen location specified by x and y. | |
void |
type (string message)Sends the characters contained in message to this device, as if they had been typed onthe device‘s keyboard. This is equivalent to callingpress() for each keycode in message using the key event type DOWN_AND_UP. | |
void |
wake ()Wakes the screen of this device. |
Return Type |
Methods |
Comment |
HierarchyViewer |
getHierarchyViewer(PyObject args[], String kws[])获取一个HierarchyViewer对象 | 请查看《MonkenRunner通过HierarchyViewer定位控件的方法和建议》 |
PyList |
getPropertyList(PyObject args[], String kws[]) | 取得所有的property属性键值 |
PyList |
getViewIdList(PyObject args[], String kws[]) | Failed |
MonkeyView |
getViewById(PyObject args[], String kws[]) | Failed |
MonkeyView |
getViewByAccessibilityIds(PyObject args[], String kws[]) | Failed |
MonkeyView |
getRootView(PyObject args[], String kws[]) | Failed |
PyList |
getViewsByText(PyObject args[], String kws[]) | Failed |
targetDevice.broadcastIntent(action=‘android.intent.action.INSERT‘, mimetype=‘vnd.android.cursor.dir/contact‘, extras = {‘name‘:‘user1501488‘, ‘phone‘:‘123-15489‘}如果使用同样的参数,使用下面的startActivity是没有问题的。
targetDevice.startActivity(action=‘android.intent.action.INSERT‘, mimetype=‘vnd.android.cursor.dir/contact‘, extras = {‘name‘:‘user1501488‘, ‘phone‘:‘123-15489‘})google了半天网上根本找不到这个方法的使用例子,倒是stackOverFlow上有人建议用Shell来达到同样的效果。
targetDevice.shell("am start -a android.intent.action.INSERT -t vnd.android.cursor.dir/contact -e name ‘Donald Duck‘ -e phone 555-1234").所以可见这个方法并没有多少人在用,原因应该是它完全可以用上面介绍的两个方法替代。
targetDevice.startActivity(action=‘android.intent.action.VIEW‘, mimetype=‘vnd.android.cursor.dir/vnd.google.note‘)使用component来启动一个Activity:
targetDevice.startActivity(component="com.example.android.notepad/com.example.android.notepad.NotesList")使用action,mimetype和指定extras参数来启动一个Activity:
targetDevice.startActivity(action=‘android.intent.action.INSERT‘, mimetype=‘vnd.android.cursor.dir/contact‘, extras = {‘name‘:‘user1501488‘, ‘phone‘:‘123-15489‘})
viewer = targetDevice.getHierarchyViewer() note = viewer.findViewById(‘id/text1‘) point = viewer.getAbsoluteCenterOfView(note) startX = point.x startY = point.y targetDevice.drag((startX,startY),(startX,startY),1) targetDevice.press(‘KEYCODE_BACK‘, MonkeyDevice.DOWN_AND_UP)
Property Group |
Property |
Description |
Notes |
build |
board |
Code name for the device‘s system board | See Build |
brand |
The carrier or provider for which the OS is customized. | ||
device |
The device design name. | ||
fingerprint |
A unique identifier for the currently-running build. | ||
host |
|||
ID |
A changelist number or label. | ||
model |
The end-user-visible name for the device. | ||
product |
The overall product name. | ||
tags |
Comma-separated tags that describe the build, such as "unsigned" and "debug". | ||
type |
The build type, such as "user" or "eng". | ||
user |
|||
CPU_ABI |
The name of the native code instruction set, in the form CPU type plus ABI convention. | ||
manufacturer |
The product/hardware manufacturer. | ||
version.incremental |
The internal code used by the source control system to represent this version of the software. | ||
version.release |
The user-visible name of this version of the software. | ||
version.sdk |
The user-visible SDK version associated with this version of the OS. | ||
version.codename |
The current development codename, or "REL" if this version of the software has been released. | ||
display |
width |
The device‘s display width in pixels. | SeeDisplayMetricsfor details. |
height |
The device‘s display height in pixels. | ||
density |
The logical density of the display. This is a factor that scales DIP (Density-Independent Pixel) units to the device‘s resolution. DIP is adjusted so that 1 DIP is equivalent to one pixel on a 160 pixel-per-inch display. For example, on a 160-dpi screen, density = 1.0, while on a 120-dpi screen, density = .75.The value does not exactly follow the real screen size, but is adjusted to conform to large changes in the display DPI. See density for more details. | ||
am.current |
package |
The Android package name of the currently running package. | The am.currentkeys return information about the currently-running Activity. |
action |
The current activity‘s action. This has the same format as the name attribute of the action element in a package manifest. | ||
comp.class |
The class name of the component that started the current Activity. See comp.package for more details. | ||
comp.package |
The package name of the component that started the current Activity. A component is specified by a package name and the name of class that the package contains. | ||
data |
The data (if any) contained in the Intent that started the current Activity. | ||
categories |
The categories specified by the Intent that started the current Activity. | ||
clock |
realtime |
The number of milliseconds since the device rebooted, including deep-sleep time. | SeeSystemClock for more information. |
displayWidth =targetDevice.getProperty (‘display.width‘) printdisplayWidth.encode(‘utf-8‘) displayHight =targetDevice.getProperty(‘display.width‘) printdisplayHight.encode(‘utf-8‘)
displayWidth = targetDevice.getSystemProperty (‘service.adb.tcp.port‘) print displayWidth.encode(‘utf-8‘)
displayWidth = targetDevice.getSystemProperty (‘display.width‘) print displayWidth.encode(‘utf-8‘)
if True == targetDevice.installPackage(‘D:\\Projects\\Workspace\\PythonMonkeyRunnerDemo\\apps\\MPortal.apk‘): print "Installationfinished successfully" else: print "Failedto install the apk"
if True == targetDevice.removePackage(‘com.majcit.portal‘): print "Succeed toremove the package" else: print "Failedto remove teh package"
dict = targetDevice.instrument(‘com.example.android.notepad.tryout/android.test.InstrumentationTestRunner‘) print dict指定只跑其中的一个Case:
dict = dict = targetDevice.instrument(‘com.example.android.notepad.tryout/android.test.InstrumentationTestRunner‘, {‘class‘:‘com.example.android.notepad.tryout.TCCreateNote‘}) print dict
package com.example.android.notepad.tryout; import com.robotium.solo.Solo; import android.test.ActivityInstrumentationTestCase2; import android.app.Activity; @SuppressWarnings("rawtypes") public class TCCreateNote extends ActivityInstrumentationTestCase2{ private static Solo solo = null; public Activity activity; private static final int NUMBER_TOTAL_CASES = 2; private static int run = 0; private static Class<?> launchActivityClass; //对应re-sign.jar生成出来的信息框里的两个值 private static String mainActiviy = "com.example.android.notepad.NotesList"; private static String packageName = "com.example.android.notepad"; static { try { launchActivityClass = Class.forName(mainActiviy); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") public TCCreateNote() { super(packageName, launchActivityClass); } @Override public void setUp() throws Exception { //setUp() is run before a test case is started. //This is where the solo object is created. super.setUp(); //The variable solo has to be static, since every time after a case‘s finished, this class TCCreateNote would be re-instantiated // which would lead to soto to re-instantiated to be null if it‘s not set as static if(solo == null) { TCCreateNote.solo = new Solo(getInstrumentation(), getActivity()); } } @Override public void tearDown() throws Exception { //Check whether it‘s the last case executed. run += countTestCases(); if(run >= NUMBER_TOTAL_CASES) { solo.finishOpenedActivities(); } } public void testAddNoteCNTitle() throws Exception { solo.clickOnMenuItem("Add note"); solo.enterText(0, "中文标签笔记"); solo.clickOnMenuItem("Save"); solo.clickInList(0); solo.clearEditText(0); solo.enterText(0, "Text 1"); solo.clickOnMenuItem("Save"); solo.assertCurrentActivity("Expected NotesList Activity", "NotesList"); solo.clickLongOnText("中文标签笔记"); solo.clickOnText("Delete"); } public void testAddNoteEngTitle() throws Exception { solo.clickOnMenuItem("Add note"); solo.enterText(0, "English Title Note"); solo.clickOnMenuItem("Save"); solo.clickInList(0); solo.clearEditText(0); solo.enterText(0, "Text 1"); solo.clickOnMenuItem("Save"); solo.assertCurrentActivity("Expected NotesList Activity", "NotesList"); solo.clickLongOnText("English Title Note"); solo.clickOnText("Delete"); } }那么我们先在目标机器上执行命令“pm list instrumentation”看是否能列出这个“Component”: 这其中哪一个是我们想要的呢?这要看我们的Robotium测试项目中的AndroidManifest.xml的定义了,根据下图的packageName再对照上图的输出我们就定位到我们想要的Component了: 如果我们调用这个方法的时候只是填写了第一个参数的话,上图处在”com.example.andriod.notepad.tryout”这个Component下的所有三个方法都会执行。但在我的测试中,发现除了跑这个Case之外,它还跑多了一些步骤,就是额外的多创建了一个Note1。我查了半天,发现原来我之前除了编写了基于ActivityInstrumentationTestCase2的Robotium的这个项目之外,还在NoetePad这个项目上直接用InstrumentationTestCase写了一个基于Instrumentation的测试用例,做得事情就是增加一个Note1,具体请看本人CSDN上另外一篇blog《SDK Instrumentation创建一个Note的实例》 其实调用这个方法相当于在shell脚本上执行如下的命令: am instrument -w -r -e class com.example.android.notepad.tryout.TCCreateNote com.example.android.notepad.tryout/android.test.InstrumentationTestRunner 最后提一下的是,我们的脚本在执行示例的时候大概5秒左右就会失败,但事实上在设备端所有的指定component的测试用例已经在执行的了。要解决这个问题需要重新编译源码,这里就免了,具体请查看:http://stackoverflow.com/questions/4264057/android-cts-is-showing-shellcommandunresponsiveexception-on-emulator 这里尝试做一个简单的总结
targetDevice.press(‘KEYCODE_BACK‘,MonkeyDevice.DOWN_AND_UP)
Type |
Constants |
Notes |
Comment |
int(官网是string,下同) |
Use this with the type argument of press() or touch() to send a DOWN event. | ||
int |
Use this with the type argument of press() or touch() to send an UP event. | ||
int |
Use this with the type argument of press() or touch() to send a DOWN event immediately followed by an UP event. | ||
int |
MOVE |
TBD | 官网没有列出来 |
viewer = targetDevice.getHierarchyViewer() note = viewer.findViewById(‘id/text1‘) point = viewer.getAbsoluteCenterOfView(note) startX = point.x startY = point.y targetDevice.touch(startX,startY,MonkeyDevice.DOWN_AND_UP)
viewer = targetDevice.getHierarchyViewer() note = viewer.findViewById(‘id/text1‘) point = viewer.getAbsoluteCenterOfView(note) startX = point.x startY = point.y targetDevice.touch(startX,startY,MonkeyDevice.DOWN_AND_UP) MonkeyRunner.sleep(3) targetDevice.type(‘NewContent‘)
targetDevice.wake()
#Connect to the target targetDevice targetDevice = MonkeyRunner.waitForConnection() easy_device = EasyMonkeyDevice(targetDevice) #touch a button by id would need this targetDevice.startActivity(component="com.example.android.notepad/com.example.android.notepad.NotesList") #invoke the menu options MonkeyRunner.sleep(6) #targetDevice.press(‘KEYCODE_MENU‘, MonkeyDevice.DOWN_AND_UP); ‘‘‘ public ViewNode findViewById(String id) * @param id id for the view. * @return view with the specified ID, or {@code null} if no view found. ‘‘‘ #MonkeyRunner.alert("Continue?", "help", "Ok?") pic = targetDevice.takeSnapshot() pic = pic.getSubImage((0,38,480,762)) newPic = targetDevice.takeSnapshot() newPic = newPic.getSubImage((0,38,480,762)) print (newPic.sameAs(pic,1.0)) newPic.writeToFile(‘./shot1.png‘,‘png‘)
res = targetDevice.shell(‘ls /data/local/tmp|grep note‘) print res
targetDevice.reboot()这里有点需要提下的是,如果你是在MonkeyRunner命令行下执行这条命令的话,就算目标机器重启,整个MonkeyRunner的环境还是依然有效的。也就是说你如果继续打进一条"targetDevice.reboot()",你的设备就会再重启一次。
作者 | 自主博客 | 微信服务号及扫描码 | CSDN |
天地会珠海分舵 | http://techgogogo.com | 服务号:TechGoGoGo扫描码: | http://blog.csdn.net/zhubaitian |
标签:
原文地址:http://www.cnblogs.com/techgogogo/p/4284811.html