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
.utils
import mock_calls
32 # RunCommand from third_party/android_testrunner/run_command.py is mocked
33 # below, so its path needs to be in sys.path.
34 sys
.path
.append(os
.path
.join(
35 constants
.DIR_SOURCE_ROOT
, 'third_party', 'android_testrunner'))
37 sys
.path
.append(os
.path
.join(
38 constants
.DIR_SOURCE_ROOT
, 'third_party', 'pymock'))
39 import mock
# pylint: disable=F0401
42 class DeviceUtilsInitTest(unittest
.TestCase
):
44 def testInitWithStr(self
):
45 serial_as_str
= str('0123456789abcdef')
46 d
= device_utils
.DeviceUtils('0123456789abcdef')
47 self
.assertEqual(serial_as_str
, d
.adb
.GetDeviceSerial())
49 def testInitWithUnicode(self
):
50 serial_as_unicode
= unicode('fedcba9876543210')
51 d
= device_utils
.DeviceUtils(serial_as_unicode
)
52 self
.assertEqual(serial_as_unicode
, d
.adb
.GetDeviceSerial())
54 def testInitWithAdbWrapper(self
):
55 serial
= '123456789abcdef0'
56 a
= adb_wrapper
.AdbWrapper(serial
)
57 d
= device_utils
.DeviceUtils(a
)
58 self
.assertEqual(serial
, d
.adb
.GetDeviceSerial())
60 def testInitWithAndroidCommands(self
):
61 serial
= '0fedcba987654321'
62 a
= android_commands
.AndroidCommands(device
=serial
)
63 d
= device_utils
.DeviceUtils(a
)
64 self
.assertEqual(serial
, d
.adb
.GetDeviceSerial())
66 def testInitWithMissing_fails(self
):
67 with self
.assertRaises(ValueError):
68 device_utils
.DeviceUtils(None)
69 with self
.assertRaises(ValueError):
70 device_utils
.DeviceUtils('')
73 class DeviceUtilsGetAVDsTest(mock_calls
.TestCase
):
75 def testGetAVDs(self
):
77 mock
.call
.pylib
.cmd_helper
.GetCmdOutput([mock
.ANY
, 'list', 'avd']),
78 'Available Android Virtual Devices:\n'
79 ' Name: my_android5.0\n'
80 ' Path: /some/path/to/.android/avd/my_android5.0.avd\n'
81 ' Target: Android 5.0 (API level 21)\n'
82 ' Tag/ABI: default/x86\n'
84 self
.assertEquals(['my_android5.0'],
85 device_utils
.GetAVDs())
88 class DeviceUtilsRestartServerTest(mock_calls
.TestCase
):
90 @mock.patch('time.sleep', mock
.Mock())
91 def testRestartServer_succeeds(self
):
92 with self
.assertCalls(
93 mock
.call
.pylib
.device
.adb_wrapper
.AdbWrapper
.KillServer(),
94 (mock
.call
.pylib
.cmd_helper
.GetCmdStatusAndOutput(['pgrep', 'adb']),
96 mock
.call
.pylib
.device
.adb_wrapper
.AdbWrapper
.StartServer(),
97 (mock
.call
.pylib
.cmd_helper
.GetCmdStatusAndOutput(['pgrep', 'adb']),
99 (mock
.call
.pylib
.cmd_helper
.GetCmdStatusAndOutput(['pgrep', 'adb']),
101 device_utils
.RestartServer()
104 class MockTempFile(object):
106 def __init__(self
, name
='/tmp/some/file'):
107 self
.file = mock
.MagicMock(spec
=file)
108 self
.file.name
= name
109 self
.file.name_quoted
= cmd_helper
.SingleQuote(name
)
114 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
119 return self
.file.name
122 class _PatchedFunction(object):
123 def __init__(self
, patched
=None, mocked
=None):
124 self
.patched
= patched
128 def _AdbWrapperMock(test_serial
):
129 adb
= mock
.Mock(spec
=adb_wrapper
.AdbWrapper
)
130 adb
.__str
__ = mock
.Mock(return_value
=test_serial
)
131 adb
.GetDeviceSerial
.return_value
= test_serial
135 class DeviceUtilsTest(mock_calls
.TestCase
):
138 self
.adb
= _AdbWrapperMock('0123456789abcdef')
139 self
.device
= device_utils
.DeviceUtils(
140 self
.adb
, default_timeout
=10, default_retries
=0)
141 self
.watchMethodCalls(self
.call
.adb
, ignore
=['GetDeviceSerial'])
143 def ShellError(self
, output
=None, status
=1):
144 def action(cmd
, *args
, **kwargs
):
145 raise device_errors
.AdbShellCommandFailedError(
146 cmd
, output
, status
, str(self
.device
))
148 output
= 'Permission denied\n'
151 def TimeoutError(self
, msg
=None):
153 msg
= 'Operation timed out'
154 return mock
.Mock(side_effect
=device_errors
.CommandTimeoutError(
155 msg
, str(self
.device
)))
157 def CommandError(self
, msg
=None):
159 msg
= 'Command failed'
160 return mock
.Mock(side_effect
=device_errors
.CommandFailedError(
161 msg
, str(self
.device
)))
164 class DeviceUtilsEqTest(DeviceUtilsTest
):
166 def testEq_equal_deviceUtils(self
):
167 other
= device_utils
.DeviceUtils(_AdbWrapperMock('0123456789abcdef'))
168 self
.assertTrue(self
.device
== other
)
169 self
.assertTrue(other
== self
.device
)
171 def testEq_equal_adbWrapper(self
):
172 other
= adb_wrapper
.AdbWrapper('0123456789abcdef')
173 self
.assertTrue(self
.device
== other
)
174 self
.assertTrue(other
== self
.device
)
176 def testEq_equal_string(self
):
177 other
= '0123456789abcdef'
178 self
.assertTrue(self
.device
== other
)
179 self
.assertTrue(other
== self
.device
)
181 def testEq_devicesNotEqual(self
):
182 other
= device_utils
.DeviceUtils(_AdbWrapperMock('0123456789abcdee'))
183 self
.assertFalse(self
.device
== other
)
184 self
.assertFalse(other
== self
.device
)
186 def testEq_identity(self
):
187 self
.assertTrue(self
.device
== self
.device
)
189 def testEq_serialInList(self
):
190 devices
= [self
.device
]
191 self
.assertTrue('0123456789abcdef' in devices
)
194 class DeviceUtilsLtTest(DeviceUtilsTest
):
196 def testLt_lessThan(self
):
197 other
= device_utils
.DeviceUtils(_AdbWrapperMock('ffffffffffffffff'))
198 self
.assertTrue(self
.device
< other
)
199 self
.assertTrue(other
> self
.device
)
201 def testLt_greaterThan_lhs(self
):
202 other
= device_utils
.DeviceUtils(_AdbWrapperMock('0000000000000000'))
203 self
.assertFalse(self
.device
< other
)
204 self
.assertFalse(other
> self
.device
)
206 def testLt_equal(self
):
207 other
= device_utils
.DeviceUtils(_AdbWrapperMock('0123456789abcdef'))
208 self
.assertFalse(self
.device
< other
)
209 self
.assertFalse(other
> self
.device
)
211 def testLt_sorted(self
):
213 device_utils
.DeviceUtils(_AdbWrapperMock('ffffffffffffffff')),
214 device_utils
.DeviceUtils(_AdbWrapperMock('0000000000000000')),
216 sorted_devices
= sorted(devices
)
217 self
.assertEquals('0000000000000000',
218 sorted_devices
[0].adb
.GetDeviceSerial())
219 self
.assertEquals('ffffffffffffffff',
220 sorted_devices
[1].adb
.GetDeviceSerial())
223 class DeviceUtilsStrTest(DeviceUtilsTest
):
225 def testStr_returnsSerial(self
):
226 with self
.assertCalls(
227 (self
.call
.adb
.GetDeviceSerial(), '0123456789abcdef')):
228 self
.assertEqual('0123456789abcdef', str(self
.device
))
231 class DeviceUtilsIsOnlineTest(DeviceUtilsTest
):
233 def testIsOnline_true(self
):
234 with self
.assertCall(self
.call
.adb
.GetState(), 'device'):
235 self
.assertTrue(self
.device
.IsOnline())
237 def testIsOnline_false(self
):
238 with self
.assertCall(self
.call
.adb
.GetState(), 'offline'):
239 self
.assertFalse(self
.device
.IsOnline())
241 def testIsOnline_error(self
):
242 with self
.assertCall(self
.call
.adb
.GetState(), self
.CommandError()):
243 self
.assertFalse(self
.device
.IsOnline())
246 class DeviceUtilsHasRootTest(DeviceUtilsTest
):
248 def testHasRoot_true(self
):
249 with self
.assertCall(self
.call
.adb
.Shell('ls /root'), 'foo\n'):
250 self
.assertTrue(self
.device
.HasRoot())
252 def testHasRoot_false(self
):
253 with self
.assertCall(self
.call
.adb
.Shell('ls /root'), self
.ShellError()):
254 self
.assertFalse(self
.device
.HasRoot())
257 class DeviceUtilsEnableRootTest(DeviceUtilsTest
):
259 def testEnableRoot_succeeds(self
):
260 with self
.assertCalls(
261 (self
.call
.device
.IsUserBuild(), False),
262 self
.call
.adb
.Root(),
263 self
.call
.adb
.WaitForDevice()):
264 self
.device
.EnableRoot()
266 def testEnableRoot_userBuild(self
):
267 with self
.assertCalls(
268 (self
.call
.device
.IsUserBuild(), True)):
269 with self
.assertRaises(device_errors
.CommandFailedError
):
270 self
.device
.EnableRoot()
272 def testEnableRoot_rootFails(self
):
273 with self
.assertCalls(
274 (self
.call
.device
.IsUserBuild(), False),
275 (self
.call
.adb
.Root(), self
.CommandError())):
276 with self
.assertRaises(device_errors
.CommandFailedError
):
277 self
.device
.EnableRoot()
280 class DeviceUtilsIsUserBuildTest(DeviceUtilsTest
):
282 def testIsUserBuild_yes(self
):
283 with self
.assertCall(
284 self
.call
.device
.GetProp('ro.build.type', cache
=True), 'user'):
285 self
.assertTrue(self
.device
.IsUserBuild())
287 def testIsUserBuild_no(self
):
288 with self
.assertCall(
289 self
.call
.device
.GetProp('ro.build.type', cache
=True), 'userdebug'):
290 self
.assertFalse(self
.device
.IsUserBuild())
293 class DeviceUtilsGetExternalStoragePathTest(DeviceUtilsTest
):
295 def testGetExternalStoragePath_succeeds(self
):
296 with self
.assertCall(
297 self
.call
.adb
.Shell('echo $EXTERNAL_STORAGE'), '/fake/storage/path\n'):
298 self
.assertEquals('/fake/storage/path',
299 self
.device
.GetExternalStoragePath())
301 def testGetExternalStoragePath_fails(self
):
302 with self
.assertCall(self
.call
.adb
.Shell('echo $EXTERNAL_STORAGE'), '\n'):
303 with self
.assertRaises(device_errors
.CommandFailedError
):
304 self
.device
.GetExternalStoragePath()
307 class DeviceUtilsGetApplicationPathTest(DeviceUtilsTest
):
309 def testGetApplicationPath_exists(self
):
310 with self
.assertCalls(
311 (self
.call
.adb
.Shell('getprop ro.build.version.sdk'), '19\n'),
312 (self
.call
.adb
.Shell('pm path android'),
313 'package:/path/to/android.apk\n')):
314 self
.assertEquals('/path/to/android.apk',
315 self
.device
.GetApplicationPath('android'))
317 def testGetApplicationPath_notExists(self
):
318 with self
.assertCalls(
319 (self
.call
.adb
.Shell('getprop ro.build.version.sdk'), '19\n'),
320 (self
.call
.adb
.Shell('pm path not.installed.app'), '')):
321 self
.assertEquals(None,
322 self
.device
.GetApplicationPath('not.installed.app'))
324 def testGetApplicationPath_fails(self
):
325 with self
.assertCalls(
326 (self
.call
.adb
.Shell('getprop ro.build.version.sdk'), '19\n'),
327 (self
.call
.adb
.Shell('pm path android'),
328 self
.CommandError('ERROR. Is package manager running?\n'))):
329 with self
.assertRaises(device_errors
.CommandFailedError
):
330 self
.device
.GetApplicationPath('android')
333 @mock.patch('time.sleep', mock
.Mock())
334 class DeviceUtilsWaitUntilFullyBootedTest(DeviceUtilsTest
):
336 def testWaitUntilFullyBooted_succeedsNoWifi(self
):
337 with self
.assertCalls(
338 self
.call
.adb
.WaitForDevice(),
340 (self
.call
.device
.GetExternalStoragePath(), '/fake/storage/path'),
341 (self
.call
.adb
.Shell('test -d /fake/storage/path'), ''),
343 (self
.call
.device
.GetApplicationPath('android'),
344 'package:/some/fake/path'),
346 (self
.call
.device
.GetProp('sys.boot_completed'), '1')):
347 self
.device
.WaitUntilFullyBooted(wifi
=False)
349 def testWaitUntilFullyBooted_succeedsWithWifi(self
):
350 with self
.assertCalls(
351 self
.call
.adb
.WaitForDevice(),
353 (self
.call
.device
.GetExternalStoragePath(), '/fake/storage/path'),
354 (self
.call
.adb
.Shell('test -d /fake/storage/path'), ''),
356 (self
.call
.device
.GetApplicationPath('android'),
357 'package:/some/fake/path'),
359 (self
.call
.device
.GetProp('sys.boot_completed'), '1'),
361 (self
.call
.adb
.Shell('dumpsys wifi'),
362 'stuff\nWi-Fi is enabled\nmore stuff\n')):
363 self
.device
.WaitUntilFullyBooted(wifi
=True)
365 def testWaitUntilFullyBooted_sdCardReadyFails_noPath(self
):
366 with self
.assertCalls(
367 self
.call
.adb
.WaitForDevice(),
369 (self
.call
.device
.GetExternalStoragePath(), self
.CommandError())):
370 with self
.assertRaises(device_errors
.CommandFailedError
):
371 self
.device
.WaitUntilFullyBooted(wifi
=False)
373 def testWaitUntilFullyBooted_sdCardReadyFails_notExists(self
):
374 with self
.assertCalls(
375 self
.call
.adb
.WaitForDevice(),
377 (self
.call
.device
.GetExternalStoragePath(), '/fake/storage/path'),
378 (self
.call
.adb
.Shell('test -d /fake/storage/path'), self
.ShellError()),
380 (self
.call
.device
.GetExternalStoragePath(), '/fake/storage/path'),
381 (self
.call
.adb
.Shell('test -d /fake/storage/path'), self
.ShellError()),
383 (self
.call
.device
.GetExternalStoragePath(), '/fake/storage/path'),
384 (self
.call
.adb
.Shell('test -d /fake/storage/path'),
385 self
.TimeoutError())):
386 with self
.assertRaises(device_errors
.CommandTimeoutError
):
387 self
.device
.WaitUntilFullyBooted(wifi
=False)
389 def testWaitUntilFullyBooted_devicePmFails(self
):
390 with self
.assertCalls(
391 self
.call
.adb
.WaitForDevice(),
393 (self
.call
.device
.GetExternalStoragePath(), '/fake/storage/path'),
394 (self
.call
.adb
.Shell('test -d /fake/storage/path'), ''),
396 (self
.call
.device
.GetApplicationPath('android'), self
.CommandError()),
398 (self
.call
.device
.GetApplicationPath('android'), self
.CommandError()),
400 (self
.call
.device
.GetApplicationPath('android'), self
.TimeoutError())):
401 with self
.assertRaises(device_errors
.CommandTimeoutError
):
402 self
.device
.WaitUntilFullyBooted(wifi
=False)
404 def testWaitUntilFullyBooted_bootFails(self
):
405 with self
.assertCalls(
406 self
.call
.adb
.WaitForDevice(),
408 (self
.call
.device
.GetExternalStoragePath(), '/fake/storage/path'),
409 (self
.call
.adb
.Shell('test -d /fake/storage/path'), ''),
411 (self
.call
.device
.GetApplicationPath('android'),
412 'package:/some/fake/path'),
414 (self
.call
.device
.GetProp('sys.boot_completed'), '0'),
416 (self
.call
.device
.GetProp('sys.boot_completed'), '0'),
418 (self
.call
.device
.GetProp('sys.boot_completed'), self
.TimeoutError())):
419 with self
.assertRaises(device_errors
.CommandTimeoutError
):
420 self
.device
.WaitUntilFullyBooted(wifi
=False)
422 def testWaitUntilFullyBooted_wifiFails(self
):
423 with self
.assertCalls(
424 self
.call
.adb
.WaitForDevice(),
426 (self
.call
.device
.GetExternalStoragePath(), '/fake/storage/path'),
427 (self
.call
.adb
.Shell('test -d /fake/storage/path'), ''),
429 (self
.call
.device
.GetApplicationPath('android'),
430 'package:/some/fake/path'),
432 (self
.call
.device
.GetProp('sys.boot_completed'), '1'),
434 (self
.call
.adb
.Shell('dumpsys wifi'), 'stuff\nmore stuff\n'),
436 (self
.call
.adb
.Shell('dumpsys wifi'), 'stuff\nmore stuff\n'),
438 (self
.call
.adb
.Shell('dumpsys wifi'), self
.TimeoutError())):
439 with self
.assertRaises(device_errors
.CommandTimeoutError
):
440 self
.device
.WaitUntilFullyBooted(wifi
=True)
443 @mock.patch('time.sleep', mock
.Mock())
444 class DeviceUtilsRebootTest(DeviceUtilsTest
):
446 def testReboot_nonBlocking(self
):
447 with self
.assertCalls(
448 self
.call
.adb
.Reboot(),
449 (self
.call
.device
.IsOnline(), True),
450 (self
.call
.device
.IsOnline(), False)):
451 self
.device
.Reboot(block
=False)
453 def testReboot_blocking(self
):
454 with self
.assertCalls(
455 self
.call
.adb
.Reboot(),
456 (self
.call
.device
.IsOnline(), True),
457 (self
.call
.device
.IsOnline(), False),
458 self
.call
.device
.WaitUntilFullyBooted(wifi
=False)):
459 self
.device
.Reboot(block
=True)
461 def testReboot_blockUntilWifi(self
):
462 with self
.assertCalls(
463 self
.call
.adb
.Reboot(),
464 (self
.call
.device
.IsOnline(), True),
465 (self
.call
.device
.IsOnline(), False),
466 self
.call
.device
.WaitUntilFullyBooted(wifi
=True)):
467 self
.device
.Reboot(block
=True, wifi
=True)
470 class DeviceUtilsInstallTest(DeviceUtilsTest
):
472 def testInstall_noPriorInstall(self
):
473 with self
.assertCalls(
474 (mock
.call
.pylib
.utils
.apk_helper
.GetPackageName('/fake/test/app.apk'),
475 'this.is.a.test.package'),
476 (self
.call
.device
.GetApplicationPath('this.is.a.test.package'), None),
477 self
.call
.adb
.Install('/fake/test/app.apk', reinstall
=False)):
478 self
.device
.Install('/fake/test/app.apk', retries
=0)
480 def testInstall_differentPriorInstall(self
):
481 with self
.assertCalls(
482 (mock
.call
.pylib
.utils
.apk_helper
.GetPackageName('/fake/test/app.apk'),
483 'this.is.a.test.package'),
484 (self
.call
.device
.GetApplicationPath('this.is.a.test.package'),
485 '/fake/data/app/this.is.a.test.package.apk'),
486 (self
.call
.device
._GetChangedFilesImpl
(
487 '/fake/test/app.apk', '/fake/data/app/this.is.a.test.package.apk'),
488 [('/fake/test/app.apk', '/fake/data/app/this.is.a.test.package.apk')]),
489 self
.call
.adb
.Uninstall('this.is.a.test.package'),
490 self
.call
.adb
.Install('/fake/test/app.apk', reinstall
=False)):
491 self
.device
.Install('/fake/test/app.apk', retries
=0)
493 def testInstall_differentPriorInstall_reinstall(self
):
494 with self
.assertCalls(
495 (mock
.call
.pylib
.utils
.apk_helper
.GetPackageName('/fake/test/app.apk'),
496 'this.is.a.test.package'),
497 (self
.call
.device
.GetApplicationPath('this.is.a.test.package'),
498 '/fake/data/app/this.is.a.test.package.apk'),
499 (self
.call
.device
._GetChangedFilesImpl
(
500 '/fake/test/app.apk', '/fake/data/app/this.is.a.test.package.apk'),
501 [('/fake/test/app.apk', '/fake/data/app/this.is.a.test.package.apk')]),
502 self
.call
.adb
.Install('/fake/test/app.apk', reinstall
=True)):
503 self
.device
.Install('/fake/test/app.apk', reinstall
=True, retries
=0)
505 def testInstall_identicalPriorInstall(self
):
506 with self
.assertCalls(
507 (mock
.call
.pylib
.utils
.apk_helper
.GetPackageName('/fake/test/app.apk'),
508 'this.is.a.test.package'),
509 (self
.call
.device
.GetApplicationPath('this.is.a.test.package'),
510 '/fake/data/app/this.is.a.test.package.apk'),
511 (self
.call
.device
._GetChangedFilesImpl
(
512 '/fake/test/app.apk', '/fake/data/app/this.is.a.test.package.apk'),
514 self
.device
.Install('/fake/test/app.apk', retries
=0)
516 def testInstall_fails(self
):
517 with self
.assertCalls(
518 (mock
.call
.pylib
.utils
.apk_helper
.GetPackageName('/fake/test/app.apk'),
519 'this.is.a.test.package'),
520 (self
.call
.device
.GetApplicationPath('this.is.a.test.package'), None),
521 (self
.call
.adb
.Install('/fake/test/app.apk', reinstall
=False),
522 self
.CommandError('Failure\r\n'))):
523 with self
.assertRaises(device_errors
.CommandFailedError
):
524 self
.device
.Install('/fake/test/app.apk', retries
=0)
527 class DeviceUtilsRunShellCommandTest(DeviceUtilsTest
):
530 super(DeviceUtilsRunShellCommandTest
, self
).setUp()
531 self
.device
.NeedsSU
= mock
.Mock(return_value
=False)
533 def testRunShellCommand_commandAsList(self
):
534 with self
.assertCall(self
.call
.adb
.Shell('pm list packages'), ''):
535 self
.device
.RunShellCommand(['pm', 'list', 'packages'])
537 def testRunShellCommand_commandAsListQuoted(self
):
538 with self
.assertCall(self
.call
.adb
.Shell("echo 'hello world' '$10'"), ''):
539 self
.device
.RunShellCommand(['echo', 'hello world', '$10'])
541 def testRunShellCommand_commandAsString(self
):
542 with self
.assertCall(self
.call
.adb
.Shell('echo "$VAR"'), ''):
543 self
.device
.RunShellCommand('echo "$VAR"')
545 def testNewRunShellImpl_withEnv(self
):
546 with self
.assertCall(
547 self
.call
.adb
.Shell('VAR=some_string echo "$VAR"'), ''):
548 self
.device
.RunShellCommand('echo "$VAR"', env
={'VAR': 'some_string'})
550 def testNewRunShellImpl_withEnvQuoted(self
):
551 with self
.assertCall(
552 self
.call
.adb
.Shell('PATH="$PATH:/other/path" run_this'), ''):
553 self
.device
.RunShellCommand('run_this', env
={'PATH': '$PATH:/other/path'})
555 def testNewRunShellImpl_withEnv_failure(self
):
556 with self
.assertRaises(KeyError):
557 self
.device
.RunShellCommand('some_cmd', env
={'INVALID NAME': 'value'})
559 def testNewRunShellImpl_withCwd(self
):
560 with self
.assertCall(self
.call
.adb
.Shell('cd /some/test/path && ls'), ''):
561 self
.device
.RunShellCommand('ls', cwd
='/some/test/path')
563 def testNewRunShellImpl_withCwdQuoted(self
):
564 with self
.assertCall(
565 self
.call
.adb
.Shell("cd '/some test/path with/spaces' && ls"), ''):
566 self
.device
.RunShellCommand('ls', cwd
='/some test/path with/spaces')
568 def testRunShellCommand_withHugeCmd(self
):
569 payload
= 'hi! ' * 1024
570 expected_cmd
= "echo '%s'" % payload
571 with self
.assertCalls(
572 (mock
.call
.pylib
.utils
.device_temp_file
.DeviceTempFile(
573 self
.adb
, suffix
='.sh'), MockTempFile('/sdcard/temp-123.sh')),
574 self
.call
.device
._WriteFileWithPush
('/sdcard/temp-123.sh', expected_cmd
),
575 (self
.call
.adb
.Shell('sh /sdcard/temp-123.sh'), payload
+ '\n')):
576 self
.assertEquals([payload
],
577 self
.device
.RunShellCommand(['echo', payload
]))
579 def testRunShellCommand_withHugeCmdAmdSU(self
):
580 payload
= 'hi! ' * 1024
581 expected_cmd
= """su -c sh -c 'echo '"'"'%s'"'"''""" % payload
582 with self
.assertCalls(
583 (self
.call
.device
.NeedsSU(), True),
584 (mock
.call
.pylib
.utils
.device_temp_file
.DeviceTempFile(
585 self
.adb
, suffix
='.sh'), MockTempFile('/sdcard/temp-123.sh')),
586 self
.call
.device
._WriteFileWithPush
('/sdcard/temp-123.sh', expected_cmd
),
587 (self
.call
.adb
.Shell('sh /sdcard/temp-123.sh'), payload
+ '\n')):
590 self
.device
.RunShellCommand(['echo', payload
], as_root
=True))
592 def testRunShellCommand_withSu(self
):
593 with self
.assertCalls(
594 (self
.call
.device
.NeedsSU(), True),
595 (self
.call
.adb
.Shell("su -c sh -c 'setprop service.adb.root 0'"), '')):
596 self
.device
.RunShellCommand('setprop service.adb.root 0', as_root
=True)
598 def testRunShellCommand_manyLines(self
):
599 cmd
= 'ls /some/path'
600 with self
.assertCall(self
.call
.adb
.Shell(cmd
), 'file1\nfile2\nfile3\n'):
601 self
.assertEquals(['file1', 'file2', 'file3'],
602 self
.device
.RunShellCommand(cmd
))
604 def testRunShellCommand_singleLine_success(self
):
606 with self
.assertCall(self
.call
.adb
.Shell(cmd
), 'some value\n'):
607 self
.assertEquals('some value',
608 self
.device
.RunShellCommand(cmd
, single_line
=True))
610 def testRunShellCommand_singleLine_successEmptyLine(self
):
612 with self
.assertCall(self
.call
.adb
.Shell(cmd
), '\n'):
613 self
.assertEquals('',
614 self
.device
.RunShellCommand(cmd
, single_line
=True))
616 def testRunShellCommand_singleLine_successWithoutEndLine(self
):
617 cmd
= 'echo -n $VALUE'
618 with self
.assertCall(self
.call
.adb
.Shell(cmd
), 'some value'):
619 self
.assertEquals('some value',
620 self
.device
.RunShellCommand(cmd
, single_line
=True))
622 def testRunShellCommand_singleLine_successNoOutput(self
):
623 cmd
= 'echo -n $VALUE'
624 with self
.assertCall(self
.call
.adb
.Shell(cmd
), ''):
625 self
.assertEquals('',
626 self
.device
.RunShellCommand(cmd
, single_line
=True))
628 def testRunShellCommand_singleLine_failTooManyLines(self
):
630 with self
.assertCall(self
.call
.adb
.Shell(cmd
),
631 'some value\nanother value\n'):
632 with self
.assertRaises(device_errors
.CommandFailedError
):
633 self
.device
.RunShellCommand(cmd
, single_line
=True)
635 def testRunShellCommand_checkReturn_success(self
):
636 cmd
= 'echo $ANDROID_DATA'
638 with self
.assertCall(self
.call
.adb
.Shell(cmd
), output
):
639 self
.assertEquals([output
.rstrip()],
640 self
.device
.RunShellCommand(cmd
, check_return
=True))
642 def testRunShellCommand_checkReturn_failure(self
):
644 output
= 'opendir failed, Permission denied\n'
645 with self
.assertCall(self
.call
.adb
.Shell(cmd
), self
.ShellError(output
)):
646 with self
.assertRaises(device_errors
.AdbCommandFailedError
):
647 self
.device
.RunShellCommand(cmd
, check_return
=True)
649 def testRunShellCommand_checkReturn_disabled(self
):
651 output
= 'opendir failed, Permission denied\n'
652 with self
.assertCall(self
.call
.adb
.Shell(cmd
), self
.ShellError(output
)):
653 self
.assertEquals([output
.rstrip()],
654 self
.device
.RunShellCommand(cmd
, check_return
=False))
656 def testRunShellCommand_largeOutput_enabled(self
):
658 temp_file
= MockTempFile('/sdcard/temp-123')
659 cmd_redirect
= '%s > %s' % (cmd
, temp_file
.name
)
660 with self
.assertCalls(
661 (mock
.call
.pylib
.utils
.device_temp_file
.DeviceTempFile(self
.adb
),
663 (self
.call
.adb
.Shell(cmd_redirect
)),
664 (self
.call
.device
.ReadFile(temp_file
.name
, force_pull
=True),
668 self
.device
.RunShellCommand(
669 cmd
, large_output
=True, check_return
=True))
671 def testRunShellCommand_largeOutput_disabledNoTrigger(self
):
673 with self
.assertCall(self
.call
.adb
.Shell(cmd
), self
.ShellError('')):
674 with self
.assertRaises(device_errors
.AdbCommandFailedError
):
675 self
.device
.RunShellCommand(cmd
, check_return
=True)
677 def testRunShellCommand_largeOutput_disabledTrigger(self
):
679 temp_file
= MockTempFile('/sdcard/temp-123')
680 cmd_redirect
= '%s > %s' % (cmd
, temp_file
.name
)
681 with self
.assertCalls(
682 (self
.call
.adb
.Shell(cmd
), self
.ShellError('', None)),
683 (mock
.call
.pylib
.utils
.device_temp_file
.DeviceTempFile(self
.adb
),
685 (self
.call
.adb
.Shell(cmd_redirect
)),
686 (self
.call
.device
.ReadFile(mock
.ANY
, force_pull
=True),
688 self
.assertEquals(['something'],
689 self
.device
.RunShellCommand(cmd
, check_return
=True))
692 class DeviceUtilsRunPipedShellCommandTest(DeviceUtilsTest
):
694 def testRunPipedShellCommand_success(self
):
695 with self
.assertCall(
696 self
.call
.device
.RunShellCommand(
697 'ps | grep foo; echo "PIPESTATUS: ${PIPESTATUS[@]}"',
699 ['This line contains foo', 'PIPESTATUS: 0 0']):
700 self
.assertEquals(['This line contains foo'],
701 self
.device
._RunPipedShellCommand
('ps | grep foo'))
703 def testRunPipedShellCommand_firstCommandFails(self
):
704 with self
.assertCall(
705 self
.call
.device
.RunShellCommand(
706 'ps | grep foo; echo "PIPESTATUS: ${PIPESTATUS[@]}"',
708 ['PIPESTATUS: 1 0']):
709 with self
.assertRaises(device_errors
.AdbShellCommandFailedError
) as ec
:
710 self
.device
._RunPipedShellCommand
('ps | grep foo')
711 self
.assertEquals([1, 0], ec
.exception
.status
)
713 def testRunPipedShellCommand_secondCommandFails(self
):
714 with self
.assertCall(
715 self
.call
.device
.RunShellCommand(
716 'ps | grep foo; echo "PIPESTATUS: ${PIPESTATUS[@]}"',
718 ['PIPESTATUS: 0 1']):
719 with self
.assertRaises(device_errors
.AdbShellCommandFailedError
) as ec
:
720 self
.device
._RunPipedShellCommand
('ps | grep foo')
721 self
.assertEquals([0, 1], ec
.exception
.status
)
723 def testRunPipedShellCommand_outputCutOff(self
):
724 with self
.assertCall(
725 self
.call
.device
.RunShellCommand(
726 'ps | grep foo; echo "PIPESTATUS: ${PIPESTATUS[@]}"',
728 ['foo.bar'] * 256 + ['foo.ba']):
729 with self
.assertRaises(device_errors
.AdbShellCommandFailedError
) as ec
:
730 self
.device
._RunPipedShellCommand
('ps | grep foo')
731 self
.assertIs(None, ec
.exception
.status
)
734 @mock.patch('time.sleep', mock
.Mock())
735 class DeviceUtilsKillAllTest(DeviceUtilsTest
):
737 def testKillAll_noMatchingProcessesFailure(self
):
738 with self
.assertCall(self
.call
.device
.GetPids('test_process'), {}):
739 with self
.assertRaises(device_errors
.CommandFailedError
):
740 self
.device
.KillAll('test_process')
742 def testKillAll_noMatchingProcessesQuiet(self
):
743 with self
.assertCall(self
.call
.device
.GetPids('test_process'), {}):
744 self
.assertEqual(0, self
.device
.KillAll('test_process', quiet
=True))
746 def testKillAll_nonblocking(self
):
747 with self
.assertCalls(
748 (self
.call
.device
.GetPids('some.process'), {'some.process': '1234'}),
749 (self
.call
.adb
.Shell('kill -9 1234'), '')):
751 1, self
.device
.KillAll('some.process', blocking
=False))
753 def testKillAll_blocking(self
):
754 with self
.assertCalls(
755 (self
.call
.device
.GetPids('some.process'), {'some.process': '1234'}),
756 (self
.call
.adb
.Shell('kill -9 1234'), ''),
757 (self
.call
.device
.GetPids('some.process'), {'some.process': '1234'}),
758 (self
.call
.device
.GetPids('some.process'), [])):
760 1, self
.device
.KillAll('some.process', blocking
=True))
762 def testKillAll_root(self
):
763 with self
.assertCalls(
764 (self
.call
.device
.GetPids('some.process'), {'some.process': '1234'}),
765 (self
.call
.device
.NeedsSU(), True),
766 (self
.call
.adb
.Shell("su -c sh -c 'kill -9 1234'"), '')):
768 1, self
.device
.KillAll('some.process', as_root
=True))
770 def testKillAll_sigterm(self
):
771 with self
.assertCalls(
772 (self
.call
.device
.GetPids('some.process'), {'some.process': '1234'}),
773 (self
.call
.adb
.Shell('kill -15 1234'), '')):
775 1, self
.device
.KillAll('some.process', signum
=device_signal
.SIGTERM
))
778 class DeviceUtilsStartActivityTest(DeviceUtilsTest
):
780 def testStartActivity_actionOnly(self
):
781 test_intent
= intent
.Intent(action
='android.intent.action.VIEW')
782 with self
.assertCall(
783 self
.call
.adb
.Shell('am start '
784 '-a android.intent.action.VIEW'),
785 'Starting: Intent { act=android.intent.action.VIEW }'):
786 self
.device
.StartActivity(test_intent
)
788 def testStartActivity_success(self
):
789 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
790 package
='this.is.a.test.package',
792 with self
.assertCall(
793 self
.call
.adb
.Shell('am start '
794 '-a android.intent.action.VIEW '
795 '-n this.is.a.test.package/.Main'),
796 'Starting: Intent { act=android.intent.action.VIEW }'):
797 self
.device
.StartActivity(test_intent
)
799 def testStartActivity_failure(self
):
800 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
801 package
='this.is.a.test.package',
803 with self
.assertCall(
804 self
.call
.adb
.Shell('am start '
805 '-a android.intent.action.VIEW '
806 '-n this.is.a.test.package/.Main'),
807 'Error: Failed to start test activity'):
808 with self
.assertRaises(device_errors
.CommandFailedError
):
809 self
.device
.StartActivity(test_intent
)
811 def testStartActivity_blocking(self
):
812 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
813 package
='this.is.a.test.package',
815 with self
.assertCall(
816 self
.call
.adb
.Shell('am start '
818 '-a android.intent.action.VIEW '
819 '-n this.is.a.test.package/.Main'),
820 'Starting: Intent { act=android.intent.action.VIEW }'):
821 self
.device
.StartActivity(test_intent
, blocking
=True)
823 def testStartActivity_withCategory(self
):
824 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
825 package
='this.is.a.test.package',
827 category
='android.intent.category.HOME')
828 with self
.assertCall(
829 self
.call
.adb
.Shell('am start '
830 '-a android.intent.action.VIEW '
831 '-c android.intent.category.HOME '
832 '-n this.is.a.test.package/.Main'),
833 'Starting: Intent { act=android.intent.action.VIEW }'):
834 self
.device
.StartActivity(test_intent
)
836 def testStartActivity_withMultipleCategories(self
):
837 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
838 package
='this.is.a.test.package',
840 category
=['android.intent.category.HOME',
841 'android.intent.category.BROWSABLE'])
842 with self
.assertCall(
843 self
.call
.adb
.Shell('am start '
844 '-a android.intent.action.VIEW '
845 '-c android.intent.category.HOME '
846 '-c android.intent.category.BROWSABLE '
847 '-n this.is.a.test.package/.Main'),
848 'Starting: Intent { act=android.intent.action.VIEW }'):
849 self
.device
.StartActivity(test_intent
)
851 def testStartActivity_withData(self
):
852 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
853 package
='this.is.a.test.package',
855 data
='http://www.google.com/')
856 with self
.assertCall(
857 self
.call
.adb
.Shell('am start '
858 '-a android.intent.action.VIEW '
859 '-d http://www.google.com/ '
860 '-n this.is.a.test.package/.Main'),
861 'Starting: Intent { act=android.intent.action.VIEW }'):
862 self
.device
.StartActivity(test_intent
)
864 def testStartActivity_withStringExtra(self
):
865 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
866 package
='this.is.a.test.package',
868 extras
={'foo': 'test'})
869 with self
.assertCall(
870 self
.call
.adb
.Shell('am start '
871 '-a android.intent.action.VIEW '
872 '-n this.is.a.test.package/.Main '
874 'Starting: Intent { act=android.intent.action.VIEW }'):
875 self
.device
.StartActivity(test_intent
)
877 def testStartActivity_withBoolExtra(self
):
878 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
879 package
='this.is.a.test.package',
881 extras
={'foo': True})
882 with self
.assertCall(
883 self
.call
.adb
.Shell('am start '
884 '-a android.intent.action.VIEW '
885 '-n this.is.a.test.package/.Main '
887 'Starting: Intent { act=android.intent.action.VIEW }'):
888 self
.device
.StartActivity(test_intent
)
890 def testStartActivity_withIntExtra(self
):
891 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
892 package
='this.is.a.test.package',
895 with self
.assertCall(
896 self
.call
.adb
.Shell('am start '
897 '-a android.intent.action.VIEW '
898 '-n this.is.a.test.package/.Main '
900 'Starting: Intent { act=android.intent.action.VIEW }'):
901 self
.device
.StartActivity(test_intent
)
903 def testStartActivity_withTraceFile(self
):
904 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
905 package
='this.is.a.test.package',
907 with self
.assertCall(
908 self
.call
.adb
.Shell('am start '
909 '--start-profiler test_trace_file.out '
910 '-a android.intent.action.VIEW '
911 '-n this.is.a.test.package/.Main'),
912 'Starting: Intent { act=android.intent.action.VIEW }'):
913 self
.device
.StartActivity(test_intent
,
914 trace_file_name
='test_trace_file.out')
916 def testStartActivity_withForceStop(self
):
917 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
918 package
='this.is.a.test.package',
920 with self
.assertCall(
921 self
.call
.adb
.Shell('am start '
923 '-a android.intent.action.VIEW '
924 '-n this.is.a.test.package/.Main'),
925 'Starting: Intent { act=android.intent.action.VIEW }'):
926 self
.device
.StartActivity(test_intent
, force_stop
=True)
928 def testStartActivity_withFlags(self
):
929 test_intent
= intent
.Intent(action
='android.intent.action.VIEW',
930 package
='this.is.a.test.package',
933 with self
.assertCall(
934 self
.call
.adb
.Shell('am start '
935 '-a android.intent.action.VIEW '
936 '-n this.is.a.test.package/.Main '
938 'Starting: Intent { act=android.intent.action.VIEW }'):
939 self
.device
.StartActivity(test_intent
)
942 class DeviceUtilsStartInstrumentationTest(DeviceUtilsTest
):
944 def testStartInstrumentation_nothing(self
):
945 with self
.assertCalls(
946 self
.call
.device
.RunShellCommand(
947 ['am', 'instrument', 'test.package/.TestInstrumentation'],
949 self
.device
.StartInstrumentation(
950 'test.package/.TestInstrumentation',
951 finish
=False, raw
=False, extras
=None)
953 def testStartInstrumentation_finish(self
):
954 with self
.assertCalls(
955 (self
.call
.device
.RunShellCommand(
956 ['am', 'instrument', '-w', 'test.package/.TestInstrumentation'],
959 output
= self
.device
.StartInstrumentation(
960 'test.package/.TestInstrumentation',
961 finish
=True, raw
=False, extras
=None)
962 self
.assertEquals(['OK (1 test)'], output
)
964 def testStartInstrumentation_raw(self
):
965 with self
.assertCalls(
966 self
.call
.device
.RunShellCommand(
967 ['am', 'instrument', '-r', 'test.package/.TestInstrumentation'],
969 self
.device
.StartInstrumentation(
970 'test.package/.TestInstrumentation',
971 finish
=False, raw
=True, extras
=None)
973 def testStartInstrumentation_extras(self
):
974 with self
.assertCalls(
975 self
.call
.device
.RunShellCommand(
976 ['am', 'instrument', '-e', 'foo', 'Foo', '-e', 'bar', 'Bar',
977 'test.package/.TestInstrumentation'],
979 self
.device
.StartInstrumentation(
980 'test.package/.TestInstrumentation',
981 finish
=False, raw
=False, extras
={'foo': 'Foo', 'bar': 'Bar'})
984 class DeviceUtilsBroadcastIntentTest(DeviceUtilsTest
):
986 def testBroadcastIntent_noExtras(self
):
987 test_intent
= intent
.Intent(action
='test.package.with.an.INTENT')
988 with self
.assertCall(
989 self
.call
.adb
.Shell('am broadcast -a test.package.with.an.INTENT'),
990 'Broadcasting: Intent { act=test.package.with.an.INTENT } '):
991 self
.device
.BroadcastIntent(test_intent
)
993 def testBroadcastIntent_withExtra(self
):
994 test_intent
= intent
.Intent(action
='test.package.with.an.INTENT',
995 extras
={'foo': 'bar value'})
996 with self
.assertCall(
998 "am broadcast -a test.package.with.an.INTENT --es foo 'bar value'"),
999 'Broadcasting: Intent { act=test.package.with.an.INTENT } '):
1000 self
.device
.BroadcastIntent(test_intent
)
1002 def testBroadcastIntent_withExtra_noValue(self
):
1003 test_intent
= intent
.Intent(action
='test.package.with.an.INTENT',
1004 extras
={'foo': None})
1005 with self
.assertCall(
1006 self
.call
.adb
.Shell(
1007 'am broadcast -a test.package.with.an.INTENT --esn foo'),
1008 'Broadcasting: Intent { act=test.package.with.an.INTENT } '):
1009 self
.device
.BroadcastIntent(test_intent
)
1012 class DeviceUtilsGoHomeTest(DeviceUtilsTest
):
1014 def testGoHome(self
):
1015 with self
.assertCall(
1016 self
.call
.adb
.Shell('am start -W -a android.intent.action.MAIN '
1017 '-c android.intent.category.HOME'),
1018 'Starting: Intent { act=android.intent.action.MAIN }\r\n'):
1019 self
.device
.GoHome()
1022 class DeviceUtilsForceStopTest(DeviceUtilsTest
):
1024 def testForceStop(self
):
1025 with self
.assertCall(
1026 self
.call
.adb
.Shell('am force-stop this.is.a.test.package'),
1028 self
.device
.ForceStop('this.is.a.test.package')
1031 class DeviceUtilsClearApplicationStateTest(DeviceUtilsTest
):
1033 def testClearApplicationState_packageDoesntExist(self
):
1034 with self
.assertCalls(
1035 (self
.call
.adb
.Shell('getprop ro.build.version.sdk'), '17\n'),
1036 (self
.call
.device
.GetApplicationPath('this.package.does.not.exist'),
1038 self
.device
.ClearApplicationState('this.package.does.not.exist')
1040 def testClearApplicationState_packageDoesntExistOnAndroidJBMR2OrAbove(self
):
1041 with self
.assertCalls(
1042 (self
.call
.adb
.Shell('getprop ro.build.version.sdk'), '18\n'),
1043 (self
.call
.adb
.Shell('pm clear this.package.does.not.exist'),
1045 self
.device
.ClearApplicationState('this.package.does.not.exist')
1047 def testClearApplicationState_packageExists(self
):
1048 with self
.assertCalls(
1049 (self
.call
.adb
.Shell('getprop ro.build.version.sdk'), '17\n'),
1050 (self
.call
.device
.GetApplicationPath('this.package.exists'),
1051 '/data/app/this.package.exists.apk'),
1052 (self
.call
.adb
.Shell('pm clear this.package.exists'),
1054 self
.device
.ClearApplicationState('this.package.exists')
1056 def testClearApplicationState_packageExistsOnAndroidJBMR2OrAbove(self
):
1057 with self
.assertCalls(
1058 (self
.call
.adb
.Shell('getprop ro.build.version.sdk'), '18\n'),
1059 (self
.call
.adb
.Shell('pm clear this.package.exists'),
1061 self
.device
.ClearApplicationState('this.package.exists')
1064 class DeviceUtilsSendKeyEventTest(DeviceUtilsTest
):
1066 def testSendKeyEvent(self
):
1067 with self
.assertCall(self
.call
.adb
.Shell('input keyevent 66'), ''):
1068 self
.device
.SendKeyEvent(66)
1071 class DeviceUtilsPushChangedFilesIndividuallyTest(DeviceUtilsTest
):
1073 def testPushChangedFilesIndividually_empty(self
):
1075 with self
.assertCalls():
1076 self
.device
._PushChangedFilesIndividually
(test_files
)
1078 def testPushChangedFilesIndividually_single(self
):
1079 test_files
= [('/test/host/path', '/test/device/path')]
1080 with self
.assertCalls(self
.call
.adb
.Push(*test_files
[0])):
1081 self
.device
._PushChangedFilesIndividually
(test_files
)
1083 def testPushChangedFilesIndividually_multiple(self
):
1085 ('/test/host/path/file1', '/test/device/path/file1'),
1086 ('/test/host/path/file2', '/test/device/path/file2')]
1087 with self
.assertCalls(
1088 self
.call
.adb
.Push(*test_files
[0]),
1089 self
.call
.adb
.Push(*test_files
[1])):
1090 self
.device
._PushChangedFilesIndividually
(test_files
)
1093 class DeviceUtilsPushChangedFilesZippedTest(DeviceUtilsTest
):
1095 def testPushChangedFilesZipped_empty(self
):
1097 with self
.assertCalls():
1098 self
.device
._PushChangedFilesZipped
(test_files
)
1100 def _testPushChangedFilesZipped_spec(self
, test_files
):
1101 mock_zip_temp
= mock
.mock_open()
1102 mock_zip_temp
.return_value
.name
= '/test/temp/file/tmp.zip'
1103 with self
.assertCalls(
1104 (mock
.call
.tempfile
.NamedTemporaryFile(suffix
='.zip'), mock_zip_temp
),
1105 (mock
.call
.multiprocessing
.Process(
1106 target
=device_utils
.DeviceUtils
._CreateDeviceZip
,
1107 args
=('/test/temp/file/tmp.zip', test_files
)), mock
.Mock()),
1108 (self
.call
.device
.GetExternalStoragePath(),
1109 '/test/device/external_dir'),
1111 '/test/temp/file/tmp.zip', '/test/device/external_dir/tmp.zip'),
1112 self
.call
.device
.RunShellCommand(
1113 ['unzip', '/test/device/external_dir/tmp.zip'],
1115 env
={'PATH': '/data/local/tmp/bin:$PATH'},
1117 (self
.call
.device
.IsOnline(), True),
1118 self
.call
.device
.RunShellCommand(
1119 ['rm', '/test/device/external_dir/tmp.zip'], check_return
=True)):
1120 self
.device
._PushChangedFilesZipped
(test_files
)
1122 def testPushChangedFilesZipped_single(self
):
1123 self
._testPushChangedFilesZipped
_spec
(
1124 [('/test/host/path/file1', '/test/device/path/file1')])
1126 def testPushChangedFilesZipped_multiple(self
):
1127 self
._testPushChangedFilesZipped
_spec
(
1128 [('/test/host/path/file1', '/test/device/path/file1'),
1129 ('/test/host/path/file2', '/test/device/path/file2')])
1132 class DeviceUtilsFileExistsTest(DeviceUtilsTest
):
1134 def testFileExists_usingTest_fileExists(self
):
1135 with self
.assertCall(
1136 self
.call
.device
.RunShellCommand(
1137 ['test', '-e', '/path/file.exists'], check_return
=True), ''):
1138 self
.assertTrue(self
.device
.FileExists('/path/file.exists'))
1140 def testFileExists_usingTest_fileDoesntExist(self
):
1141 with self
.assertCall(
1142 self
.call
.device
.RunShellCommand(
1143 ['test', '-e', '/does/not/exist'], check_return
=True),
1144 self
.ShellError('', 1)):
1145 self
.assertFalse(self
.device
.FileExists('/does/not/exist'))
1148 class DeviceUtilsPullFileTest(DeviceUtilsTest
):
1150 def testPullFile_existsOnDevice(self
):
1151 with mock
.patch('os.path.exists', return_value
=True):
1152 with self
.assertCall(
1153 self
.call
.adb
.Pull('/data/app/test.file.exists',
1154 '/test/file/host/path')):
1155 self
.device
.PullFile('/data/app/test.file.exists',
1156 '/test/file/host/path')
1158 def testPullFile_doesntExistOnDevice(self
):
1159 with mock
.patch('os.path.exists', return_value
=True):
1160 with self
.assertCall(
1161 self
.call
.adb
.Pull('/data/app/test.file.does.not.exist',
1162 '/test/file/host/path'),
1163 self
.CommandError('remote object does not exist')):
1164 with self
.assertRaises(device_errors
.CommandFailedError
):
1165 self
.device
.PullFile('/data/app/test.file.does.not.exist',
1166 '/test/file/host/path')
1169 class DeviceUtilsReadFileTest(DeviceUtilsTest
):
1171 def testReadFileWithPull_success(self
):
1172 tmp_host_dir
= '/tmp/dir/on.host/'
1173 tmp_host
= MockTempFile('/tmp/dir/on.host/tmp_ReadFileWithPull')
1174 tmp_host
.file.read
.return_value
= 'some interesting contents'
1175 with self
.assertCalls(
1176 (mock
.call
.tempfile
.mkdtemp(), tmp_host_dir
),
1177 (self
.call
.adb
.Pull('/path/to/device/file', mock
.ANY
)),
1178 (mock
.call
.__builtin
__.open(mock
.ANY
, 'r'), tmp_host
),
1179 (mock
.call
.os
.path
.exists(tmp_host_dir
), True),
1180 (mock
.call
.shutil
.rmtree(tmp_host_dir
), None)):
1181 self
.assertEquals('some interesting contents',
1182 self
.device
._ReadFileWithPull
('/path/to/device/file'))
1183 tmp_host
.file.read
.assert_called_once_with()
1185 def testReadFileWithPull_rejected(self
):
1186 tmp_host_dir
= '/tmp/dir/on.host/'
1187 with self
.assertCalls(
1188 (mock
.call
.tempfile
.mkdtemp(), tmp_host_dir
),
1189 (self
.call
.adb
.Pull('/path/to/device/file', mock
.ANY
),
1190 self
.CommandError()),
1191 (mock
.call
.os
.path
.exists(tmp_host_dir
), True),
1192 (mock
.call
.shutil
.rmtree(tmp_host_dir
), None)):
1193 with self
.assertRaises(device_errors
.CommandFailedError
):
1194 self
.device
._ReadFileWithPull
('/path/to/device/file')
1196 def testReadFile_exists(self
):
1197 with self
.assertCalls(
1198 (self
.call
.device
.RunShellCommand(
1199 ['ls', '-l', '/read/this/test/file'],
1200 as_root
=False, check_return
=True),
1201 ['-rw-rw---- root foo 256 1970-01-01 00:00 file']),
1202 (self
.call
.device
.RunShellCommand(
1203 ['cat', '/read/this/test/file'],
1204 as_root
=False, check_return
=True),
1205 ['this is a test file'])):
1206 self
.assertEqual('this is a test file\n',
1207 self
.device
.ReadFile('/read/this/test/file'))
1209 def testReadFile_doesNotExist(self
):
1210 with self
.assertCall(
1211 self
.call
.device
.RunShellCommand(
1212 ['ls', '-l', '/this/file/does.not.exist'],
1213 as_root
=False, check_return
=True),
1214 self
.CommandError('File does not exist')):
1215 with self
.assertRaises(device_errors
.CommandFailedError
):
1216 self
.device
.ReadFile('/this/file/does.not.exist')
1218 def testReadFile_zeroSize(self
):
1219 with self
.assertCalls(
1220 (self
.call
.device
.RunShellCommand(
1221 ['ls', '-l', '/this/file/has/zero/size'],
1222 as_root
=False, check_return
=True),
1223 ['-r--r--r-- root foo 0 1970-01-01 00:00 zero_size_file']),
1224 (self
.call
.device
._ReadFileWithPull
('/this/file/has/zero/size'),
1225 'but it has contents\n')):
1226 self
.assertEqual('but it has contents\n',
1227 self
.device
.ReadFile('/this/file/has/zero/size'))
1229 def testReadFile_withSU(self
):
1230 with self
.assertCalls(
1231 (self
.call
.device
.RunShellCommand(
1232 ['ls', '-l', '/this/file/can.be.read.with.su'],
1233 as_root
=True, check_return
=True),
1234 ['-rw------- root root 256 1970-01-01 00:00 can.be.read.with.su']),
1235 (self
.call
.device
.RunShellCommand(
1236 ['cat', '/this/file/can.be.read.with.su'],
1237 as_root
=True, check_return
=True),
1238 ['this is a test file', 'read with su'])):
1240 'this is a test file\nread with su\n',
1241 self
.device
.ReadFile('/this/file/can.be.read.with.su',
1244 def testReadFile_withPull(self
):
1245 contents
= 'a' * 123456
1246 with self
.assertCalls(
1247 (self
.call
.device
.RunShellCommand(
1248 ['ls', '-l', '/read/this/big/test/file'],
1249 as_root
=False, check_return
=True),
1250 ['-rw-rw---- root foo 123456 1970-01-01 00:00 file']),
1251 (self
.call
.device
._ReadFileWithPull
('/read/this/big/test/file'),
1254 contents
, self
.device
.ReadFile('/read/this/big/test/file'))
1256 def testReadFile_withPullAndSU(self
):
1257 contents
= 'b' * 123456
1258 with self
.assertCalls(
1259 (self
.call
.device
.RunShellCommand(
1260 ['ls', '-l', '/this/big/file/can.be.read.with.su'],
1261 as_root
=True, check_return
=True),
1262 ['-rw------- root root 123456 1970-01-01 00:00 can.be.read.with.su']),
1263 (self
.call
.device
.NeedsSU(), True),
1264 (mock
.call
.pylib
.utils
.device_temp_file
.DeviceTempFile(self
.adb
),
1265 MockTempFile('/sdcard/tmp/on.device')),
1266 self
.call
.device
.RunShellCommand(
1267 ['cp', '/this/big/file/can.be.read.with.su',
1268 '/sdcard/tmp/on.device'],
1269 as_root
=True, check_return
=True),
1270 (self
.call
.device
._ReadFileWithPull
('/sdcard/tmp/on.device'),
1274 self
.device
.ReadFile('/this/big/file/can.be.read.with.su',
1277 def testReadFile_forcePull(self
):
1278 contents
= 'a' * 123456
1279 with self
.assertCall(
1280 self
.call
.device
._ReadFileWithPull
('/read/this/big/test/file'),
1284 self
.device
.ReadFile('/read/this/big/test/file', force_pull
=True))
1287 class DeviceUtilsWriteFileTest(DeviceUtilsTest
):
1289 def testWriteFileWithPush_success(self
):
1290 tmp_host
= MockTempFile('/tmp/file/on.host')
1291 contents
= 'some interesting contents'
1292 with self
.assertCalls(
1293 (mock
.call
.tempfile
.NamedTemporaryFile(), tmp_host
),
1294 self
.call
.adb
.Push('/tmp/file/on.host', '/path/to/device/file')):
1295 self
.device
._WriteFileWithPush
('/path/to/device/file', contents
)
1296 tmp_host
.file.write
.assert_called_once_with(contents
)
1298 def testWriteFileWithPush_rejected(self
):
1299 tmp_host
= MockTempFile('/tmp/file/on.host')
1300 contents
= 'some interesting contents'
1301 with self
.assertCalls(
1302 (mock
.call
.tempfile
.NamedTemporaryFile(), tmp_host
),
1303 (self
.call
.adb
.Push('/tmp/file/on.host', '/path/to/device/file'),
1304 self
.CommandError())):
1305 with self
.assertRaises(device_errors
.CommandFailedError
):
1306 self
.device
._WriteFileWithPush
('/path/to/device/file', contents
)
1308 def testWriteFile_withPush(self
):
1309 contents
= 'some large contents ' * 26 # 20 * 26 = 520 chars
1310 with self
.assertCalls(
1311 self
.call
.device
._WriteFileWithPush
('/path/to/device/file', contents
)):
1312 self
.device
.WriteFile('/path/to/device/file', contents
)
1314 def testWriteFile_withPushForced(self
):
1315 contents
= 'tiny contents'
1316 with self
.assertCalls(
1317 self
.call
.device
._WriteFileWithPush
('/path/to/device/file', contents
)):
1318 self
.device
.WriteFile('/path/to/device/file', contents
, force_push
=True)
1320 def testWriteFile_withPushAndSU(self
):
1321 contents
= 'some large contents ' * 26 # 20 * 26 = 520 chars
1322 with self
.assertCalls(
1323 (self
.call
.device
.NeedsSU(), True),
1324 (mock
.call
.pylib
.utils
.device_temp_file
.DeviceTempFile(self
.adb
),
1325 MockTempFile('/sdcard/tmp/on.device')),
1326 self
.call
.device
._WriteFileWithPush
('/sdcard/tmp/on.device', contents
),
1327 self
.call
.device
.RunShellCommand(
1328 ['cp', '/sdcard/tmp/on.device', '/path/to/device/file'],
1329 as_root
=True, check_return
=True)):
1330 self
.device
.WriteFile('/path/to/device/file', contents
, as_root
=True)
1332 def testWriteFile_withEcho(self
):
1333 with self
.assertCall(self
.call
.adb
.Shell(
1334 "echo -n the.contents > /test/file/to.write"), ''):
1335 self
.device
.WriteFile('/test/file/to.write', 'the.contents')
1337 def testWriteFile_withEchoAndQuotes(self
):
1338 with self
.assertCall(self
.call
.adb
.Shell(
1339 "echo -n 'the contents' > '/test/file/to write'"), ''):
1340 self
.device
.WriteFile('/test/file/to write', 'the contents')
1342 def testWriteFile_withEchoAndSU(self
):
1343 with self
.assertCalls(
1344 (self
.call
.device
.NeedsSU(), True),
1345 (self
.call
.adb
.Shell("su -c sh -c 'echo -n contents > /test/file'"),
1347 self
.device
.WriteFile('/test/file', 'contents', as_root
=True)
1350 class DeviceUtilsLsTest(DeviceUtilsTest
):
1352 def testLs_directory(self
):
1353 result
= [('.', adb_wrapper
.DeviceStat(16889, 4096, 1417436123)),
1354 ('..', adb_wrapper
.DeviceStat(16873, 4096, 12382237)),
1355 ('testfile.txt', adb_wrapper
.DeviceStat(33206, 3, 1417436122))]
1356 with self
.assertCalls(
1357 (self
.call
.adb
.Ls('/data/local/tmp'), result
)):
1358 self
.assertEquals(result
,
1359 self
.device
.Ls('/data/local/tmp'))
1361 def testLs_nothing(self
):
1362 with self
.assertCalls(
1363 (self
.call
.adb
.Ls('/data/local/tmp/testfile.txt'), [])):
1364 self
.assertEquals([],
1365 self
.device
.Ls('/data/local/tmp/testfile.txt'))
1368 class DeviceUtilsStatTest(DeviceUtilsTest
):
1370 def testStat_file(self
):
1371 result
= [('.', adb_wrapper
.DeviceStat(16889, 4096, 1417436123)),
1372 ('..', adb_wrapper
.DeviceStat(16873, 4096, 12382237)),
1373 ('testfile.txt', adb_wrapper
.DeviceStat(33206, 3, 1417436122))]
1374 with self
.assertCalls(
1375 (self
.call
.adb
.Ls('/data/local/tmp'), result
)):
1376 self
.assertEquals(adb_wrapper
.DeviceStat(33206, 3, 1417436122),
1377 self
.device
.Stat('/data/local/tmp/testfile.txt'))
1379 def testStat_directory(self
):
1380 result
= [('.', adb_wrapper
.DeviceStat(16873, 4096, 12382237)),
1381 ('..', adb_wrapper
.DeviceStat(16873, 4096, 12382237)),
1382 ('tmp', adb_wrapper
.DeviceStat(16889, 4096, 1417436123))]
1383 with self
.assertCalls(
1384 (self
.call
.adb
.Ls('/data/local'), result
)):
1385 self
.assertEquals(adb_wrapper
.DeviceStat(16889, 4096, 1417436123),
1386 self
.device
.Stat('/data/local/tmp'))
1388 def testStat_doesNotExist(self
):
1389 result
= [('.', adb_wrapper
.DeviceStat(16889, 4096, 1417436123)),
1390 ('..', adb_wrapper
.DeviceStat(16873, 4096, 12382237)),
1391 ('testfile.txt', adb_wrapper
.DeviceStat(33206, 3, 1417436122))]
1392 with self
.assertCalls(
1393 (self
.call
.adb
.Ls('/data/local/tmp'), result
)):
1394 with self
.assertRaises(device_errors
.CommandFailedError
):
1395 self
.device
.Stat('/data/local/tmp/does.not.exist.txt')
1398 class DeviceUtilsSetJavaAssertsTest(DeviceUtilsTest
):
1400 def testSetJavaAsserts_enable(self
):
1401 with self
.assertCalls(
1402 (self
.call
.device
.ReadFile(constants
.DEVICE_LOCAL_PROPERTIES_PATH
),
1403 'some.example.prop=with an example value\n'
1404 'some.other.prop=value_ok\n'),
1405 self
.call
.device
.WriteFile(
1406 constants
.DEVICE_LOCAL_PROPERTIES_PATH
,
1407 'some.example.prop=with an example value\n'
1408 'some.other.prop=value_ok\n'
1409 'dalvik.vm.enableassertions=all\n'),
1410 (self
.call
.device
.GetProp('dalvik.vm.enableassertions'), ''),
1411 self
.call
.device
.SetProp('dalvik.vm.enableassertions', 'all')):
1412 self
.assertTrue(self
.device
.SetJavaAsserts(True))
1414 def testSetJavaAsserts_disable(self
):
1415 with self
.assertCalls(
1416 (self
.call
.device
.ReadFile(constants
.DEVICE_LOCAL_PROPERTIES_PATH
),
1417 'some.example.prop=with an example value\n'
1418 'dalvik.vm.enableassertions=all\n'
1419 'some.other.prop=value_ok\n'),
1420 self
.call
.device
.WriteFile(
1421 constants
.DEVICE_LOCAL_PROPERTIES_PATH
,
1422 'some.example.prop=with an example value\n'
1423 'some.other.prop=value_ok\n'),
1424 (self
.call
.device
.GetProp('dalvik.vm.enableassertions'), 'all'),
1425 self
.call
.device
.SetProp('dalvik.vm.enableassertions', '')):
1426 self
.assertTrue(self
.device
.SetJavaAsserts(False))
1428 def testSetJavaAsserts_alreadyEnabled(self
):
1429 with self
.assertCalls(
1430 (self
.call
.device
.ReadFile(constants
.DEVICE_LOCAL_PROPERTIES_PATH
),
1431 'some.example.prop=with an example value\n'
1432 'dalvik.vm.enableassertions=all\n'
1433 'some.other.prop=value_ok\n'),
1434 (self
.call
.device
.GetProp('dalvik.vm.enableassertions'), 'all')):
1435 self
.assertFalse(self
.device
.SetJavaAsserts(True))
1438 class DeviceUtilsGetPropTest(DeviceUtilsTest
):
1440 def testGetProp_exists(self
):
1441 with self
.assertCall(
1442 self
.call
.adb
.Shell('getprop test.property'), 'property_value\n'):
1443 self
.assertEqual('property_value',
1444 self
.device
.GetProp('test.property'))
1446 def testGetProp_doesNotExist(self
):
1447 with self
.assertCall(
1448 self
.call
.adb
.Shell('getprop property.does.not.exist'), '\n'):
1449 self
.assertEqual('', self
.device
.GetProp('property.does.not.exist'))
1451 def testGetProp_cachedRoProp(self
):
1452 with self
.assertCall(
1453 self
.call
.adb
.Shell('getprop ro.build.type'), 'userdebug\n'):
1454 self
.assertEqual('userdebug',
1455 self
.device
.GetProp('ro.build.type', cache
=True))
1456 self
.assertEqual('userdebug',
1457 self
.device
.GetProp('ro.build.type', cache
=True))
1459 def testGetProp_retryAndCache(self
):
1460 with self
.assertCalls(
1461 (self
.call
.adb
.Shell('getprop ro.build.type'), self
.ShellError()),
1462 (self
.call
.adb
.Shell('getprop ro.build.type'), self
.ShellError()),
1463 (self
.call
.adb
.Shell('getprop ro.build.type'), 'userdebug\n')):
1464 self
.assertEqual('userdebug',
1465 self
.device
.GetProp('ro.build.type',
1466 cache
=True, retries
=3))
1467 self
.assertEqual('userdebug',
1468 self
.device
.GetProp('ro.build.type',
1469 cache
=True, retries
=3))
1472 class DeviceUtilsSetPropTest(DeviceUtilsTest
):
1474 def testSetProp(self
):
1475 with self
.assertCall(
1476 self
.call
.adb
.Shell("setprop test.property 'test value'"), ''):
1477 self
.device
.SetProp('test.property', 'test value')
1479 def testSetProp_check_succeeds(self
):
1480 with self
.assertCalls(
1481 (self
.call
.adb
.Shell('setprop test.property new_value'), ''),
1482 (self
.call
.adb
.Shell('getprop test.property'), 'new_value')):
1483 self
.device
.SetProp('test.property', 'new_value', check
=True)
1485 def testSetProp_check_fails(self
):
1486 with self
.assertCalls(
1487 (self
.call
.adb
.Shell('setprop test.property new_value'), ''),
1488 (self
.call
.adb
.Shell('getprop test.property'), 'old_value')):
1489 with self
.assertRaises(device_errors
.CommandFailedError
):
1490 self
.device
.SetProp('test.property', 'new_value', check
=True)
1493 class DeviceUtilsGetPidsTest(DeviceUtilsTest
):
1495 def testGetPids_noMatches(self
):
1496 with self
.assertCall(
1497 self
.call
.device
._RunPipedShellCommand
('ps | grep -F does.not.match'),
1499 self
.assertEqual({}, self
.device
.GetPids('does.not.match'))
1501 def testGetPids_oneMatch(self
):
1502 with self
.assertCall(
1503 self
.call
.device
._RunPipedShellCommand
('ps | grep -F one.match'),
1504 ['user 1001 100 1024 1024 ffffffff 00000000 one.match']):
1505 self
.assertEqual({'one.match': '1001'}, self
.device
.GetPids('one.match'))
1507 def testGetPids_mutlipleMatches(self
):
1508 with self
.assertCall(
1509 self
.call
.device
._RunPipedShellCommand
('ps | grep -F match'),
1510 ['user 1001 100 1024 1024 ffffffff 00000000 one.match',
1511 'user 1002 100 1024 1024 ffffffff 00000000 two.match',
1512 'user 1003 100 1024 1024 ffffffff 00000000 three.match']):
1514 {'one.match': '1001', 'two.match': '1002', 'three.match': '1003'},
1515 self
.device
.GetPids('match'))
1517 def testGetPids_exactMatch(self
):
1518 with self
.assertCall(
1519 self
.call
.device
._RunPipedShellCommand
('ps | grep -F exact.match'),
1520 ['user 1000 100 1024 1024 ffffffff 00000000 not.exact.match',
1521 'user 1234 100 1024 1024 ffffffff 00000000 exact.match']):
1523 {'not.exact.match': '1000', 'exact.match': '1234'},
1524 self
.device
.GetPids('exact.match'))
1526 def testGetPids_quotable(self
):
1527 with self
.assertCall(
1528 self
.call
.device
._RunPipedShellCommand
("ps | grep -F 'my$process'"),
1529 ['user 1234 100 1024 1024 ffffffff 00000000 my$process']):
1531 {'my$process': '1234'}, self
.device
.GetPids('my$process'))
1534 class DeviceUtilsTakeScreenshotTest(DeviceUtilsTest
):
1536 def testTakeScreenshot_fileNameProvided(self
):
1537 with self
.assertCalls(
1538 (mock
.call
.pylib
.utils
.device_temp_file
.DeviceTempFile(
1539 self
.adb
, suffix
='.png'),
1540 MockTempFile('/tmp/path/temp-123.png')),
1541 (self
.call
.adb
.Shell('/system/bin/screencap -p /tmp/path/temp-123.png'),
1543 self
.call
.device
.PullFile('/tmp/path/temp-123.png',
1544 '/test/host/screenshot.png')):
1545 self
.device
.TakeScreenshot('/test/host/screenshot.png')
1548 class DeviceUtilsGetMemoryUsageForPidTest(DeviceUtilsTest
):
1551 super(DeviceUtilsGetMemoryUsageForPidTest
, self
).setUp()
1553 def testGetMemoryUsageForPid_validPid(self
):
1554 with self
.assertCalls(
1555 (self
.call
.device
._RunPipedShellCommand
(
1556 'showmap 1234 | grep TOTAL', as_root
=True),
1557 ['100 101 102 103 104 105 106 107 TOTAL']),
1558 (self
.call
.device
.ReadFile('/proc/1234/status', as_root
=True),
1559 'VmHWM: 1024 kB\n')):
1565 'Shared_Clean': 103,
1566 'Shared_Dirty': 104,
1567 'Private_Clean': 105,
1568 'Private_Dirty': 106,
1571 self
.device
.GetMemoryUsageForPid(1234))
1573 def testGetMemoryUsageForPid_noSmaps(self
):
1574 with self
.assertCalls(
1575 (self
.call
.device
._RunPipedShellCommand
(
1576 'showmap 4321 | grep TOTAL', as_root
=True),
1577 ['cannot open /proc/4321/smaps: No such file or directory']),
1578 (self
.call
.device
.ReadFile('/proc/4321/status', as_root
=True),
1579 'VmHWM: 1024 kb\n')):
1580 self
.assertEquals({'VmHWM': 1024}, self
.device
.GetMemoryUsageForPid(4321))
1582 def testGetMemoryUsageForPid_noStatus(self
):
1583 with self
.assertCalls(
1584 (self
.call
.device
._RunPipedShellCommand
(
1585 'showmap 4321 | grep TOTAL', as_root
=True),
1586 ['100 101 102 103 104 105 106 107 TOTAL']),
1587 (self
.call
.device
.ReadFile('/proc/4321/status', as_root
=True),
1588 self
.CommandError())):
1594 'Shared_Clean': 103,
1595 'Shared_Dirty': 104,
1596 'Private_Clean': 105,
1597 'Private_Dirty': 106,
1599 self
.device
.GetMemoryUsageForPid(4321))
1602 class DeviceUtilsClientCache(DeviceUtilsTest
):
1604 def testClientCache_twoCaches(self
):
1605 self
.device
._cache
['test'] = 0
1606 client_cache_one
= self
.device
.GetClientCache('ClientOne')
1607 client_cache_one
['test'] = 1
1608 client_cache_two
= self
.device
.GetClientCache('ClientTwo')
1609 client_cache_two
['test'] = 2
1610 self
.assertEqual(self
.device
._cache
, {'test': 0})
1611 self
.assertEqual(client_cache_one
, {'test': 1})
1612 self
.assertEqual(client_cache_two
, {'test': 2})
1613 self
.device
._ClearCache
()
1614 self
.assertEqual(self
.device
._cache
, {})
1615 self
.assertEqual(client_cache_one
, {})
1616 self
.assertEqual(client_cache_two
, {})
1618 def testClientCache_multipleInstances(self
):
1619 client_cache_one
= self
.device
.GetClientCache('ClientOne')
1620 client_cache_one
['test'] = 1
1621 client_cache_two
= self
.device
.GetClientCache('ClientOne')
1622 self
.assertEqual(client_cache_one
, {'test': 1})
1623 self
.assertEqual(client_cache_two
, {'test': 1})
1624 self
.device
._ClearCache
()
1625 self
.assertEqual(client_cache_one
, {})
1626 self
.assertEqual(client_cache_two
, {})
1629 class DeviceUtilsParallelTest(mock_calls
.TestCase
):
1631 def testParallel_default(self
):
1632 test_serials
= ['0123456789abcdef', 'fedcba9876543210']
1633 with self
.assertCall(
1634 mock
.call
.pylib
.device
.device_utils
.DeviceUtils
.HealthyDevices(),
1635 [device_utils
.DeviceUtils(s
) for s
in test_serials
]):
1636 parallel_devices
= device_utils
.DeviceUtils
.parallel()
1637 for serial
, device
in zip(test_serials
, parallel_devices
.pGet(None)):
1638 self
.assertTrue(isinstance(device
, device_utils
.DeviceUtils
))
1639 self
.assertEquals(serial
, device
.adb
.GetDeviceSerial())
1641 def testParallel_noDevices(self
):
1642 with self
.assertCall(
1643 mock
.call
.pylib
.device
.device_utils
.DeviceUtils
.HealthyDevices(), []):
1644 with self
.assertRaises(device_errors
.NoDevicesError
):
1645 device_utils
.DeviceUtils
.parallel()
1648 class DeviceUtilsHealthyDevicesTest(mock_calls
.TestCase
):
1650 def _createAdbWrapperMock(self
, serial
, is_ready
=True):
1651 adb
= _AdbWrapperMock(serial
)
1652 adb
.is_ready
= is_ready
1655 def testHealthyDevices_default(self
):
1656 test_serials
= ['0123456789abcdef', 'fedcba9876543210']
1657 with self
.assertCalls(
1658 (mock
.call
.pylib
.device
.device_blacklist
.ReadBlacklist(), []),
1659 (mock
.call
.pylib
.device
.adb_wrapper
.AdbWrapper
.Devices(),
1660 [self
._createAdbWrapperMock
(s
) for s
in test_serials
])):
1661 devices
= device_utils
.DeviceUtils
.HealthyDevices()
1662 for serial
, device
in zip(test_serials
, devices
):
1663 self
.assertTrue(isinstance(device
, device_utils
.DeviceUtils
))
1664 self
.assertEquals(serial
, device
.adb
.GetDeviceSerial())
1666 def testHealthyDevices_blacklisted(self
):
1667 test_serials
= ['0123456789abcdef', 'fedcba9876543210']
1668 with self
.assertCalls(
1669 (mock
.call
.pylib
.device
.device_blacklist
.ReadBlacklist(),
1670 ['fedcba9876543210']),
1671 (mock
.call
.pylib
.device
.adb_wrapper
.AdbWrapper
.Devices(),
1672 [self
._createAdbWrapperMock
(s
) for s
in test_serials
])):
1673 devices
= device_utils
.DeviceUtils
.HealthyDevices()
1674 self
.assertEquals(1, len(devices
))
1675 self
.assertTrue(isinstance(devices
[0], device_utils
.DeviceUtils
))
1676 self
.assertEquals('0123456789abcdef', devices
[0].adb
.GetDeviceSerial())
1679 if __name__
== '__main__':
1680 logging
.getLogger().setLevel(logging
.DEBUG
)
1681 unittest
.main(verbosity
=2)