Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(56)

Side by Side Diff: build/android/pylib/device/device_utils_test.py

Issue 659533002: New run shell implementation for DeviceUtils (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: fixed nit, and TODO to make cmd_helper_test run on bots Created 6 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 #!/usr/bin/env python 1 #!/usr/bin/env python
2 # Copyright 2014 The Chromium Authors. All rights reserved. 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 3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file. 4 # found in the LICENSE file.
5 5
6 """ 6 """
7 Unit tests for the contents of device_utils.py (mostly DeviceUtils). 7 Unit tests for the contents of device_utils.py (mostly DeviceUtils).
8 """ 8 """
9 9
10 # pylint: disable=C0321 10 # pylint: disable=C0321
(...skipping 200 matching lines...) Expand 10 before | Expand all | Expand 10 after
211 return type(self).AndroidCommandsCalls(self, [(cmd, ret)], comp) 211 return type(self).AndroidCommandsCalls(self, [(cmd, ret)], comp)
212 212
213 def assertCallsSequence(self, cmd_ret, comp=str.__eq__): 213 def assertCallsSequence(self, cmd_ret, comp=str.__eq__):
214 return type(self).AndroidCommandsCalls(self, cmd_ret, comp) 214 return type(self).AndroidCommandsCalls(self, cmd_ret, comp)
215 215
216 def setUp(self): 216 def setUp(self):
217 self.device = device_utils.DeviceUtils( 217 self.device = device_utils.DeviceUtils(
218 '0123456789abcdef', default_timeout=1, default_retries=0) 218 '0123456789abcdef', default_timeout=1, default_retries=0)
219 219
220 220
221 class Args:
222 def __init__(self, *args, **kwargs):
223 self.args = args
224 self.kwargs = kwargs
225
226 def __eq__(self, other):
227 return (self.args, self.kwargs) == (other.args, other.kwargs)
228
229 def __repr__(self):
230 return '%s(%s)' % (type(self).__name__, str(self))
231
232 def __str__(self):
233 toks = (['%r' % v for v in self.args] +
234 ['%s=%r' % (k, self.kwargs[k]) for k in sorted(self.kwargs)])
235 return ', '.join(toks)
236
237
238 class MockCallSequence(object):
239 def __init__(self, test_case, obj, method, calls):
240 def assert_and_return(*args, **kwargs):
241 received_args = Args(*args, **kwargs)
242 test_case.assertTrue(
243 self._calls,
244 msg=('Unexpected call\n'
245 ' received: %s(%s)\n' % (self._method, received_args)))
246 expected_args, return_value = self._calls.pop(0)
247 test_case.assertTrue(
248 received_args == expected_args,
249 msg=('Call does not match expected args\n'
250 ' received: %s(%s)\n'
251 ' expected: %s(%s)\n'
252 % (self._method, received_args,
253 self._method, expected_args)))
254 if isinstance(return_value, Exception):
255 raise return_value
256 else:
257 return return_value
258
259 self._calls = list(calls)
260 self._test_case = test_case
261 self._method = method
262 self._patched = mock.patch.object(obj, self._method,
263 side_effect=assert_and_return)
264
265 def __enter__(self):
266 return self._patched.__enter__()
267
268 def __exit__(self, exc_type, exc_val, exc_tb):
269 self._patched.__exit__(exc_type, exc_val, exc_tb)
270 if exc_type is None:
271 missing = ''.join(' expected: %s(%s)\n'
272 % (self._method, expected_args)
273 for expected_args, _ in self._calls)
274 self._test_case.assertTrue(
275 not missing,
276 msg=('Expected calls not found\n' + missing))
277
278
279 class _ShellError:
280 def __init__(self, output=None, return_code=1):
281 if output is None:
282 self.output = 'Permission denied\r\n'
283 else:
284 self.output = output
285 self.return_code = return_code
286
287
221 class DeviceUtilsNewImplTest(unittest.TestCase): 288 class DeviceUtilsNewImplTest(unittest.TestCase):
222 289
223 def setUp(self): 290 def setUp(self):
224 test_serial = '0123456789abcdef' 291 test_serial = '0123456789abcdef'
225 self.adb = mock.Mock(spec=adb_wrapper.AdbWrapper) 292 self.adb = mock.Mock(spec=adb_wrapper.AdbWrapper)
226 self.adb.__str__ = mock.Mock(return_value=test_serial) 293 self.adb.__str__ = mock.Mock(return_value=test_serial)
227 self.adb.GetDeviceSerial.return_value = test_serial 294 self.adb.GetDeviceSerial.return_value = test_serial
228 self.device = device_utils.DeviceUtils( 295 self.device = device_utils.DeviceUtils(
229 self.adb, default_timeout=1, default_retries=0) 296 self.adb, default_timeout=1, default_retries=0)
230 297
298 def assertShellCallSequence(self, calls):
299 '''Assert that we expect a sequence of calls to adb.Shell.
300
301 Args:
302 calls: a sequence of (cmd, return_value) pairs, where |cmd| is the
303 expected shell command to run on the device (with any quoting already
304 applied), and |return_value| is either a string to give as mock output
305 or a _ShellError object to raise an AdbShellCommandFailedError.
306 '''
307 def mk_expected_call(cmd, return_value):
308 expected_args = Args(cmd, expect_rc=0)
309 if isinstance(return_value, _ShellError):
310 return_value = device_errors.AdbShellCommandFailedError(cmd,
311 return_value.return_code, return_value.output, str(self.device))
312 return (expected_args, return_value)
313
314 expected_calls = (mk_expected_call(a, r) for a, r in calls)
315 return MockCallSequence(self, self.adb, 'Shell', expected_calls)
316
317 def assertShellCall(self, cmd, return_value=''):
318 return self.assertShellCallSequence([(cmd, return_value)])
319
231 320
232 class DeviceUtilsHybridImplTest(DeviceUtilsOldImplTest): 321 class DeviceUtilsHybridImplTest(DeviceUtilsOldImplTest):
233 322
234 def setUp(self): 323 def setUp(self):
235 super(DeviceUtilsHybridImplTest, self).setUp() 324 super(DeviceUtilsHybridImplTest, self).setUp()
236 self.device.adb = self.adb = mock.Mock(spec=adb_wrapper.AdbWrapper) 325 self.device.adb = self.adb = mock.Mock(spec=adb_wrapper.AdbWrapper)
237 326
238 327
239 class DeviceUtilsIsOnlineTest(DeviceUtilsOldImplTest): 328 class DeviceUtilsIsOnlineTest(DeviceUtilsOldImplTest):
240 329
241 def testIsOnline_true(self): 330 def testIsOnline_true(self):
242 with self.assertCalls('adb -s 0123456789abcdef devices', 331 with self.assertCalls('adb -s 0123456789abcdef devices',
243 '00123456789abcdef device\r\n'): 332 '00123456789abcdef device\r\n'):
244 self.assertTrue(self.device.IsOnline()) 333 self.assertTrue(self.device.IsOnline())
245 334
246 def testIsOnline_false(self): 335 def testIsOnline_false(self):
247 with self.assertCalls('adb -s 0123456789abcdef devices', '\r\n'): 336 with self.assertCalls('adb -s 0123456789abcdef devices', '\r\n'):
248 self.assertFalse(self.device.IsOnline()) 337 self.assertFalse(self.device.IsOnline())
249 338
250 339
251 class DeviceUtilsHasRootTest(DeviceUtilsOldImplTest): 340 class DeviceUtilsHasRootTest(DeviceUtilsNewImplTest):
252 341
253 def testHasRoot_true(self): 342 def testHasRoot_true(self):
254 with self.assertCalls("adb -s 0123456789abcdef shell 'ls /root'", 343 with self.assertShellCall('ls /root', 'foo\r\n'):
255 'foo\r\n'):
256 self.assertTrue(self.device.HasRoot()) 344 self.assertTrue(self.device.HasRoot())
257 345
258 def testHasRoot_false(self): 346 def testHasRoot_false(self):
259 with self.assertCalls("adb -s 0123456789abcdef shell 'ls /root'", 347 with self.assertShellCall('ls /root', _ShellError()):
260 'Permission denied\r\n'):
261 self.assertFalse(self.device.HasRoot()) 348 self.assertFalse(self.device.HasRoot())
262 349
263 350
264 class DeviceUtilsEnableRootTest(DeviceUtilsOldImplTest): 351 class DeviceUtilsEnableRootTest(DeviceUtilsOldImplTest):
265 352
266 def testEnableRoot_succeeds(self): 353 def testEnableRoot_succeeds(self):
267 with self.assertCallsSequence([ 354 with self.assertCallsSequence([
268 ('adb -s 0123456789abcdef shell getprop ro.build.type', 355 ('adb -s 0123456789abcdef shell getprop ro.build.type',
269 'userdebug\r\n'), 356 'userdebug\r\n'),
270 ('adb -s 0123456789abcdef root', 'restarting adbd as root\r\n'), 357 ('adb -s 0123456789abcdef root', 'restarting adbd as root\r\n'),
(...skipping 25 matching lines...) Expand all
296 'user\r\n'): 383 'user\r\n'):
297 self.assertTrue(self.device.IsUserBuild()) 384 self.assertTrue(self.device.IsUserBuild())
298 385
299 def testIsUserBuild_no(self): 386 def testIsUserBuild_no(self):
300 with self.assertCalls( 387 with self.assertCalls(
301 'adb -s 0123456789abcdef shell getprop ro.build.type', 388 'adb -s 0123456789abcdef shell getprop ro.build.type',
302 'userdebug\r\n'): 389 'userdebug\r\n'):
303 self.assertFalse(self.device.IsUserBuild()) 390 self.assertFalse(self.device.IsUserBuild())
304 391
305 392
306 class DeviceUtilsGetExternalStoragePathTest(DeviceUtilsOldImplTest): 393 class DeviceUtilsGetExternalStoragePathTest(DeviceUtilsNewImplTest):
307 394
308 def testGetExternalStoragePath_succeeds(self): 395 def testGetExternalStoragePath_succeeds(self):
309 fakeStoragePath = '/fake/storage/path' 396 fakeStoragePath = '/fake/storage/path'
310 with self.assertCalls( 397 with self.assertShellCall('echo $EXTERNAL_STORAGE',
311 "adb -s 0123456789abcdef shell 'echo $EXTERNAL_STORAGE'", 398 '%s\r\n' % fakeStoragePath):
312 '%s\r\n' % fakeStoragePath):
313 self.assertEquals(fakeStoragePath, 399 self.assertEquals(fakeStoragePath,
314 self.device.GetExternalStoragePath()) 400 self.device.GetExternalStoragePath())
315 401
316 def testGetExternalStoragePath_fails(self): 402 def testGetExternalStoragePath_fails(self):
317 with self.assertCalls( 403 with self.assertShellCall('echo $EXTERNAL_STORAGE', '\r\n'):
318 "adb -s 0123456789abcdef shell 'echo $EXTERNAL_STORAGE'", '\r\n'):
319 with self.assertRaises(device_errors.CommandFailedError): 404 with self.assertRaises(device_errors.CommandFailedError):
320 self.device.GetExternalStoragePath() 405 self.device.GetExternalStoragePath()
321 406
322 407
323 class DeviceUtilsWaitUntilFullyBootedTest(DeviceUtilsOldImplTest): 408 class DeviceUtilsWaitUntilFullyBootedTest(DeviceUtilsOldImplTest):
324 409
325 def testWaitUntilFullyBooted_succeedsNoWifi(self): 410 def testWaitUntilFullyBooted_succeedsNoWifi(self):
326 with self.assertCallsSequence([ 411 with self.assertCallsSequence([
327 # AndroidCommands.WaitForSystemBootCompleted 412 # AndroidCommands.WaitForSystemBootCompleted
328 ('adb -s 0123456789abcdef wait-for-device', ''), 413 ('adb -s 0123456789abcdef wait-for-device', ''),
(...skipping 208 matching lines...) Expand 10 before | Expand all | Expand 10 after
537 return_value='this.is.a.test.package')): 622 return_value='this.is.a.test.package')):
538 with self.assertCallsSequence([ 623 with self.assertCallsSequence([
539 ("adb -s 0123456789abcdef shell 'pm path this.is.a.test.package'", 624 ("adb -s 0123456789abcdef shell 'pm path this.is.a.test.package'",
540 ''), 625 ''),
541 ("adb -s 0123456789abcdef install /fake/test/app.apk", 626 ("adb -s 0123456789abcdef install /fake/test/app.apk",
542 'Failure\r\n')]): 627 'Failure\r\n')]):
543 with self.assertRaises(device_errors.CommandFailedError): 628 with self.assertRaises(device_errors.CommandFailedError):
544 self.device.Install('/fake/test/app.apk', retries=0) 629 self.device.Install('/fake/test/app.apk', retries=0)
545 630
546 631
547 class DeviceUtilsRunShellCommandTest(DeviceUtilsOldImplTest): 632 class DeviceUtilsRunShellCommandTest(DeviceUtilsNewImplTest):
548
549 def testRunShellCommand_commandAsList(self): 633 def testRunShellCommand_commandAsList(self):
550 with self.assertCalls( 634 with self.assertShellCall('pm list packages'):
551 "adb -s 0123456789abcdef shell 'pm list packages'",
552 'pacakge:android\r\n'):
553 self.device.RunShellCommand(['pm', 'list', 'packages']) 635 self.device.RunShellCommand(['pm', 'list', 'packages'])
554 636
637 def testRunShellCommand_commandAsListQuoted(self):
638 with self.assertShellCall("echo 'hello world' '$10'"):
639 self.device.RunShellCommand(['echo', 'hello world', '$10'])
640
555 def testRunShellCommand_commandAsString(self): 641 def testRunShellCommand_commandAsString(self):
556 with self.assertCalls( 642 with self.assertShellCall('echo "$VAR"'):
557 "adb -s 0123456789abcdef shell 'dumpsys wifi'", 643 self.device.RunShellCommand('echo "$VAR"')
558 'Wi-Fi is enabled\r\n'): 644
559 self.device.RunShellCommand('dumpsys wifi') 645 def testNewRunShellImpl_withEnv(self):
646 with self.assertShellCall('VAR=some_string echo "$VAR"'):
647 self.device.RunShellCommand('echo "$VAR"', env={'VAR': 'some_string'})
648
649 def testNewRunShellImpl_withEnvQuoted(self):
650 with self.assertShellCall('PATH="$PATH:/other/path" run_this'):
651 self.device.RunShellCommand('run_this', env={'PATH': '$PATH:/other/path'})
652
653 def testNewRunShellImpl_withEnv_failure(self):
654 with self.assertRaises(KeyError):
655 self.device.RunShellCommand('some_cmd', env={'INVALID NAME': 'value'})
656
657 def testNewRunShellImpl_withCwd(self):
658 with self.assertShellCall('cd /some/test/path && ls'):
659 self.device.RunShellCommand('ls', cwd='/some/test/path')
660
661 def testNewRunShellImpl_withCwdQuoted(self):
662 with self.assertShellCall("cd '/some test/path with/spaces' && ls"):
663 self.device.RunShellCommand('ls', cwd='/some test/path with/spaces')
560 664
561 def testRunShellCommand_withSu(self): 665 def testRunShellCommand_withSu(self):
562 with self.assertCallsSequence([ 666 with self.assertShellCallSequence([
563 ("adb -s 0123456789abcdef shell 'ls /root'", 'Permission denied\r\n'), 667 ('ls /root', _ShellError()),
564 ("adb -s 0123456789abcdef shell 'su -c setprop service.adb.root 0'", 668 ('su -c setprop service.adb.root 0', '')]):
565 '')]):
566 self.device.RunShellCommand('setprop service.adb.root 0', as_root=True) 669 self.device.RunShellCommand('setprop service.adb.root 0', as_root=True)
567 670
568 def testRunShellCommand_withRoot(self): 671 def testRunShellCommand_withRoot(self):
569 with self.assertCallsSequence([ 672 with self.assertShellCallSequence([
570 ("adb -s 0123456789abcdef shell 'ls /root'", 'hello\r\nworld\r\n'), 673 ('ls /root', '\r\n'),
571 ("adb -s 0123456789abcdef shell 'setprop service.adb.root 0'", '')]): 674 ('setprop service.adb.root 0', '')]):
572 self.device.RunShellCommand('setprop service.adb.root 0', as_root=True) 675 self.device.RunShellCommand('setprop service.adb.root 0', as_root=True)
573 676
677 def testRunShellCommand_manyLines(self):
678 cmd = 'ls /some/path'
679 with self.assertShellCall(cmd, 'file1\r\nfile2\r\nfile3\r\n'):
680 self.assertEquals(['file1', 'file2', 'file3'],
681 self.device.RunShellCommand(cmd))
682
683 def testRunShellCommand_singleLine_success(self):
684 cmd = 'echo $VALUE'
685 with self.assertShellCall(cmd, 'some value\r\n'):
686 self.assertEquals('some value',
687 self.device.RunShellCommand(cmd, single_line=True))
688
689 def testRunShellCommand_singleLine_successEmptyLine(self):
690 cmd = 'echo $VALUE'
691 with self.assertShellCall(cmd, '\r\n'):
692 self.assertEquals('',
693 self.device.RunShellCommand(cmd, single_line=True))
694
695 def testRunShellCommand_singleLine_successWithoutEndLine(self):
696 cmd = 'echo -n $VALUE'
697 with self.assertShellCall(cmd, 'some value'):
698 self.assertEquals('some value',
699 self.device.RunShellCommand(cmd, single_line=True))
700
701 def testRunShellCommand_singleLine_failNoLines(self):
702 cmd = 'echo $VALUE'
703 with self.assertShellCall(cmd, ''):
704 with self.assertRaises(device_errors.CommandFailedError):
705 self.device.RunShellCommand(cmd, single_line=True)
706
707 def testRunShellCommand_singleLine_failTooManyLines(self):
708 cmd = 'echo $VALUE'
709 with self.assertShellCall(cmd, 'some value\r\nanother value\r\n'):
710 with self.assertRaises(device_errors.CommandFailedError):
711 self.device.RunShellCommand(cmd, single_line=True)
712
574 def testRunShellCommand_checkReturn_success(self): 713 def testRunShellCommand_checkReturn_success(self):
575 with self.assertCalls( 714 cmd = 'echo $ANDROID_DATA'
576 "adb -s 0123456789abcdef shell 'echo $ANDROID_DATA; echo %$?'", 715 output = '/data\r\n'
577 '/data\r\n%0\r\n'): 716 with self.assertShellCall(cmd, output):
578 self.device.RunShellCommand('echo $ANDROID_DATA', check_return=True) 717 self.assertEquals([output.rstrip()],
718 self.device.RunShellCommand(cmd, check_return=True))
579 719
580 def testRunShellCommand_checkReturn_failure(self): 720 def testRunShellCommand_checkReturn_failure(self):
581 with self.assertCalls( 721 cmd = 'ls /root'
582 "adb -s 0123456789abcdef shell 'echo $ANDROID_DATA; echo %$?'", 722 output = 'opendir failed, Permission denied\r\n'
583 '\r\n%1\r\n'): 723 with self.assertShellCall(cmd, _ShellError(output)):
584 with self.assertRaises(device_errors.CommandFailedError): 724 with self.assertRaises(device_errors.AdbShellCommandFailedError):
585 self.device.RunShellCommand('echo $ANDROID_DATA', check_return=True) 725 self.device.RunShellCommand(cmd, check_return=True)
726
727 def testRunShellCommand_checkReturn_disabled(self):
728 cmd = 'ls /root'
729 output = 'opendir failed, Permission denied\r\n'
730 with self.assertShellCall(cmd, _ShellError(output)):
731 self.assertEquals([output.rstrip()],
732 self.device.RunShellCommand(cmd, check_return=False))
586 733
587 734
588 class DeviceUtilsKillAllTest(DeviceUtilsOldImplTest): 735 class DeviceUtilsKillAllTest(DeviceUtilsNewImplTest):
589 736
590 def testKillAll_noMatchingProcesses(self): 737 def testKillAll_noMatchingProcesses(self):
591 with self.assertCalls( 738 output = 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n'
592 "adb -s 0123456789abcdef shell 'ps'", 739 with self.assertShellCallSequence([('ps', output)]):
593 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n'):
594 with self.assertRaises(device_errors.CommandFailedError): 740 with self.assertRaises(device_errors.CommandFailedError):
595 self.device.KillAll('test_process') 741 self.device.KillAll('test_process')
596 742
597 def testKillAll_nonblocking(self): 743 def testKillAll_nonblocking(self):
598 with self.assertCallsSequence([ 744 with self.assertShellCallSequence([
599 ("adb -s 0123456789abcdef shell 'ps'", 745 ('ps', 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n'
600 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' 746 'u0_a1 1234 174 123456 54321 ffffffff 456789ab '
601 'u0_a1 1234 174 123456 54321 ffffffff 456789ab ' 747 'this.is.a.test.process\r\n'),
602 'this.is.a.test.process\r\n'), 748 ('kill -9 1234', '')]):
603 ("adb -s 0123456789abcdef shell 'kill -9 1234'", '')]):
604 self.assertEquals(1, 749 self.assertEquals(1,
605 self.device.KillAll('this.is.a.test.process', blocking=False)) 750 self.device.KillAll('this.is.a.test.process', blocking=False))
606 751
607 def testKillAll_blocking(self): 752 def testKillAll_blocking(self):
608 with mock.patch('time.sleep'): 753 with mock.patch('time.sleep'):
609 with self.assertCallsSequence([ 754 with self.assertShellCallSequence([
610 ("adb -s 0123456789abcdef shell 'ps'", 755 ('ps', 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n'
611 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' 756 'u0_a1 1234 174 123456 54321 ffffffff 456789ab '
612 'u0_a1 1234 174 123456 54321 ffffffff 456789ab ' 757 'this.is.a.test.process\r\n'),
613 'this.is.a.test.process\r\n'), 758 ('kill -9 1234', ''),
614 ("adb -s 0123456789abcdef shell 'kill -9 1234'", ''), 759 ('ps', 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n'
615 ("adb -s 0123456789abcdef shell 'ps'", 760 'u0_a1 1234 174 123456 54321 ffffffff 456789ab '
616 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' 761 'this.is.a.test.process\r\n'),
617 'u0_a1 1234 174 123456 54321 ffffffff 456789ab ' 762 ('ps', 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n')]):
618 'this.is.a.test.process\r\n'),
619 ("adb -s 0123456789abcdef shell 'ps'",
620 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n')]):
621 self.assertEquals(1, 763 self.assertEquals(1,
622 self.device.KillAll('this.is.a.test.process', blocking=True)) 764 self.device.KillAll('this.is.a.test.process', blocking=True))
623 765
624 def testKillAll_root(self): 766 def testKillAll_root(self):
625 with self.assertCallsSequence([ 767 with self.assertShellCallSequence([
626 ("adb -s 0123456789abcdef shell 'ps'", 768 ('ps', 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n'
627 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' 769 'u0_a1 1234 174 123456 54321 ffffffff 456789ab '
628 'u0_a1 1234 174 123456 54321 ffffffff 456789ab ' 770 'this.is.a.test.process\r\n'),
629 'this.is.a.test.process\r\n'), 771 ('ls /root', _ShellError()),
630 ("adb -s 0123456789abcdef shell 'ls /root'", 'Permission denied\r\n'), 772 ('su -c kill -9 1234', '')]):
631 ("adb -s 0123456789abcdef shell 'su -c kill -9 1234'", '')]):
632 self.assertEquals(1, 773 self.assertEquals(1,
633 self.device.KillAll('this.is.a.test.process', as_root=True)) 774 self.device.KillAll('this.is.a.test.process', as_root=True))
634 775
635 def testKillAll_sigterm(self): 776 def testKillAll_sigterm(self):
636 with self.assertCallsSequence([ 777 with self.assertShellCallSequence([
637 ("adb -s 0123456789abcdef shell 'ps'", 778 ('ps', 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n'
638 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' 779 'u0_a1 1234 174 123456 54321 ffffffff 456789ab '
639 'u0_a1 1234 174 123456 54321 ffffffff 456789ab ' 780 'this.is.a.test.process\r\n'),
640 'this.is.a.test.process\r\n'), 781 ('kill -15 1234', '')]):
641 ("adb -s 0123456789abcdef shell 'kill -15 1234'", '')]):
642 self.assertEquals(1, 782 self.assertEquals(1,
643 self.device.KillAll('this.is.a.test.process', signum=signal.SIGTERM)) 783 self.device.KillAll('this.is.a.test.process', signum=signal.SIGTERM))
644 784
645 785
646 class DeviceUtilsStartActivityTest(DeviceUtilsOldImplTest): 786 class DeviceUtilsStartActivityTest(DeviceUtilsOldImplTest):
647 787
648 def testStartActivity_actionOnly(self): 788 def testStartActivity_actionOnly(self):
649 test_intent = intent.Intent(action='android.intent.action.VIEW') 789 test_intent = intent.Intent(action='android.intent.action.VIEW')
650 with self.assertCalls( 790 with self.assertCalls(
651 "adb -s 0123456789abcdef shell 'am start " 791 "adb -s 0123456789abcdef shell 'am start "
(...skipping 285 matching lines...) Expand 10 before | Expand all | Expand 10 after
937 self.device._PushChangedFilesZipped(test_files) 1077 self.device._PushChangedFilesZipped(test_files)
938 1078
939 mock_zip_proc.assert_called_once_with( 1079 mock_zip_proc.assert_called_once_with(
940 target=device_utils.DeviceUtils._CreateDeviceZip, 1080 target=device_utils.DeviceUtils._CreateDeviceZip,
941 args=('/test/temp/file/tmp.zip', test_files)) 1081 args=('/test/temp/file/tmp.zip', test_files))
942 self.adb.Push.assert_called_once_with( 1082 self.adb.Push.assert_called_once_with(
943 '/test/temp/file/tmp.zip', '/test/device/external_dir/tmp.zip') 1083 '/test/temp/file/tmp.zip', '/test/device/external_dir/tmp.zip')
944 self.assertEqual(2, self.device._RunShellCommandImpl.call_count) 1084 self.assertEqual(2, self.device._RunShellCommandImpl.call_count)
945 self.device._RunShellCommandImpl.assert_any_call( 1085 self.device._RunShellCommandImpl.assert_any_call(
946 ['unzip', '/test/device/external_dir/tmp.zip'], 1086 ['unzip', '/test/device/external_dir/tmp.zip'],
947 as_root=True, check_return=True, 1087 as_root=True,
948 env={'PATH': '$PATH:/data/local/tmp/bin'}) 1088 env={'PATH': '$PATH:/data/local/tmp/bin'},
1089 check_return=True)
949 self.device._RunShellCommandImpl.assert_any_call( 1090 self.device._RunShellCommandImpl.assert_any_call(
950 ['rm', '/test/device/external_dir/tmp.zip']) 1091 ['rm', '/test/device/external_dir/tmp.zip'], check_return=True)
951 1092
952 def testPushChangedFilesZipped_multiple(self): 1093 def testPushChangedFilesZipped_multiple(self):
953 test_files = [('/test/host/path/file1', '/test/device/path/file1'), 1094 test_files = [('/test/host/path/file1', '/test/device/path/file1'),
954 ('/test/host/path/file2', '/test/device/path/file2')] 1095 ('/test/host/path/file2', '/test/device/path/file2')]
955 1096
956 self.device._GetExternalStoragePathImpl = mock.Mock( 1097 self.device._GetExternalStoragePathImpl = mock.Mock(
957 return_value='/test/device/external_dir') 1098 return_value='/test/device/external_dir')
958 self.device._IsOnlineImpl = mock.Mock(return_value=True) 1099 self.device._IsOnlineImpl = mock.Mock(return_value=True)
959 self.device._RunShellCommandImpl = mock.Mock() 1100 self.device._RunShellCommandImpl = mock.Mock()
960 mock_zip_temp = mock.mock_open() 1101 mock_zip_temp = mock.mock_open()
961 mock_zip_temp.return_value.name = '/test/temp/file/tmp.zip' 1102 mock_zip_temp.return_value.name = '/test/temp/file/tmp.zip'
962 with mock.patch('multiprocessing.Process') as mock_zip_proc, ( 1103 with mock.patch('multiprocessing.Process') as mock_zip_proc, (
963 mock.patch('tempfile.NamedTemporaryFile', mock_zip_temp)): 1104 mock.patch('tempfile.NamedTemporaryFile', mock_zip_temp)):
964 self.device._PushChangedFilesZipped(test_files) 1105 self.device._PushChangedFilesZipped(test_files)
965 1106
966 mock_zip_proc.assert_called_once_with( 1107 mock_zip_proc.assert_called_once_with(
967 target=device_utils.DeviceUtils._CreateDeviceZip, 1108 target=device_utils.DeviceUtils._CreateDeviceZip,
968 args=('/test/temp/file/tmp.zip', test_files)) 1109 args=('/test/temp/file/tmp.zip', test_files))
969 self.adb.Push.assert_called_once_with( 1110 self.adb.Push.assert_called_once_with(
970 '/test/temp/file/tmp.zip', '/test/device/external_dir/tmp.zip') 1111 '/test/temp/file/tmp.zip', '/test/device/external_dir/tmp.zip')
971 self.assertEqual(2, self.device._RunShellCommandImpl.call_count) 1112 self.assertEqual(2, self.device._RunShellCommandImpl.call_count)
972 self.device._RunShellCommandImpl.assert_any_call( 1113 self.device._RunShellCommandImpl.assert_any_call(
973 ['unzip', '/test/device/external_dir/tmp.zip'], 1114 ['unzip', '/test/device/external_dir/tmp.zip'],
974 as_root=True, check_return=True, 1115 as_root=True,
975 env={'PATH': '$PATH:/data/local/tmp/bin'}) 1116 env={'PATH': '$PATH:/data/local/tmp/bin'},
1117 check_return=True)
976 self.device._RunShellCommandImpl.assert_any_call( 1118 self.device._RunShellCommandImpl.assert_any_call(
977 ['rm', '/test/device/external_dir/tmp.zip']) 1119 ['rm', '/test/device/external_dir/tmp.zip'], check_return=True)
978 1120
979 1121
980 class DeviceUtilsFileExistsTest(DeviceUtilsOldImplTest): 1122 class DeviceUtilsFileExistsTest(DeviceUtilsOldImplTest):
981 1123
982 def testFileExists_usingTest_fileExists(self): 1124 def testFileExists_usingTest_fileExists(self):
983 with self.assertCalls( 1125 with self.assertCalls(
984 "adb -s 0123456789abcdef shell " 1126 "adb -s 0123456789abcdef shell "
985 "'test -e \"/data/app/test.file.exists\"; echo $?'", 1127 "'test -e \"/data/app/test.file.exists\"; echo $?'",
986 '0\r\n'): 1128 '0\r\n'):
987 self.assertTrue(self.device.FileExists('/data/app/test.file.exists')) 1129 self.assertTrue(self.device.FileExists('/data/app/test.file.exists'))
(...skipping 207 matching lines...) Expand 10 before | Expand all | Expand 10 after
1195 self.device.WriteFile('/test/file/written.to.device', 1337 self.device.WriteFile('/test/file/written.to.device',
1196 'new test file contents', as_root=True) 1338 'new test file contents', as_root=True)
1197 1339
1198 def testWriteFile_asRoot_rejected(self): 1340 def testWriteFile_asRoot_rejected(self):
1199 self.device.old_interface._privileged_command_runner = None 1341 self.device.old_interface._privileged_command_runner = None
1200 self.device.old_interface._protected_file_access_method_initialized = True 1342 self.device.old_interface._protected_file_access_method_initialized = True
1201 with self.assertRaises(device_errors.CommandFailedError): 1343 with self.assertRaises(device_errors.CommandFailedError):
1202 self.device.WriteFile('/test/file/no.permissions.to.write', 1344 self.device.WriteFile('/test/file/no.permissions.to.write',
1203 'new test file contents', as_root=True) 1345 'new test file contents', as_root=True)
1204 1346
1205 class DeviceUtilsWriteTextFileTest(DeviceUtilsOldImplTest): 1347 class DeviceUtilsWriteTextFileTest(DeviceUtilsNewImplTest):
1206 1348
1207 def testWriteTextFileTest_basic(self): 1349 def testWriteTextFileTest_basic(self):
1208 with self.assertCalls( 1350 with self.assertShellCall('echo some.string > /test/file/to.write'):
1209 "adb -s 0123456789abcdef shell 'echo some.string"
1210 " > /test/file/to.write; echo %$?'", '%0\r\n'):
1211 self.device.WriteTextFile('/test/file/to.write', 'some.string') 1351 self.device.WriteTextFile('/test/file/to.write', 'some.string')
1212 1352
1213 def testWriteTextFileTest_stringWithSpaces(self): 1353 def testWriteTextFileTest_quoted(self):
1214 with self.assertCalls( 1354 with self.assertShellCall(
1215 "adb -s 0123456789abcdef shell 'echo '\\''some other string'\\''" 1355 "echo 'some other string' > '/test/file/to write'"):
1216 " > /test/file/to.write; echo %$?'", '%0\r\n'): 1356 self.device.WriteTextFile('/test/file/to write', 'some other string')
1217 self.device.WriteTextFile('/test/file/to.write', 'some other string')
1218 1357
1219 def testWriteTextFileTest_asRoot_withSu(self): 1358 def testWriteTextFileTest_asRoot(self):
1220 with self.assertCallsSequence([ 1359 with self.assertShellCallSequence([
1221 ("adb -s 0123456789abcdef shell 'ls /root'", 'Permission denied\r\n'), 1360 ('ls /root', _ShellError()),
1222 ("adb -s 0123456789abcdef shell 'su -c echo some.string" 1361 ('su -c echo string > /test/file', '')]):
1223 " > /test/file/to.write; echo %$?'", '%0\r\n')]): 1362 self.device.WriteTextFile('/test/file', 'string', as_root=True)
1224 self.device.WriteTextFile('/test/file/to.write', 'some.string',
1225 as_root=True)
1226
1227 def testWriteTextFileTest_asRoot_withRoot(self):
1228 with self.assertCallsSequence([
1229 ("adb -s 0123456789abcdef shell 'ls /root'", 'hello\r\nworld\r\n'),
1230 ("adb -s 0123456789abcdef shell 'echo some.string"
1231 " > /test/file/to.write; echo %$?'", '%0\r\n')]):
1232 self.device.WriteTextFile('/test/file/to.write', 'some.string',
1233 as_root=True)
1234
1235 def testWriteTextFileTest_asRoot_rejected(self):
1236 with self.assertCallsSequence([
1237 ("adb -s 0123456789abcdef shell 'ls /root'", 'Permission denied\r\n'),
1238 ("adb -s 0123456789abcdef shell 'su -c echo some.string"
1239 " > /test/file/to.write; echo %$?'", '%1\r\n')]):
1240 with self.assertRaises(device_errors.CommandFailedError):
1241 self.device.WriteTextFile('/test/file/to.write', 'some.string',
1242 as_root=True)
1243 1363
1244 class DeviceUtilsLsTest(DeviceUtilsOldImplTest): 1364 class DeviceUtilsLsTest(DeviceUtilsOldImplTest):
1245 1365
1246 def testLs_nothing(self): 1366 def testLs_nothing(self):
1247 with self.assertCallsSequence([ 1367 with self.assertCallsSequence([
1248 ("adb -s 0123456789abcdef shell 'ls -lR /this/file/does.not.exist'", 1368 ("adb -s 0123456789abcdef shell 'ls -lR /this/file/does.not.exist'",
1249 '/this/file/does.not.exist: No such file or directory\r\n'), 1369 '/this/file/does.not.exist: No such file or directory\r\n'),
1250 ("adb -s 0123456789abcdef shell 'date +%z'", '+0000')]): 1370 ("adb -s 0123456789abcdef shell 'date +%z'", '+0000')]):
1251 self.assertEqual({}, self.device.Ls('/this/file/does.not.exist')) 1371 self.assertEqual({}, self.device.Ls('/this/file/does.not.exist'))
1252 1372
(...skipping 136 matching lines...) Expand 10 before | Expand all | Expand 10 after
1389 class DeviceUtilsSetPropTest(DeviceUtilsOldImplTest): 1509 class DeviceUtilsSetPropTest(DeviceUtilsOldImplTest):
1390 1510
1391 def testSetProp(self): 1511 def testSetProp(self):
1392 with self.assertCalls( 1512 with self.assertCalls(
1393 'adb -s 0123456789abcdef shell ' 1513 'adb -s 0123456789abcdef shell '
1394 'setprop this.is.a.test.property "test_property_value"', 1514 'setprop this.is.a.test.property "test_property_value"',
1395 ''): 1515 ''):
1396 self.device.SetProp('this.is.a.test.property', 'test_property_value') 1516 self.device.SetProp('this.is.a.test.property', 'test_property_value')
1397 1517
1398 1518
1399 class DeviceUtilsGetPidsTest(DeviceUtilsOldImplTest): 1519 class DeviceUtilsGetPidsTest(DeviceUtilsNewImplTest):
1400 1520
1401 def testGetPids_noMatches(self): 1521 def testGetPids_noMatches(self):
1402 with self.assertCalls( 1522 with self.assertShellCall(
1403 "adb -s 0123456789abcdef shell 'ps'", 1523 'ps',
1404 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' 1524 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n'
1405 'user 1000 100 1024 1024 ffffffff 00000000 no.match\r\n'): 1525 'user 1000 100 1024 1024 ffffffff 00000000 no.match\r\n'):
1406 self.assertEqual({}, self.device.GetPids('does.not.match')) 1526 self.assertEqual({}, self.device.GetPids('does.not.match'))
1407 1527
1408 def testGetPids_oneMatch(self): 1528 def testGetPids_oneMatch(self):
1409 with self.assertCalls( 1529 with self.assertShellCall(
1410 "adb -s 0123456789abcdef shell 'ps'", 1530 'ps',
1411 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' 1531 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n'
1412 'user 1000 100 1024 1024 ffffffff 00000000 not.a.match\r\n' 1532 'user 1000 100 1024 1024 ffffffff 00000000 not.a.match\r\n'
1413 'user 1001 100 1024 1024 ffffffff 00000000 one.match\r\n'): 1533 'user 1001 100 1024 1024 ffffffff 00000000 one.match\r\n'):
1414 self.assertEqual({'one.match': '1001'}, self.device.GetPids('one.match')) 1534 self.assertEqual({'one.match': '1001'}, self.device.GetPids('one.match'))
1415 1535
1416 def testGetPids_mutlipleMatches(self): 1536 def testGetPids_mutlipleMatches(self):
1417 with self.assertCalls( 1537 with self.assertShellCall(
1418 "adb -s 0123456789abcdef shell 'ps'", 1538 'ps',
1419 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' 1539 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n'
1420 'user 1000 100 1024 1024 ffffffff 00000000 not\r\n' 1540 'user 1000 100 1024 1024 ffffffff 00000000 not\r\n'
1421 'user 1001 100 1024 1024 ffffffff 00000000 one.match\r\n' 1541 'user 1001 100 1024 1024 ffffffff 00000000 one.match\r\n'
1422 'user 1002 100 1024 1024 ffffffff 00000000 two.match\r\n' 1542 'user 1002 100 1024 1024 ffffffff 00000000 two.match\r\n'
1423 'user 1003 100 1024 1024 ffffffff 00000000 three.match\r\n'): 1543 'user 1003 100 1024 1024 ffffffff 00000000 three.match\r\n'):
1424 self.assertEqual( 1544 self.assertEqual(
1425 {'one.match': '1001', 'two.match': '1002', 'three.match': '1003'}, 1545 {'one.match': '1001', 'two.match': '1002', 'three.match': '1003'},
1426 self.device.GetPids('match')) 1546 self.device.GetPids('match'))
1427 1547
1428 def testGetPids_exactMatch(self): 1548 def testGetPids_exactMatch(self):
1429 with self.assertCalls( 1549 with self.assertShellCall(
1430 "adb -s 0123456789abcdef shell 'ps'", 1550 'ps',
1431 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' 1551 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n'
1432 'user 1000 100 1024 1024 ffffffff 00000000 not.exact.match\r\n' 1552 'user 1000 100 1024 1024 ffffffff 00000000 not.exact.match\r\n'
1433 'user 1234 100 1024 1024 ffffffff 00000000 exact.match\r\n'): 1553 'user 1234 100 1024 1024 ffffffff 00000000 exact.match\r\n'):
1434 self.assertEqual( 1554 self.assertEqual(
1435 {'not.exact.match': '1000', 'exact.match': '1234'}, 1555 {'not.exact.match': '1000', 'exact.match': '1234'},
1436 self.device.GetPids('exact.match')) 1556 self.device.GetPids('exact.match'))
1437 1557
1438 1558
1439 class DeviceUtilsTakeScreenshotTest(DeviceUtilsOldImplTest): 1559 class DeviceUtilsTakeScreenshotTest(DeviceUtilsOldImplTest):
1440 1560
(...skipping 85 matching lines...) Expand 10 before | Expand all | Expand 10 after
1526 self.device = device_utils.DeviceUtils(None) 1646 self.device = device_utils.DeviceUtils(None)
1527 with self.assertCalls('adb get-serialno', 'unknown'), ( 1647 with self.assertCalls('adb get-serialno', 'unknown'), (
1528 self.assertRaises(device_errors.NoDevicesError)): 1648 self.assertRaises(device_errors.NoDevicesError)):
1529 str(self.device) 1649 str(self.device)
1530 1650
1531 1651
1532 if __name__ == '__main__': 1652 if __name__ == '__main__':
1533 logging.getLogger().setLevel(logging.DEBUG) 1653 logging.getLogger().setLevel(logging.DEBUG)
1534 unittest.main(verbosity=2) 1654 unittest.main(verbosity=2)
1535 1655
OLDNEW
« no previous file with comments | « build/android/pylib/device/device_utils.py ('k') | build/android/pylib/instrumentation/test_runner.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698