使用MonkeyRunner和AndroidViewClient(触摸)的脚本错误

时间:2015-12-21 17:00:25

标签: android python-2.7 monkeyrunner androidviewclient

我尝试使用monkeyrunner和AndroidViewClient测试一些应用程序,我也使用culebra生成代码,但我有这个错误:

from com.dtmilano.android.viewclient import ViewClient, TextView, EditText
SyntaxError: ("mismatched input 'as' expecting COLON", ('/home/experts/AndroidViewClient-master/src/com/dtmilano/android/viewclient.py', 3795, 35, ''))

这是我的脚本whit monkeyrunner和AndroidViewClient

import re
import sys
import os

try:
   sys.path.append(os.path.join(os.environ['ANDROID_VIEW_CLIENT_HOME'], 'src'))
except:
   pass

from com.dtmilano.android.viewclient import ViewClient, TextView, EditText
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage

def main():
# Connects to the current device, returning a MonkeyDevice object
   emulatorid = 'emulator-5558'
   device = MonkeyRunner.waitForConnection('',emulatorid)
   print "waiting for connection...\n"

   package = "com.duolingo"
   activity = "app.LoginActivity"

   # sets the name of the component to start
   runComponent = package + "/." + activity

   #Runs the component
   print "Start Component"
   device.startActivity(component=runComponent)
   MonkeyRunner.sleep(10)

   vc = ViewClient(device)
   vc.dump()
   vc.sleep(_s)
   vc.dump(window=-1)
   vc.findViewWithTextOrRaise(u'GET STARTED').touch()
   vc.sleep(_s)
   vc.dump(window=-1)
   vc.findViewWithTextOrRaise(u'Spanish', root=self.vc.findViewByIdOrRaise('id/no_id/3')).touch()

   # Takes a screenshot
   screenshot = device.takeSnapshot()

   # Writes the screenshot to a file
   screenshot.writeToFile('./device1.png','png')

   print "end"
   if __name__ == '__main__':
   main()

如果我执行这个wthiout monkeyrunner它会显示一个关于“ViewClient(device)”的错误,这个脚本在一个循环中(for)。

修改

我执行了culebra,现在我的脚本运行良好!但是,它适用于CommandLine($ myscripttest.py模拟器-5554)如果我使用subprocess.call调用它,其中emulatorid ='emulator-5554'

subprocess.call('path/script_files/myscripttest.py' + ' ' + emulatorid, shell=True)

显示错误:

  File "/path/script_files/myscripttest.py", line 9, in <module>
from com.dtmilano.android.viewclient import ViewClient
File "/usr/local/lib/python2.7/dist-packages/androidviewclient-11.0.7-py2.7.egg/com/dtmilano/android/viewclient.py", line 43, in <module>
import xml.parsers.expat
File "/usr/lib/python2.7/xml/parsers/expat.py", line 4, in <module>
from pyexpat import *
ImportError: /usr/lib/python2.7/lib-dynload/pyexpat.x86_64-linux-gnu.so: undefined symbol: XML_SetHashSalt

我使用此代码验证:错误在哪里?

$ ldd /usr/lib/python2.7/lib-dynload/pyexpat.x86_64-linux-gnu.so 
linux-vdso.so.1 =>  (0x00007fffe5dc2000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f55d2fd4000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f55d2c0f000)
libexpat.so.1 => /lib/x86_64-linux-gnu/libexpat.so.1 (0x00007f55d29e5000)
/lib64/ld-linux-x86-64.so.2 (0x00007f55d3403000)

1 个答案:

答案 0 :(得分:8)

AndroidViewClient/culebramonkeyrunner的替代品。您应该在脚本中使用其中一个,而不是两个一起使用。

culerbaCulebra GUI会为您生成正确的测试或脚本模板,您可以进一步自定义。

这些工具生成的所有测试和脚本都应该使用 python 2.x 执行。

我想我可以猜到你想用脚本实现的目标,并且我将使用culebra给出一个分步示例,这样你就可以理解它是多么容易。

第1步

启动culebra,告知您还要启动特定活动

$ culebra -GuU --start-activity=com.duolingo/.app.LoginActivity --scale=0.5 -o ~/tmp/duolingo-screenshot.py

这会运行GUI(-G),不会验证转储中的视图(-u),创建单元测试(-U),启动活动(--start-activity) ,将窗口缩放50%,使其适合屏幕(--scale),并将测试保存在文件(-o)中。

如果一切顺利,你会看到Culebra GUI。

enter image description here

第2步

点击窗口上的 GET STARTED 按钮。

enter image description here

第3步

点击西班牙文

enter image description here

第4步

使用上下文菜单(交替点击窗口)或键盘快捷键

获取所需的屏幕截图

enter image description here

第5步

关闭窗口。

此时生成测试,它包含类似的内容

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


import re
import sys
import os


import unittest

from com.dtmilano.android.viewclient import ViewClient, CulebraTestCase

TAG = 'CULEBRA'


class CulebraTests(CulebraTestCase):

    @classmethod
    def setUpClass(cls):
        cls.kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': False}
        cls.kwargs2 = {'forceviewserveruse': False, 'useuiautomatorhelper': False, 'ignoreuiautomatorkilled': True, 'autodump': False, 'startviewserver': True, 'compresseddump': True}
        cls.options = {'start-activity': 'com.duolingo/.app.LoginActivity', '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': 0.5, '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': True, '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.dump(window=-1)
        self.vc.findViewWithTextOrRaise(u'GET STARTED').touch()
        self.vc.sleep(_s)
        self.vc.dump(window=-1)
        self.vc.findViewWithTextOrRaise(u'Spanish', root=self.vc.findViewByIdOrRaise('id/no_id/5')).touch()
        self.vc.sleep(_s)
        self.vc.dump(window=-1)
        self.vc.writeImageToFile('/tmp/${serialno}-${focusedwindowname}-${timestamp}.png', 'PNG', 'None', False, False)


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

因此,当您再次运行测试时,您将获得新的屏幕截图。

重要:因为测试不包含有关设备或其特性的任何特定信息,例如屏幕尺寸等,并且它没有使用坐标来触摸但是查看属性,如文本或ID你可以在一个非常不同的设备上运行相同的测试,比如让我们说一个表,它会成功运行。甚至屏幕截图都以设备的序列号为前缀保存,因此您可以同时在同一个CI服务器上运行所有这些序列号。

额外提示

如果您在不重新安装应用程序的情况下多次运行测试,可能是第二次没有出现 GET STARTED 屏幕,但选择每日目标。如果我们也想考虑这个替代方案,我们可以编辑脚本并添加相应的条件

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

    _s = CulebraTests.sleep
    _v = CulebraTests.verbose

    self.vc.dump(window=-1)
    if not self.vc.findViewWithText(u'Pick a Daily Goal'):
        self.vc.findViewWithTextOrRaise(u'GET STARTED').touch()
        self.vc.sleep(_s)
        self.vc.dump(window=-1)
        self.vc.findViewWithTextOrRaise(u'Spanish', root=self.vc.findViewByIdOrRaise('id/no_id/5')).touch()
        self.vc.sleep(_s)
        self.vc.dump(window=-1)
    self.vc.writeImageToFile('/tmp/${serialno}-${focusedwindowname}-${timestamp}.png', 'PNG', 'None', False, False)

即使您想在设备图片中构建屏幕截图,也可以比使用 Android Studio 更轻松地完成此操作,您必须一次又一次地重新选择这些选项。只需更改takeScreenshot的参数,将STUDIO_DIR环境变量设置为指向 Studio 安装

self.vc.writeImageToFile('/tmp/${serialno}-${focusedwindowname}-${timestamp}.png', 'PNG', 'nexus_5', True, True)

瞧!

enter image description here