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

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

Issue 1108173002: Roll //build, //native_client, and a few more targets of opportunity. Base URL: git@github.com:domokit/mojo.git@master
Patch Set: Test fix Created 5 years, 7 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
« no previous file with comments | « build/android/pylib/device/device_utils.py ('k') | build/android/pylib/device_signal.py » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
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
11 # pylint: disable=W0212 11 # pylint: disable=W0212
12 # pylint: disable=W0613 12 # pylint: disable=W0613
13 13
14 import collections 14 import collections
15 import datetime 15 import datetime
16 import logging 16 import logging
17 import os 17 import os
18 import re 18 import re
19 import signal
20 import sys 19 import sys
21 import unittest 20 import unittest
22 21
23 from pylib import android_commands 22 from pylib import android_commands
24 from pylib import cmd_helper 23 from pylib import cmd_helper
25 from pylib import constants 24 from pylib import constants
25 from pylib import device_signal
26 from pylib.device import adb_wrapper 26 from pylib.device import adb_wrapper
27 from pylib.device import device_errors 27 from pylib.device import device_errors
28 from pylib.device import device_utils 28 from pylib.device import device_utils
29 from pylib.device import intent 29 from pylib.device import intent
30 from pylib.utils import mock_calls 30 from pylib.utils import mock_calls
31 31
32 # RunCommand from third_party/android_testrunner/run_command.py is mocked 32 # RunCommand from third_party/android_testrunner/run_command.py is mocked
33 # below, so its path needs to be in sys.path. 33 # below, so its path needs to be in sys.path.
34 sys.path.append(os.path.join( 34 sys.path.append(os.path.join(
35 constants.DIR_SOURCE_ROOT, 'third_party', 'android_testrunner')) 35 constants.DIR_SOURCE_ROOT, 'third_party', 'android_testrunner'))
(...skipping 71 matching lines...) Expand 10 before | Expand all | Expand 10 after
107 self.file = mock.MagicMock(spec=file) 107 self.file = mock.MagicMock(spec=file)
108 self.file.name = name 108 self.file.name = name
109 self.file.name_quoted = cmd_helper.SingleQuote(name) 109 self.file.name_quoted = cmd_helper.SingleQuote(name)
110 110
111 def __enter__(self): 111 def __enter__(self):
112 return self.file 112 return self.file
113 113
114 def __exit__(self, exc_type, exc_val, exc_tb): 114 def __exit__(self, exc_type, exc_val, exc_tb):
115 pass 115 pass
116 116
117 @property
118 def name(self):
119 return self.file.name
120
117 121
118 class _PatchedFunction(object): 122 class _PatchedFunction(object):
119 def __init__(self, patched=None, mocked=None): 123 def __init__(self, patched=None, mocked=None):
120 self.patched = patched 124 self.patched = patched
121 self.mocked = mocked 125 self.mocked = mocked
122 126
123 127
124 def _AdbWrapperMock(test_serial): 128 def _AdbWrapperMock(test_serial):
125 adb = mock.Mock(spec=adb_wrapper.AdbWrapper) 129 adb = mock.Mock(spec=adb_wrapper.AdbWrapper)
126 adb.__str__ = mock.Mock(return_value=test_serial) 130 adb.__str__ = mock.Mock(return_value=test_serial)
(...skipping 448 matching lines...) Expand 10 before | Expand all | Expand 10 after
575 with self.assertRaises(device_errors.AdbCommandFailedError): 579 with self.assertRaises(device_errors.AdbCommandFailedError):
576 self.device.RunShellCommand(cmd, check_return=True) 580 self.device.RunShellCommand(cmd, check_return=True)
577 581
578 def testRunShellCommand_checkReturn_disabled(self): 582 def testRunShellCommand_checkReturn_disabled(self):
579 cmd = 'ls /root' 583 cmd = 'ls /root'
580 output = 'opendir failed, Permission denied\n' 584 output = 'opendir failed, Permission denied\n'
581 with self.assertCall(self.call.adb.Shell(cmd), self.ShellError(output)): 585 with self.assertCall(self.call.adb.Shell(cmd), self.ShellError(output)):
582 self.assertEquals([output.rstrip()], 586 self.assertEquals([output.rstrip()],
583 self.device.RunShellCommand(cmd, check_return=False)) 587 self.device.RunShellCommand(cmd, check_return=False))
584 588
589 def testRunShellCommand_largeOutput_enabled(self):
590 cmd = 'echo $VALUE'
591 temp_file = MockTempFile('/sdcard/temp-123')
592 cmd_redirect = '%s > %s' % (cmd, temp_file.name)
593 with self.assertCalls(
594 (mock.call.pylib.utils.device_temp_file.DeviceTempFile(self.adb),
595 temp_file),
596 (self.call.adb.Shell(cmd_redirect)),
597 (self.call.device.ReadFile(temp_file.name), 'something')):
598 self.assertEquals(
599 ['something'],
600 self.device.RunShellCommand(
601 cmd, large_output=True, check_return=True))
602
603 def testRunShellCommand_largeOutput_disabledNoTrigger(self):
604 cmd = 'something'
605 with self.assertCall(self.call.adb.Shell(cmd), self.ShellError('')):
606 with self.assertRaises(device_errors.AdbCommandFailedError):
607 self.device.RunShellCommand(cmd, check_return=True)
608
609 def testRunShellCommand_largeOutput_disabledTrigger(self):
610 cmd = 'echo $VALUE'
611 temp_file = MockTempFile('/sdcard/temp-123')
612 cmd_redirect = '%s > %s' % (cmd, temp_file.name)
613 with self.assertCalls(
614 (self.call.adb.Shell(cmd), self.ShellError('', None)),
615 (mock.call.pylib.utils.device_temp_file.DeviceTempFile(self.adb),
616 temp_file),
617 (self.call.adb.Shell(cmd_redirect)),
618 (self.call.device.ReadFile(mock.ANY), 'something')):
619 self.assertEquals(['something'],
620 self.device.RunShellCommand(cmd, check_return=True))
621
622
623 class DeviceUtilsRunPipedShellCommandTest(DeviceUtilsTest):
624
625 def testRunPipedShellCommand_success(self):
626 with self.assertCall(
627 self.call.device.RunShellCommand(
628 'ps | grep foo; echo "PIPESTATUS: ${PIPESTATUS[@]}"',
629 check_return=True),
630 ['This line contains foo', 'PIPESTATUS: 0 0']):
631 self.assertEquals(['This line contains foo'],
632 self.device._RunPipedShellCommand('ps | grep foo'))
633
634 def testRunPipedShellCommand_firstCommandFails(self):
635 with self.assertCall(
636 self.call.device.RunShellCommand(
637 'ps | grep foo; echo "PIPESTATUS: ${PIPESTATUS[@]}"',
638 check_return=True),
639 ['PIPESTATUS: 1 0']):
640 with self.assertRaises(device_errors.AdbShellCommandFailedError) as ec:
641 self.device._RunPipedShellCommand('ps | grep foo')
642 self.assertEquals([1, 0], ec.exception.status)
643
644 def testRunPipedShellCommand_secondCommandFails(self):
645 with self.assertCall(
646 self.call.device.RunShellCommand(
647 'ps | grep foo; echo "PIPESTATUS: ${PIPESTATUS[@]}"',
648 check_return=True),
649 ['PIPESTATUS: 0 1']):
650 with self.assertRaises(device_errors.AdbShellCommandFailedError) as ec:
651 self.device._RunPipedShellCommand('ps | grep foo')
652 self.assertEquals([0, 1], ec.exception.status)
653
654 def testRunPipedShellCommand_outputCutOff(self):
655 with self.assertCall(
656 self.call.device.RunShellCommand(
657 'ps | grep foo; echo "PIPESTATUS: ${PIPESTATUS[@]}"',
658 check_return=True),
659 ['foo.bar'] * 256 + ['foo.ba']):
660 with self.assertRaises(device_errors.AdbShellCommandFailedError) as ec:
661 self.device._RunPipedShellCommand('ps | grep foo')
662 self.assertIs(None, ec.exception.status)
663
585 664
586 class DeviceUtilsGetDevicePieWrapper(DeviceUtilsTest): 665 class DeviceUtilsGetDevicePieWrapper(DeviceUtilsTest):
587 666
588 def testGetDevicePieWrapper_jb(self): 667 def testGetDevicePieWrapper_jb(self):
589 with self.assertCall( 668 with self.assertCall(
590 self.call.device.build_version_sdk(), 669 self.call.device.build_version_sdk(),
591 constants.ANDROID_SDK_VERSION_CODES.JELLY_BEAN): 670 constants.ANDROID_SDK_VERSION_CODES.JELLY_BEAN):
592 self.assertEqual('', self.device.GetDevicePieWrapper()) 671 self.assertEqual('', self.device.GetDevicePieWrapper())
593 672
594 def testGetDevicePieWrapper_ics(self): 673 def testGetDevicePieWrapper_ics(self):
595 with self.assertCalls( 674 with self.assertCalls(
596 (self.call.device.build_version_sdk(), 675 (self.call.device.build_version_sdk(),
597 constants.ANDROID_SDK_VERSION_CODES.ICE_CREAM_SANDWICH), 676 constants.ANDROID_SDK_VERSION_CODES.ICE_CREAM_SANDWICH),
598 (mock.call.pylib.constants.GetOutDirectory(), '/foo/bar'), 677 (mock.call.pylib.constants.GetOutDirectory(), '/foo/bar'),
599 (mock.call.os.path.exists(mock.ANY), True), 678 (mock.call.os.path.exists(mock.ANY), True),
600 (self.call.adb.Push(mock.ANY, mock.ANY), '')): 679 (self.call.adb.Push(mock.ANY, mock.ANY), '')):
601 self.assertNotEqual('', self.device.GetDevicePieWrapper()) 680 self.assertNotEqual('', self.device.GetDevicePieWrapper())
602 681
603 682
604 @mock.patch('time.sleep', mock.Mock()) 683 @mock.patch('time.sleep', mock.Mock())
605 class DeviceUtilsKillAllTest(DeviceUtilsTest): 684 class DeviceUtilsKillAllTest(DeviceUtilsTest):
606 685
607 def testKillAll_noMatchingProcesses(self): 686 def testKillAll_noMatchingProcessesFailure(self):
608 with self.assertCall(self.call.adb.Shell('ps'), 687 with self.assertCall(self.call.device.GetPids('test_process'), {}):
609 'USER PID PPID VSIZE RSS WCHAN PC NAME\n'):
610 with self.assertRaises(device_errors.CommandFailedError): 688 with self.assertRaises(device_errors.CommandFailedError):
611 self.device.KillAll('test_process') 689 self.device.KillAll('test_process')
612 690
691 def testKillAll_noMatchingProcessesQuiet(self):
692 with self.assertCall(self.call.device.GetPids('test_process'), {}):
693 self.assertEqual(0, self.device.KillAll('test_process', quiet=True))
694
613 def testKillAll_nonblocking(self): 695 def testKillAll_nonblocking(self):
614 with self.assertCalls( 696 with self.assertCalls(
615 (self.call.adb.Shell('ps'), 697 (self.call.device.GetPids('some.process'), {'some.process': '1234'}),
616 'USER PID PPID VSIZE RSS WCHAN PC NAME\n'
617 'u0_a1 1234 174 123456 54321 ffffffff 456789ab some.process\n'),
618 (self.call.adb.Shell('kill -9 1234'), '')): 698 (self.call.adb.Shell('kill -9 1234'), '')):
619 self.assertEquals(1, 699 self.assertEquals(
620 self.device.KillAll('some.process', blocking=False)) 700 1, self.device.KillAll('some.process', blocking=False))
621 701
622 def testKillAll_blocking(self): 702 def testKillAll_blocking(self):
623 with self.assertCalls( 703 with self.assertCalls(
624 (self.call.adb.Shell('ps'), 704 (self.call.device.GetPids('some.process'), {'some.process': '1234'}),
625 'USER PID PPID VSIZE RSS WCHAN PC NAME\n'
626 'u0_a1 1234 174 123456 54321 ffffffff 456789ab some.process\n'),
627 (self.call.adb.Shell('kill -9 1234'), ''), 705 (self.call.adb.Shell('kill -9 1234'), ''),
628 (self.call.adb.Shell('ps'), 706 (self.call.device.GetPids('some.process'), {'some.process': '1234'}),
629 'USER PID PPID VSIZE RSS WCHAN PC NAME\n' 707 (self.call.device.GetPids('some.process'), [])):
630 'u0_a1 1234 174 123456 54321 ffffffff 456789ab some.process\n'), 708 self.assertEquals(
631 (self.call.adb.Shell('ps'), 709 1, self.device.KillAll('some.process', blocking=True))
632 'USER PID PPID VSIZE RSS WCHAN PC NAME\n')):
633 self.assertEquals(1,
634 self.device.KillAll('some.process', blocking=True))
635 710
636 def testKillAll_root(self): 711 def testKillAll_root(self):
637 with self.assertCalls( 712 with self.assertCalls(
638 (self.call.adb.Shell('ps'), 713 (self.call.device.GetPids('some.process'), {'some.process': '1234'}),
639 'USER PID PPID VSIZE RSS WCHAN PC NAME\n'
640 'u0_a1 1234 174 123456 54321 ffffffff 456789ab some.process\n'),
641 (self.call.device.NeedsSU(), True), 714 (self.call.device.NeedsSU(), True),
642 (self.call.adb.Shell("su -c sh -c 'kill -9 1234'"), '')): 715 (self.call.adb.Shell("su -c sh -c 'kill -9 1234'"), '')):
643 self.assertEquals(1, 716 self.assertEquals(
644 self.device.KillAll('some.process', as_root=True)) 717 1, self.device.KillAll('some.process', as_root=True))
645 718
646 def testKillAll_sigterm(self): 719 def testKillAll_sigterm(self):
647 with self.assertCalls( 720 with self.assertCalls(
648 (self.call.adb.Shell('ps'), 721 (self.call.device.GetPids('some.process'), {'some.process': '1234'}),
649 'USER PID PPID VSIZE RSS WCHAN PC NAME\n'
650 'u0_a1 1234 174 123456 54321 ffffffff 456789ab some.process\n'),
651 (self.call.adb.Shell('kill -15 1234'), '')): 722 (self.call.adb.Shell('kill -15 1234'), '')):
652 self.assertEquals(1, 723 self.assertEquals(
653 self.device.KillAll('some.process', signum=signal.SIGTERM)) 724 1, self.device.KillAll('some.process', signum=device_signal.SIGTERM))
654 725
655 726
656 class DeviceUtilsStartActivityTest(DeviceUtilsTest): 727 class DeviceUtilsStartActivityTest(DeviceUtilsTest):
657 728
658 def testStartActivity_actionOnly(self): 729 def testStartActivity_actionOnly(self):
659 test_intent = intent.Intent(action='android.intent.action.VIEW') 730 test_intent = intent.Intent(action='android.intent.action.VIEW')
660 with self.assertCall( 731 with self.assertCall(
661 self.call.adb.Shell('am start ' 732 self.call.adb.Shell('am start '
662 '-a android.intent.action.VIEW'), 733 '-a android.intent.action.VIEW'),
663 'Starting: Intent { act=android.intent.action.VIEW }'): 734 'Starting: Intent { act=android.intent.action.VIEW }'):
(...skipping 407 matching lines...) Expand 10 before | Expand all | Expand 10 after
1071 with self.assertRaises(device_errors.CommandFailedError): 1142 with self.assertRaises(device_errors.CommandFailedError):
1072 self.device._ReadFileWithPull('/path/to/device/file') 1143 self.device._ReadFileWithPull('/path/to/device/file')
1073 1144
1074 def testReadFile_exists(self): 1145 def testReadFile_exists(self):
1075 with self.assertCalls( 1146 with self.assertCalls(
1076 (self.call.device.RunShellCommand( 1147 (self.call.device.RunShellCommand(
1077 ['ls', '-l', '/read/this/test/file'], 1148 ['ls', '-l', '/read/this/test/file'],
1078 as_root=False, check_return=True), 1149 as_root=False, check_return=True),
1079 ['-rw-rw---- root foo 256 1970-01-01 00:00 file']), 1150 ['-rw-rw---- root foo 256 1970-01-01 00:00 file']),
1080 (self.call.device.RunShellCommand( 1151 (self.call.device.RunShellCommand(
1081 ['cat', '/read/this/test/file'], as_root=False, check_return=True), 1152 ['cat', '/read/this/test/file'],
1153 as_root=False, check_return=True),
1082 ['this is a test file'])): 1154 ['this is a test file'])):
1083 self.assertEqual('this is a test file\n', 1155 self.assertEqual('this is a test file\n',
1084 self.device.ReadFile('/read/this/test/file')) 1156 self.device.ReadFile('/read/this/test/file'))
1085 1157
1086 def testReadFile_doesNotExist(self): 1158 def testReadFile_doesNotExist(self):
1087 with self.assertCall( 1159 with self.assertCall(
1088 self.call.device.RunShellCommand( 1160 self.call.device.RunShellCommand(
1089 ['ls', '-l', '/this/file/does.not.exist'], 1161 ['ls', '-l', '/this/file/does.not.exist'],
1090 as_root=False, check_return=True), 1162 as_root=False, check_return=True),
1091 self.CommandError('File does not exist')): 1163 self.CommandError('File does not exist')):
1092 with self.assertRaises(device_errors.CommandFailedError): 1164 with self.assertRaises(device_errors.CommandFailedError):
1093 self.device.ReadFile('/this/file/does.not.exist') 1165 self.device.ReadFile('/this/file/does.not.exist')
1094 1166
1167 def testReadFile_zeroSize(self):
1168 with self.assertCalls(
1169 (self.call.device.RunShellCommand(
1170 ['ls', '-l', '/this/file/has/zero/size'],
1171 as_root=False, check_return=True),
1172 ['-r--r--r-- root foo 0 1970-01-01 00:00 zero_size_file']),
1173 (self.call.device._ReadFileWithPull('/this/file/has/zero/size'),
1174 'but it has contents\n')):
1175 self.assertEqual('but it has contents\n',
1176 self.device.ReadFile('/this/file/has/zero/size'))
1177
1095 def testReadFile_withSU(self): 1178 def testReadFile_withSU(self):
1096 with self.assertCalls( 1179 with self.assertCalls(
1097 (self.call.device.RunShellCommand( 1180 (self.call.device.RunShellCommand(
1098 ['ls', '-l', '/this/file/can.be.read.with.su'], 1181 ['ls', '-l', '/this/file/can.be.read.with.su'],
1099 as_root=True, check_return=True), 1182 as_root=True, check_return=True),
1100 ['-rw------- root root 256 1970-01-01 00:00 can.be.read.with.su']), 1183 ['-rw------- root root 256 1970-01-01 00:00 can.be.read.with.su']),
1101 (self.call.device.RunShellCommand( 1184 (self.call.device.RunShellCommand(
1102 ['cat', '/this/file/can.be.read.with.su'], 1185 ['cat', '/this/file/can.be.read.with.su'],
1103 as_root=True, check_return=True), 1186 as_root=True, check_return=True),
1104 ['this is a test file', 'read with su'])): 1187 ['this is a test file', 'read with su'])):
(...skipping 238 matching lines...) Expand 10 before | Expand all | Expand 10 after
1343 with self.assertCalls( 1426 with self.assertCalls(
1344 (self.call.adb.Shell('setprop test.property new_value'), ''), 1427 (self.call.adb.Shell('setprop test.property new_value'), ''),
1345 (self.call.adb.Shell('getprop test.property'), 'old_value')): 1428 (self.call.adb.Shell('getprop test.property'), 'old_value')):
1346 with self.assertRaises(device_errors.CommandFailedError): 1429 with self.assertRaises(device_errors.CommandFailedError):
1347 self.device.SetProp('test.property', 'new_value', check=True) 1430 self.device.SetProp('test.property', 'new_value', check=True)
1348 1431
1349 1432
1350 class DeviceUtilsGetPidsTest(DeviceUtilsTest): 1433 class DeviceUtilsGetPidsTest(DeviceUtilsTest):
1351 1434
1352 def testGetPids_noMatches(self): 1435 def testGetPids_noMatches(self):
1353 with self.assertCall(self.call.adb.Shell('ps'), 1436 with self.assertCall(
1354 'USER PID PPID VSIZE RSS WCHAN PC NAME\n' 1437 self.call.device._RunPipedShellCommand('ps | grep -F does.not.match'),
1355 'user 1000 100 1024 1024 ffffffff 00000000 no.match\n'): 1438 []):
1356 self.assertEqual({}, self.device.GetPids('does.not.match')) 1439 self.assertEqual({}, self.device.GetPids('does.not.match'))
1357 1440
1358 def testGetPids_oneMatch(self): 1441 def testGetPids_oneMatch(self):
1359 with self.assertCall(self.call.adb.Shell('ps'), 1442 with self.assertCall(
1360 'USER PID PPID VSIZE RSS WCHAN PC NAME\n' 1443 self.call.device._RunPipedShellCommand('ps | grep -F one.match'),
1361 'user 1000 100 1024 1024 ffffffff 00000000 not.a.match\n' 1444 ['user 1001 100 1024 1024 ffffffff 00000000 one.match']):
1362 'user 1001 100 1024 1024 ffffffff 00000000 one.match\n'):
1363 self.assertEqual({'one.match': '1001'}, self.device.GetPids('one.match')) 1445 self.assertEqual({'one.match': '1001'}, self.device.GetPids('one.match'))
1364 1446
1365 def testGetPids_mutlipleMatches(self): 1447 def testGetPids_mutlipleMatches(self):
1366 with self.assertCall(self.call.adb.Shell('ps'), 1448 with self.assertCall(
1367 'USER PID PPID VSIZE RSS WCHAN PC NAME\n' 1449 self.call.device._RunPipedShellCommand('ps | grep -F match'),
1368 'user 1000 100 1024 1024 ffffffff 00000000 not\n' 1450 ['user 1001 100 1024 1024 ffffffff 00000000 one.match',
1369 'user 1001 100 1024 1024 ffffffff 00000000 one.match\n' 1451 'user 1002 100 1024 1024 ffffffff 00000000 two.match',
1370 'user 1002 100 1024 1024 ffffffff 00000000 two.match\n' 1452 'user 1003 100 1024 1024 ffffffff 00000000 three.match']):
1371 'user 1003 100 1024 1024 ffffffff 00000000 three.match\n'):
1372 self.assertEqual( 1453 self.assertEqual(
1373 {'one.match': '1001', 'two.match': '1002', 'three.match': '1003'}, 1454 {'one.match': '1001', 'two.match': '1002', 'three.match': '1003'},
1374 self.device.GetPids('match')) 1455 self.device.GetPids('match'))
1375 1456
1376 def testGetPids_exactMatch(self): 1457 def testGetPids_exactMatch(self):
1377 with self.assertCall(self.call.adb.Shell('ps'), 1458 with self.assertCall(
1378 'USER PID PPID VSIZE RSS WCHAN PC NAME\n' 1459 self.call.device._RunPipedShellCommand('ps | grep -F exact.match'),
1379 'user 1000 100 1024 1024 ffffffff 00000000 not.exact.match\n' 1460 ['user 1000 100 1024 1024 ffffffff 00000000 not.exact.match',
1380 'user 1234 100 1024 1024 ffffffff 00000000 exact.match\n'): 1461 'user 1234 100 1024 1024 ffffffff 00000000 exact.match']):
1381 self.assertEqual( 1462 self.assertEqual(
1382 {'not.exact.match': '1000', 'exact.match': '1234'}, 1463 {'not.exact.match': '1000', 'exact.match': '1234'},
1383 self.device.GetPids('exact.match')) 1464 self.device.GetPids('exact.match'))
1384 1465
1466 def testGetPids_quotable(self):
1467 with self.assertCall(
1468 self.call.device._RunPipedShellCommand("ps | grep -F 'my$process'"),
1469 ['user 1234 100 1024 1024 ffffffff 00000000 my$process']):
1470 self.assertEqual(
1471 {'my$process': '1234'}, self.device.GetPids('my$process'))
1472
1385 1473
1386 class DeviceUtilsTakeScreenshotTest(DeviceUtilsTest): 1474 class DeviceUtilsTakeScreenshotTest(DeviceUtilsTest):
1387 1475
1388 def testTakeScreenshot_fileNameProvided(self): 1476 def testTakeScreenshot_fileNameProvided(self):
1389 with self.assertCalls( 1477 with self.assertCalls(
1390 (mock.call.pylib.utils.device_temp_file.DeviceTempFile( 1478 (mock.call.pylib.utils.device_temp_file.DeviceTempFile(
1391 self.adb, suffix='.png'), 1479 self.adb, suffix='.png'),
1392 MockTempFile('/tmp/path/temp-123.png')), 1480 MockTempFile('/tmp/path/temp-123.png')),
1393 (self.call.adb.Shell('/system/bin/screencap -p /tmp/path/temp-123.png'), 1481 (self.call.adb.Shell('/system/bin/screencap -p /tmp/path/temp-123.png'),
1394 ''), 1482 ''),
1395 self.call.device.PullFile('/tmp/path/temp-123.png', 1483 self.call.device.PullFile('/tmp/path/temp-123.png',
1396 '/test/host/screenshot.png')): 1484 '/test/host/screenshot.png')):
1397 self.device.TakeScreenshot('/test/host/screenshot.png') 1485 self.device.TakeScreenshot('/test/host/screenshot.png')
1398 1486
1399 1487
1400 class DeviceUtilsGetMemoryUsageForPidTest(DeviceUtilsTest): 1488 class DeviceUtilsGetMemoryUsageForPidTest(DeviceUtilsTest):
1401 1489
1402 def setUp(self): 1490 def setUp(self):
1403 super(DeviceUtilsGetMemoryUsageForPidTest, self).setUp() 1491 super(DeviceUtilsGetMemoryUsageForPidTest, self).setUp()
1404 1492
1405 def testGetMemoryUsageForPid_validPid(self): 1493 def testGetMemoryUsageForPid_validPid(self):
1406 with self.assertCalls( 1494 with self.assertCalls(
1407 (self.call.device.RunShellCommand( 1495 (self.call.device._RunPipedShellCommand(
1408 ['showmap', '1234'], as_root=True, check_return=True), 1496 'showmap 1234 | grep TOTAL', as_root=True),
1409 ['100 101 102 103 104 105 106 107 TOTAL']), 1497 ['100 101 102 103 104 105 106 107 TOTAL']),
1410 (self.call.device.ReadFile('/proc/1234/status', as_root=True), 1498 (self.call.device.ReadFile('/proc/1234/status', as_root=True),
1411 'VmHWM: 1024 kB\n')): 1499 'VmHWM: 1024 kB\n')):
1412 self.assertEqual( 1500 self.assertEqual(
1413 { 1501 {
1414 'Size': 100, 1502 'Size': 100,
1415 'Rss': 101, 1503 'Rss': 101,
1416 'Pss': 102, 1504 'Pss': 102,
1417 'Shared_Clean': 103, 1505 'Shared_Clean': 103,
1418 'Shared_Dirty': 104, 1506 'Shared_Dirty': 104,
1419 'Private_Clean': 105, 1507 'Private_Clean': 105,
1420 'Private_Dirty': 106, 1508 'Private_Dirty': 106,
1421 'VmHWM': 1024 1509 'VmHWM': 1024
1422 }, 1510 },
1423 self.device.GetMemoryUsageForPid(1234)) 1511 self.device.GetMemoryUsageForPid(1234))
1424 1512
1425 def testGetMemoryUsageForPid_noSmaps(self): 1513 def testGetMemoryUsageForPid_noSmaps(self):
1426 with self.assertCalls( 1514 with self.assertCalls(
1427 (self.call.device.RunShellCommand( 1515 (self.call.device._RunPipedShellCommand(
1428 ['showmap', '4321'], as_root=True, check_return=True), 1516 'showmap 4321 | grep TOTAL', as_root=True),
1429 ['cannot open /proc/4321/smaps: No such file or directory']), 1517 ['cannot open /proc/4321/smaps: No such file or directory']),
1430 (self.call.device.ReadFile('/proc/4321/status', as_root=True), 1518 (self.call.device.ReadFile('/proc/4321/status', as_root=True),
1431 'VmHWM: 1024 kb\n')): 1519 'VmHWM: 1024 kb\n')):
1432 self.assertEquals({'VmHWM': 1024}, self.device.GetMemoryUsageForPid(4321)) 1520 self.assertEquals({'VmHWM': 1024}, self.device.GetMemoryUsageForPid(4321))
1433 1521
1434 def testGetMemoryUsageForPid_noStatus(self): 1522 def testGetMemoryUsageForPid_noStatus(self):
1435 with self.assertCalls( 1523 with self.assertCalls(
1436 (self.call.device.RunShellCommand( 1524 (self.call.device._RunPipedShellCommand(
1437 ['showmap', '4321'], as_root=True, check_return=True), 1525 'showmap 4321 | grep TOTAL', as_root=True),
1438 ['100 101 102 103 104 105 106 107 TOTAL']), 1526 ['100 101 102 103 104 105 106 107 TOTAL']),
1439 (self.call.device.ReadFile('/proc/4321/status', as_root=True), 1527 (self.call.device.ReadFile('/proc/4321/status', as_root=True),
1440 self.CommandError())): 1528 self.CommandError())):
1441 self.assertEquals( 1529 self.assertEquals(
1442 { 1530 {
1443 'Size': 100, 1531 'Size': 100,
1444 'Rss': 101, 1532 'Rss': 101,
1445 'Pss': 102, 1533 'Pss': 102,
1446 'Shared_Clean': 103, 1534 'Shared_Clean': 103,
1447 'Shared_Dirty': 104, 1535 'Shared_Dirty': 104,
1448 'Private_Clean': 105, 1536 'Private_Clean': 105,
1449 'Private_Dirty': 106, 1537 'Private_Dirty': 106,
1450 }, 1538 },
1451 self.device.GetMemoryUsageForPid(4321)) 1539 self.device.GetMemoryUsageForPid(4321))
1452 1540
1453 1541
1454 class DeviceUtilsGetBatteryInfoTest(DeviceUtilsTest):
1455 def testGetBatteryInfo_normal(self):
1456 with self.assertCall(
1457 self.call.device.RunShellCommand(
1458 ['dumpsys', 'battery'], check_return=True),
1459 [
1460 'Current Battery Service state:',
1461 ' AC powered: false',
1462 ' USB powered: true',
1463 ' level: 100',
1464 ' temperature: 321',
1465 ]):
1466 self.assertEquals(
1467 {
1468 'AC powered': 'false',
1469 'USB powered': 'true',
1470 'level': '100',
1471 'temperature': '321',
1472 },
1473 self.device.GetBatteryInfo())
1474
1475
1476 def testGetBatteryInfo_nothing(self):
1477 with self.assertCall(
1478 self.call.device.RunShellCommand(
1479 ['dumpsys', 'battery'], check_return=True), []):
1480 self.assertEquals({}, self.device.GetBatteryInfo())
1481
1482
1483 class DeviceUtilsGetChargingTest(DeviceUtilsTest):
1484 def testGetCharging_usb(self):
1485 with self.assertCall(
1486 self.call.device.GetBatteryInfo(), {'USB powered': 'true'}):
1487 self.assertTrue(self.device.GetCharging())
1488
1489 def testGetCharging_usbFalse(self):
1490 with self.assertCall(
1491 self.call.device.GetBatteryInfo(), {'USB powered': 'false'}):
1492 self.assertFalse(self.device.GetCharging())
1493
1494 def testGetCharging_ac(self):
1495 with self.assertCall(
1496 self.call.device.GetBatteryInfo(), {'AC powered': 'true'}):
1497 self.assertTrue(self.device.GetCharging())
1498
1499 def testGetCharging_wireless(self):
1500 with self.assertCall(
1501 self.call.device.GetBatteryInfo(), {'Wireless powered': 'true'}):
1502 self.assertTrue(self.device.GetCharging())
1503
1504 def testGetCharging_unknown(self):
1505 with self.assertCall(
1506 self.call.device.GetBatteryInfo(), {'level': '42'}):
1507 self.assertFalse(self.device.GetCharging())
1508
1509
1510 class DeviceUtilsSetChargingTest(DeviceUtilsTest):
1511
1512 @mock.patch('time.sleep', mock.Mock())
1513 def testSetCharging_enabled(self):
1514 with self.assertCalls(
1515 (self.call.device.FileExists(mock.ANY), True),
1516 (self.call.device.RunShellCommand(mock.ANY, check_return=True), []),
1517 (self.call.device.GetCharging(), False),
1518 (self.call.device.RunShellCommand(mock.ANY, check_return=True), []),
1519 (self.call.device.GetCharging(), True)):
1520 self.device.SetCharging(True)
1521
1522 def testSetCharging_alreadyEnabled(self):
1523 with self.assertCalls(
1524 (self.call.device.FileExists(mock.ANY), True),
1525 (self.call.device.RunShellCommand(mock.ANY, check_return=True), []),
1526 (self.call.device.GetCharging(), True)):
1527 self.device.SetCharging(True)
1528
1529 @mock.patch('time.sleep', mock.Mock())
1530 def testSetCharging_disabled(self):
1531 with self.assertCalls(
1532 (self.call.device.FileExists(mock.ANY), True),
1533 (self.call.device.RunShellCommand(mock.ANY, check_return=True), []),
1534 (self.call.device.GetCharging(), True),
1535 (self.call.device.RunShellCommand(mock.ANY, check_return=True), []),
1536 (self.call.device.GetCharging(), False)):
1537 self.device.SetCharging(False)
1538
1539
1540 class DeviceUtilsSetBatteryMeasurementTest(DeviceUtilsTest):
1541
1542 def testBatteryMeasurement(self):
1543 with self.assertCalls(
1544 (self.call.device.RunShellCommand(
1545 mock.ANY, retries=0, single_line=True,
1546 timeout=10, check_return=True), '22'),
1547 (self.call.device.RunShellCommand(
1548 ['dumpsys', 'batterystats', '--reset'], check_return=True), []),
1549 (self.call.device.RunShellCommand(
1550 ['dumpsys', 'batterystats', '--charged', '--checkin'],
1551 check_return=True), []),
1552 (self.call.device.RunShellCommand(
1553 ['dumpsys', 'battery', 'set', 'usb', '0'], check_return=True), []),
1554 (self.call.device.GetCharging(), False),
1555 (self.call.device.RunShellCommand(
1556 ['dumpsys', 'battery', 'set', 'usb', '1'], check_return=True), []),
1557 (self.call.device.RunShellCommand(
1558 ['dumpsys', 'battery', 'reset'], check_return=True), []),
1559 (self.call.device.GetCharging(), True)):
1560 with self.device.BatteryMeasurement():
1561 pass
1562
1563
1564 class DeviceUtilsStrTest(DeviceUtilsTest): 1542 class DeviceUtilsStrTest(DeviceUtilsTest):
1565 1543
1566 def testStr_returnsSerial(self): 1544 def testStr_returnsSerial(self):
1567 with self.assertCalls( 1545 with self.assertCalls(
1568 (self.call.adb.GetDeviceSerial(), '0123456789abcdef')): 1546 (self.call.adb.GetDeviceSerial(), '0123456789abcdef')):
1569 self.assertEqual('0123456789abcdef', str(self.device)) 1547 self.assertEqual('0123456789abcdef', str(self.device))
1570 1548
1571 1549
1550 class DeviceUtilsClientCache(DeviceUtilsTest):
1551
1552 def testClientCache_twoCaches(self):
1553 self.device._cache['test'] = 0
1554 client_cache_one = self.device.GetClientCache('ClientOne')
1555 client_cache_one['test'] = 1
1556 client_cache_two = self.device.GetClientCache('ClientTwo')
1557 client_cache_two['test'] = 2
1558 self.assertEqual(self.device._cache, {'test': 0})
1559 self.assertEqual(client_cache_one, {'test': 1})
1560 self.assertEqual(client_cache_two, {'test': 2})
1561 self.device._ClearCache()
1562 self.assertEqual(self.device._cache, {})
1563 self.assertEqual(client_cache_one, {})
1564 self.assertEqual(client_cache_two, {})
1565
1566 def testClientCache_multipleInstances(self):
1567 client_cache_one = self.device.GetClientCache('ClientOne')
1568 client_cache_one['test'] = 1
1569 client_cache_two = self.device.GetClientCache('ClientOne')
1570 self.assertEqual(client_cache_one, {'test': 1})
1571 self.assertEqual(client_cache_two, {'test': 1})
1572 self.device._ClearCache()
1573 self.assertEqual(client_cache_one, {})
1574 self.assertEqual(client_cache_two, {})
1575
1576
1572 class DeviceUtilsParallelTest(mock_calls.TestCase): 1577 class DeviceUtilsParallelTest(mock_calls.TestCase):
1573 1578
1574 def testParallel_default(self): 1579 def testParallel_default(self):
1575 test_serials = ['0123456789abcdef', 'fedcba9876543210'] 1580 test_serials = ['0123456789abcdef', 'fedcba9876543210']
1576 with self.assertCall( 1581 with self.assertCall(
1577 mock.call.pylib.device.adb_wrapper.AdbWrapper.GetDevices(), 1582 mock.call.pylib.device.device_utils.DeviceUtils.HealthyDevices(),
1578 [_AdbWrapperMock(serial) for serial in test_serials]): 1583 [device_utils.DeviceUtils(s) for s in test_serials]):
1579 parallel_devices = device_utils.DeviceUtils.parallel() 1584 parallel_devices = device_utils.DeviceUtils.parallel()
1580 for serial, device in zip(test_serials, parallel_devices.pGet(None)): 1585 for serial, device in zip(test_serials, parallel_devices.pGet(None)):
1581 self.assertTrue( 1586 self.assertTrue(isinstance(device, device_utils.DeviceUtils))
1582 isinstance(device, device_utils.DeviceUtils) 1587 self.assertEquals(serial, device.adb.GetDeviceSerial())
1583 and serial == str(device),
1584 'Expected a DeviceUtils object with serial %s' % serial)
1585 1588
1586 def testParallel_noDevices(self): 1589 def testParallel_noDevices(self):
1587 with self.assertCall( 1590 with self.assertCall(
1588 mock.call.pylib.device.adb_wrapper.AdbWrapper.GetDevices(), []): 1591 mock.call.pylib.device.device_utils.DeviceUtils.HealthyDevices(), []):
1589 with self.assertRaises(device_errors.NoDevicesError): 1592 with self.assertRaises(device_errors.NoDevicesError):
1590 device_utils.DeviceUtils.parallel() 1593 device_utils.DeviceUtils.parallel()
1591 1594
1592 1595
1596 class DeviceUtilsHealthyDevicesTest(mock_calls.TestCase):
1597
1598 def _createAdbWrapperMock(self, serial, is_ready=True):
1599 adb = _AdbWrapperMock(serial)
1600 adb.is_ready = is_ready
1601 return adb
1602
1603 def testHealthyDevices_default(self):
1604 test_serials = ['0123456789abcdef', 'fedcba9876543210']
1605 with self.assertCalls(
1606 (mock.call.pylib.device.device_blacklist.ReadBlacklist(), []),
1607 (mock.call.pylib.device.adb_wrapper.AdbWrapper.Devices(),
1608 [self._createAdbWrapperMock(s) for s in test_serials])):
1609 devices = device_utils.DeviceUtils.HealthyDevices()
1610 for serial, device in zip(test_serials, devices):
1611 self.assertTrue(isinstance(device, device_utils.DeviceUtils))
1612 self.assertEquals(serial, device.adb.GetDeviceSerial())
1613
1614 def testHealthyDevices_blacklisted(self):
1615 test_serials = ['0123456789abcdef', 'fedcba9876543210']
1616 with self.assertCalls(
1617 (mock.call.pylib.device.device_blacklist.ReadBlacklist(),
1618 ['fedcba9876543210']),
1619 (mock.call.pylib.device.adb_wrapper.AdbWrapper.Devices(),
1620 [self._createAdbWrapperMock(s) for s in test_serials])):
1621 devices = device_utils.DeviceUtils.HealthyDevices()
1622 self.assertEquals(1, len(devices))
1623 self.assertTrue(isinstance(devices[0], device_utils.DeviceUtils))
1624 self.assertEquals('0123456789abcdef', devices[0].adb.GetDeviceSerial())
1625
1626
1593 if __name__ == '__main__': 1627 if __name__ == '__main__':
1594 logging.getLogger().setLevel(logging.DEBUG) 1628 logging.getLogger().setLevel(logging.DEBUG)
1595 unittest.main(verbosity=2) 1629 unittest.main(verbosity=2)
1596 1630
OLDNEW
« no previous file with comments | « build/android/pylib/device/device_utils.py ('k') | build/android/pylib/device_signal.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698