Merge lp:~liuyq0307/lava-android-test/add-unittest into lp:lava-android-test

Proposed by Yongqin Liu
Status: Merged
Merged at revision: 123
Proposed branch: lp:~liuyq0307/lava-android-test/add-unittest
Merge into: lp:lava-android-test
Diff against target: 936 lines (+850/-6)
12 files modified
lava_android_test/hwprofile.py (+6/-6)
tests/__init__.py (+29/-0)
tests/fixtures.py (+37/-0)
tests/imposters.py (+78/-0)
tests/test_hwprofile.py (+176/-0)
tests/test_lavaandroidtest_commands.py (+95/-0)
tests/test_lavaandroidtest_test.py (+88/-0)
tests/test_lavaandroidtest_testinstaller.py (+58/-0)
tests/test_lavaandroidtest_testparser.py (+55/-0)
tests/test_lavaandroidtest_testrunner.py (+65/-0)
tests/test_swprofile.py (+87/-0)
tests/tests_util.py (+76/-0)
To merge this branch: bzr merge lp:~liuyq0307/lava-android-test/add-unittest
Reviewer Review Type Date Requested Status
Paul Larson (community) Approve
Review via email: mp+85809@code.launchpad.net

This proposal supersedes a proposal from 2011-12-14.

Description of the change

add unit test for packages hwprofile/swprofile, class AndroidTest/AndroidTestInstaller/AndroidTestRunner/AndroidTestParser
according to review comments, make the fake_adb to use bash exactly.

To post a comment you must log in.
Revision history for this message
Paul Larson (pwlars) wrote : Posted in a previous version of this proposal

running=PYTHONPATH=. python -m subunit.run tests.test_suite
======================================================================
FAIL: tests.test_lavaandroidtest_commands.ListInstalled.test_list_installed
----------------------------------------------------------------------
Text attachment: traceback
------------
Traceback (most recent call last):
  File "tests/test_lavaandroidtest_commands.py", line 59, in test_list_installed
    self.assertTrue(test_name in self.out.getvalue())
AssertionError: False is not true
------------
======================================================================
FAIL: tests.test_lavaandroidtest_commands.RunTest.test_run_command_test_not_exist
----------------------------------------------------------------------
Text attachment: traceback
------------
Traceback (most recent call last):
  File "tests/test_lavaandroidtest_commands.py", line 86, in test_run_command_test_not_exist
    self.assertRaises(SystemExit, LAVAAndroidTestDispatcher().dispatch, ['run', 'abc'])
AssertionError: SystemExit not raised
------------
======================================================================
FAIL: tests.test_swprofile.SwprofileTests.test_get_package_info
----------------------------------------------------------------------
Text attachment: traceback
------------
Traceback (most recent call last):
  File "tests/test_swprofile.py", line 86, in test_get_package_info
    self.assertEqual(packages, result_hash)
AssertionError: {'com.android.wallpaper': '4.0.1.2.3.4.5.6.7.8.9-3 (#14)', 'com.android.videoedi [truncated]... != {'com.android.wallpaper': '4.0.1.2.3.4.5.6.7.8.9-3 (#14)', 'com.android.videoedi [truncated]...
+ {'[': '4: CLASSPATH=/data/lava-android-test/temp/lavatools.jar: unexpected operator',
- {'android': '4.0.1.2.3.4.5.6.7.8.9-3 (#14)',
? ^

+ 'android': '4.0.1.2.3.4.5.6.7.8.9-3 (#14)',
? ^

   'com.android.musicvis': '4.0.1.2.3.4.5.6.7.8.9-3 (#14)',
   'com.android.videoeditor': '1.1 (#11)',
   'com.android.vpndialogs': '4.0.1.2.3.4.5.6.7.8.9-3 (#14)',
   'com.android.wallpaper': '4.0.1.2.3.4.5.6.7.8.9-3 (#14)',
   'com.android.wallpaper.livepicker': '4.0.1.2.3.4.5.6.7.8.9-3 (#14)',
   'com.svox.pico': '1.0 (#1)'}
------------
======================================================================
FAIL: tests.test_hwprofile.HwprofileTests.test_get_cpu_devs
----------------------------------------------------------------------
Text attachment: traceback
------------
Traceback (most recent call last):
  File "tests/test_hwprofile.py", line 117, in test_get_cpu_devs
    self.assertEqual(cpuinfo, devs[0])
AssertionError: {'attributes': {'cpu_model_name': 'ARMv7 Processor rev 2 (v7l)', 'processor': '0 [truncated]... != {'attributes': {'cpu_model_name': 'ARMv7 Processor rev 2 (v7l)', '[': '4: cat: u [truncated]...
  {'attributes': {'BogoMIPS': '1576.53',
+ '[': '4: cat: unexpected operator',
                  'cpu_model_name': 'ARMv7 Processor rev 2 (v7l)',
                  'processor': '0'},
   'description': 'Processor #0',
   'device_type': 'device.cpu'}
------------
id=0, tests=29, failures=4

Revision history for this message
Yongqin Liu (liuyq0307) wrote :

and for the command to run test, why we not use "python setup.py test"?

I had try to use "running=PYTHONPATH=. python -m subunit.run tests.test_suite" to run the test,
but there are errors like these because it can't find the entry_points for lava_android_test package.
I found that if we want to use "running=PYTHONPATH=. python -m subunit.run tests.test_suite",
we need to install lava-android-test first or run "python setup.py test" first.

test: tests.test_lavaandroidtest_commands.ListDevices.test_list_devices
error: tests.test_lavaandroidtest_commands.ListDevices.test_list_devices [
Traceback (most recent call last):
  File "tests/test_lavaandroidtest_commands.py", line 70, in test_list_devices
    self._runLavaTest(['list-devices'])
  File "tests/test_lavaandroidtest_commands.py", line 33, in _runLavaTest
    LAVAAndroidTestDispatcher().dispatch(cmds)
  File "/usr/lib/pymodules/python2.7/lava_tool/dispatcher.py", line 67, in dispatch
    args = self.parser.parse_args(raw_args)
  File "/usr/lib/python2.7/argparse.py", line 1688, in parse_args
    args, argv = self.parse_known_args(args, namespace)
  File "/usr/lib/python2.7/argparse.py", line 1727, in parse_known_args
    self.error(str(err))
  File "/usr/lib/python2.7/argparse.py", line 2347, in error
    self.exit(2, _('%s: error: %s\n') % (self.prog, message))
  File "/usr/lib/python2.7/argparse.py", line 2335, in exit
    _sys.exit(status)
SystemExit: 2
]

Revision history for this message
Paul Larson (pwlars) wrote :

ah, ok. If that's how you intend the tests to be run then, we should probably remove the testr stuff. I'll take care of that though. Thanks.

review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'lava_android_test/hwprofile.py'
2--- lava_android_test/hwprofile.py 2011-10-19 06:05:16 +0000
3+++ lava_android_test/hwprofile.py 2011-12-15 08:41:23 +0000
4@@ -59,8 +59,8 @@
5 keymap, valmap = ARM_KEYMAP, ARM_VALMAP
6
7 try:
8- cpuinfo = adb.get_shellcmdoutput("cat /proc/cpuinfo")[1]
9- if cpuinfo is None:
10+ (retcode, cpuinfo) = adb.get_shellcmdoutput("cat /proc/cpuinfo")
11+ if retcode != 0 or cpuinfo is None :
12 raise IOError("Faile to get content of file(%s)" % "/proc/cpuinfo")
13 for line in cpuinfo:
14 match = pattern.match(line)
15@@ -95,8 +95,8 @@
16 device = {}
17
18 try:
19- cpuinfo = adb.get_shellcmdoutput("cat /proc/cpuinfo")[1]
20- if cpuinfo is None:
21+ (retcode, cpuinfo) = adb.get_shellcmdoutput("cat /proc/cpuinfo")
22+ if retcode != 0 or cpuinfo is None :
23 raise IOError("Faile to get content of file(%s)" % "/proc/cpuinfo")
24 pattern = re.compile("^Hardware\s*:\s*(?P<description>.+)$", re.M)
25 found = False
26@@ -126,8 +126,8 @@
27 pattern = re.compile('^(?P<key>.+?)\s*:\s*(?P<value>.+) kB$', re.M)
28
29 try:
30- meminfo = adb.get_shellcmdoutput("cat /proc/meminfo")[1]
31- if meminfo is None:
32+ (retcode, meminfo) = adb.get_shellcmdoutput("cat /proc/meminfo")
33+ if retcode != 0 or meminfo is None:
34 raise IOError("Faile to get content of file(%s)" % "/proc/meminfo")
35 for line in meminfo:
36 match = pattern.search(line)
37
38=== added directory 'tests'
39=== added file 'tests/__init__.py'
40--- tests/__init__.py 1970-01-01 00:00:00 +0000
41+++ tests/__init__.py 2011-12-15 08:41:23 +0000
42@@ -0,0 +1,29 @@
43+# Copyright (c) 2010, 2011 Linaro
44+#
45+# This program is free software: you can redistribute it and/or modify
46+# it under the terms of the GNU General Public License as published by
47+# the Free Software Foundation, either version 3 of the License, or
48+# (at your option) any later version.
49+#
50+# This program is distributed in the hope that it will be useful,
51+# but WITHOUT ANY WARRANTY; without even the implied warranty of
52+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
53+# GNU General Public License for more details.
54+#
55+# You should have received a copy of the GNU General Public License
56+# along with this program. If not, see <http://www.gnu.org/licenses/>.
57+
58+import unittest
59+
60+def test_suite():
61+ module_names = [
62+ 'tests.test_lavaandroidtest_commands',
63+ 'tests.test_lavaandroidtest_test',
64+ 'tests.test_lavaandroidtest_testinstaller',
65+ 'tests.test_lavaandroidtest_testparser',
66+ 'tests.test_lavaandroidtest_testrunner',
67+ 'tests.test_swprofile',
68+ 'tests.test_hwprofile']
69+ loader = unittest.TestLoader()
70+ suite = loader.loadTestsFromNames(module_names)
71+ return suite
72
73=== added file 'tests/fixtures.py'
74--- tests/fixtures.py 1970-01-01 00:00:00 +0000
75+++ tests/fixtures.py 2011-12-15 08:41:23 +0000
76@@ -0,0 +1,37 @@
77+# Copyright (c) 2010, 2011 Linaro
78+#
79+# This program is free software: you can redistribute it and/or modify
80+# it under the terms of the GNU General Public License as published by
81+# the Free Software Foundation, either version 3 of the License, or
82+# (at your option) any later version.
83+#
84+# This program is distributed in the hope that it will be useful,
85+# but WITHOUT ANY WARRANTY; without even the implied warranty of
86+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
87+# GNU General Public License for more details.
88+#
89+# You should have received a copy of the GNU General Public License
90+# along with this program. If not, see <http://www.gnu.org/licenses/>.
91+
92+import unittest
93+
94+
95+class TestCaseWithFixtures(unittest.TestCase):
96+ """TestCase extended to allow adding fixtures
97+
98+ Fixtures added should contain at least a setUp() method, and
99+ optionally a tearDown method as well
100+ """
101+
102+ def add_fixture(self, fixture):
103+ if not hasattr(self, "_fixtures"):
104+ self._fixtures = []
105+ fixture.setUp()
106+ if hasattr(self, "tearDown"):
107+ self._fixtures.append(fixture)
108+ return fixture
109+
110+ def tearDown(self):
111+ for fixture in self._fixtures:
112+ fixture.tearDown()
113+ self._fixtures = []
114
115=== added file 'tests/imposters.py'
116--- tests/imposters.py 1970-01-01 00:00:00 +0000
117+++ tests/imposters.py 2011-12-15 08:41:23 +0000
118@@ -0,0 +1,78 @@
119+# Copyright (c) 2010, 2011 Linaro
120+#
121+# This program is free software: you can redistribute it and/or modify
122+# it under the terms of the GNU General Public License as published by
123+# the Free Software Foundation, either version 3 of the License, or
124+# (at your option) any later version.
125+#
126+# This program is distributed in the hope that it will be useful,
127+# but WITHOUT ANY WARRANTY; without even the implied warranty of
128+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
129+# GNU General Public License for more details.
130+#
131+# You should have received a copy of the GNU General Public License
132+# along with this program. If not, see <http://www.gnu.org/licenses/>.
133+
134+import os
135+import shutil
136+import sys
137+import tempfile
138+import StringIO
139+
140+class OutputImposter(object):
141+ def setUp(self):
142+ self.origstdout = sys.stdout
143+ self.origstderr = sys.stderr
144+ sys.stdout = sys.stderr = self.fakestdout = StringIO.StringIO()
145+
146+ def tearDown(self):
147+ sys.stdout = self.origstdout
148+ sys.stderr = self.origstderr
149+
150+ def getvalue(self):
151+ return self.fakestdout.getvalue()
152+
153+class ConfigImposter(object):
154+ def setUp(self):
155+ class fakeconfig:
156+ def __init__(self, basedir):
157+ self.configdir = os.path.join(basedir, "config")
158+ self.installdir = os.path.join(basedir, "install")
159+ self.resultsdir = os.path.join(basedir, "results")
160+ self.registry = {
161+ "format": "LAVA Test Test Registry 1.0",
162+ "providers": [
163+ {
164+ "entry_point": "lava_test.core.providers:BuiltInProvider"
165+ },
166+ {
167+ "entry_point": "lava_test.core.providers:PkgResourcesProvider",
168+ "config": {"namespace": "lava_test.test_definitions" }
169+ },
170+ {
171+ "entry_point": "lava_test.core.providers:RegistryProvider",
172+ "config": {
173+ "entries": []
174+ }
175+ }
176+ ]
177+ }
178+
179+ self.tmpdir = tempfile.mkdtemp()
180+ self.config = fakeconfig(self.tmpdir)
181+
182+ def tearDown(self):
183+ shutil.rmtree(self.tmpdir)
184+
185+ @property
186+ def configdir(self):
187+ return self.config.configdir
188+
189+ @property
190+ def installdir(self):
191+ return self.config.installdir
192+
193+ @property
194+ def resultsdir(self):
195+ return self.config.resultsdir
196+
197
198=== added file 'tests/test_hwprofile.py'
199--- tests/test_hwprofile.py 1970-01-01 00:00:00 +0000
200+++ tests/test_hwprofile.py 2011-12-15 08:41:23 +0000
201@@ -0,0 +1,176 @@
202+#!/usr/bin/env python
203+# Copyright (c) 2011 Linaro
204+#
205+# This program is free software: you can redistribute it and/or modify
206+# it under the terms of the GNU General Public License as published by
207+# the Free Software Foundation, either version 3 of the License, or
208+# (at your option) any later version.
209+#
210+# This program is distributed in the hope that it will be useful,
211+# but WITHOUT ANY WARRANTY; without even the implied warranty of
212+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
213+# GNU General Public License for more details.
214+#
215+# You should have received a copy of the GNU General Public License
216+# along with this program. If not, see <http://www.gnu.org/licenses/>.
217+
218+import unittest
219+
220+import lava_android_test.hwprofile
221+from tests.tests_util import fake_adb, clear_fake
222+
223+from tests.imposters import OutputImposter
224+from tests.fixtures import TestCaseWithFixtures
225+
226+FAKE_BOARDNAME_FILE = "XXXXXXX"
227+FAKE_BOARDVENDOR_FILE = "YYYYYYY"
228+FAKE_BOARDVERSION_FILE = "ZZZZZZZ"
229+
230+panda_cpu_info = '''Processor : ARMv7 Processor rev 2 (v7l)
231+processor : 0
232+BogoMIPS : 1576.53
233+
234+processor : 1
235+BogoMIPS : 1539.77
236+
237+Features : swp half thumb fastmult vfp edsp thumbee neon vfpv3 tls
238+CPU implementer : 0x41
239+CPU architecture: 7
240+CPU variant : 0x1
241+CPU part : 0xc09
242+CPU revision : 2
243+
244+Hardware : OMAP4 Panda board
245+Revision : 0020
246+Serial : 0000000000000000
247+'''
248+
249+panda_mem_info = '''MemTotal: 921832 kB
250+MemFree: 545032 kB
251+Buffers: 488 kB
252+Cached: 183964 kB
253+SwapCached: 0 kB
254+Active: 212628 kB
255+Inactive: 125480 kB
256+Active(anon): 153680 kB
257+Inactive(anon): 60744 kB
258+Active(file): 58948 kB
259+Inactive(file): 64736 kB
260+Unevictable: 0 kB
261+Mlocked: 0 kB
262+HighTotal: 211968 kB
263+HighFree: 408 kB
264+LowTotal: 709864 kB
265+LowFree: 544624 kB
266+SwapTotal: 0 kB
267+SwapFree: 0 kB
268+Dirty: 0 kB
269+Writeback: 0 kB
270+AnonPages: 153640 kB
271+Mapped: 105236 kB
272+Shmem: 60768 kB
273+Slab: 10728 kB
274+SReclaimable: 4760 kB
275+SUnreclaim: 5968 kB
276+KernelStack: 3272 kB
277+PageTables: 5528 kB
278+NFS_Unstable: 0 kB
279+Bounce: 0 kB
280+WritebackTmp: 0 kB
281+CommitLimit: 460916 kB
282+Committed_AS: 4237400 kB
283+VmallocTotal: 122880 kB
284+VmallocUsed: 75536 kB
285+VmallocChunk: 36868 kB
286+'''
287+
288+class HwprofileTests(unittest.TestCase):
289+ maxDiff = None
290+
291+ def test_get_cpu_devs(self):
292+ fake_adb(output_str=panda_cpu_info)
293+ devs = lava_android_test.hwprofile.get_cpu_devs()
294+ clear_fake()
295+ cpuinfo = {
296+ 'attributes': {
297+ 'processor': '1',
298+ 'cpu_features': 'swp half thumb fastmult vfp edsp thumbee neon vfpv3 tls',
299+ 'cpu_variant': 1,
300+ 'cpu_architecture': 7,
301+ 'BogoMIPS': '1539.77',
302+ 'Hardware': 'OMAP4 Panda board',
303+ 'cpu_implementer': 65,
304+ 'cpu_part': 3081,
305+ 'cpu_revision': 2,
306+ 'Serial': '0000000000000000',
307+ 'Revision': '0020'},
308+ 'description': 'Processor #1',
309+ 'device_type': 'device.cpu'}
310+ self.assertEqual(cpuinfo, devs[1])
311+ cpuinfo = {
312+ 'attributes': {
313+ 'processor': '0',
314+ 'cpu_model_name': 'ARMv7 Processor rev 2 (v7l)',
315+ 'BogoMIPS': '1576.53'},
316+ 'description': 'Processor #0',
317+ 'device_type': 'device.cpu'}
318+ self.assertEqual(cpuinfo, devs[0])
319+
320+ def test_get_board_devs(self):
321+ fake_adb(output_str=panda_cpu_info)
322+ devs = lava_android_test.hwprofile.get_board_devs()
323+ clear_fake()
324+ boardinfo = {
325+ 'description': 'OMAP4 Panda board',
326+ 'device_type': 'device.board'}
327+ self.assertEqual(boardinfo, devs[0])
328+
329+ def test_get_mem_devs(self):
330+ fake_adb(output_str=panda_mem_info)
331+ devs = lava_android_test.hwprofile.get_mem_devs()
332+ clear_fake()
333+
334+ meminfo = {
335+ 'attributes': {
336+ 'kind': 'RAM',
337+ 'capacity': '943955968'},
338+ 'description': '900MiB of RAM',
339+ 'device_type': 'device.mem'}
340+ self.assertEqual(meminfo, devs[0])
341+
342+class MissingFiles(TestCaseWithFixtures):
343+ """
344+ These are tests for situations where certain files used for gathering
345+ hardware profile information may be missing
346+ """
347+ def setUp(self):
348+ super(MissingFiles, self).setUp()
349+ clear_fake()
350+ self.out = self.add_fixture(OutputImposter())
351+
352+ def test_bad_cpuinfo(self):
353+ errmsg = 'WARNING: Could not read cpu information\n'
354+ fake_adb(output_str='', ret_code=255)
355+ devs = lava_android_test.hwprofile.get_cpu_devs()
356+ clear_fake();
357+ self.assertEqual([], devs)
358+ self.assertEqual(errmsg, self.out.getvalue())
359+
360+ def test_bad_boardinfo(self):
361+ errmsg = 'WARNING: Could not read board information\n'
362+ fake_adb(output_str='', ret_code=255)
363+ devs = lava_android_test.hwprofile.get_board_devs()
364+ clear_fake();
365+ self.assertEqual([], devs)
366+ self.assertEqual(errmsg, self.out.getvalue())
367+
368+ def test_bad_meminfo(self):
369+ errmsg = 'WARNING: Could not read memory information\n'
370+ fake_adb(output_str='', ret_code=255)
371+ devs = lava_android_test.hwprofile.get_mem_devs()
372+ clear_fake();
373+ self.assertEqual([], devs)
374+ self.assertEqual(errmsg, self.out.getvalue())
375+
376+if __name__ == '__main__':
377+ unittest.main()
378
379=== added file 'tests/test_lavaandroidtest_commands.py'
380--- tests/test_lavaandroidtest_commands.py 1970-01-01 00:00:00 +0000
381+++ tests/test_lavaandroidtest_commands.py 2011-12-15 08:41:23 +0000
382@@ -0,0 +1,95 @@
383+# Copyright (c) 2011 Linaro
384+#
385+# This program is free software: you can redistribute it and/or modify
386+# it under the terms of the GNU General Public License as published by
387+# the Free Software Foundation, either version 3 of the License, or
388+# (at your option) any later version.
389+#
390+# This program is distributed in the hope that it will be useful,
391+# but WITHOUT ANY WARRANTY; without even the implied warranty of
392+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
393+# GNU General Public License for more details.
394+#
395+# You should have received a copy of the GNU General Public License
396+# along with this program. If not, see <http://www.gnu.org/licenses/>.
397+
398+import re
399+from tests.tests_util import fake_adb, clear_fake
400+
401+from tests.imposters import ConfigImposter, OutputImposter
402+from tests.fixtures import TestCaseWithFixtures
403+from lava_android_test.main import LAVAAndroidTestDispatcher
404+
405+class LavaTestCommandTestCase(TestCaseWithFixtures):
406+ def setUp(self):
407+ self.config = self.add_fixture(ConfigImposter())
408+ self.out = self.add_fixture(OutputImposter())
409+ clear_fake()
410+
411+ def tearDown(self):
412+ clear_fake()
413+
414+ def _runLavaTest(self, cmds):
415+ LAVAAndroidTestDispatcher().dispatch(cmds)
416+
417+class BadCommand(LavaTestCommandTestCase):
418+ def test_bad_cmd(self):
419+ # Running an unknown command that does not exist of a command that does
420+ # gives a nice error message.
421+ errmsg = "invalid choice: 'results'"
422+
423+ self.assertRaises(SystemExit, LAVAAndroidTestDispatcher().dispatch, ['results', 'foo'])
424+ self.assertNotEqual(None, re.search(errmsg, self.out.getvalue()), re.MULTILINE)
425+ self.assertTrue(errmsg in self.out.getvalue())
426+
427+class ListKnown(LavaTestCommandTestCase):
428+ def test_list_tests(self):
429+ self._runLavaTest(['list-tests'])
430+ self.assertTrue("monkey" in self.out.getvalue())
431+
432+dir_list_info = '''monkey
433+0xbench
434+RET_CODE=0'''
435+class ListInstalled(LavaTestCommandTestCase):
436+ def test_list_installed(self):
437+ # test_name must be in the BuiltInProvider._builtin_tests
438+ fake_adb(output_str=dir_list_info)
439+ test_name = "monkey"
440+ self._runLavaTest(['list-installed'])
441+ self.assertTrue(test_name in self.out.getvalue())
442+ clear_fake()
443+
444+devices_list_info = '''List of devices attached
445+192.168.1.109:5555 device
446+'''
447+
448+class ListDevices(LavaTestCommandTestCase):
449+ def test_list_devices(self):
450+ # test_name must be in the BuiltInProvider._builtin_tests
451+ fake_adb(output_str=devices_list_info)
452+ self._runLavaTest(['list-devices'])
453+ self.assertTrue('192.168.1.109:5555 device' in self.out.getvalue())
454+ clear_fake()
455+
456+class RunTest(LavaTestCommandTestCase):
457+ def test_run_command_test_not_install(self):
458+ errmsg = 'ERROR: The test (abc) has not been installed yet.'
459+ fake_adb(output_str='RET_CODE=1')
460+ ret_code = LAVAAndroidTestDispatcher().dispatch(['run', 'abc'])
461+ self.assertEqual(1, ret_code)
462+ self.assertTrue(errmsg in self.out.getvalue())
463+ clear_fake()
464+
465+ def test_run_command_test_not_exist(self):
466+ errmsg = "unknown test 'abc'"
467+ fake_adb(output_str='RET_CODE=0')
468+ self.assertRaises(SystemExit, LAVAAndroidTestDispatcher().dispatch, ['run', 'abc'])
469+ self.assertNotEqual(None, re.search(errmsg, self.out.getvalue()), re.MULTILINE)
470+ self.assertTrue(errmsg in self.out.getvalue())
471+
472+
473+class TestHelp(LavaTestCommandTestCase):
474+ def test_command_help(self):
475+ self.assertRaises(SystemExit, LAVAAndroidTestDispatcher().dispatch, ['--help'])
476+ self.assertTrue("--help" in self.out.getvalue())
477+
478
479=== added file 'tests/test_lavaandroidtest_test.py'
480--- tests/test_lavaandroidtest_test.py 1970-01-01 00:00:00 +0000
481+++ tests/test_lavaandroidtest_test.py 2011-12-15 08:41:23 +0000
482@@ -0,0 +1,88 @@
483+# Copyright (c) 2011 Linaro
484+#
485+# This program is free software: you can redistribute it and/or modify
486+# it under the terms of the GNU General Public License as published by
487+# the Free Software Foundation, either version 3 of the License, or
488+# (at your option) any later version.
489+#
490+# This program is distributed in the hope that it will be useful,
491+# but WITHOUT ANY WARRANTY; without even the implied warranty of
492+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
493+# GNU General Public License for more details.
494+#
495+# You should have received a copy of the GNU General Public License
496+# along with this program. If not, see <http://www.gnu.org/licenses/>.
497+
498+import re, os
499+import subprocess
500+from lava_android_test.config import get_config
501+from lava_android_test.adb import ADB
502+from tests.imposters import ConfigImposter, OutputImposter
503+from tests.fixtures import TestCaseWithFixtures
504+from tests.tests_util import maketest, makerunner, test_tmp, clear_fake, \
505+ fake_adb
506+
507+class FakeAdb(ADB):
508+ def __init__(self):
509+ super(FakeAdb, self).__init__()
510+ self.tmp_dir = test_tmp
511+ if not os.path.exists(test_tmp):
512+ os.makedirs(test_tmp)
513+
514+ def shell(self, command=None, stdout=None, stderr=None):
515+ if command.startswith('mkdir'):
516+ dir_path = command[len('mkdir '):]
517+ try:
518+ os.mkdir('%s/%s' % (test_tmp, dir_path))
519+ except:
520+ return 1
521+ return 0
522+ elif command.startswith('ls'):
523+ dir_path = command[len('ls '):]
524+ real_path = '%s/%s' % (test_tmp, dir_path)
525+ if os.path.exists(real_path):
526+ return 0
527+ else:
528+ return 1
529+ elif command.startswith('rm -r'):
530+ dir_path = command[len('rm -r '):]
531+ proc = subprocess.Popen('rm -fr %s/%s' % (test_tmp, dir_path), shell=True)
532+ return proc.wait()
533+ else:
534+ return 0
535+
536+fake_output_str = '''[ro.build.display.id]: [sdk-eng 4.0.1 ICS_MR0 202595 test-keys]
537+RET_CODE=0'''
538+class TestAndroidTest(TestCaseWithFixtures):
539+ def setUp(self):
540+ super(TestAndroidTest, self).setUp()
541+ self.config = self.add_fixture(ConfigImposter())
542+ self.out = self.add_fixture(OutputImposter())
543+ clear_fake()
544+
545+ def tearDown(self):
546+ clear_fake()
547+
548+ def test_run(self):
549+ config = get_config()
550+ test_name = 'foo'
551+ clear_fake()
552+ testrunner = makerunner(steps_host_pre=["echo foo"])
553+ test = maketest(name=test_name, runner=testrunner)
554+ real_installed_path = '%s/%s/%s' % (test_tmp, config.installdir_android, test_name)
555+ test.setadb(FakeAdb())
556+ self.assertFalse(os.path.exists(real_installed_path))
557+ test.install()
558+ self.assertTrue(os.path.exists(real_installed_path))
559+
560+ fake_adb(output_str=fake_output_str)
561+ result_id = test.run()
562+ self.assertTrue("LAVA: (stdout) foo" in self.out.getvalue())
563+
564+ result_id_pattern = "foo\d+\.\d+"
565+ self.assertTrue(re.match(result_id_pattern, result_id))
566+ self.assertTrue("LAVA: (stdout) foo" in self.out.getvalue())
567+
568+ test.uninstall()
569+
570+ self.assertFalse(os.path.exists(real_installed_path))
571
572=== added file 'tests/test_lavaandroidtest_testinstaller.py'
573--- tests/test_lavaandroidtest_testinstaller.py 1970-01-01 00:00:00 +0000
574+++ tests/test_lavaandroidtest_testinstaller.py 2011-12-15 08:41:23 +0000
575@@ -0,0 +1,58 @@
576+# Copyright (c) 2010, 2011 Linaro
577+#
578+# This program is free software: you can redistribute it and/or modify
579+# it under the terms of the GNU General Public License as published by
580+# the Free Software Foundation, either version 3 of the License, or
581+# (at your option) any later version.
582+#
583+# This program is distributed in the hope that it will be useful,
584+# but WITHOUT ANY WARRANTY; without even the implied warranty of
585+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
586+# GNU General Public License for more details.
587+#
588+# You should have received a copy of the GNU General Public License
589+# along with this program. If not, see <http://www.gnu.org/licenses/>.
590+
591+import hashlib
592+import os
593+import shutil
594+import tempfile
595+import unittest
596+from tests.tests_util import makeinstaller
597+
598+class testTestInstaller(unittest.TestCase):
599+ def setUp(self):
600+ self.origdir = os.path.abspath(os.curdir)
601+ self.tmpdir = tempfile.mkdtemp()
602+ self.filename = os.path.abspath(__file__)
603+ os.chdir(self.tmpdir)
604+
605+ def tearDown(self):
606+ os.chdir(self.origdir)
607+ shutil.rmtree(self.tmpdir)
608+
609+ def test_bad_download(self):
610+ url = "file:///xxxyyyzzz"
611+ installer = makeinstaller(url=url)
612+ self.assertRaises(RuntimeError, installer._download)
613+
614+ def test_bad_md5(self):
615+ url = "file://%s" % self.filename
616+ installer = makeinstaller(url=url, md5='foo')
617+ self.assertRaises(RuntimeError, installer._download)
618+
619+ def test_good_md5(self):
620+ url = "file://%s" % self.filename
621+ md5 = hashlib.md5(file(self.filename).read()).hexdigest()
622+ installer = makeinstaller(url=url, md5=md5)
623+ location = installer._download()
624+ self.assertTrue(os.path.exists(location))
625+
626+ def test_steps_host_pre(self):
627+ self.assertFalse(os.path.exists("./foo"))
628+ steps_host_pre = ["echo test > foo"]
629+ installer = makeinstaller(steps_host_pre=steps_host_pre)
630+ installer.install('./')
631+ self.assertTrue(os.path.exists("./foo"))
632+ self.assertTrue("test" in open("./foo").read())
633+
634
635=== added file 'tests/test_lavaandroidtest_testparser.py'
636--- tests/test_lavaandroidtest_testparser.py 1970-01-01 00:00:00 +0000
637+++ tests/test_lavaandroidtest_testparser.py 2011-12-15 08:41:23 +0000
638@@ -0,0 +1,55 @@
639+# Copyright (c) 2010, 2011 Linaro
640+#
641+# This program is free software: you can redistribute it and/or modify
642+# it under the terms of the GNU General Public License as published by
643+# the Free Software Foundation, either version 3 of the License, or
644+# (at your option) any later version.
645+#
646+# This program is distributed in the hope that it will be useful,
647+# but WITHOUT ANY WARRANTY; without even the implied warranty of
648+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
649+# GNU General Public License for more details.
650+#
651+# You should have received a copy of the GNU General Public License
652+# along with this program. If not, see <http://www.gnu.org/licenses/>.
653+
654+import os
655+
656+from tests.fixtures import TestCaseWithFixtures
657+from tests.tests_util import makeparser
658+
659+class testTestParser(TestCaseWithFixtures):
660+ def setUp(self):
661+ self.test_id = "ABC"
662+
663+ def tearDown(self):
664+ os.unlink('stdout.log')
665+
666+ def writeoutputlog(self, output_str):
667+ with open("stdout.log", "w") as fd:
668+ fd.write(output_str)
669+
670+ def test_parse(self):
671+ pattern = "^(?P<testid>\w+):\W+(?P<result>\w+)"
672+ self.writeoutputlog("test001: pass")
673+ parser = makeparser(pattern)
674+ parser.parse()
675+ self.assertTrue(parser.results["test_results"][0]["testid"] == "test001" and
676+ parser.results["test_results"][0]["result"] == "pass")
677+
678+ def test_fixupdict(self):
679+ pattern = "^(?P<testid>\w+):\W+(?P<result>\w+)"
680+ fixup = {"pass":"PASS"}
681+ self.writeoutputlog("test001: pass")
682+ parser = makeparser(pattern, fixupdict=fixup)
683+ parser.parse()
684+ self.assertEquals("PASS", parser.results["test_results"][0]["result"])
685+
686+ def test_appendall(self):
687+ pattern = "^(?P<testid>\w+):\W+(?P<result>\w+)"
688+ append = {"units":"foo/s"}
689+ self.writeoutputlog("test001: pass")
690+ parser = makeparser(pattern, appendall=append)
691+ parser.parse()
692+ self.assertEqual("foo/s", parser.results["test_results"][0]["units"])
693+
694
695=== added file 'tests/test_lavaandroidtest_testrunner.py'
696--- tests/test_lavaandroidtest_testrunner.py 1970-01-01 00:00:00 +0000
697+++ tests/test_lavaandroidtest_testrunner.py 2011-12-15 08:41:23 +0000
698@@ -0,0 +1,65 @@
699+# Copyright (c) 2010, 2011 Linaro
700+#
701+# This program is free software: you can redistribute it and/or modify
702+# it under the terms of the GNU General Public License as published by
703+# the Free Software Foundation, either version 3 of the License, or
704+# (at your option) any later version.
705+#
706+# This program is distributed in the hope that it will be useful,
707+# but WITHOUT ANY WARRANTY; without even the implied warranty of
708+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
709+# GNU General Public License for more details.
710+#
711+# You should have received a copy of the GNU General Public License
712+# along with this program. If not, see <http://www.gnu.org/licenses/>.
713+
714+import os
715+import shutil
716+import tempfile
717+from datetime import datetime
718+from tests.tests_util import makerunner
719+from tests.imposters import OutputImposter, ConfigImposter
720+from tests.fixtures import TestCaseWithFixtures
721+
722+class testTestRunner(TestCaseWithFixtures):
723+ def setUp(self):
724+ self.config = self.add_fixture(ConfigImposter())
725+ self.out = self.add_fixture(OutputImposter())
726+ self.origdir = os.path.abspath(os.curdir)
727+ self.tmpdir = tempfile.mkdtemp()
728+ self.filename = os.path.abspath(__file__)
729+ os.chdir(self.tmpdir)
730+ self.test_id = "ABC"
731+
732+ def tearDown(self):
733+ os.chdir(self.origdir)
734+ shutil.rmtree(self.tmpdir)
735+
736+ def test_starttime(self):
737+ runner = makerunner()
738+ runner.run('./')
739+ self.assertTrue(isinstance(runner.starttime, datetime))
740+
741+ def test_endtime(self):
742+ runner = makerunner()
743+ runner.run('./')
744+ self.assertTrue(isinstance(runner.endtime, datetime))
745+
746+ def test_timediff(self):
747+ steps = ['sleep 2']
748+ runner = makerunner(steps_host_pre=steps)
749+ runner.run('./')
750+ self.assertNotEqual(runner.starttime, runner.endtime)
751+
752+ def test_runsteps(self):
753+ steps = ["echo test > foo"]
754+ runner = makerunner(steps_host_pre=steps)
755+ runner.run('./')
756+ self.assertTrue(os.path.exists("./foo"))
757+
758+ def test_logoutput(self):
759+ steps = ["echo test"]
760+ runner = makerunner(steps_host_pre=steps)
761+ runner.run('./')
762+ self.assertTrue('test' in self.out.getvalue())
763+
764
765=== added file 'tests/test_swprofile.py'
766--- tests/test_swprofile.py 1970-01-01 00:00:00 +0000
767+++ tests/test_swprofile.py 2011-12-15 08:41:23 +0000
768@@ -0,0 +1,87 @@
769+# Copyright (c) 2011 Linaro
770+#
771+# This program is free software: you can redistribute it and/or modify
772+# it under the terms of the GNU General Public License as published by
773+# the Free Software Foundation, either version 3 of the License, or
774+# (at your option) any later version.
775+#
776+# This program is distributed in the hope that it will be useful,
777+# but WITHOUT ANY WARRANTY; without even the implied warranty of
778+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
779+# GNU General Public License for more details.
780+#
781+# You should have received a copy of the GNU General Public License
782+# along with this program. If not, see <http://www.gnu.org/licenses/>.
783+
784+import unittest
785+
786+import lava_android_test.swprofile
787+from tests.tests_util import fake_adb, clear_fake
788+
789+package_list_info = '''android:4.0.1.2.3.4.5.6.7.8.9-3 (#14)
790+com.android.musicvis:4.0.1.2.3.4.5.6.7.8.9-3 (#14)
791+com.android.videoeditor:1.1 (#11)
792+com.android.vpndialogs:4.0.1.2.3.4.5.6.7.8.9-3 (#14)
793+com.android.wallpaper:4.0.1.2.3.4.5.6.7.8.9-3 (#14)
794+com.android.wallpaper.livepicker:4.0.1.2.3.4.5.6.7.8.9-3 (#14)
795+com.svox.pico:1.0 (#1)'''
796+
797+getprop_info = '''[dalvik.vm.heapsize]: [24m]
798+[dalvik.vm.stack-trace-file]: [/data/anr/traces.txt]
799+[dev.bootcomplete]: [1]
800+[gsm.current.phone-type]: [1]
801+[ro.build.date]: [Wed Oct 12 12:35:47 PDT 2011]
802+[ro.build.description]: [sdk-eng 4.0.1 ICS_MR0 202595 test-keys]
803+[ro.build.display.id]: [sdk-eng 4.0.1 ICS_MR0 202595 test-keys]
804+[ro.build.host]: [android-test-37.mtv.corp.google.com]
805+[ro.build.id]: [ICS_MR0]
806+[ro.build.product]: [generic]
807+[ro.build.tags]: [test-keys]
808+[ro.build.type]: [eng]
809+[ro.build.version.sdk]: [14]'''
810+
811+class SwprofileTests(unittest.TestCase):
812+ maxDiff = None
813+
814+ def test_getimage_name_from_properties(self):
815+ fake_adb(output_str=getprop_info)
816+ image_name = lava_android_test.swprofile.get_image_name_from_properties()
817+ clear_fake()
818+ self.assertEqual('sdk-eng 4.0.1 ICS_MR0 202595 test-keys', image_name)
819+
820+ def test_get_properties(self):
821+ fake_adb(output_str=getprop_info)
822+ result = lava_android_test.swprofile.get_properties()
823+ clear_fake()
824+ properties = {'dalvik.vm.heapsize': '24m',
825+ 'dalvik.vm.stack-trace-file': '/data/anr/traces.txt',
826+ 'dev.bootcomplete': '1',
827+ 'gsm.current.phone-type': '1',
828+ 'ro.build.date': 'Wed Oct 12 12:35:47 PDT 2011',
829+ 'ro.build.description': 'sdk-eng 4.0.1 ICS_MR0 202595 test-keys',
830+ 'ro.build.display.id': 'sdk-eng 4.0.1 ICS_MR0 202595 test-keys',
831+ 'ro.build.host': 'android-test-37.mtv.corp.google.com',
832+ 'ro.build.id': 'ICS_MR0',
833+ 'ro.build.product': 'generic',
834+ 'ro.build.tags': 'test-keys',
835+ 'ro.build.type': 'eng',
836+ 'ro.build.version.sdk': '14'}
837+ self.assertEqual(properties, result)
838+
839+ def test_get_package_info(self):
840+ fake_adb(output_str=package_list_info)
841+ result = lava_android_test.swprofile.get_package_info()
842+ clear_fake()
843+ packages = {'android':'4.0.1.2.3.4.5.6.7.8.9-3 (#14)',
844+ 'com.android.musicvis':'4.0.1.2.3.4.5.6.7.8.9-3 (#14)',
845+ 'com.android.videoeditor':'1.1 (#11)',
846+ 'com.android.vpndialogs':'4.0.1.2.3.4.5.6.7.8.9-3 (#14)',
847+ 'com.android.wallpaper':'4.0.1.2.3.4.5.6.7.8.9-3 (#14)',
848+ 'com.android.wallpaper.livepicker':'4.0.1.2.3.4.5.6.7.8.9-3 (#14)',
849+ 'com.svox.pico':'1.0 (#1)'}
850+ result_hash = {}
851+ for package in result:
852+ result_hash[package.get('name')] = package.get('version')
853+
854+ self.assertEqual(packages, result_hash)
855+
856
857=== added file 'tests/tests_util.py'
858--- tests/tests_util.py 1970-01-01 00:00:00 +0000
859+++ tests/tests_util.py 2011-12-15 08:41:23 +0000
860@@ -0,0 +1,76 @@
861+#!/usr/bin/env python
862+#
863+# Copyright (c) 2011 Linaro
864+#
865+# This program is free software: you can redistribute it and/or modify
866+# it under the terms of the GNU General Public License as published by
867+# the Free Software Foundation, either version 3 of the License, or
868+# (at your option) any later version.
869+#
870+# This program is distributed in the hope that it will be useful,
871+# but WITHOUT ANY WARRANTY; without even the implied warranty of
872+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
873+# GNU General Public License for more details.
874+#
875+# You should have received a copy of the GNU General Public License
876+# along with this program. If not, see <http://www.gnu.org/licenses/>.
877+import os
878+import stat
879+import subprocess
880+from lava_android_test.testdef import AndroidTest, AndroidTestInstaller, AndroidTestRunner, AndroidTestParser
881+
882+def maketest(name="foo", version="", installer=None, runner=None, parser=None):
883+ if installer is None:
884+ installer = makeinstaller()
885+ return AndroidTest(name, version, installer, runner, parser)
886+
887+def makerunner(**kwargs):
888+ return AndroidTestRunner(**kwargs)
889+
890+def makeinstaller(**kwargs):
891+ return AndroidTestInstaller(**kwargs)
892+
893+def makeparser(*args, **kwargs):
894+ return AndroidTestParser(*args, **kwargs)
895+
896+test_tmp = '/tmp/lava-android-test-tmp'
897+def fake_adb(output_str='', target_path=test_tmp, ret_code=0):
898+ if not os.path.exists(target_path):
899+ os.makedirs(target_path)
900+ fake_adb_path = os.path.join(target_path, 'adb')
901+ adb_file = open(fake_adb_path, 'w')
902+ adb_file.write('#!/bin/bash\n')
903+ adb_file.write('if [ "$2" == "chmod" ]; then\n')
904+ adb_file.write('\texit 0\n')
905+ adb_file.write('fi\n')
906+ if output_str is None or output_str == '':
907+ pass
908+ else:
909+ adb_file.write('echo \'\n')
910+ adb_file.write(output_str)
911+ adb_file.write('\'\n')
912+ adb_file.write('exit %s\n' % ret_code)
913+ adb_file.close()
914+ os.chmod(fake_adb_path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
915+ os.chmod(target_path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
916+ os.environ['PATH'] = target_path + ':' + os.environ['PATH']
917+
918+def clear_fake(target_path=test_tmp):
919+ if not os.path.exists(target_path):
920+ return
921+ if os.path.isdir(target_path):
922+ for sub_path in os.listdir(target_path):
923+ clear_fake(os.path.join(target_path, sub_path))
924+ os.rmdir(target_path)
925+ else:
926+ os.unlink(target_path)
927+
928+def main():
929+ fake_adb('hello, \ntest');
930+ cmd = 'adb shell ls'
931+ p = subprocess.Popen(cmd, shell=True)
932+ p.wait()
933+ clear_fake()
934+
935+if __name__ == '__main__':
936+ main()

Subscribers

People subscribed via source and target branches