2 # Copyright 2014 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
7 Unit tests for the contents of device_utils.py (mostly DeviceUtils).
10 # pylint: disable=C0321
11 # pylint: disable=W0212
12 # pylint: disable=W0613
22 from pylib
import android_commands
23 from pylib
import cmd_helper
24 from pylib
import constants
25 from pylib
import device_signal
26 from pylib
.device
import adb_wrapper
27 from pylib
.device
import device_errors
28 from pylib
.device
import device_utils
29 from pylib
.device
import intent
30 from pylib
.sdk
import split_select
31 from pylib
.utils
import mock_calls
33 # RunCommand from third_party/android_testrunner/run_command.py is mocked
34 # below, so its path needs to be in sys.path.
35 sys
.path
.append(os
.path
.join(
36 constants
.DIR_SOURCE_ROOT
, 'third_party', 'android_testrunner'))
38 sys
.path
.append(os
.path
.join(
39 constants
.DIR_SOURCE_ROOT
, 'third_party', 'pymock'))
40 import mock
# pylint: disable=F0401
43 class DeviceUtilsInitTest(unittest
.TestCase
):
45 def testInitWithStr(self
):
46 serial_as_str
= str('0123456789abcdef')
47 d
= device_utils
.DeviceUtils('0123456789abcdef')
48 self
.assertEqual(serial_as_str
, d
.adb
.GetDeviceSerial())
50 def testInitWithUnicode(self
):
51 serial_as_unicode
= unicode('fedcba9876543210')
52 d
= device_utils
.DeviceUtils(serial_as_unicode
)
53 self
.assertEqual(serial_as_unicode
, d
.adb
.GetDeviceSerial())
55 def testInitWithAdbWrapper(self
):
56 serial
= '123456789abcdef0'
57 a
= adb_wrapper
.AdbWrapper(serial
)
58 d
= device_utils
.DeviceUtils(a
)
59 self
.assertEqual(serial
, d
.adb
.GetDeviceSerial())
61 def testInitWithAndroidCommands(self
):
62 serial
= '0fedcba987654321'
63 a
= android_commands
.AndroidCommands(device
=serial
)
64 d
= device_utils
.DeviceUtils(a
)
65 self
.assertEqual(serial
, d
.adb
.GetDeviceSerial())
67 def testInitWithMissing_fails(self
):
68 with self
.assertRaises(ValueError):
69 device_utils
.DeviceUtils(None)
70 with self
.assertRaises(ValueError):
71 device_utils
.DeviceUtils('')
74 class DeviceUtilsGetAVDsTest(mock_calls
.TestCase
):
76 def testGetAVDs(self
):
78 mock
.call
.pylib
.cmd_helper
.GetCmdOutput([mock
.ANY
, 'list', 'avd']),
79 'Available Android Virtual Devices:\n'
80 ' Name: my_android5.0\n'
81 ' Path: /some/path/to/.android/avd/my_android5.0.avd\n'
82 ' Target: Android 5.0 (API level 21)\n'
83 ' Tag/ABI: default/x86\n'
85 self
.assertEquals(['my_android5.0'],
86 device_utils
.GetAVDs())
89 class DeviceUtilsRestartServerTest(mock_calls
.TestCase
):
91 @mock.patch('time.sleep', mock
.Mock())
92 def testRestartServer_succeeds(self
):
93 with self
.assertCalls(
94 mock
.call
.pylib
.device
.adb_wrapper
.AdbWrapper
.KillServer(),
95 (mock
.call
.pylib
.cmd_helper
.GetCmdStatusAndOutput(['pgrep', 'adb']),
97 mock
.call
.pylib
.device
.adb_wrapper
.AdbWrapper
.StartServer(),
98 (mock
.call
.pylib
.cmd_helper
.GetCmdStatusAndOutput(['pgrep', 'adb']),
100 (mock
.call
.pylib
.cmd_helper
.GetCmdStatusAndOutput(['pgrep', 'adb']),
102 device_utils
.RestartServer()
105 class MockTempFile(object):
107 def __init__(self
, name
='/tmp/some/file'):
108 self
.file = mock
.MagicMock(spec
=file)
109 self
.file.name
= name
110 self
.file.name_quoted
= cmd_helper
.SingleQuote(name
)
115 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
120 return self
.file.name
123 class _PatchedFunction(object):
124 def __init__(self
, patched
=None, mocked
=None):
125 self
.patched
= patched
129 def _AdbWrapperMock(test_serial
):
130 adb
= mock
.Mock(spec
=adb_wrapper
.AdbWrapper
)
131 adb
.__str
__ = mock
.Mock(return_value
=test_serial
)
132 adb
.GetDeviceSerial
.return_value
= test_serial
136 class DeviceUtilsTest(mock_calls
.TestCase
):
139 self
.adb
= _AdbWrapperMock('0123456789abcdef')
140 self
.device
= device_utils
.DeviceUtils(
141 self
.adb
, default_timeout
=10, default_retries
=0)
142 self
.watchMethodCalls(self
.call
.adb
, ignore
=['GetDeviceSerial'])
144 def AdbCommandError(self
, args
=None, output
=None, status
=None, msg
=None):
146 args
= ['[unspecified]']
147 return mock
.Mock(side_effect
=device_errors
.AdbCommandFailedError(
148 args
, output
, status
, msg
, str(self
.device
)))
150 def CommandError(self
, msg
=None):
152 msg
= 'Command failed'
153 return mock
.Mock(side_effect
=device_errors
.CommandFailedError(
154 msg
, str(self
.device
)))
156 def ShellError(self
, output
=None, status
=1):
157 def action(cmd
, *args
, **kwargs
):
158 raise device_errors
.AdbShellCommandFailedError(
159 cmd
, output
, status
, str(self
.device
))
161 output
= 'Permission denied\n'
164 def TimeoutError(self
, msg
=None):
166 msg
= 'Operation timed out'
167 return mock
.Mock(side_effect
=device_errors
.CommandTimeoutError(
168 msg
, str(self
.device
)))
171 class DeviceUtilsEqTest(DeviceUtilsTest
):
173 def testEq_equal_deviceUtils(self
):
174 other
= device_utils
.DeviceUtils(_AdbWrapperMock('0123456789abcdef'))
175 self
.assertTrue(self
.device
== other
)
176 self
.assertTrue(other
== self
.device
)
178 def testEq_equal_adbWrapper(self
):
179 other
= adb_wrapper
.AdbWrapper('0123456789abcdef')
180 self
.assertTrue(self
.device
== other
)
181 self
.assertTrue(other
== self
.device
)
183 def testEq_equal_string(self
):
184 other
= '0123456789abcdef'
185 self
.assertTrue(self
.device
== other
)
186 self
.assertTrue(other
== self
.device
)
188 def testEq_devicesNotEqual(self
):
189 other
= device_utils
.DeviceUtils(_AdbWrapperMock('0123456789abcdee'))
190 self
.assertFalse(self
.device
== other
)
191 self
.assertFalse(other
== self
.device
)
193 def testEq_identity(self
):
194 self
.assertTrue(self
.device
== self
.device
)
196 def testEq_serialInList(self
):
197 devices
= [self
.device
]
198 self
.assertTrue('0123456789abcdef' in devices
)
201 class DeviceUtilsLtTest(DeviceUtilsTest
):
203 def testLt_lessThan(self
):
204 other
= device_utils
.DeviceUtils(_AdbWrapperMock('ffffffffffffffff'))
205 self
.assertTrue(self
.device
< other
)
206 self
.assertTrue(other
> self
.device
)
208 def testLt_greaterThan_lhs(self
):
209 other
= device_utils
.DeviceUtils(_AdbWrapperMock('0000000000000000'))
210 self
.assertFalse(self
.device
< other
)
211 self
.assertFalse(other
> self
.device
)
213 def testLt_equal(self
):
214 other
= device_utils
.DeviceUtils(_AdbWrapperMock('0123456789abcdef'))
215 self
.assertFalse(self
.device
< other
)
216 self
.assertFalse(other
> self
.device
)
218 def testLt_sorted(self
):
220 device_utils
.DeviceUtils(_AdbWrapperMock('ffffffffffffffff')),
221 device_utils
.DeviceUtils(_AdbWrapperMock('0000000000000000')),
223 sorted_devices
= sorted(devices
)
224 self
.assertEquals('0000000000000000',
225 sorted_devices
[0].adb
.GetDeviceSerial())
226 self
.assertEquals('ffffffffffffffff',
227 sorted_devices
[1].adb
.GetDeviceSerial())
230 class DeviceUtilsStrTest(DeviceUtilsTest
):
232 def testStr_returnsSerial(self
):
233 with self
.assertCalls(
234 (self
.call
.adb
.GetDeviceSerial(), '0123456789abcdef')):
235 self
.assertEqual('0123456789abcdef', str(self
.device
))
238 class DeviceUtilsIsOnlineTest(DeviceUtilsTest
):
240 def testIsOnline_true(self
):
241 with self
.assertCall(self
.call
.adb
.GetState(), 'device'):
242 self
.assertTrue(self
.device
.IsOnline())
244 def testIsOnline_false(self
):
245 with self
.assertCall(self
.call
.adb
.GetState(), 'offline'):
246 self
.assertFalse(self
.device
.IsOnline())
248 def testIsOnline_error(self
):
249 with self
.assertCall(self
.call
.adb
.GetState(), self
.CommandError()):
250 self
.assertFalse(self
.device
.IsOnline())
253 class DeviceUtilsHasRootTest(DeviceUtilsTest
):
255 def testHasRoot_true(self
):
256 with self
.assertCall(self
.call
.adb
.Shell('ls /root'), 'foo\n'):
257 self
.assertTrue(self
.device
.HasRoot())
259 def testHasRoot_false(self
):
260 with self
.assertCall(self
.call
.adb
.Shell('ls /root'), self
.ShellError()):
261 self
.assertFalse(self
.device
.HasRoot())
264 class DeviceUtilsEnableRootTest(DeviceUtilsTest
):
266 def testEnableRoot_succeeds(self
):
267 with self
.assertCalls(
268 (self
.call
.device
.IsUserBuild(), False),
269 self
.call
.adb
.Root(),
270 self
.call
.device
.WaitUntilFullyBooted()):
271 self
.device
.EnableRoot()
273 def testEnableRoot_userBuild(self
):
274 with self
.assertCalls(
275 (self
.call
.device
.IsUserBuild(), True)):
276 with self
.assertRaises(device_errors
.CommandFailedError
):
277 self
.device
.EnableRoot()
279 def testEnableRoot_rootFails(self
):
280 with self
.assertCalls(
281 (self
.call
.device
.IsUserBuild(), False),
282 (self
.call
.adb
.Root(), self
.CommandError())):
283 with self
.assertRaises(device_errors
.CommandFailedError
):
284 self
.device
.EnableRoot()
287 class DeviceUtilsIsUserBuildTest(DeviceUtilsTest
):
289 def testIsUserBuild_yes(self
):
290 with self
.assertCall(
291 self
.call
.device
.GetProp('ro.build.type', cache
=True), 'user'):
292 self
.assertTrue(self
.device
.IsUserBuild())
294 def testIsUserBuild_no(self
):
295 with self
.assertCall(
296 self
.call
.device
.GetProp('ro.build.type', cache
=True), 'userdebug'):
297 self
.assertFalse(self
.device
.IsUserBuild())
300 class DeviceUtilsGetExternalStoragePathTest(DeviceUtilsTest
):
302 def testGetExternalStoragePath_succeeds(self
):
303 with self
.assertCall(
304 self
.call
.adb
.Shell('echo $EXTERNAL_STORAGE'), '/fake/storage/path\n'):
305 self
.assertEquals('/fake/storage/path',
306 self
.device
.GetExternalStoragePath())
308 def testGetExternalStoragePath_fails(self
):
309 with self
.assertCall(self
.call
.adb
.Shell('echo $EXTERNAL_STORAGE'), '\n'):
310 with self
.assertRaises(device_errors
.CommandFailedError
):
311 self
.device
.GetExternalStoragePath()
314 class DeviceUtilsGetApplicationPathsTest(DeviceUtilsTest
):
316 def testGetApplicationPaths_exists(self
):
317 with self
.assertCalls(
318 (self
.call
.adb
.Shell('getprop ro.build.version.sdk'), '19\n'),
319 (self
.call
.adb
.Shell('pm path android'),
320 'package:/path/to/android.apk\n')):
321 self
.assertEquals(['/path/to/android.apk'],
322 self
.device
.GetApplicationPaths('android'))
324 def testGetApplicationPaths_notExists(self
):
325 with self
.assertCalls(
326 (self
.call
.adb
.Shell('getprop ro.build.version.sdk'), '19\n'),
327 (self
.call
.adb
.Shell('pm path not.installed.app'), '')):
328 self
.assertEquals([],
329 self
.device
.GetApplicationPaths('not.installed.app'))
331 def testGetApplicationPaths_fails(self
):
332 with self
.assertCalls(
333 (self
.call
.adb
.Shell('getprop ro.build.version.sdk'), '19\n'),
334 (self
.call
.adb
.Shell('pm path android'),
335 self
.CommandError('ERROR. Is package manager running?\n'))):
336 with self
.assertRaises(device_errors
.CommandFailedError
):
337 self
.device
.GetApplicationPaths('android')
340 class DeviceUtilsGetApplicationDataDirectoryTest(DeviceUtilsTest
):
342 def testGetApplicationDataDirectory_exists(self
):
343 with self
.assertCall(
344 self
.call
.device
._RunPipedShellCommand
(
345 'pm dump foo.bar.baz | grep dataDir='),
346 ['dataDir=/data/data/foo.bar.baz']):
348 '/data/data/foo.bar.baz',
349 self
.device
.GetApplicationDataDirectory('foo.bar.baz'))
351 def testGetApplicationDataDirectory_notExists(self
):
352 with self
.assertCall(
353 self
.call
.device
._RunPipedShellCommand
(
354 'pm dump foo.bar.baz | grep dataDir='),
356 self
.assertIsNone(self
.device
.GetApplicationDataDirectory('foo.bar.baz'))
359 @mock.patch('time.sleep', mock
.Mock())
360 class DeviceUtilsWaitUntilFullyBootedTest(DeviceUtilsTest
):
362 def testWaitUntilFullyBooted_succeedsNoWifi(self
):
363 with self
.assertCalls(
364 self
.call
.adb
.WaitForDevice(),
366 (self
.call
.device
.GetExternalStoragePath(), '/fake/storage/path'),
367 (self
.call
.adb
.Shell('test -d /fake/storage/path'), ''),
369 (self
.call
.device
.GetApplicationPaths('android'),
370 ['package:/some/fake/path']),
372 (self
.call
.device
.GetProp('sys.boot_completed'), '1')):
373 self
.device
.WaitUntilFullyBooted(wifi
=False)
375 def testWaitUntilFullyBooted_succeedsWithWifi(self
):
376 with self
.assertCalls(
377 self
.call
.adb
.WaitForDevice(),
379 (self
.call
.device
.GetExternalStoragePath(), '/fake/storage/path'),
380 (self
.call
.adb
.Shell('test -d /fake/storage/path'), ''),
382 (self
.call
.device
.GetApplicationPaths('android'),
383 ['package:/some/fake/path']),
385 (self
.call
.device
.GetProp('sys.boot_completed'), '1'),
387 (self
.call
.adb
.Shell('dumpsys wifi'),
388 'stuff\nWi-Fi is enabled\nmore stuff\n')):
389 self
.device
.WaitUntilFullyBooted(wifi
=True)
391 def testWaitUntilFullyBooted_deviceNotInitiallyAvailable(self
):
392 with self
.assertCalls(
393 self
.call
.adb
.WaitForDevice(),
395 (self
.call
.device
.GetExternalStoragePath(), self
.AdbCommandError()),
397 (self
.call
.device
.GetExternalStoragePath(), self
.AdbCommandError()),
399 (self
.call
.device
.GetExternalStoragePath(), self
.AdbCommandError()),
401 (self
.call
.device
.GetExternalStoragePath(), self
.AdbCommandError()),
403 (self
.call
.device
.GetExternalStoragePath(), '/fake/storage/path'),
404 (self
.call
.adb
.Shell('test -d /fake/storage/path'), ''),
406 (self
.call
.device
.GetApplicationPaths('android'),
407 ['package:/some/fake/path']),
409 (self
.call
.device
.GetProp('sys.boot_completed'), '1')):
410 self
.device
.WaitUntilFullyBooted(wifi
=False)
412 def testWaitUntilFullyBooted_sdCardReadyFails_noPath(self
):
413 with self
.assertCalls(
414 self
.call
.adb
.WaitForDevice(),
416 (self
.call
.device
.GetExternalStoragePath(), self
.CommandError())):
417 with self
.assertRaises(device_errors
.CommandFailedError
):
418 self
.device
.WaitUntilFullyBooted(wifi
=False)
420 def testWaitUntilFullyBooted_sdCardReadyFails_notExists(self
):
421 with self
.assertCalls(
422 self
.call
.adb
.WaitForDevice(),
424 (self
.call
.device
.GetExternalStoragePath(), '/fake/storage/path'),
425 (self
.call
.adb
.Shell('test -d /fake/storage/path'), self
.ShellError()),
427 (self
.call
.device
.GetExternalStoragePath(), '/fake/storage/path'),
428 (self
.call
.adb
.Shell('test -d /fake/storage/path'), self
.ShellError()),
430 (self
.call
.device
.GetExternalStoragePath(), '/fake/storage/path'),
431 (self
.call
.adb
.Shell('test -d /fake/storage/path'),
432 self
.TimeoutError())):
433 with self
.assertRaises(device_errors
.CommandTimeoutError
):
434 self
.device
.WaitUntilFullyBooted(wifi
=False)
436 def testWaitUntilFullyBooted_devicePmFails(self
):
437 with self
.assertCalls(
438 self
.call
.adb
.WaitForDevice(),
440 (self
.call
.device
.GetExternalStoragePath(), '/fake/storage/path'),
441 (self
.call
.adb
.Shell('test -d /fake/storage/path'), ''),
443 (self
.call
.device
.GetApplicationPaths('android'), self
.CommandError()),
445 (self
.call
.device
.GetApplicationPaths('android'), self
.CommandError()),
447 (self
.call
.device
.GetApplicationPaths('android'), self
.TimeoutError())):
448 with self
.assertRaises(device_errors
.CommandTimeoutError
):
449 self
.device
.WaitUntilFullyBooted(wifi
=False)
451 def testWaitUntilFullyBooted_bootFails(self
):
452 with self
.assertCalls(
453 self
.call
.adb
.WaitForDevice(),
455 (self
.call
.device
.GetExternalStoragePath(), '/fake/storage/path'),
456 (self
.call
.adb
.Shell('test -d /fake/storage/path'), ''),
458 (self
.call
.device
.GetApplicationPaths('android'),
459 ['package:/some/fake/path']),
461 (self
.call
.device
.GetProp('sys.boot_completed'), '0'),
463 (self
.call
.device
.GetProp('sys.boot_completed'), '0'),
465 (self
.call
.device
.GetProp('sys.boot_completed'), self
.TimeoutError())):
466 with self
.assertRaises(device_errors
.CommandTimeoutError
):
467 self
.device
.WaitUntilFullyBooted(wifi
=False)
469 def testWaitUntilFullyBooted_wifiFails(self
):
470 with self
.assertCalls(
471 self
.call
.adb
.WaitForDevice(),
473 (self
.call
.device
.GetExternalStoragePath(), '/fake/storage/path'),
474 (self
.call
.adb
.Shell('test -d /fake/storage/path'), ''),
476 (self
.call
.device
.GetApplicationPaths('android'),
477 ['package:/some/fake/path']),
479 (self
.call
.device
.GetProp('sys.boot_completed'), '1'),
481 (self
.call
.adb
.Shell('dumpsys wifi'), 'stuff\nmore stuff\n'),
483 (self
.call
.adb
.Shell('dumpsys wifi'), 'stuff\nmore stuff\n'),
485 (self
.call
.adb
.Shell('dumpsys wifi'), self
.TimeoutError())):
486 with self
.assertRaises(device_errors
.CommandTimeoutError
):
487 self
.device
.WaitUntilFullyBooted(wifi
=True)
490 @mock.patch('time.sleep', mock
.Mock())
491 class DeviceUtilsRebootTest(DeviceUtilsTest
):
493 def testReboot_nonBlocking(self
):
494 with self
.assertCalls(
495 self
.call
.adb
.Reboot(),
496 (self
.call
.device
.IsOnline(), True),
497 (self
.call
.device
.IsOnline(), False)):
498 self
.device
.Reboot(block
=False)
500 def testReboot_blocking(self
):
501 with self
.assertCalls(
502 self
.call
.adb
.Reboot(),
503 (self
.call
.device
.IsOnline(), True),
504 (self
.call
.device
.IsOnline(), False),
505 self
.call
.device
.WaitUntilFullyBooted(wifi
=False)):
506 self
.device
.Reboot(block
=True)
508 def testReboot_blockUntilWifi(self
):
509 with self
.assertCalls(
510 self
.call
.adb
.Reboot(),
511 (self
.call
.device
.IsOnline(), True),
512 (self
.call
.device
.IsOnline(), False),
513 self
.call
.device
.WaitUntilFullyBooted(wifi
=True)):
514 self
.device
.Reboot(block
=True, wifi
=True)
517 class DeviceUtilsInstallTest(DeviceUtilsTest
):
519 def testInstall_noPriorInstall(self
):
520 with self
.assertCalls(
521 (mock
.call
.pylib
.utils
.apk_helper
.GetPackageName('/fake/test/app.apk'),
522 'this.is.a.test.package'),
523 (self
.call
.device
.GetApplicationPaths('this.is.a.test.package'), []),
524 self
.call
.adb
.Install('/fake/test/app.apk', reinstall
=False)):
525 self
.device
.Install('/fake/test/app.apk', retries
=0)
527 def testInstall_differentPriorInstall(self
):
528 with self
.assertCalls(
529 (mock
.call
.pylib
.utils
.apk_helper
.GetPackageName('/fake/test/app.apk'),
530 'this.is.a.test.package'),
531 (self
.call
.device
.GetApplicationPaths('this.is.a.test.package'),
532 ['/fake/data/app/this.is.a.test.package.apk']),
533 (self
.call
.device
._GetChangedAndStaleFiles
(
534 '/fake/test/app.apk', '/fake/data/app/this.is.a.test.package.apk'),
535 ([('/fake/test/app.apk', '/fake/data/app/this.is.a.test.package.apk')],
537 self
.call
.adb
.Uninstall('this.is.a.test.package'),
538 self
.call
.adb
.Install('/fake/test/app.apk', reinstall
=False)):
539 self
.device
.Install('/fake/test/app.apk', retries
=0)
541 def testInstall_differentPriorInstall_reinstall(self
):
542 with self
.assertCalls(
543 (mock
.call
.pylib
.utils
.apk_helper
.GetPackageName('/fake/test/app.apk'),
544 'this.is.a.test.package'),
545 (self
.call
.device
.GetApplicationPaths('this.is.a.test.package'),
546 ['/fake/data/app/this.is.a.test.package.apk']),
547 (self
.call
.device
._GetChangedAndStaleFiles
(
548 '/fake/test/app.apk', '/fake/data/app/this.is.a.test.package.apk'),
549 ([('/fake/test/app.apk', '/fake/data/app/this.is.a.test.package.apk')],
551 self
.call
.adb
.Install('/fake/test/app.apk', reinstall
=True)):
552 self
.device
.Install('/fake/test/app.apk', reinstall
=True, retries
=0)
554 def testInstall_identicalPriorInstall(self
):
555 with self
.assertCalls(
556 (mock
.call
.pylib
.utils
.apk_helper
.GetPackageName('/fake/test/app.apk'),
557 'this.is.a.test.package'),
558 (self
.call
.device
.GetApplicationPaths('this.is.a.test.package'),
559 ['/fake/data/app/this.is.a.test.package.apk']),
560 (self
.call
.device
._GetChangedAndStaleFiles
(
561 '/fake/test/app.apk', '/fake/data/app/this.is.a.test.package.apk'),
563 self
.device
.Install('/fake/test/app.apk', retries
=0)
565 def testInstall_fails(self
):
566 with self
.assertCalls(
567 (mock
.call
.pylib
.utils
.apk_helper
.GetPackageName('/fake/test/app.apk'),
568 'this.is.a.test.package'),
569 (self
.call
.device
.GetApplicationPaths('this.is.a.test.package'), []),
570 (self
.call
.adb
.Install('/fake/test/app.apk', reinstall
=False),
571 self
.CommandError('Failure\r\n'))):
572 with self
.assertRaises(device_errors
.CommandFailedError
):
573 self
.device
.Install('/fake/test/app.apk', retries
=0)
575 class DeviceUtilsInstallSplitApkTest(DeviceUtilsTest
):
577 def testInstallSplitApk_noPriorInstall(self
):
578 with self
.assertCalls(
579 (self
.call
.device
._CheckSdkLevel
(21)),
580 (mock
.call
.pylib
.sdk
.split_select
.SelectSplits(
581 self
.device
, 'base.apk',
582 ['split1.apk', 'split2.apk', 'split3.apk']),
584 (mock
.call
.pylib
.utils
.apk_helper
.GetPackageName('base.apk'),
585 'this.is.a.test.package'),
586 (self
.call
.device
.GetApplicationPaths('this.is.a.test.package'), []),
587 (self
.call
.adb
.InstallMultiple(
588 ['base.apk', 'split2.apk'], partial
=None, reinstall
=False))):
589 self
.device
.InstallSplitApk('base.apk',
590 ['split1.apk', 'split2.apk', 'split3.apk'], retries
=0)
592 def testInstallSplitApk_partialInstall(self
):
593 with self
.assertCalls(
594 (self
.call
.device
._CheckSdkLevel
(21)),
595 (mock
.call
.pylib
.sdk
.split_select
.SelectSplits(
596 self
.device
, 'base.apk',
597 ['split1.apk', 'split2.apk', 'split3.apk']),
599 (mock
.call
.pylib
.utils
.apk_helper
.GetPackageName('base.apk'),
601 (self
.call
.device
.GetApplicationPaths('test.package'),
602 ['base-on-device.apk', 'split2-on-device.apk']),
603 (mock
.call
.pylib
.utils
.md5sum
.CalculateDeviceMd5Sums(
604 ['base-on-device.apk', 'split2-on-device.apk'], self
.device
),
605 {'base-on-device.apk': 'AAA', 'split2-on-device.apk': 'BBB'}),
606 (mock
.call
.pylib
.utils
.md5sum
.CalculateHostMd5Sums(
607 ['base.apk', 'split2.apk']),
608 {'base.apk': 'AAA', 'split2.apk': 'CCC'}),
609 (self
.call
.adb
.InstallMultiple(
610 ['split2.apk'], partial
='test.package', reinstall
=True))):
611 self
.device
.InstallSplitApk('base.apk',
612 ['split1.apk', 'split2.apk', 'split3.apk'], reinstall
=True, retries
=0)
615 class DeviceUtilsRunShellCommandTest(DeviceUtilsTest
):
618 super(DeviceUtilsRunShellCommandTest
, self
).setUp()
619 self
.device
.NeedsSU
= mock
.Mock(return_value
=False)
621 def testRunShellCommand_commandAsList(self
):
622 with self
.assertCall(self
.call
.adb
.Shell('pm list packages'), ''):
623 self
.device
.RunShellCommand(['pm', 'list', 'packages'])
625 def testRunShellCommand_commandAsListQuoted(self
):
626 with self
.assertCall(self
.call
.adb
.Shell("echo 'hello world' '$10'"), ''):
627 self
.device
.RunShellCommand(['echo', 'hello world', '$10'])
629 def testRunShellCommand_commandAsString(self
):
630 with self
.assertCall(self
.call
.adb
.Shell('echo "$VAR"'), ''):
631 self
.device
.RunShellCommand('echo "$VAR"')
633 def testNewRunShellImpl_withEnv(self
):
634 with self
.assertCall(
635 self
.call
.adb
.Shell('VAR=some_string echo "$VAR"'), ''):
636 self
.device
.RunShellCommand('echo "$VAR"', env
={'VAR': 'some_string'})
638 def testNewRunShellImpl_withEnvQuoted(self
):
639 with self
.assertCall(
640 self
.call
.adb
.Shell('PATH="$PATH:/other/path" run_this'), ''):
641 self
.device
.RunShellCommand('run_this', env
={'PATH': '$PATH:/other/path'})
643 def testNewRunShellImpl_withEnv_failure(self
):
644 with self
.assertRaises(KeyError):
645 self
.device
.RunShellCommand('some_cmd', env
={'INVALID NAME': 'value'})
647 def testNewRunShellImpl_withCwd(self
):
648 with self
.assertCall(self
.call
.adb
.Shell('cd /some/test/path && ls'), ''):
649 self
.device
.RunShellCommand('ls', cwd
='/some/test/path')
651 def testNewRunShellImpl_withCwdQuoted(self
):
652 with self
.assertCall(
653 self
.call
.adb
.Shell("cd '/some test/path with/spaces' && ls"), ''):
654 self
.device
.RunShellCommand('ls', cwd
='/some test/path with/spaces')
656 def testRunShellCommand_withHugeCmd(self
):
657 payload
= 'hi! ' * 1024
658 expected_cmd
= "echo '%s'" % payload
659 with self
.assertCalls(
660 (mock
.call
.pylib
.utils
.device_temp_file
.DeviceTempFile(
661 self
.adb
, suffix
='.sh'), MockTempFile('/sdcard/temp-123.sh')),
662 self
.call
.device
._WriteFileWithPush
('/sdcard/temp-123.sh', expected_cmd
),
663 (self
.call
.adb
.Shell('sh /sdcard/temp-123.sh'), payload
+ '\n')):
664 self
.assertEquals([payload
],
665 self
.device
.RunShellCommand(['echo', payload
]))
667 def testRunShellCommand_withHugeCmdAmdSU(self
):
668 payload
= 'hi! ' * 1024
669 expected_cmd
= """su -c sh -c 'echo '"'"'%s'"'"''""" % payload
670 with self
.assertCalls(
671 (self
.call
.device
.NeedsSU(), True),
672 (mock
.call
.pylib
.utils
.device_temp_file
.DeviceTempFile(
673 self
.adb
, suffix
='.sh'), MockTempFile('/sdcard/temp-123.sh')),
674 self
.call
.device
._WriteFileWithPush
('/sdcard/temp-123.sh', expected_cmd
),
675 (self
.call
.adb
.Shell('sh /sdcard/temp-123.sh'), payload
+ '\n')):
678 self
.device
.RunShellCommand(['echo', payload
], as_root
=True))
680 def testRunShellCommand_withSu(self
):
681 with self
.assertCalls(
682 (self
.call
.device
.NeedsSU(), True),
683 (self
.call
.adb
.Shell("su -c sh -c 'setprop service.adb.root 0'"), '')):
684 self
.device
.RunShellCommand('setprop service.adb.root 0', as_root
=True)
686 def testRunShellCommand_manyLines(self
):
687 cmd
= 'ls /some/path'
688 with self
.assertCall(self
.call
.adb
.Shell(cmd
), 'file1\nfile2\nfile3\n'):
689 self
.assertEquals(['file1', 'file2', 'file3'],
690 self
.device
.RunShellCommand(cmd
))
692 def testRunShellCommand_singleLine_success(self
):
694 with self
.assertCall(self
.call
.adb
.Shell(cmd
), 'some value\n'):
695 self
.assertEquals('some value',
696 self
.device
.RunShellCommand(cmd
, single_line
=True))
698 def testRunShellCommand_singleLine_successEmptyLine(self
):
700 with self
.assertCall(self
.call
.adb
.Shell(cmd
), '\n'):
701 self
.assertEquals('',
702 self
.device
.RunShellCommand(cmd
, single_line
=True))
704 def testRunShellCommand_singleLine_successWithoutEndLine(self
):
705 cmd
= 'echo -n $VALUE'
706 with self
.assertCall(self
.call
.adb
.Shell(cmd
), 'some value'):
707 self
.assertEquals('some value',
708 self
.device
.RunShellCommand(cmd
, single_line
=True))
710 def testRunShellCommand_singleLine_successNoOutput(self
):
711 cmd
= 'echo -n $VALUE'
712 with self
.assertCall(self
.call
.adb
.Shell(cmd
), ''):
713 self
.assertEquals('',
714 self
.device
.RunShellCommand(cmd
, single_line
=True))
716 def testRunShellCommand_singleLine_failTooManyLines(self
):
718 with self
.assertCall(self
.call
.adb
.Shell(cmd
),
719 'some value\nanother value\n'):
720 with self
.assertRaises(device_errors
.CommandFailedError
):
721 self
.device
.RunShellCommand(cmd
, single_line
=True)
723 def testRunShellCommand_checkReturn_success(self
):
724 cmd
= 'echo $ANDROID_DATA'
726 with self
.assertCall(self
.call
.adb
.Shell(cmd
), output
):
727 self
.assertEquals([output
.rstrip()],
728 self
.device
.RunShellCommand(cmd
, check_return
=True))
730 def testRunShellCommand_checkReturn_failure(self
):
732 output
= 'opendir failed, Permission denied\n'
733 with self
.assertCall(self
.call
.adb
.Shell(cmd
), self
.ShellError(output
)):
734 with self
.assertRaises(device_errors
.AdbCommandFailedError
):
735 self
.device
.RunShellCommand(cmd
, check_return
=True)
737 def testRunShellCommand_checkReturn_disabled(self
):
739 output
= 'opendir failed, Permission denied\n'
740 with self
.assertCall(self
.call
.adb
.Shell(cmd
), self
.ShellError(output
)):
741 self
.assertEquals([output
.rstrip()],
742 self
.device
.RunShellCommand(cmd
, check_return
=False))
744 def testRunShellCommand_largeOutput_enabled(self
):
746 temp_file
= MockTempFile('/sdcard/temp-123')
747 cmd_redirect
= '%s > %s' % (cmd
, temp_file
.name
)
748 with self
.assertCalls(
749 (mock
.call
.pylib
.utils
.device_temp_file
.DeviceTempFile(self
.adb
),
751 (self
.call
.adb
.Shell(cmd_redirect
)),
752 (self
.call
.device
.ReadFile(temp_file
.name
, force_pull
=True),
756 self
.device
.RunShellCommand(
757 cmd
, large_output
=True, check_return
=True))
759 def testRunShellCommand_largeOutput_disabledNoTrigger(self
):
761 with self
.assertCall(self
.call
.adb
.Shell(cmd
), self
.ShellError('')):
762 with self
.assertRaises(device_errors
.AdbCommandFailedError
):
763 self
.device
.RunShellCommand(cmd
, check_return
=True)
765 def testRunShellCommand_largeOutput_disabledTrigger(self
):
767 temp_file
= MockTempFile('/sdcard/temp-123')
768 cmd_redirect
= '%s > %s' % (cmd
, temp_file
.name
)
769 with self
.assertCalls(
770 (self
.call
.adb
.Shell(cmd
), self
.ShellError('', None)),
771 (mock
.call
.pylib
.utils
.device_temp_file
.DeviceTempFile(self
.adb
),
773 (self
.call
.adb
.Shell(cmd_redirect
)),
774 (self
.call
.device
.ReadFile(mock
.ANY
, force_pull
=True),
776 self
.assertEquals(['something'],
777 self
.device
.RunShellCommand(cmd
, check_return
=True))
780 class DeviceUtilsRunPipedShellCommandTest(DeviceUtilsTest
):
782 def testRunPipedShellCommand_success(self
):
783 with self
.assertCall(
784 self
.call
.device
.RunShellCommand(
785 'ps | grep foo; echo "PIPESTATUS: ${PIPESTATUS[@]}"',
787 ['This line contains foo', 'PIPESTATUS: 0 0']):
788 self
.assertEquals(['This line contains foo'],
789 self
.device
._RunPipedShellCommand
('ps | grep foo'))
791 def testRunPipedShellCommand_firstCommandFails(self
):
792 with self
.assertCall(
793 self
.call
.device
.RunShellCommand(
794 'ps | grep foo; echo "PIPESTATUS: ${PIPESTATUS[@]}"',
796 ['PIPESTATUS: 1 0']):
797 with self
.assertRaises(device_errors
.AdbShellCommandFailedError
) as ec
:
798 self
.device
._RunPipedShellCommand
('ps | grep foo')
799 self
.assertEquals([1, 0], ec
.exception
.status
)
801 def testRunPipedShellCommand_secondCommandFails(self
):
802 with self
.assertCall(
803 self
.call
.device
.RunShellCommand(
804 'ps | grep foo; echo "PIPESTATUS: ${PIPESTATUS[@]}"',
806 ['PIPESTATUS: 0 1']):
807 with self
.assertRaises(device_errors
.AdbShellCommandFailedError
) as ec
:
808 self
.device
._RunPipedShellCommand
('ps | grep foo')
809 self
.assertEquals([0, 1], ec
.exception
.status
)
811 def testRunPipedShellCommand_outputCutOff(self
):
812 with self
.assertCall(
813 self
.call
.device
.RunShellCommand(
814 'ps | grep foo; echo "PIPESTATUS: ${PIPESTATUS[@]}"',
816 ['foo.bar'] * 256 + ['foo.ba']):
817 with self
.assertRaises(device_errors
.AdbShellCommandFailedError
) as ec
:
818 self
.device
._RunPipedShellCommand
('ps | grep foo')
819 self
.assertIs(None, ec
.exception
.status
)
822 @mock.patch('time.sleep', mock
.Mock())
823 class DeviceUtilsKillAllTest(DeviceUtilsTest
):
825 def testKillAll_noMatchingProcessesFailure(self
):
826 with self
.assertCall(self
.call
.device
.GetPids('test_process'), {}):
827 with self
.assertRaises(device_errors
.CommandFailedError
):
828 self
.device
.KillAll('test_process')
830 def testKillAll_noMatchingProcessesQuiet(self
):
831 with self
.assertCall(self
.call
.device
.GetPids('test_process'), {}):
832 self
.assertEqual(0, self
.device
.KillAll('test_process', quiet
=True))
834 def testKillAll_nonblocking(self
):
835 with self
.assertCalls(
836 (self
.call
.device
.GetPids('some.process'), {'some.process': '1234'}),
837 (self
.call
.adb
.Shell('kill -9 1234'), '')):
839 1, self
.device
.KillAll('some.process', blocking
=False))
841 def testKillAll_blocking(self
):
842 with self
.assertCalls(
843 (self
.call
.device
.GetPids('some.process'), {'some.process': '1234'}),
844 (self
.call
.adb
.Shell('kill -9 1234'), ''),
845 (self
.call
.device
.GetPids('some.process'), {'some.process': '1234'}),
846 (self
.call
.device
.GetPids('some.process'), [])):
848 1, self
.device
.KillAll('some.process', blocking
=True))
850 def testKillAll_root(self
):
851 with self
.assertCalls(
852 (self
.call
.device
.GetPids('some.process'), {'some.process': '1234'}),
853 (self
.call
.device
.NeedsSU(), True),
854 (self
.call
.adb
.Shell("su -c sh -c 'kill -9 1234'"), '')):
856 1, self
.device
.KillAll('some.process', as_root
=True))
858 def testKillAll_sigterm(self
):
859 with self
.assertCalls(
860 (self
.call
.device
.GetPids('some.process'), {'some.process': '1234'}),
861 (self
.call
.adb
.Shell('kill -15 1234'), '')):
863 1, self
.device
.KillAll('some.process', signum
=device_signal
.SIGTERM
))
866 class DeviceUtilsStartActivityTest(DeviceUtilsTest
):
868 def testStartActivity_actionOnly(self
):
869 test_intent
= intent
.Intent(action
='android.intent.action.VIEW')
870 with self
.assertCall(
871 self
.call
.adb
.Shell('am start '
872 '-a android.intent.action.VIEW'),
873 'Starting: Intent { act=android.intent.action.VIEW }'):
874 self
.device
.StartActivity(test_intent
)
876 def testStartActivity_success(self
):
877 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
878 package
='this.is.a.test.package',
880 with self
.assertCall(
881 self
.call
.adb
.Shell('am start '
882 '-a android.intent.action.VIEW '
883 '-n this.is.a.test.package/.Main'),
884 'Starting: Intent { act=android.intent.action.VIEW }'):
885 self
.device
.StartActivity(test_intent
)
887 def testStartActivity_failure(self
):
888 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
889 package
='this.is.a.test.package',
891 with self
.assertCall(
892 self
.call
.adb
.Shell('am start '
893 '-a android.intent.action.VIEW '
894 '-n this.is.a.test.package/.Main'),
895 'Error: Failed to start test activity'):
896 with self
.assertRaises(device_errors
.CommandFailedError
):
897 self
.device
.StartActivity(test_intent
)
899 def testStartActivity_blocking(self
):
900 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
901 package
='this.is.a.test.package',
903 with self
.assertCall(
904 self
.call
.adb
.Shell('am start '
906 '-a android.intent.action.VIEW '
907 '-n this.is.a.test.package/.Main'),
908 'Starting: Intent { act=android.intent.action.VIEW }'):
909 self
.device
.StartActivity(test_intent
, blocking
=True)
911 def testStartActivity_withCategory(self
):
912 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
913 package
='this.is.a.test.package',
915 category
='android.intent.category.HOME')
916 with self
.assertCall(
917 self
.call
.adb
.Shell('am start '
918 '-a android.intent.action.VIEW '
919 '-c android.intent.category.HOME '
920 '-n this.is.a.test.package/.Main'),
921 'Starting: Intent { act=android.intent.action.VIEW }'):
922 self
.device
.StartActivity(test_intent
)
924 def testStartActivity_withMultipleCategories(self
):
925 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
926 package
='this.is.a.test.package',
928 category
=['android.intent.category.HOME',
929 'android.intent.category.BROWSABLE'])
930 with self
.assertCall(
931 self
.call
.adb
.Shell('am start '
932 '-a android.intent.action.VIEW '
933 '-c android.intent.category.HOME '
934 '-c android.intent.category.BROWSABLE '
935 '-n this.is.a.test.package/.Main'),
936 'Starting: Intent { act=android.intent.action.VIEW }'):
937 self
.device
.StartActivity(test_intent
)
939 def testStartActivity_withData(self
):
940 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
941 package
='this.is.a.test.package',
943 data
='http://www.google.com/')
944 with self
.assertCall(
945 self
.call
.adb
.Shell('am start '
946 '-a android.intent.action.VIEW '
947 '-d http://www.google.com/ '
948 '-n this.is.a.test.package/.Main'),
949 'Starting: Intent { act=android.intent.action.VIEW }'):
950 self
.device
.StartActivity(test_intent
)
952 def testStartActivity_withStringExtra(self
):
953 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
954 package
='this.is.a.test.package',
956 extras
={'foo': 'test'})
957 with self
.assertCall(
958 self
.call
.adb
.Shell('am start '
959 '-a android.intent.action.VIEW '
960 '-n this.is.a.test.package/.Main '
962 'Starting: Intent { act=android.intent.action.VIEW }'):
963 self
.device
.StartActivity(test_intent
)
965 def testStartActivity_withBoolExtra(self
):
966 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
967 package
='this.is.a.test.package',
969 extras
={'foo': True})
970 with self
.assertCall(
971 self
.call
.adb
.Shell('am start '
972 '-a android.intent.action.VIEW '
973 '-n this.is.a.test.package/.Main '
975 'Starting: Intent { act=android.intent.action.VIEW }'):
976 self
.device
.StartActivity(test_intent
)
978 def testStartActivity_withIntExtra(self
):
979 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
980 package
='this.is.a.test.package',
983 with self
.assertCall(
984 self
.call
.adb
.Shell('am start '
985 '-a android.intent.action.VIEW '
986 '-n this.is.a.test.package/.Main '
988 'Starting: Intent { act=android.intent.action.VIEW }'):
989 self
.device
.StartActivity(test_intent
)
991 def testStartActivity_withTraceFile(self
):
992 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
993 package
='this.is.a.test.package',
995 with self
.assertCall(
996 self
.call
.adb
.Shell('am start '
997 '--start-profiler test_trace_file.out '
998 '-a android.intent.action.VIEW '
999 '-n this.is.a.test.package/.Main'),
1000 'Starting: Intent { act=android.intent.action.VIEW }'):
1001 self
.device
.StartActivity(test_intent
,
1002 trace_file_name
='test_trace_file.out')
1004 def testStartActivity_withForceStop(self
):
1005 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
1006 package
='this.is.a.test.package',
1008 with self
.assertCall(
1009 self
.call
.adb
.Shell('am start '
1011 '-a android.intent.action.VIEW '
1012 '-n this.is.a.test.package/.Main'),
1013 'Starting: Intent { act=android.intent.action.VIEW }'):
1014 self
.device
.StartActivity(test_intent
, force_stop
=True)
1016 def testStartActivity_withFlags(self
):
1017 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
1018 package
='this.is.a.test.package',
1021 with self
.assertCall(
1022 self
.call
.adb
.Shell('am start '
1023 '-a android.intent.action.VIEW '
1024 '-n this.is.a.test.package/.Main '
1026 'Starting: Intent { act=android.intent.action.VIEW }'):
1027 self
.device
.StartActivity(test_intent
)
1030 class DeviceUtilsStartInstrumentationTest(DeviceUtilsTest
):
1032 def testStartInstrumentation_nothing(self
):
1033 with self
.assertCalls(
1034 self
.call
.device
.RunShellCommand(
1035 ['am', 'instrument', 'test.package/.TestInstrumentation'],
1036 check_return
=True, large_output
=True)):
1037 self
.device
.StartInstrumentation(
1038 'test.package/.TestInstrumentation',
1039 finish
=False, raw
=False, extras
=None)
1041 def testStartInstrumentation_finish(self
):
1042 with self
.assertCalls(
1043 (self
.call
.device
.RunShellCommand(
1044 ['am', 'instrument', '-w', 'test.package/.TestInstrumentation'],
1045 check_return
=True, large_output
=True),
1047 output
= self
.device
.StartInstrumentation(
1048 'test.package/.TestInstrumentation',
1049 finish
=True, raw
=False, extras
=None)
1050 self
.assertEquals(['OK (1 test)'], output
)
1052 def testStartInstrumentation_raw(self
):
1053 with self
.assertCalls(
1054 self
.call
.device
.RunShellCommand(
1055 ['am', 'instrument', '-r', 'test.package/.TestInstrumentation'],
1056 check_return
=True, large_output
=True)):
1057 self
.device
.StartInstrumentation(
1058 'test.package/.TestInstrumentation',
1059 finish
=False, raw
=True, extras
=None)
1061 def testStartInstrumentation_extras(self
):
1062 with self
.assertCalls(
1063 self
.call
.device
.RunShellCommand(
1064 ['am', 'instrument', '-e', 'foo', 'Foo', '-e', 'bar', 'Bar',
1065 'test.package/.TestInstrumentation'],
1066 check_return
=True, large_output
=True)):
1067 self
.device
.StartInstrumentation(
1068 'test.package/.TestInstrumentation',
1069 finish
=False, raw
=False, extras
={'foo': 'Foo', 'bar': 'Bar'})
1072 class DeviceUtilsBroadcastIntentTest(DeviceUtilsTest
):
1074 def testBroadcastIntent_noExtras(self
):
1075 test_intent
= intent
.Intent(action
='test.package.with.an.INTENT')
1076 with self
.assertCall(
1077 self
.call
.adb
.Shell('am broadcast -a test.package.with.an.INTENT'),
1078 'Broadcasting: Intent { act=test.package.with.an.INTENT } '):
1079 self
.device
.BroadcastIntent(test_intent
)
1081 def testBroadcastIntent_withExtra(self
):
1082 test_intent
= intent
.Intent(action
='test.package.with.an.INTENT',
1083 extras
={'foo': 'bar value'})
1084 with self
.assertCall(
1085 self
.call
.adb
.Shell(
1086 "am broadcast -a test.package.with.an.INTENT --es foo 'bar value'"),
1087 'Broadcasting: Intent { act=test.package.with.an.INTENT } '):
1088 self
.device
.BroadcastIntent(test_intent
)
1090 def testBroadcastIntent_withExtra_noValue(self
):
1091 test_intent
= intent
.Intent(action
='test.package.with.an.INTENT',
1092 extras
={'foo': None})
1093 with self
.assertCall(
1094 self
.call
.adb
.Shell(
1095 'am broadcast -a test.package.with.an.INTENT --esn foo'),
1096 'Broadcasting: Intent { act=test.package.with.an.INTENT } '):
1097 self
.device
.BroadcastIntent(test_intent
)
1100 class DeviceUtilsGoHomeTest(DeviceUtilsTest
):
1102 def testGoHome_popupsExist(self
):
1103 with self
.assertCalls(
1104 (self
.call
.device
.RunShellCommand(
1105 ['dumpsys', 'window', 'windows'], check_return
=True,
1106 large_output
=True), []),
1107 (self
.call
.device
.RunShellCommand(
1108 ['am', 'start', '-W', '-a', 'android.intent.action.MAIN',
1109 '-c', 'android.intent.category.HOME'], check_return
=True),
1110 'Starting: Intent { act=android.intent.action.MAIN }\r\n'''),
1111 (self.call.device.RunShellCommand(
1112 ['dumpsys
', 'window
', 'windows
'], check_return=True,
1113 large_output=True), []),
1114 (self.call.device.RunShellCommand(
1115 ['input', 'keyevent
', '66'], check_return=True)),
1116 (self.call.device.RunShellCommand(
1117 ['input', 'keyevent
', '4'], check_return=True)),
1118 (self.call.device.RunShellCommand(
1119 ['dumpsys
', 'window
', 'windows
'], check_return=True,
1121 ['mCurrentFocus Launcher
'])):
1122 self.device.GoHome()
1124 def testGoHome_willRetry(self):
1125 with self.assertCalls(
1126 (self.call.device.RunShellCommand(
1127 ['dumpsys
', 'window
', 'windows
'], check_return=True,
1128 large_output=True), []),
1129 (self.call.device.RunShellCommand(
1130 ['am
', 'start
', '-W
', '-a
', 'android
.intent
.action
.MAIN
',
1131 '-c
', 'android
.intent
.category
.HOME
'], check_return=True),
1132 'Starting
: Intent
{ act
=android
.intent
.action
.MAIN
}\r\n'''),
1133 (self.call.device.RunShellCommand(
1134 ['dumpsys', 'window', 'windows'], check_return=True,
1135 large_output=True), []),
1136 (self.call.device.RunShellCommand(
1137 ['input', 'keyevent', '66'], check_return=True,)),
1138 (self.call.device.RunShellCommand(
1139 ['input', 'keyevent', '4'], check_return=True)),
1140 (self.call.device.RunShellCommand(
1141 ['dumpsys', 'window', 'windows'], check_return=True,
1142 large_output=True), []),
1143 (self.call.device.RunShellCommand(
1144 ['input', 'keyevent', '66'], check_return=True)),
1145 (self.call.device.RunShellCommand(
1146 ['input', 'keyevent', '4'], check_return=True)),
1147 (self.call.device.RunShellCommand(
1148 ['dumpsys', 'window', 'windows'], check_return=True,
1150 self.TimeoutError())):
1151 with self.assertRaises(device_errors.CommandTimeoutError):
1152 self.device.GoHome()
1154 def testGoHome_alreadyFocused(self):
1155 with self.assertCall(
1156 self.call.device.RunShellCommand(
1157 ['dumpsys', 'window', 'windows'], check_return=True,
1159 ['mCurrentFocus Launcher']):
1160 self.device.GoHome()
1162 def testGoHome_alreadyFocusedAlternateCase(self):
1163 with self.assertCall(
1164 self.call.device.RunShellCommand(
1165 ['dumpsys', 'window', 'windows'], check_return=True,
1167 [' mCurrentFocus .launcher/.']):
1168 self.device.GoHome()
1170 def testGoHome_obtainsFocusAfterGoingHome(self):
1171 with self.assertCalls(
1172 (self.call.device.RunShellCommand(
1173 ['dumpsys', 'window', 'windows'], check_return=True,
1174 large_output=True), []),
1175 (self.call.device.RunShellCommand(
1176 ['am', 'start', '-W', '-a', 'android.intent.action.MAIN',
1177 '-c', 'android.intent.category.HOME'], check_return=True),
1178 'Starting: Intent { act=android.intent.action.MAIN }\r\n'''),
1179 (self
.call
.device
.RunShellCommand(
1180 ['dumpsys', 'window', 'windows'], check_return
=True,
1182 ['mCurrentFocus Launcher'])):
1183 self
.device
.GoHome()
1185 class DeviceUtilsForceStopTest(DeviceUtilsTest
):
1187 def testForceStop(self
):
1188 with self
.assertCall(
1189 self
.call
.adb
.Shell('am force-stop this.is.a.test.package'),
1191 self
.device
.ForceStop('this.is.a.test.package')
1194 class DeviceUtilsClearApplicationStateTest(DeviceUtilsTest
):
1196 def testClearApplicationState_packageDoesntExist(self
):
1197 with self
.assertCalls(
1198 (self
.call
.adb
.Shell('getprop ro.build.version.sdk'), '17\n'),
1199 (self
.call
.device
.GetApplicationPaths('this.package.does.not.exist'),
1201 self
.device
.ClearApplicationState('this.package.does.not.exist')
1203 def testClearApplicationState_packageDoesntExistOnAndroidJBMR2OrAbove(self
):
1204 with self
.assertCalls(
1205 (self
.call
.adb
.Shell('getprop ro.build.version.sdk'), '18\n'),
1206 (self
.call
.adb
.Shell('pm clear this.package.does.not.exist'),
1208 self
.device
.ClearApplicationState('this.package.does.not.exist')
1210 def testClearApplicationState_packageExists(self
):
1211 with self
.assertCalls(
1212 (self
.call
.adb
.Shell('getprop ro.build.version.sdk'), '17\n'),
1213 (self
.call
.device
.GetApplicationPaths('this.package.exists'),
1214 ['/data/app/this.package.exists.apk']),
1215 (self
.call
.adb
.Shell('pm clear this.package.exists'),
1217 self
.device
.ClearApplicationState('this.package.exists')
1219 def testClearApplicationState_packageExistsOnAndroidJBMR2OrAbove(self
):
1220 with self
.assertCalls(
1221 (self
.call
.adb
.Shell('getprop ro.build.version.sdk'), '18\n'),
1222 (self
.call
.adb
.Shell('pm clear this.package.exists'),
1224 self
.device
.ClearApplicationState('this.package.exists')
1227 class DeviceUtilsSendKeyEventTest(DeviceUtilsTest
):
1229 def testSendKeyEvent(self
):
1230 with self
.assertCall(self
.call
.adb
.Shell('input keyevent 66'), ''):
1231 self
.device
.SendKeyEvent(66)
1234 class DeviceUtilsPushChangedFilesIndividuallyTest(DeviceUtilsTest
):
1236 def testPushChangedFilesIndividually_empty(self
):
1238 with self
.assertCalls():
1239 self
.device
._PushChangedFilesIndividually
(test_files
)
1241 def testPushChangedFilesIndividually_single(self
):
1242 test_files
= [('/test/host/path', '/test/device/path')]
1243 with self
.assertCalls(self
.call
.adb
.Push(*test_files
[0])):
1244 self
.device
._PushChangedFilesIndividually
(test_files
)
1246 def testPushChangedFilesIndividually_multiple(self
):
1248 ('/test/host/path/file1', '/test/device/path/file1'),
1249 ('/test/host/path/file2', '/test/device/path/file2')]
1250 with self
.assertCalls(
1251 self
.call
.adb
.Push(*test_files
[0]),
1252 self
.call
.adb
.Push(*test_files
[1])):
1253 self
.device
._PushChangedFilesIndividually
(test_files
)
1256 class DeviceUtilsPushChangedFilesZippedTest(DeviceUtilsTest
):
1258 def testPushChangedFilesZipped_empty(self
):
1260 with self
.assertCalls():
1261 self
.device
._PushChangedFilesZipped
(test_files
)
1263 def _testPushChangedFilesZipped_spec(self
, test_files
):
1264 mock_zip_temp
= mock
.mock_open()
1265 mock_zip_temp
.return_value
.name
= '/test/temp/file/tmp.zip'
1266 with self
.assertCalls(
1267 (mock
.call
.tempfile
.NamedTemporaryFile(suffix
='.zip'), mock_zip_temp
),
1268 (mock
.call
.multiprocessing
.Process(
1269 target
=device_utils
.DeviceUtils
._CreateDeviceZip
,
1270 args
=('/test/temp/file/tmp.zip', test_files
)), mock
.Mock()),
1271 (self
.call
.device
.GetExternalStoragePath(),
1272 '/test/device/external_dir'),
1274 '/test/temp/file/tmp.zip', '/test/device/external_dir/tmp.zip'),
1275 self
.call
.device
.RunShellCommand(
1276 ['unzip', '/test/device/external_dir/tmp.zip'],
1278 env
={'PATH': '/data/local/tmp/bin:$PATH'},
1280 (self
.call
.device
.IsOnline(), True),
1281 self
.call
.device
.RunShellCommand(
1282 ['rm', '/test/device/external_dir/tmp.zip'], check_return
=True)):
1283 self
.device
._PushChangedFilesZipped
(test_files
)
1285 def testPushChangedFilesZipped_single(self
):
1286 self
._testPushChangedFilesZipped
_spec
(
1287 [('/test/host/path/file1', '/test/device/path/file1')])
1289 def testPushChangedFilesZipped_multiple(self
):
1290 self
._testPushChangedFilesZipped
_spec
(
1291 [('/test/host/path/file1', '/test/device/path/file1'),
1292 ('/test/host/path/file2', '/test/device/path/file2')])
1295 class DeviceUtilsPathExistsTest(DeviceUtilsTest
):
1297 def testPathExists_usingTest_pathExists(self
):
1298 with self
.assertCall(
1299 self
.call
.device
.RunShellCommand(
1300 ['test', '-e', '/path/file.exists'], check_return
=True), ''):
1301 self
.assertTrue(self
.device
.PathExists('/path/file.exists'))
1303 def testPathExists_usingTest_pathDoesntExist(self
):
1304 with self
.assertCall(
1305 self
.call
.device
.RunShellCommand(
1306 ['test', '-e', '/path/does/not/exist'], check_return
=True),
1307 self
.ShellError('', 1)):
1308 self
.assertFalse(self
.device
.PathExists('/path/does/not/exist'))
1310 def testFileExists_usingTest_pathDoesntExist(self
):
1311 with self
.assertCall(
1312 self
.call
.device
.RunShellCommand(
1313 ['test', '-e', '/does/not/exist.html'], check_return
=True),
1314 self
.ShellError('', 1)):
1315 self
.assertFalse(self
.device
.FileExists('/does/not/exist.html'))
1318 class DeviceUtilsPullFileTest(DeviceUtilsTest
):
1320 def testPullFile_existsOnDevice(self
):
1321 with mock
.patch('os.path.exists', return_value
=True):
1322 with self
.assertCall(
1323 self
.call
.adb
.Pull('/data/app/test.file.exists',
1324 '/test/file/host/path')):
1325 self
.device
.PullFile('/data/app/test.file.exists',
1326 '/test/file/host/path')
1328 def testPullFile_doesntExistOnDevice(self
):
1329 with mock
.patch('os.path.exists', return_value
=True):
1330 with self
.assertCall(
1331 self
.call
.adb
.Pull('/data/app/test.file.does.not.exist',
1332 '/test/file/host/path'),
1333 self
.CommandError('remote object does not exist')):
1334 with self
.assertRaises(device_errors
.CommandFailedError
):
1335 self
.device
.PullFile('/data/app/test.file.does.not.exist',
1336 '/test/file/host/path')
1339 class DeviceUtilsReadFileTest(DeviceUtilsTest
):
1341 def testReadFileWithPull_success(self
):
1342 tmp_host_dir
= '/tmp/dir/on.host/'
1343 tmp_host
= MockTempFile('/tmp/dir/on.host/tmp_ReadFileWithPull')
1344 tmp_host
.file.read
.return_value
= 'some interesting contents'
1345 with self
.assertCalls(
1346 (mock
.call
.tempfile
.mkdtemp(), tmp_host_dir
),
1347 (self
.call
.adb
.Pull('/path/to/device/file', mock
.ANY
)),
1348 (mock
.call
.__builtin
__.open(mock
.ANY
, 'r'), tmp_host
),
1349 (mock
.call
.os
.path
.exists(tmp_host_dir
), True),
1350 (mock
.call
.shutil
.rmtree(tmp_host_dir
), None)):
1351 self
.assertEquals('some interesting contents',
1352 self
.device
._ReadFileWithPull
('/path/to/device/file'))
1353 tmp_host
.file.read
.assert_called_once_with()
1355 def testReadFileWithPull_rejected(self
):
1356 tmp_host_dir
= '/tmp/dir/on.host/'
1357 with self
.assertCalls(
1358 (mock
.call
.tempfile
.mkdtemp(), tmp_host_dir
),
1359 (self
.call
.adb
.Pull('/path/to/device/file', mock
.ANY
),
1360 self
.CommandError()),
1361 (mock
.call
.os
.path
.exists(tmp_host_dir
), True),
1362 (mock
.call
.shutil
.rmtree(tmp_host_dir
), None)):
1363 with self
.assertRaises(device_errors
.CommandFailedError
):
1364 self
.device
._ReadFileWithPull
('/path/to/device/file')
1366 def testReadFile_exists(self
):
1367 with self
.assertCalls(
1368 (self
.call
.device
.RunShellCommand(
1369 ['ls', '-l', '/read/this/test/file'],
1370 as_root
=False, check_return
=True),
1371 ['-rw-rw---- root foo 256 1970-01-01 00:00 file']),
1372 (self
.call
.device
.RunShellCommand(
1373 ['cat', '/read/this/test/file'],
1374 as_root
=False, check_return
=True),
1375 ['this is a test file'])):
1376 self
.assertEqual('this is a test file\n',
1377 self
.device
.ReadFile('/read/this/test/file'))
1379 def testReadFile_doesNotExist(self
):
1380 with self
.assertCall(
1381 self
.call
.device
.RunShellCommand(
1382 ['ls', '-l', '/this/file/does.not.exist'],
1383 as_root
=False, check_return
=True),
1384 self
.CommandError('File does not exist')):
1385 with self
.assertRaises(device_errors
.CommandFailedError
):
1386 self
.device
.ReadFile('/this/file/does.not.exist')
1388 def testReadFile_zeroSize(self
):
1389 with self
.assertCalls(
1390 (self
.call
.device
.RunShellCommand(
1391 ['ls', '-l', '/this/file/has/zero/size'],
1392 as_root
=False, check_return
=True),
1393 ['-r--r--r-- root foo 0 1970-01-01 00:00 zero_size_file']),
1394 (self
.call
.device
._ReadFileWithPull
('/this/file/has/zero/size'),
1395 'but it has contents\n')):
1396 self
.assertEqual('but it has contents\n',
1397 self
.device
.ReadFile('/this/file/has/zero/size'))
1399 def testReadFile_withSU(self
):
1400 with self
.assertCalls(
1401 (self
.call
.device
.RunShellCommand(
1402 ['ls', '-l', '/this/file/can.be.read.with.su'],
1403 as_root
=True, check_return
=True),
1404 ['-rw------- root root 256 1970-01-01 00:00 can.be.read.with.su']),
1405 (self
.call
.device
.RunShellCommand(
1406 ['cat', '/this/file/can.be.read.with.su'],
1407 as_root
=True, check_return
=True),
1408 ['this is a test file', 'read with su'])):
1410 'this is a test file\nread with su\n',
1411 self
.device
.ReadFile('/this/file/can.be.read.with.su',
1414 def testReadFile_withPull(self
):
1415 contents
= 'a' * 123456
1416 with self
.assertCalls(
1417 (self
.call
.device
.RunShellCommand(
1418 ['ls', '-l', '/read/this/big/test/file'],
1419 as_root
=False, check_return
=True),
1420 ['-rw-rw---- root foo 123456 1970-01-01 00:00 file']),
1421 (self
.call
.device
._ReadFileWithPull
('/read/this/big/test/file'),
1424 contents
, self
.device
.ReadFile('/read/this/big/test/file'))
1426 def testReadFile_withPullAndSU(self
):
1427 contents
= 'b' * 123456
1428 with self
.assertCalls(
1429 (self
.call
.device
.RunShellCommand(
1430 ['ls', '-l', '/this/big/file/can.be.read.with.su'],
1431 as_root
=True, check_return
=True),
1432 ['-rw------- root root 123456 1970-01-01 00:00 can.be.read.with.su']),
1433 (self
.call
.device
.NeedsSU(), True),
1434 (mock
.call
.pylib
.utils
.device_temp_file
.DeviceTempFile(self
.adb
),
1435 MockTempFile('/sdcard/tmp/on.device')),
1436 self
.call
.device
.RunShellCommand(
1437 ['cp', '/this/big/file/can.be.read.with.su',
1438 '/sdcard/tmp/on.device'],
1439 as_root
=True, check_return
=True),
1440 (self
.call
.device
._ReadFileWithPull
('/sdcard/tmp/on.device'),
1444 self
.device
.ReadFile('/this/big/file/can.be.read.with.su',
1447 def testReadFile_forcePull(self
):
1448 contents
= 'a' * 123456
1449 with self
.assertCall(
1450 self
.call
.device
._ReadFileWithPull
('/read/this/big/test/file'),
1454 self
.device
.ReadFile('/read/this/big/test/file', force_pull
=True))
1457 class DeviceUtilsWriteFileTest(DeviceUtilsTest
):
1459 def testWriteFileWithPush_success(self
):
1460 tmp_host
= MockTempFile('/tmp/file/on.host')
1461 contents
= 'some interesting contents'
1462 with self
.assertCalls(
1463 (mock
.call
.tempfile
.NamedTemporaryFile(), tmp_host
),
1464 self
.call
.adb
.Push('/tmp/file/on.host', '/path/to/device/file')):
1465 self
.device
._WriteFileWithPush
('/path/to/device/file', contents
)
1466 tmp_host
.file.write
.assert_called_once_with(contents
)
1468 def testWriteFileWithPush_rejected(self
):
1469 tmp_host
= MockTempFile('/tmp/file/on.host')
1470 contents
= 'some interesting contents'
1471 with self
.assertCalls(
1472 (mock
.call
.tempfile
.NamedTemporaryFile(), tmp_host
),
1473 (self
.call
.adb
.Push('/tmp/file/on.host', '/path/to/device/file'),
1474 self
.CommandError())):
1475 with self
.assertRaises(device_errors
.CommandFailedError
):
1476 self
.device
._WriteFileWithPush
('/path/to/device/file', contents
)
1478 def testWriteFile_withPush(self
):
1479 contents
= 'some large contents ' * 26 # 20 * 26 = 520 chars
1480 with self
.assertCalls(
1481 self
.call
.device
._WriteFileWithPush
('/path/to/device/file', contents
)):
1482 self
.device
.WriteFile('/path/to/device/file', contents
)
1484 def testWriteFile_withPushForced(self
):
1485 contents
= 'tiny contents'
1486 with self
.assertCalls(
1487 self
.call
.device
._WriteFileWithPush
('/path/to/device/file', contents
)):
1488 self
.device
.WriteFile('/path/to/device/file', contents
, force_push
=True)
1490 def testWriteFile_withPushAndSU(self
):
1491 contents
= 'some large contents ' * 26 # 20 * 26 = 520 chars
1492 with self
.assertCalls(
1493 (self
.call
.device
.NeedsSU(), True),
1494 (mock
.call
.pylib
.utils
.device_temp_file
.DeviceTempFile(self
.adb
),
1495 MockTempFile('/sdcard/tmp/on.device')),
1496 self
.call
.device
._WriteFileWithPush
('/sdcard/tmp/on.device', contents
),
1497 self
.call
.device
.RunShellCommand(
1498 ['cp', '/sdcard/tmp/on.device', '/path/to/device/file'],
1499 as_root
=True, check_return
=True)):
1500 self
.device
.WriteFile('/path/to/device/file', contents
, as_root
=True)
1502 def testWriteFile_withEcho(self
):
1503 with self
.assertCall(self
.call
.adb
.Shell(
1504 "echo -n the.contents > /test/file/to.write"), ''):
1505 self
.device
.WriteFile('/test/file/to.write', 'the.contents')
1507 def testWriteFile_withEchoAndQuotes(self
):
1508 with self
.assertCall(self
.call
.adb
.Shell(
1509 "echo -n 'the contents' > '/test/file/to write'"), ''):
1510 self
.device
.WriteFile('/test/file/to write', 'the contents')
1512 def testWriteFile_withEchoAndSU(self
):
1513 with self
.assertCalls(
1514 (self
.call
.device
.NeedsSU(), True),
1515 (self
.call
.adb
.Shell("su -c sh -c 'echo -n contents > /test/file'"),
1517 self
.device
.WriteFile('/test/file', 'contents', as_root
=True)
1520 class DeviceUtilsLsTest(DeviceUtilsTest
):
1522 def testLs_directory(self
):
1523 result
= [('.', adb_wrapper
.DeviceStat(16889, 4096, 1417436123)),
1524 ('..', adb_wrapper
.DeviceStat(16873, 4096, 12382237)),
1525 ('testfile.txt', adb_wrapper
.DeviceStat(33206, 3, 1417436122))]
1526 with self
.assertCalls(
1527 (self
.call
.adb
.Ls('/data/local/tmp'), result
)):
1528 self
.assertEquals(result
,
1529 self
.device
.Ls('/data/local/tmp'))
1531 def testLs_nothing(self
):
1532 with self
.assertCalls(
1533 (self
.call
.adb
.Ls('/data/local/tmp/testfile.txt'), [])):
1534 self
.assertEquals([],
1535 self
.device
.Ls('/data/local/tmp/testfile.txt'))
1538 class DeviceUtilsStatTest(DeviceUtilsTest
):
1540 def testStat_file(self
):
1541 result
= [('.', adb_wrapper
.DeviceStat(16889, 4096, 1417436123)),
1542 ('..', adb_wrapper
.DeviceStat(16873, 4096, 12382237)),
1543 ('testfile.txt', adb_wrapper
.DeviceStat(33206, 3, 1417436122))]
1544 with self
.assertCalls(
1545 (self
.call
.adb
.Ls('/data/local/tmp'), result
)):
1546 self
.assertEquals(adb_wrapper
.DeviceStat(33206, 3, 1417436122),
1547 self
.device
.Stat('/data/local/tmp/testfile.txt'))
1549 def testStat_directory(self
):
1550 result
= [('.', adb_wrapper
.DeviceStat(16873, 4096, 12382237)),
1551 ('..', adb_wrapper
.DeviceStat(16873, 4096, 12382237)),
1552 ('tmp', adb_wrapper
.DeviceStat(16889, 4096, 1417436123))]
1553 with self
.assertCalls(
1554 (self
.call
.adb
.Ls('/data/local'), result
)):
1555 self
.assertEquals(adb_wrapper
.DeviceStat(16889, 4096, 1417436123),
1556 self
.device
.Stat('/data/local/tmp'))
1558 def testStat_doesNotExist(self
):
1559 result
= [('.', adb_wrapper
.DeviceStat(16889, 4096, 1417436123)),
1560 ('..', adb_wrapper
.DeviceStat(16873, 4096, 12382237)),
1561 ('testfile.txt', adb_wrapper
.DeviceStat(33206, 3, 1417436122))]
1562 with self
.assertCalls(
1563 (self
.call
.adb
.Ls('/data/local/tmp'), result
)):
1564 with self
.assertRaises(device_errors
.CommandFailedError
):
1565 self
.device
.Stat('/data/local/tmp/does.not.exist.txt')
1568 class DeviceUtilsSetJavaAssertsTest(DeviceUtilsTest
):
1570 def testSetJavaAsserts_enable(self
):
1571 with self
.assertCalls(
1572 (self
.call
.device
.ReadFile(constants
.DEVICE_LOCAL_PROPERTIES_PATH
),
1573 'some.example.prop=with an example value\n'
1574 'some.other.prop=value_ok\n'),
1575 self
.call
.device
.WriteFile(
1576 constants
.DEVICE_LOCAL_PROPERTIES_PATH
,
1577 'some.example.prop=with an example value\n'
1578 'some.other.prop=value_ok\n'
1579 'dalvik.vm.enableassertions=all\n'),
1580 (self
.call
.device
.GetProp('dalvik.vm.enableassertions'), ''),
1581 self
.call
.device
.SetProp('dalvik.vm.enableassertions', 'all')):
1582 self
.assertTrue(self
.device
.SetJavaAsserts(True))
1584 def testSetJavaAsserts_disable(self
):
1585 with self
.assertCalls(
1586 (self
.call
.device
.ReadFile(constants
.DEVICE_LOCAL_PROPERTIES_PATH
),
1587 'some.example.prop=with an example value\n'
1588 'dalvik.vm.enableassertions=all\n'
1589 'some.other.prop=value_ok\n'),
1590 self
.call
.device
.WriteFile(
1591 constants
.DEVICE_LOCAL_PROPERTIES_PATH
,
1592 'some.example.prop=with an example value\n'
1593 'some.other.prop=value_ok\n'),
1594 (self
.call
.device
.GetProp('dalvik.vm.enableassertions'), 'all'),
1595 self
.call
.device
.SetProp('dalvik.vm.enableassertions', '')):
1596 self
.assertTrue(self
.device
.SetJavaAsserts(False))
1598 def testSetJavaAsserts_alreadyEnabled(self
):
1599 with self
.assertCalls(
1600 (self
.call
.device
.ReadFile(constants
.DEVICE_LOCAL_PROPERTIES_PATH
),
1601 'some.example.prop=with an example value\n'
1602 'dalvik.vm.enableassertions=all\n'
1603 'some.other.prop=value_ok\n'),
1604 (self
.call
.device
.GetProp('dalvik.vm.enableassertions'), 'all')):
1605 self
.assertFalse(self
.device
.SetJavaAsserts(True))
1608 class DeviceUtilsGetPropTest(DeviceUtilsTest
):
1610 def testGetProp_exists(self
):
1611 with self
.assertCall(
1612 self
.call
.adb
.Shell('getprop test.property'), 'property_value\n'):
1613 self
.assertEqual('property_value',
1614 self
.device
.GetProp('test.property'))
1616 def testGetProp_doesNotExist(self
):
1617 with self
.assertCall(
1618 self
.call
.adb
.Shell('getprop property.does.not.exist'), '\n'):
1619 self
.assertEqual('', self
.device
.GetProp('property.does.not.exist'))
1621 def testGetProp_cachedRoProp(self
):
1622 with self
.assertCall(
1623 self
.call
.adb
.Shell('getprop ro.build.type'), 'userdebug\n'):
1624 self
.assertEqual('userdebug',
1625 self
.device
.GetProp('ro.build.type', cache
=True))
1626 self
.assertEqual('userdebug',
1627 self
.device
.GetProp('ro.build.type', cache
=True))
1629 def testGetProp_retryAndCache(self
):
1630 with self
.assertCalls(
1631 (self
.call
.adb
.Shell('getprop ro.build.type'), self
.ShellError()),
1632 (self
.call
.adb
.Shell('getprop ro.build.type'), self
.ShellError()),
1633 (self
.call
.adb
.Shell('getprop ro.build.type'), 'userdebug\n')):
1634 self
.assertEqual('userdebug',
1635 self
.device
.GetProp('ro.build.type',
1636 cache
=True, retries
=3))
1637 self
.assertEqual('userdebug',
1638 self
.device
.GetProp('ro.build.type',
1639 cache
=True, retries
=3))
1642 class DeviceUtilsSetPropTest(DeviceUtilsTest
):
1644 def testSetProp(self
):
1645 with self
.assertCall(
1646 self
.call
.adb
.Shell("setprop test.property 'test value'"), ''):
1647 self
.device
.SetProp('test.property', 'test value')
1649 def testSetProp_check_succeeds(self
):
1650 with self
.assertCalls(
1651 (self
.call
.adb
.Shell('setprop test.property new_value'), ''),
1652 (self
.call
.adb
.Shell('getprop test.property'), 'new_value')):
1653 self
.device
.SetProp('test.property', 'new_value', check
=True)
1655 def testSetProp_check_fails(self
):
1656 with self
.assertCalls(
1657 (self
.call
.adb
.Shell('setprop test.property new_value'), ''),
1658 (self
.call
.adb
.Shell('getprop test.property'), 'old_value')):
1659 with self
.assertRaises(device_errors
.CommandFailedError
):
1660 self
.device
.SetProp('test.property', 'new_value', check
=True)
1663 class DeviceUtilsGetPidsTest(DeviceUtilsTest
):
1665 def testGetPids_noMatches(self
):
1666 with self
.assertCall(
1667 self
.call
.device
._RunPipedShellCommand
('ps | grep -F does.not.match'),
1669 self
.assertEqual({}, self
.device
.GetPids('does.not.match'))
1671 def testGetPids_oneMatch(self
):
1672 with self
.assertCall(
1673 self
.call
.device
._RunPipedShellCommand
('ps | grep -F one.match'),
1674 ['user 1001 100 1024 1024 ffffffff 00000000 one.match']):
1675 self
.assertEqual({'one.match': '1001'}, self
.device
.GetPids('one.match'))
1677 def testGetPids_mutlipleMatches(self
):
1678 with self
.assertCall(
1679 self
.call
.device
._RunPipedShellCommand
('ps | grep -F match'),
1680 ['user 1001 100 1024 1024 ffffffff 00000000 one.match',
1681 'user 1002 100 1024 1024 ffffffff 00000000 two.match',
1682 'user 1003 100 1024 1024 ffffffff 00000000 three.match']):
1684 {'one.match': '1001', 'two.match': '1002', 'three.match': '1003'},
1685 self
.device
.GetPids('match'))
1687 def testGetPids_exactMatch(self
):
1688 with self
.assertCall(
1689 self
.call
.device
._RunPipedShellCommand
('ps | grep -F exact.match'),
1690 ['user 1000 100 1024 1024 ffffffff 00000000 not.exact.match',
1691 'user 1234 100 1024 1024 ffffffff 00000000 exact.match']):
1693 {'not.exact.match': '1000', 'exact.match': '1234'},
1694 self
.device
.GetPids('exact.match'))
1696 def testGetPids_quotable(self
):
1697 with self
.assertCall(
1698 self
.call
.device
._RunPipedShellCommand
("ps | grep -F 'my$process'"),
1699 ['user 1234 100 1024 1024 ffffffff 00000000 my$process']):
1701 {'my$process': '1234'}, self
.device
.GetPids('my$process'))
1704 class DeviceUtilsTakeScreenshotTest(DeviceUtilsTest
):
1706 def testTakeScreenshot_fileNameProvided(self
):
1707 with self
.assertCalls(
1708 (mock
.call
.pylib
.utils
.device_temp_file
.DeviceTempFile(
1709 self
.adb
, suffix
='.png'),
1710 MockTempFile('/tmp/path/temp-123.png')),
1711 (self
.call
.adb
.Shell('/system/bin/screencap -p /tmp/path/temp-123.png'),
1713 self
.call
.device
.PullFile('/tmp/path/temp-123.png',
1714 '/test/host/screenshot.png')):
1715 self
.device
.TakeScreenshot('/test/host/screenshot.png')
1718 class DeviceUtilsGetMemoryUsageForPidTest(DeviceUtilsTest
):
1721 super(DeviceUtilsGetMemoryUsageForPidTest
, self
).setUp()
1723 def testGetMemoryUsageForPid_validPid(self
):
1724 with self
.assertCalls(
1725 (self
.call
.device
._RunPipedShellCommand
(
1726 'showmap 1234 | grep TOTAL', as_root
=True),
1727 ['100 101 102 103 104 105 106 107 TOTAL']),
1728 (self
.call
.device
.ReadFile('/proc/1234/status', as_root
=True),
1729 'VmHWM: 1024 kB\n')):
1735 'Shared_Clean': 103,
1736 'Shared_Dirty': 104,
1737 'Private_Clean': 105,
1738 'Private_Dirty': 106,
1741 self
.device
.GetMemoryUsageForPid(1234))
1743 def testGetMemoryUsageForPid_noSmaps(self
):
1744 with self
.assertCalls(
1745 (self
.call
.device
._RunPipedShellCommand
(
1746 'showmap 4321 | grep TOTAL', as_root
=True),
1747 ['cannot open /proc/4321/smaps: No such file or directory']),
1748 (self
.call
.device
.ReadFile('/proc/4321/status', as_root
=True),
1749 'VmHWM: 1024 kb\n')):
1750 self
.assertEquals({'VmHWM': 1024}, self
.device
.GetMemoryUsageForPid(4321))
1752 def testGetMemoryUsageForPid_noStatus(self
):
1753 with self
.assertCalls(
1754 (self
.call
.device
._RunPipedShellCommand
(
1755 'showmap 4321 | grep TOTAL', as_root
=True),
1756 ['100 101 102 103 104 105 106 107 TOTAL']),
1757 (self
.call
.device
.ReadFile('/proc/4321/status', as_root
=True),
1758 self
.CommandError())):
1764 'Shared_Clean': 103,
1765 'Shared_Dirty': 104,
1766 'Private_Clean': 105,
1767 'Private_Dirty': 106,
1769 self
.device
.GetMemoryUsageForPid(4321))
1772 class DeviceUtilsClientCache(DeviceUtilsTest
):
1774 def testClientCache_twoCaches(self
):
1775 self
.device
._cache
['test'] = 0
1776 client_cache_one
= self
.device
.GetClientCache('ClientOne')
1777 client_cache_one
['test'] = 1
1778 client_cache_two
= self
.device
.GetClientCache('ClientTwo')
1779 client_cache_two
['test'] = 2
1780 self
.assertEqual(self
.device
._cache
, {'test': 0})
1781 self
.assertEqual(client_cache_one
, {'test': 1})
1782 self
.assertEqual(client_cache_two
, {'test': 2})
1783 self
.device
._ClearCache
()
1784 self
.assertEqual(self
.device
._cache
, {})
1785 self
.assertEqual(client_cache_one
, {})
1786 self
.assertEqual(client_cache_two
, {})
1788 def testClientCache_multipleInstances(self
):
1789 client_cache_one
= self
.device
.GetClientCache('ClientOne')
1790 client_cache_one
['test'] = 1
1791 client_cache_two
= self
.device
.GetClientCache('ClientOne')
1792 self
.assertEqual(client_cache_one
, {'test': 1})
1793 self
.assertEqual(client_cache_two
, {'test': 1})
1794 self
.device
._ClearCache
()
1795 self
.assertEqual(client_cache_one
, {})
1796 self
.assertEqual(client_cache_two
, {})
1799 class DeviceUtilsParallelTest(mock_calls
.TestCase
):
1801 def testParallel_default(self
):
1802 test_serials
= ['0123456789abcdef', 'fedcba9876543210']
1803 with self
.assertCall(
1804 mock
.call
.pylib
.device
.device_utils
.DeviceUtils
.HealthyDevices(),
1805 [device_utils
.DeviceUtils(s
) for s
in test_serials
]):
1806 parallel_devices
= device_utils
.DeviceUtils
.parallel()
1807 for serial
, device
in zip(test_serials
, parallel_devices
.pGet(None)):
1808 self
.assertTrue(isinstance(device
, device_utils
.DeviceUtils
))
1809 self
.assertEquals(serial
, device
.adb
.GetDeviceSerial())
1811 def testParallel_noDevices(self
):
1812 with self
.assertCall(
1813 mock
.call
.pylib
.device
.device_utils
.DeviceUtils
.HealthyDevices(), []):
1814 with self
.assertRaises(device_errors
.NoDevicesError
):
1815 device_utils
.DeviceUtils
.parallel()
1818 class DeviceUtilsHealthyDevicesTest(mock_calls
.TestCase
):
1820 def _createAdbWrapperMock(self
, serial
, is_ready
=True):
1821 adb
= _AdbWrapperMock(serial
)
1822 adb
.is_ready
= is_ready
1825 def testHealthyDevices_default(self
):
1826 test_serials
= ['0123456789abcdef', 'fedcba9876543210']
1827 with self
.assertCalls(
1828 (mock
.call
.pylib
.device
.device_blacklist
.ReadBlacklist(), []),
1829 (mock
.call
.pylib
.device
.adb_wrapper
.AdbWrapper
.Devices(),
1830 [self
._createAdbWrapperMock
(s
) for s
in test_serials
])):
1831 devices
= device_utils
.DeviceUtils
.HealthyDevices()
1832 for serial
, device
in zip(test_serials
, devices
):
1833 self
.assertTrue(isinstance(device
, device_utils
.DeviceUtils
))
1834 self
.assertEquals(serial
, device
.adb
.GetDeviceSerial())
1836 def testHealthyDevices_blacklisted(self
):
1837 test_serials
= ['0123456789abcdef', 'fedcba9876543210']
1838 with self
.assertCalls(
1839 (mock
.call
.pylib
.device
.device_blacklist
.ReadBlacklist(),
1840 ['fedcba9876543210']),
1841 (mock
.call
.pylib
.device
.adb_wrapper
.AdbWrapper
.Devices(),
1842 [self
._createAdbWrapperMock
(s
) for s
in test_serials
])):
1843 devices
= device_utils
.DeviceUtils
.HealthyDevices()
1844 self
.assertEquals(1, len(devices
))
1845 self
.assertTrue(isinstance(devices
[0], device_utils
.DeviceUtils
))
1846 self
.assertEquals('0123456789abcdef', devices
[0].adb
.GetDeviceSerial())
1849 if __name__
== '__main__':
1850 logging
.getLogger().setLevel(logging
.DEBUG
)
1851 unittest
.main(verbosity
=2)