避免 MonkeyRunner.sleep

Avoiding MonkeyRunner.sleep

我对 monkeyrunner 和 Android 总体开发完全陌生。按照 bogstandard monkeyrunner 教程,有人建议我在 startActivity 之后也执行以下睡眠调用:

runComponent = package + '/' + activity

# Runs the component
device.startActivity(component=runComponent)
MonkeyRunner.sleep(5)
# Presses the Menu button
device.press('KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP)

# Takes a screenshot
result = device.takeSnapshot()

# Writes the screenshot to a file
result.writeToFile('C:\Users\username\Desktop\shot1.png','png')

...声称需要 MonkeyRunner.sleep() 以确保某些操作有足够的时间执行。 (但是在慢速设备上 5 秒是否足够?我怎么知道?)

根据其他语言的经验,我知道依赖 .sleep 是一个糟糕的主意。我想开始使用 monkeyrunner 对一些基本的测试自动化策略进行原型设计,如果我到处使用 .sleep,我的测试最终会累积任意数量的浪费时间。

如何使用某种事件驱动模型来等待设备任务共同完成?是否存在我无法连接到某些事件并且我将不得不利用任意数量的休眠时间的常见情况?

你应该使用比 monkeyrunner 更复杂的东西来实现你的目标。

备选方案之一是 CulebraTester,它可以根据条件等待。

此示例使用 CulebraTester 使用启动器抽屉启动 Calculator.

生成的python脚本是这个

#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C) 2013-2018  Diego Torres Milano
Created on 2018-04-13 by CulebraTester 
                      __    __    __    __
                     /  \  /  \  /  \  /  \ 
____________________/  __\/  __\/  __\/  __\_____________________________
___________________/  /__/  /__/  /__/  /________________________________
                   | / \   / \   / \   / \   \___
                   |/   \_/   \_/   \_/   \    o \ 
                                           \_____/--<
@author: Diego Torres Milano
@author: Jennifer E. Swofford (ascii art snake)
'''


import re
import sys
import os


import unittest
try:
    sys.path.insert(0, os.path.join(os.environ['ANDROID_VIEW_CLIENT_HOME'], 'src'))
except:
    pass

import pkg_resources
pkg_resources.require('androidviewclient>=12.4.0')
from com.dtmilano.android.viewclient import ViewClient, CulebraTestCase
from com.dtmilano.android.uiautomator.uiautomatorhelper import UiAutomatorHelper, UiScrollable, UiObject, UiObject2

TAG = 'CULEBRA'


class CulebraTests(CulebraTestCase):

    @classmethod
    def setUpClass(cls):
        cls.kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': False}
        cls.kwargs2 = {'forceviewserveruse': False, 'useuiautomatorhelper': True, 'ignoreuiautomatorkilled': True, 'autodump': False, 'startviewserver': True, 'compresseddump': True}
        cls.options = {'start-activity': None, 'concertina': False, 'device-art': None, 'use-jar': False, 'multi-device': False, 'unit-test-class': True, 'save-screenshot': None, 'use-dictionary': False, 'glare': False, 'dictionary-keys-from': 'id', 'scale': 1, 'find-views-with-content-description': True, 'window': -1, 'orientation-locked': None, 'save-view-screenshots': None, 'find-views-by-id': True, 'log-actions': False, 'use-regexps': False, 'null-back-end': False, 'auto-regexps': None, 'do-not-verify-screen-dump': True, 'verbose-comments': False, 'gui': False, 'find-views-with-text': True, 'prepend-to-sys-path': False, 'install-apk': None, 'drop-shadow': False, 'output': None, 'unit-test-method': None, 'interactive': False}
        cls.sleep = 5

    def setUp(self):
        super(CulebraTests, self).setUp()

    def tearDown(self):
        super(CulebraTests, self).tearDown()

    def preconditions(self):
        if not super(CulebraTests, self).preconditions():
            return False
        return True

    def testSomething(self):
        if not self.preconditions():
            self.fail('Preconditions failed')

        _s = CulebraTests.sleep
        _v = CulebraTests.verbose

        self.vc.uiAutomatorHelper.findObject(bySelector='res@com.google.android.apps.nexuslauncher:id/all_apps_handle,desc@Apps list,clazz@android.widget.ImageView,text@$,package@com.google.android.apps.nexuslauncher').clickAndWait(eventCondition='until:newWindow', timeout=_s*1000)
        UiScrollable(self.vc.uiAutomatorHelper, uiSelector='clazz@android.support.v7.widget.RecyclerView,res@com.google.android.apps.nexuslauncher:id/apps_list_view,index@2,parentIndex@1,package@com.google.android.apps.nexuslauncher').getChildByDescription(uiSelector='desc@Calculator', description="Calculator", allowScrollSearch=True).click()


if __name__ == '__main__':
    CulebraTests.main()

在脚本末尾,您可以看到(我刚刚删除了 Apps 选择器以减小大小)

self.vc.uiAutomatorHelper.findObject(bySelector='...').\
        clickAndWait(eventCondition='until:newWindow', timeout=_s*1000)

找到应用程序按钮,单击它,然后等待抽屉打开,作为一个新的 window。

关闭计算器和抽屉以及运行脚本,您将看到它如何再次打开

testSomething (__main__.CulebraTests) ... ok

----------------------------------------------------------------------
Ran 1 test in 13.103s

OK