[转] Android自动化测试之MonkeyRunner录制和回放脚本(四)

时间:2021-08-15 12:37:03

测试脚本录制:

方案一:

我们先看看以下monkeyrecoder.py脚本:

  1. #Usage: monkeyrunner recorder.py
  2. #recorder.py  http://mirror.yongbok.net/linux/ ... ey_recorder.py;
  3. com.android.monkeyrunner import MonkeyRunner as mr
  4. com.android.monkeyrunner.recorder import MonkeyRecorder as recorder
  5. device = mr.waitForConnection()
  6. recorder.start(device)
  7. #END recorder.py

首先,连接你已经打开调试模式的ANDROID设备或模拟器,然后运行上面的脚本,例如在cmd窗口中执行命令: monkeyrunner monkeyrecoder.py

执行下面的代码后,将运行录制脚本的程序:

#Press ExportAction to save recorded scrip to a file

#Example of result:
#PRESS|{""name"":""MENU"",""type"":""downAndUp"",}
#TOUCH|{""x"":180,""y"":175,""type"":""downAndUp"",}
#TYPE|{""message"":"""",}

=================================================

这种脚本需要另外一个monkeyrunner的脚本来解释执行。monkeyplayback.py

  1. #Usage: monkeyrunner playback.py "myscript"
  2. #playback.py   http://mirror.yongbok.net/linux/ ... ey_playback.py;
  3. import sys
  4. com.android.monkeyrunner import MonkeyRunner
  5. # The format of the file we are parsing is very carfeully constructed.
  6. # Each line corresponds to a single command.  The line is split into 2
  7. # parts with a | character.  Text to the left of the pipe denotes
  8. # which command to run.  The text to the right of the pipe is a python
  9. # dictionary (it can be evaled into existence) that specifies the
  10. # arguments for the command.  In most cases, this directly maps to the
  11. # keyword argument dictionary that could be passed to the underlying
  12. # command.
  13. # Lookup table to map command strings to functions that implement that
  14. # command.
  15. CMD_MAP = {
  16. ""TOUCH"": lambda dev, arg: dev.touch(**arg),
  17. ""DRAG"": lambda dev, arg: dev.drag(**arg),
  18. ""PRESS"": lambda dev, arg: dev.press(**arg),
  19. ""TYPE"": lambda dev, arg: dev.type(**arg),
  20. ""WAIT"": lambda dev, arg: MonkeyRunner.sleep(**arg)
  21. }
  22. # Process a single file for the specified device.
  23. def process_file(fp, device):
  24. for line in fp:
  25. (cmd, rest) = line.split(""|"")
  26. try:
  27. # Parse the pydict
  28. rest = eval(rest)
  29. except:
  30. print ""unable to parse options""
  31. continue
  32. if cmd not in CMD_MAP:
  33. print ""unknown command: "" + cmd
  34. continue
  35. CMD_MAP[cmd](device, rest)
  36. def main():
  37. file = sys.argv[1]
  38. fp = open(file, ""r"")
  39. device = MonkeyRunner.waitForConnection()
  40. process_file(fp, device)
  41. fp.close();
  42. if __name__ == ""__main__"":
  43. main()

=================================================

Usage:monkeyrunner playback.py "myscript"