Saturday, April 23, 2011

Running instrumentation from monkeyrunner

Sometimes you may want to run the instrumentation for a package from monkeyrunner, and the following script does just this. It has the advantage of using the package manager to find the correct instrumentation for the specified package simplifying the parameters you must provide.

#! /usr/bin/env monkeyrunner

import sys
import os
from import MonkeyRunner

PLI = 'pm list instrumentation'
prog = os.path.basename(sys.argv[0])

def usage():
   print >>sys.stderr, \
       "usage: %s target-package-name" % prog

def main():
   if len(sys.argv) != 2:

   pkg = sys.argv[1]

   print "waiting for connection..."
   device = MonkeyRunner.waitForConnection()

   print "running istrumentation for %s" % pkg
   for (i, t) in map(lambda l: l.split(),
      if t == '(target=%s)' % pkg:
         print device.instrument(i.split(':')[1], { 'wait':True })['stream']
   print >>sys.stderr, "ERROR: instrumentation for %s not found" % pkg

if __name__ == '__main__':

You can invoke this script as in the following command line:

   $ com.example.package

compare this against the command line you may need to invoke the same instrumentation using plain am instrument.
Once you invoke the script with the correct package name, the instrumentation for that package is run and the results are presented, like in this example:

waiting for connection...
running istrumentation for com.example.package

Test results for InstrumentationTestRunner=..................................
Time: 37.844

OK (34 tests)


Unknown said...

I am getting exception while running this script. Can you please mention, what string need to provide in instrument method? I tried to use following method but, still getting the error:



Diego Torres Milano said...

Which exception ?

Diego Torres Milano said...

The idea of this script is to provide the right parameter to device.instrument() without forcing you to remember (or guess).
What's the output of your 'pm list instrumentation' ?

RV IT Group said...

I appreciate your post, thanks for sharing the post
android apps

Diego Torres Milano said...

Thanks for your comments.

小腳掌 said...

Dear Diego,

Many thanks for your sharing MonkeyRunner example.

Now my concern is, if I want to use MonkeyRunner to reach auto test of Android system, how could I check the result?

For example, if I want to open a browser, input a URL, then reload it. During these procedure, how should I make the check point, and what could I check?