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

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

Issue 952893003: Update from https://crrev.com/317530 (Closed) Base URL: https://github.com/domokit/mojo.git@master
Patch Set: Fix gn for nacl Created 5 years, 10 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 21 matching lines...) Expand all
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'))
36 36
37 sys.path.append(os.path.join( 37 sys.path.append(os.path.join(
38 constants.DIR_SOURCE_ROOT, 'third_party', 'pymock')) 38 constants.DIR_SOURCE_ROOT, 'third_party', 'pymock'))
39 import mock # pylint: disable=F0401 39 import mock # pylint: disable=F0401
40 40
41 41
42 class DeviceUtilsTest(unittest.TestCase): 42 class DeviceUtilsInitTest(unittest.TestCase):
43 43
44 def testInitWithStr(self): 44 def testInitWithStr(self):
45 serial_as_str = str('0123456789abcdef') 45 serial_as_str = str('0123456789abcdef')
46 d = device_utils.DeviceUtils('0123456789abcdef') 46 d = device_utils.DeviceUtils('0123456789abcdef')
47 self.assertEqual(serial_as_str, d.adb.GetDeviceSerial()) 47 self.assertEqual(serial_as_str, d.adb.GetDeviceSerial())
48 48
49 def testInitWithUnicode(self): 49 def testInitWithUnicode(self):
50 serial_as_unicode = unicode('fedcba9876543210') 50 serial_as_unicode = unicode('fedcba9876543210')
51 d = device_utils.DeviceUtils(serial_as_unicode) 51 d = device_utils.DeviceUtils(serial_as_unicode)
52 self.assertEqual(serial_as_unicode, d.adb.GetDeviceSerial()) 52 self.assertEqual(serial_as_unicode, d.adb.GetDeviceSerial())
(...skipping 61 matching lines...) Expand 10 before | Expand all | Expand 10 after
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 117
118 class _PatchedFunction(object): 118 class _PatchedFunction(object):
119 def __init__(self, patched=None, mocked=None): 119 def __init__(self, patched=None, mocked=None):
120 self.patched = patched 120 self.patched = patched
121 self.mocked = mocked 121 self.mocked = mocked
122 122
123 123
124 class DeviceUtilsOldImplTest(unittest.TestCase):
125
126 class AndroidCommandsCalls(object):
127
128 def __init__(self, test_case, cmd_ret, comp):
129 self._cmds = cmd_ret
130 self._comp = comp
131 self._run_command = _PatchedFunction()
132 self._test_case = test_case
133 self._total_received = 0
134
135 def __enter__(self):
136 self._run_command.patched = mock.patch(
137 'run_command.RunCommand',
138 side_effect=lambda c, **kw: self._ret(c))
139 self._run_command.mocked = self._run_command.patched.__enter__()
140
141 def _ret(self, actual_cmd):
142 if sys.exc_info()[0] is None:
143 on_failure_fmt = ('\n'
144 ' received command: %s\n'
145 ' expected command: %s')
146 self._test_case.assertGreater(
147 len(self._cmds), self._total_received,
148 msg=on_failure_fmt % (actual_cmd, None))
149 expected_cmd, ret = self._cmds[self._total_received]
150 self._total_received += 1
151 self._test_case.assertTrue(
152 self._comp(expected_cmd, actual_cmd),
153 msg=on_failure_fmt % (actual_cmd, expected_cmd))
154 return ret
155 return ''
156
157 def __exit__(self, exc_type, exc_val, exc_tb):
158 self._run_command.patched.__exit__(exc_type, exc_val, exc_tb)
159 if exc_type is None:
160 on_failure = "adb commands don't match.\nExpected:%s\nActual:%s" % (
161 ''.join('\n %s' % c for c, _ in self._cmds),
162 ''.join('\n %s' % a[0]
163 for _, a, kw in self._run_command.mocked.mock_calls))
164 self._test_case.assertEqual(
165 len(self._cmds), len(self._run_command.mocked.mock_calls),
166 msg=on_failure)
167 for (expected_cmd, _r), (_n, actual_args, actual_kwargs) in zip(
168 self._cmds, self._run_command.mocked.mock_calls):
169 self._test_case.assertEqual(1, len(actual_args), msg=on_failure)
170 self._test_case.assertTrue(self._comp(expected_cmd, actual_args[0]),
171 msg=on_failure)
172 self._test_case.assertTrue('timeout_time' in actual_kwargs,
173 msg=on_failure)
174 self._test_case.assertTrue('retry_count' in actual_kwargs,
175 msg=on_failure)
176
177 def assertNoAdbCalls(self):
178 return type(self).AndroidCommandsCalls(self, [], str.__eq__)
179
180 def assertCalls(self, cmd, ret, comp=str.__eq__):
181 return type(self).AndroidCommandsCalls(self, [(cmd, ret)], comp)
182
183 def assertCallsSequence(self, cmd_ret, comp=str.__eq__):
184 return type(self).AndroidCommandsCalls(self, cmd_ret, comp)
185
186 def setUp(self):
187 self._get_adb_path_patch = mock.patch('pylib.constants.GetAdbPath',
188 mock.Mock(return_value='adb'))
189 self._get_adb_path_patch.start()
190 self.device = device_utils.DeviceUtils(
191 '0123456789abcdef', default_timeout=1, default_retries=0)
192
193 def tearDown(self):
194 self._get_adb_path_patch.stop()
195
196
197 def _AdbWrapperMock(test_serial): 124 def _AdbWrapperMock(test_serial):
198 adb = mock.Mock(spec=adb_wrapper.AdbWrapper) 125 adb = mock.Mock(spec=adb_wrapper.AdbWrapper)
199 adb.__str__ = mock.Mock(return_value=test_serial) 126 adb.__str__ = mock.Mock(return_value=test_serial)
200 adb.GetDeviceSerial.return_value = test_serial 127 adb.GetDeviceSerial.return_value = test_serial
201 return adb 128 return adb
202 129
203 130
204 class DeviceUtilsNewImplTest(mock_calls.TestCase): 131 class DeviceUtilsTest(mock_calls.TestCase):
205 132
206 def setUp(self): 133 def setUp(self):
207 self.adb = _AdbWrapperMock('0123456789abcdef') 134 self.adb = _AdbWrapperMock('0123456789abcdef')
208 self.device = device_utils.DeviceUtils( 135 self.device = device_utils.DeviceUtils(
209 self.adb, default_timeout=10, default_retries=0) 136 self.adb, default_timeout=10, default_retries=0)
210 self.watchMethodCalls(self.call.adb, ignore=['GetDeviceSerial']) 137 self.watchMethodCalls(self.call.adb, ignore=['GetDeviceSerial'])
211 138
212 def ShellError(self, output=None, status=1): 139 def ShellError(self, output=None, status=1):
213 def action(cmd, *args, **kwargs): 140 def action(cmd, *args, **kwargs):
214 raise device_errors.AdbShellCommandFailedError( 141 raise device_errors.AdbShellCommandFailedError(
215 cmd, output, status, str(self.device)) 142 cmd, output, status, str(self.device))
216 if output is None: 143 if output is None:
217 output = 'Permission denied\n' 144 output = 'Permission denied\n'
218 return action 145 return action
219 146
220 def TimeoutError(self, msg=None): 147 def TimeoutError(self, msg=None):
221 if msg is None: 148 if msg is None:
222 msg = 'Operation timed out' 149 msg = 'Operation timed out'
223 return mock.Mock(side_effect=device_errors.CommandTimeoutError( 150 return mock.Mock(side_effect=device_errors.CommandTimeoutError(
224 msg, str(self.device))) 151 msg, str(self.device)))
225 152
226 def CommandError(self, msg=None): 153 def CommandError(self, msg=None):
227 if msg is None: 154 if msg is None:
228 msg = 'Command failed' 155 msg = 'Command failed'
229 return mock.Mock(side_effect=device_errors.CommandFailedError( 156 return mock.Mock(side_effect=device_errors.CommandFailedError(
230 msg, str(self.device))) 157 msg, str(self.device)))
231 158
232 159
233 class DeviceUtilsIsOnlineTest(DeviceUtilsNewImplTest): 160 class DeviceUtilsIsOnlineTest(DeviceUtilsTest):
234 161
235 def testIsOnline_true(self): 162 def testIsOnline_true(self):
236 with self.assertCall(self.call.adb.GetState(), 'device'): 163 with self.assertCall(self.call.adb.GetState(), 'device'):
237 self.assertTrue(self.device.IsOnline()) 164 self.assertTrue(self.device.IsOnline())
238 165
239 def testIsOnline_false(self): 166 def testIsOnline_false(self):
240 with self.assertCall(self.call.adb.GetState(), 'offline'): 167 with self.assertCall(self.call.adb.GetState(), 'offline'):
241 self.assertFalse(self.device.IsOnline()) 168 self.assertFalse(self.device.IsOnline())
242 169
243 def testIsOnline_error(self): 170 def testIsOnline_error(self):
244 with self.assertCall(self.call.adb.GetState(), self.CommandError()): 171 with self.assertCall(self.call.adb.GetState(), self.CommandError()):
245 self.assertFalse(self.device.IsOnline()) 172 self.assertFalse(self.device.IsOnline())
246 173
247 174
248 class DeviceUtilsHasRootTest(DeviceUtilsNewImplTest): 175 class DeviceUtilsHasRootTest(DeviceUtilsTest):
249 176
250 def testHasRoot_true(self): 177 def testHasRoot_true(self):
251 with self.assertCall(self.call.adb.Shell('ls /root'), 'foo\n'): 178 with self.assertCall(self.call.adb.Shell('ls /root'), 'foo\n'):
252 self.assertTrue(self.device.HasRoot()) 179 self.assertTrue(self.device.HasRoot())
253 180
254 def testHasRoot_false(self): 181 def testHasRoot_false(self):
255 with self.assertCall(self.call.adb.Shell('ls /root'), self.ShellError()): 182 with self.assertCall(self.call.adb.Shell('ls /root'), self.ShellError()):
256 self.assertFalse(self.device.HasRoot()) 183 self.assertFalse(self.device.HasRoot())
257 184
258 185
259 class DeviceUtilsEnableRootTest(DeviceUtilsNewImplTest): 186 class DeviceUtilsEnableRootTest(DeviceUtilsTest):
260 187
261 def testEnableRoot_succeeds(self): 188 def testEnableRoot_succeeds(self):
262 with self.assertCalls( 189 with self.assertCalls(
263 (self.call.device.IsUserBuild(), False), 190 (self.call.device.IsUserBuild(), False),
264 self.call.adb.Root(), 191 self.call.adb.Root(),
265 self.call.adb.WaitForDevice()): 192 self.call.adb.WaitForDevice()):
266 self.device.EnableRoot() 193 self.device.EnableRoot()
267 194
268 def testEnableRoot_userBuild(self): 195 def testEnableRoot_userBuild(self):
269 with self.assertCalls( 196 with self.assertCalls(
270 (self.call.device.IsUserBuild(), True)): 197 (self.call.device.IsUserBuild(), True)):
271 with self.assertRaises(device_errors.CommandFailedError): 198 with self.assertRaises(device_errors.CommandFailedError):
272 self.device.EnableRoot() 199 self.device.EnableRoot()
273 200
274 def testEnableRoot_rootFails(self): 201 def testEnableRoot_rootFails(self):
275 with self.assertCalls( 202 with self.assertCalls(
276 (self.call.device.IsUserBuild(), False), 203 (self.call.device.IsUserBuild(), False),
277 (self.call.adb.Root(), self.CommandError())): 204 (self.call.adb.Root(), self.CommandError())):
278 with self.assertRaises(device_errors.CommandFailedError): 205 with self.assertRaises(device_errors.CommandFailedError):
279 self.device.EnableRoot() 206 self.device.EnableRoot()
280 207
281 208
282 class DeviceUtilsIsUserBuildTest(DeviceUtilsNewImplTest): 209 class DeviceUtilsIsUserBuildTest(DeviceUtilsTest):
283 210
284 def testIsUserBuild_yes(self): 211 def testIsUserBuild_yes(self):
285 with self.assertCall( 212 with self.assertCall(
286 self.call.device.GetProp('ro.build.type', cache=True), 'user'): 213 self.call.device.GetProp('ro.build.type', cache=True), 'user'):
287 self.assertTrue(self.device.IsUserBuild()) 214 self.assertTrue(self.device.IsUserBuild())
288 215
289 def testIsUserBuild_no(self): 216 def testIsUserBuild_no(self):
290 with self.assertCall( 217 with self.assertCall(
291 self.call.device.GetProp('ro.build.type', cache=True), 'userdebug'): 218 self.call.device.GetProp('ro.build.type', cache=True), 'userdebug'):
292 self.assertFalse(self.device.IsUserBuild()) 219 self.assertFalse(self.device.IsUserBuild())
293 220
294 221
295 class DeviceUtilsGetExternalStoragePathTest(DeviceUtilsNewImplTest): 222 class DeviceUtilsGetExternalStoragePathTest(DeviceUtilsTest):
296 223
297 def testGetExternalStoragePath_succeeds(self): 224 def testGetExternalStoragePath_succeeds(self):
298 with self.assertCall( 225 with self.assertCall(
299 self.call.adb.Shell('echo $EXTERNAL_STORAGE'), '/fake/storage/path\n'): 226 self.call.adb.Shell('echo $EXTERNAL_STORAGE'), '/fake/storage/path\n'):
300 self.assertEquals('/fake/storage/path', 227 self.assertEquals('/fake/storage/path',
301 self.device.GetExternalStoragePath()) 228 self.device.GetExternalStoragePath())
302 229
303 def testGetExternalStoragePath_fails(self): 230 def testGetExternalStoragePath_fails(self):
304 with self.assertCall(self.call.adb.Shell('echo $EXTERNAL_STORAGE'), '\n'): 231 with self.assertCall(self.call.adb.Shell('echo $EXTERNAL_STORAGE'), '\n'):
305 with self.assertRaises(device_errors.CommandFailedError): 232 with self.assertRaises(device_errors.CommandFailedError):
306 self.device.GetExternalStoragePath() 233 self.device.GetExternalStoragePath()
307 234
308 235
309 class DeviceUtilsGetApplicationPathTest(DeviceUtilsNewImplTest): 236 class DeviceUtilsGetApplicationPathTest(DeviceUtilsTest):
310 237
311 def testGetApplicationPath_exists(self): 238 def testGetApplicationPath_exists(self):
312 with self.assertCalls( 239 with self.assertCalls(
313 (self.call.adb.Shell('getprop ro.build.version.sdk'), '19\n'), 240 (self.call.adb.Shell('getprop ro.build.version.sdk'), '19\n'),
314 (self.call.adb.Shell('pm path android'), 241 (self.call.adb.Shell('pm path android'),
315 'package:/path/to/android.apk\n')): 242 'package:/path/to/android.apk\n')):
316 self.assertEquals('/path/to/android.apk', 243 self.assertEquals('/path/to/android.apk',
317 self.device.GetApplicationPath('android')) 244 self.device.GetApplicationPath('android'))
318 245
319 def testGetApplicationPath_notExists(self): 246 def testGetApplicationPath_notExists(self):
320 with self.assertCalls( 247 with self.assertCalls(
321 (self.call.adb.Shell('getprop ro.build.version.sdk'), '19\n'), 248 (self.call.adb.Shell('getprop ro.build.version.sdk'), '19\n'),
322 (self.call.adb.Shell('pm path not.installed.app'), '')): 249 (self.call.adb.Shell('pm path not.installed.app'), '')):
323 self.assertEquals(None, 250 self.assertEquals(None,
324 self.device.GetApplicationPath('not.installed.app')) 251 self.device.GetApplicationPath('not.installed.app'))
325 252
326 def testGetApplicationPath_fails(self): 253 def testGetApplicationPath_fails(self):
327 with self.assertCalls( 254 with self.assertCalls(
328 (self.call.adb.Shell('getprop ro.build.version.sdk'), '19\n'), 255 (self.call.adb.Shell('getprop ro.build.version.sdk'), '19\n'),
329 (self.call.adb.Shell('pm path android'), 256 (self.call.adb.Shell('pm path android'),
330 self.CommandError('ERROR. Is package manager running?\n'))): 257 self.CommandError('ERROR. Is package manager running?\n'))):
331 with self.assertRaises(device_errors.CommandFailedError): 258 with self.assertRaises(device_errors.CommandFailedError):
332 self.device.GetApplicationPath('android') 259 self.device.GetApplicationPath('android')
333 260
334 261
335 @mock.patch('time.sleep', mock.Mock()) 262 @mock.patch('time.sleep', mock.Mock())
336 class DeviceUtilsWaitUntilFullyBootedTest(DeviceUtilsNewImplTest): 263 class DeviceUtilsWaitUntilFullyBootedTest(DeviceUtilsTest):
337 264
338 def testWaitUntilFullyBooted_succeedsNoWifi(self): 265 def testWaitUntilFullyBooted_succeedsNoWifi(self):
339 with self.assertCalls( 266 with self.assertCalls(
340 self.call.adb.WaitForDevice(), 267 self.call.adb.WaitForDevice(),
341 # sd_card_ready 268 # sd_card_ready
342 (self.call.device.GetExternalStoragePath(), '/fake/storage/path'), 269 (self.call.device.GetExternalStoragePath(), '/fake/storage/path'),
343 (self.call.adb.Shell('test -d /fake/storage/path'), ''), 270 (self.call.adb.Shell('test -d /fake/storage/path'), ''),
344 # pm_ready 271 # pm_ready
345 (self.call.device.GetApplicationPath('android'), 272 (self.call.device.GetApplicationPath('android'),
346 'package:/some/fake/path'), 273 'package:/some/fake/path'),
(...skipping 89 matching lines...) Expand 10 before | Expand all | Expand 10 after
436 (self.call.adb.Shell('dumpsys wifi'), 'stuff\nmore stuff\n'), 363 (self.call.adb.Shell('dumpsys wifi'), 'stuff\nmore stuff\n'),
437 # wifi_enabled 364 # wifi_enabled
438 (self.call.adb.Shell('dumpsys wifi'), 'stuff\nmore stuff\n'), 365 (self.call.adb.Shell('dumpsys wifi'), 'stuff\nmore stuff\n'),
439 # wifi_enabled 366 # wifi_enabled
440 (self.call.adb.Shell('dumpsys wifi'), self.TimeoutError())): 367 (self.call.adb.Shell('dumpsys wifi'), self.TimeoutError())):
441 with self.assertRaises(device_errors.CommandTimeoutError): 368 with self.assertRaises(device_errors.CommandTimeoutError):
442 self.device.WaitUntilFullyBooted(wifi=True) 369 self.device.WaitUntilFullyBooted(wifi=True)
443 370
444 371
445 @mock.patch('time.sleep', mock.Mock()) 372 @mock.patch('time.sleep', mock.Mock())
446 class DeviceUtilsRebootTest(DeviceUtilsNewImplTest): 373 class DeviceUtilsRebootTest(DeviceUtilsTest):
447 374
448 def testReboot_nonBlocking(self): 375 def testReboot_nonBlocking(self):
449 with self.assertCalls( 376 with self.assertCalls(
450 self.call.adb.Reboot(), 377 self.call.adb.Reboot(),
451 (self.call.device.IsOnline(), True), 378 (self.call.device.IsOnline(), True),
452 (self.call.device.IsOnline(), False)): 379 (self.call.device.IsOnline(), False)):
453 self.device.Reboot(block=False) 380 self.device.Reboot(block=False)
454 381
455 def testReboot_blocking(self): 382 def testReboot_blocking(self):
456 with self.assertCalls( 383 with self.assertCalls(
457 self.call.adb.Reboot(), 384 self.call.adb.Reboot(),
458 (self.call.device.IsOnline(), True), 385 (self.call.device.IsOnline(), True),
459 (self.call.device.IsOnline(), False), 386 (self.call.device.IsOnline(), False),
460 self.call.device.WaitUntilFullyBooted(wifi=False)): 387 self.call.device.WaitUntilFullyBooted(wifi=False)):
461 self.device.Reboot(block=True) 388 self.device.Reboot(block=True)
462 389
463 def testReboot_blockUntilWifi(self): 390 def testReboot_blockUntilWifi(self):
464 with self.assertCalls( 391 with self.assertCalls(
465 self.call.adb.Reboot(), 392 self.call.adb.Reboot(),
466 (self.call.device.IsOnline(), True), 393 (self.call.device.IsOnline(), True),
467 (self.call.device.IsOnline(), False), 394 (self.call.device.IsOnline(), False),
468 self.call.device.WaitUntilFullyBooted(wifi=True)): 395 self.call.device.WaitUntilFullyBooted(wifi=True)):
469 self.device.Reboot(block=True, wifi=True) 396 self.device.Reboot(block=True, wifi=True)
470 397
471 398
472 class DeviceUtilsInstallTest(DeviceUtilsNewImplTest): 399 class DeviceUtilsInstallTest(DeviceUtilsTest):
473 400
474 def testInstall_noPriorInstall(self): 401 def testInstall_noPriorInstall(self):
475 with self.assertCalls( 402 with self.assertCalls(
476 (mock.call.pylib.utils.apk_helper.GetPackageName('/fake/test/app.apk'), 403 (mock.call.pylib.utils.apk_helper.GetPackageName('/fake/test/app.apk'),
477 'this.is.a.test.package'), 404 'this.is.a.test.package'),
478 (self.call.device.GetApplicationPath('this.is.a.test.package'), None), 405 (self.call.device.GetApplicationPath('this.is.a.test.package'), None),
479 self.call.adb.Install('/fake/test/app.apk', reinstall=False)): 406 self.call.adb.Install('/fake/test/app.apk', reinstall=False)):
480 self.device.Install('/fake/test/app.apk', retries=0) 407 self.device.Install('/fake/test/app.apk', retries=0)
481 408
482 def testInstall_differentPriorInstall(self): 409 def testInstall_differentPriorInstall(self):
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
519 with self.assertCalls( 446 with self.assertCalls(
520 (mock.call.pylib.utils.apk_helper.GetPackageName('/fake/test/app.apk'), 447 (mock.call.pylib.utils.apk_helper.GetPackageName('/fake/test/app.apk'),
521 'this.is.a.test.package'), 448 'this.is.a.test.package'),
522 (self.call.device.GetApplicationPath('this.is.a.test.package'), None), 449 (self.call.device.GetApplicationPath('this.is.a.test.package'), None),
523 (self.call.adb.Install('/fake/test/app.apk', reinstall=False), 450 (self.call.adb.Install('/fake/test/app.apk', reinstall=False),
524 self.CommandError('Failure\r\n'))): 451 self.CommandError('Failure\r\n'))):
525 with self.assertRaises(device_errors.CommandFailedError): 452 with self.assertRaises(device_errors.CommandFailedError):
526 self.device.Install('/fake/test/app.apk', retries=0) 453 self.device.Install('/fake/test/app.apk', retries=0)
527 454
528 455
529 class DeviceUtilsRunShellCommandTest(DeviceUtilsNewImplTest): 456 class DeviceUtilsRunShellCommandTest(DeviceUtilsTest):
530 457
531 def setUp(self): 458 def setUp(self):
532 super(DeviceUtilsRunShellCommandTest, self).setUp() 459 super(DeviceUtilsRunShellCommandTest, self).setUp()
533 self.device.NeedsSU = mock.Mock(return_value=False) 460 self.device.NeedsSU = mock.Mock(return_value=False)
534 461
535 def testRunShellCommand_commandAsList(self): 462 def testRunShellCommand_commandAsList(self):
536 with self.assertCall(self.call.adb.Shell('pm list packages'), ''): 463 with self.assertCall(self.call.adb.Shell('pm list packages'), ''):
537 self.device.RunShellCommand(['pm', 'list', 'packages']) 464 self.device.RunShellCommand(['pm', 'list', 'packages'])
538 465
539 def testRunShellCommand_commandAsListQuoted(self): 466 def testRunShellCommand_commandAsListQuoted(self):
(...skipping 109 matching lines...) Expand 10 before | Expand all | Expand 10 after
649 self.device.RunShellCommand(cmd, check_return=True) 576 self.device.RunShellCommand(cmd, check_return=True)
650 577
651 def testRunShellCommand_checkReturn_disabled(self): 578 def testRunShellCommand_checkReturn_disabled(self):
652 cmd = 'ls /root' 579 cmd = 'ls /root'
653 output = 'opendir failed, Permission denied\n' 580 output = 'opendir failed, Permission denied\n'
654 with self.assertCall(self.call.adb.Shell(cmd), self.ShellError(output)): 581 with self.assertCall(self.call.adb.Shell(cmd), self.ShellError(output)):
655 self.assertEquals([output.rstrip()], 582 self.assertEquals([output.rstrip()],
656 self.device.RunShellCommand(cmd, check_return=False)) 583 self.device.RunShellCommand(cmd, check_return=False))
657 584
658 585
659 class DeviceUtilsGetDevicePieWrapper(DeviceUtilsNewImplTest): 586 class DeviceUtilsGetDevicePieWrapper(DeviceUtilsTest):
660 587
661 def testGetDevicePieWrapper_jb(self): 588 def testGetDevicePieWrapper_jb(self):
662 with self.assertCall( 589 with self.assertCall(
663 self.call.device.build_version_sdk(), 590 self.call.device.build_version_sdk(),
664 constants.ANDROID_SDK_VERSION_CODES.JELLY_BEAN): 591 constants.ANDROID_SDK_VERSION_CODES.JELLY_BEAN):
665 self.assertEqual('', self.device.GetDevicePieWrapper()) 592 self.assertEqual('', self.device.GetDevicePieWrapper())
666 593
667 def testGetDevicePieWrapper_ics(self): 594 def testGetDevicePieWrapper_ics(self):
668 with self.assertCalls( 595 with self.assertCalls(
669 (self.call.device.build_version_sdk(), 596 (self.call.device.build_version_sdk(),
670 constants.ANDROID_SDK_VERSION_CODES.ICE_CREAM_SANDWICH), 597 constants.ANDROID_SDK_VERSION_CODES.ICE_CREAM_SANDWICH),
671 (mock.call.pylib.constants.GetOutDirectory(), '/foo/bar'), 598 (mock.call.pylib.constants.GetOutDirectory(), '/foo/bar'),
672 (mock.call.os.path.exists(mock.ANY), True), 599 (mock.call.os.path.exists(mock.ANY), True),
673 (self.call.adb.Push(mock.ANY, mock.ANY), '')): 600 (self.call.adb.Push(mock.ANY, mock.ANY), '')):
674 self.assertNotEqual('', self.device.GetDevicePieWrapper()) 601 self.assertNotEqual('', self.device.GetDevicePieWrapper())
675 602
676 603
677 @mock.patch('time.sleep', mock.Mock()) 604 @mock.patch('time.sleep', mock.Mock())
678 class DeviceUtilsKillAllTest(DeviceUtilsNewImplTest): 605 class DeviceUtilsKillAllTest(DeviceUtilsTest):
679 606
680 def testKillAll_noMatchingProcesses(self): 607 def testKillAll_noMatchingProcesses(self):
681 with self.assertCall(self.call.adb.Shell('ps'), 608 with self.assertCall(self.call.adb.Shell('ps'),
682 'USER PID PPID VSIZE RSS WCHAN PC NAME\n'): 609 'USER PID PPID VSIZE RSS WCHAN PC NAME\n'):
683 with self.assertRaises(device_errors.CommandFailedError): 610 with self.assertRaises(device_errors.CommandFailedError):
684 self.device.KillAll('test_process') 611 self.device.KillAll('test_process')
685 612
686 def testKillAll_nonblocking(self): 613 def testKillAll_nonblocking(self):
687 with self.assertCalls( 614 with self.assertCalls(
688 (self.call.adb.Shell('ps'), 615 (self.call.adb.Shell('ps'),
(...skipping 30 matching lines...) Expand all
719 def testKillAll_sigterm(self): 646 def testKillAll_sigterm(self):
720 with self.assertCalls( 647 with self.assertCalls(
721 (self.call.adb.Shell('ps'), 648 (self.call.adb.Shell('ps'),
722 'USER PID PPID VSIZE RSS WCHAN PC NAME\n' 649 'USER PID PPID VSIZE RSS WCHAN PC NAME\n'
723 'u0_a1 1234 174 123456 54321 ffffffff 456789ab some.process\n'), 650 'u0_a1 1234 174 123456 54321 ffffffff 456789ab some.process\n'),
724 (self.call.adb.Shell('kill -15 1234'), '')): 651 (self.call.adb.Shell('kill -15 1234'), '')):
725 self.assertEquals(1, 652 self.assertEquals(1,
726 self.device.KillAll('some.process', signum=signal.SIGTERM)) 653 self.device.KillAll('some.process', signum=signal.SIGTERM))
727 654
728 655
729 class DeviceUtilsStartActivityTest(DeviceUtilsNewImplTest): 656 class DeviceUtilsStartActivityTest(DeviceUtilsTest):
730 657
731 def testStartActivity_actionOnly(self): 658 def testStartActivity_actionOnly(self):
732 test_intent = intent.Intent(action='android.intent.action.VIEW') 659 test_intent = intent.Intent(action='android.intent.action.VIEW')
733 with self.assertCall( 660 with self.assertCall(
734 self.call.adb.Shell('am start ' 661 self.call.adb.Shell('am start '
735 '-a android.intent.action.VIEW'), 662 '-a android.intent.action.VIEW'),
736 'Starting: Intent { act=android.intent.action.VIEW }'): 663 'Starting: Intent { act=android.intent.action.VIEW }'):
737 self.device.StartActivity(test_intent) 664 self.device.StartActivity(test_intent)
738 665
739 def testStartActivity_success(self): 666 def testStartActivity_success(self):
(...skipping 143 matching lines...) Expand 10 before | Expand all | Expand 10 after
883 flags='0x10000000') 810 flags='0x10000000')
884 with self.assertCall( 811 with self.assertCall(
885 self.call.adb.Shell('am start ' 812 self.call.adb.Shell('am start '
886 '-a android.intent.action.VIEW ' 813 '-a android.intent.action.VIEW '
887 '-n this.is.a.test.package/.Main ' 814 '-n this.is.a.test.package/.Main '
888 '-f 0x10000000'), 815 '-f 0x10000000'),
889 'Starting: Intent { act=android.intent.action.VIEW }'): 816 'Starting: Intent { act=android.intent.action.VIEW }'):
890 self.device.StartActivity(test_intent) 817 self.device.StartActivity(test_intent)
891 818
892 819
893 class DeviceUtilsStartInstrumentationTest(DeviceUtilsNewImplTest): 820 class DeviceUtilsStartInstrumentationTest(DeviceUtilsTest):
894 821
895 def testStartInstrumentation_nothing(self): 822 def testStartInstrumentation_nothing(self):
896 with self.assertCalls( 823 with self.assertCalls(
897 self.call.device.RunShellCommand( 824 self.call.device.RunShellCommand(
898 ['am', 'instrument', 'test.package/.TestInstrumentation'], 825 ['am', 'instrument', 'test.package/.TestInstrumentation'],
899 check_return=True)): 826 check_return=True)):
900 self.device.StartInstrumentation( 827 self.device.StartInstrumentation(
901 'test.package/.TestInstrumentation', 828 'test.package/.TestInstrumentation',
902 finish=False, raw=False, extras=None) 829 finish=False, raw=False, extras=None)
903 830
(...skipping 21 matching lines...) Expand all
925 with self.assertCalls( 852 with self.assertCalls(
926 self.call.device.RunShellCommand( 853 self.call.device.RunShellCommand(
927 ['am', 'instrument', '-e', 'foo', 'Foo', '-e', 'bar', 'Bar', 854 ['am', 'instrument', '-e', 'foo', 'Foo', '-e', 'bar', 'Bar',
928 'test.package/.TestInstrumentation'], 855 'test.package/.TestInstrumentation'],
929 check_return=True)): 856 check_return=True)):
930 self.device.StartInstrumentation( 857 self.device.StartInstrumentation(
931 'test.package/.TestInstrumentation', 858 'test.package/.TestInstrumentation',
932 finish=False, raw=False, extras={'foo': 'Foo', 'bar': 'Bar'}) 859 finish=False, raw=False, extras={'foo': 'Foo', 'bar': 'Bar'})
933 860
934 861
935 class DeviceUtilsBroadcastIntentTest(DeviceUtilsNewImplTest): 862 class DeviceUtilsBroadcastIntentTest(DeviceUtilsTest):
936 863
937 def testBroadcastIntent_noExtras(self): 864 def testBroadcastIntent_noExtras(self):
938 test_intent = intent.Intent(action='test.package.with.an.INTENT') 865 test_intent = intent.Intent(action='test.package.with.an.INTENT')
939 with self.assertCall( 866 with self.assertCall(
940 self.call.adb.Shell('am broadcast -a test.package.with.an.INTENT'), 867 self.call.adb.Shell('am broadcast -a test.package.with.an.INTENT'),
941 'Broadcasting: Intent { act=test.package.with.an.INTENT } '): 868 'Broadcasting: Intent { act=test.package.with.an.INTENT } '):
942 self.device.BroadcastIntent(test_intent) 869 self.device.BroadcastIntent(test_intent)
943 870
944 def testBroadcastIntent_withExtra(self): 871 def testBroadcastIntent_withExtra(self):
945 test_intent = intent.Intent(action='test.package.with.an.INTENT', 872 test_intent = intent.Intent(action='test.package.with.an.INTENT',
946 extras={'foo': 'bar value'}) 873 extras={'foo': 'bar value'})
947 with self.assertCall( 874 with self.assertCall(
948 self.call.adb.Shell( 875 self.call.adb.Shell(
949 "am broadcast -a test.package.with.an.INTENT --es foo 'bar value'"), 876 "am broadcast -a test.package.with.an.INTENT --es foo 'bar value'"),
950 'Broadcasting: Intent { act=test.package.with.an.INTENT } '): 877 'Broadcasting: Intent { act=test.package.with.an.INTENT } '):
951 self.device.BroadcastIntent(test_intent) 878 self.device.BroadcastIntent(test_intent)
952 879
953 def testBroadcastIntent_withExtra_noValue(self): 880 def testBroadcastIntent_withExtra_noValue(self):
954 test_intent = intent.Intent(action='test.package.with.an.INTENT', 881 test_intent = intent.Intent(action='test.package.with.an.INTENT',
955 extras={'foo': None}) 882 extras={'foo': None})
956 with self.assertCall( 883 with self.assertCall(
957 self.call.adb.Shell( 884 self.call.adb.Shell(
958 'am broadcast -a test.package.with.an.INTENT --esn foo'), 885 'am broadcast -a test.package.with.an.INTENT --esn foo'),
959 'Broadcasting: Intent { act=test.package.with.an.INTENT } '): 886 'Broadcasting: Intent { act=test.package.with.an.INTENT } '):
960 self.device.BroadcastIntent(test_intent) 887 self.device.BroadcastIntent(test_intent)
961 888
962 889
963 class DeviceUtilsGoHomeTest(DeviceUtilsNewImplTest): 890 class DeviceUtilsGoHomeTest(DeviceUtilsTest):
964 891
965 def testGoHome(self): 892 def testGoHome(self):
966 with self.assertCall( 893 with self.assertCall(
967 self.call.adb.Shell('am start -W -a android.intent.action.MAIN ' 894 self.call.adb.Shell('am start -W -a android.intent.action.MAIN '
968 '-c android.intent.category.HOME'), 895 '-c android.intent.category.HOME'),
969 'Starting: Intent { act=android.intent.action.MAIN }\r\n'): 896 'Starting: Intent { act=android.intent.action.MAIN }\r\n'):
970 self.device.GoHome() 897 self.device.GoHome()
971 898
972 899
973 class DeviceUtilsForceStopTest(DeviceUtilsNewImplTest): 900 class DeviceUtilsForceStopTest(DeviceUtilsTest):
974 901
975 def testForceStop(self): 902 def testForceStop(self):
976 with self.assertCall( 903 with self.assertCall(
977 self.call.adb.Shell('am force-stop this.is.a.test.package'), 904 self.call.adb.Shell('am force-stop this.is.a.test.package'),
978 ''): 905 ''):
979 self.device.ForceStop('this.is.a.test.package') 906 self.device.ForceStop('this.is.a.test.package')
980 907
981 908
982 class DeviceUtilsClearApplicationStateTest(DeviceUtilsNewImplTest): 909 class DeviceUtilsClearApplicationStateTest(DeviceUtilsTest):
983 910
984 def testClearApplicationState_packageDoesntExist(self): 911 def testClearApplicationState_packageDoesntExist(self):
985 with self.assertCalls( 912 with self.assertCalls(
986 (self.call.adb.Shell('getprop ro.build.version.sdk'), '17\n'), 913 (self.call.adb.Shell('getprop ro.build.version.sdk'), '17\n'),
987 (self.call.device.GetApplicationPath('this.package.does.not.exist'), 914 (self.call.device.GetApplicationPath('this.package.does.not.exist'),
988 None)): 915 None)):
989 self.device.ClearApplicationState('this.package.does.not.exist') 916 self.device.ClearApplicationState('this.package.does.not.exist')
990 917
991 def testClearApplicationState_packageDoesntExistOnAndroidJBMR2OrAbove(self): 918 def testClearApplicationState_packageDoesntExistOnAndroidJBMR2OrAbove(self):
992 with self.assertCalls( 919 with self.assertCalls(
(...skipping 12 matching lines...) Expand all
1005 self.device.ClearApplicationState('this.package.exists') 932 self.device.ClearApplicationState('this.package.exists')
1006 933
1007 def testClearApplicationState_packageExistsOnAndroidJBMR2OrAbove(self): 934 def testClearApplicationState_packageExistsOnAndroidJBMR2OrAbove(self):
1008 with self.assertCalls( 935 with self.assertCalls(
1009 (self.call.adb.Shell('getprop ro.build.version.sdk'), '18\n'), 936 (self.call.adb.Shell('getprop ro.build.version.sdk'), '18\n'),
1010 (self.call.adb.Shell('pm clear this.package.exists'), 937 (self.call.adb.Shell('pm clear this.package.exists'),
1011 'Success\r\n')): 938 'Success\r\n')):
1012 self.device.ClearApplicationState('this.package.exists') 939 self.device.ClearApplicationState('this.package.exists')
1013 940
1014 941
1015 class DeviceUtilsSendKeyEventTest(DeviceUtilsNewImplTest): 942 class DeviceUtilsSendKeyEventTest(DeviceUtilsTest):
1016 943
1017 def testSendKeyEvent(self): 944 def testSendKeyEvent(self):
1018 with self.assertCall(self.call.adb.Shell('input keyevent 66'), ''): 945 with self.assertCall(self.call.adb.Shell('input keyevent 66'), ''):
1019 self.device.SendKeyEvent(66) 946 self.device.SendKeyEvent(66)
1020 947
1021 948
1022 class DeviceUtilsPushChangedFilesIndividuallyTest(DeviceUtilsNewImplTest): 949 class DeviceUtilsPushChangedFilesIndividuallyTest(DeviceUtilsTest):
1023 950
1024 def testPushChangedFilesIndividually_empty(self): 951 def testPushChangedFilesIndividually_empty(self):
1025 test_files = [] 952 test_files = []
1026 with self.assertCalls(): 953 with self.assertCalls():
1027 self.device._PushChangedFilesIndividually(test_files) 954 self.device._PushChangedFilesIndividually(test_files)
1028 955
1029 def testPushChangedFilesIndividually_single(self): 956 def testPushChangedFilesIndividually_single(self):
1030 test_files = [('/test/host/path', '/test/device/path')] 957 test_files = [('/test/host/path', '/test/device/path')]
1031 with self.assertCalls(self.call.adb.Push(*test_files[0])): 958 with self.assertCalls(self.call.adb.Push(*test_files[0])):
1032 self.device._PushChangedFilesIndividually(test_files) 959 self.device._PushChangedFilesIndividually(test_files)
1033 960
1034 def testPushChangedFilesIndividually_multiple(self): 961 def testPushChangedFilesIndividually_multiple(self):
1035 test_files = [ 962 test_files = [
1036 ('/test/host/path/file1', '/test/device/path/file1'), 963 ('/test/host/path/file1', '/test/device/path/file1'),
1037 ('/test/host/path/file2', '/test/device/path/file2')] 964 ('/test/host/path/file2', '/test/device/path/file2')]
1038 with self.assertCalls( 965 with self.assertCalls(
1039 self.call.adb.Push(*test_files[0]), 966 self.call.adb.Push(*test_files[0]),
1040 self.call.adb.Push(*test_files[1])): 967 self.call.adb.Push(*test_files[1])):
1041 self.device._PushChangedFilesIndividually(test_files) 968 self.device._PushChangedFilesIndividually(test_files)
1042 969
1043 970
1044 class DeviceUtilsPushChangedFilesZippedTest(DeviceUtilsNewImplTest): 971 class DeviceUtilsPushChangedFilesZippedTest(DeviceUtilsTest):
1045 972
1046 def testPushChangedFilesZipped_empty(self): 973 def testPushChangedFilesZipped_empty(self):
1047 test_files = [] 974 test_files = []
1048 with self.assertCalls(): 975 with self.assertCalls():
1049 self.device._PushChangedFilesZipped(test_files) 976 self.device._PushChangedFilesZipped(test_files)
1050 977
1051 def _testPushChangedFilesZipped_spec(self, test_files): 978 def _testPushChangedFilesZipped_spec(self, test_files):
1052 mock_zip_temp = mock.mock_open() 979 mock_zip_temp = mock.mock_open()
1053 mock_zip_temp.return_value.name = '/test/temp/file/tmp.zip' 980 mock_zip_temp.return_value.name = '/test/temp/file/tmp.zip'
1054 with self.assertCalls( 981 with self.assertCalls(
(...skipping 18 matching lines...) Expand all
1073 def testPushChangedFilesZipped_single(self): 1000 def testPushChangedFilesZipped_single(self):
1074 self._testPushChangedFilesZipped_spec( 1001 self._testPushChangedFilesZipped_spec(
1075 [('/test/host/path/file1', '/test/device/path/file1')]) 1002 [('/test/host/path/file1', '/test/device/path/file1')])
1076 1003
1077 def testPushChangedFilesZipped_multiple(self): 1004 def testPushChangedFilesZipped_multiple(self):
1078 self._testPushChangedFilesZipped_spec( 1005 self._testPushChangedFilesZipped_spec(
1079 [('/test/host/path/file1', '/test/device/path/file1'), 1006 [('/test/host/path/file1', '/test/device/path/file1'),
1080 ('/test/host/path/file2', '/test/device/path/file2')]) 1007 ('/test/host/path/file2', '/test/device/path/file2')])
1081 1008
1082 1009
1083 class DeviceUtilsFileExistsTest(DeviceUtilsNewImplTest): 1010 class DeviceUtilsFileExistsTest(DeviceUtilsTest):
1084 1011
1085 def testFileExists_usingTest_fileExists(self): 1012 def testFileExists_usingTest_fileExists(self):
1086 with self.assertCall( 1013 with self.assertCall(
1087 self.call.device.RunShellCommand( 1014 self.call.device.RunShellCommand(
1088 ['test', '-e', '/path/file.exists'], check_return=True), ''): 1015 ['test', '-e', '/path/file.exists'], check_return=True), ''):
1089 self.assertTrue(self.device.FileExists('/path/file.exists')) 1016 self.assertTrue(self.device.FileExists('/path/file.exists'))
1090 1017
1091 def testFileExists_usingTest_fileDoesntExist(self): 1018 def testFileExists_usingTest_fileDoesntExist(self):
1092 with self.assertCall( 1019 with self.assertCall(
1093 self.call.device.RunShellCommand( 1020 self.call.device.RunShellCommand(
1094 ['test', '-e', '/does/not/exist'], check_return=True), 1021 ['test', '-e', '/does/not/exist'], check_return=True),
1095 self.ShellError('', 1)): 1022 self.ShellError('', 1)):
1096 self.assertFalse(self.device.FileExists('/does/not/exist')) 1023 self.assertFalse(self.device.FileExists('/does/not/exist'))
1097 1024
1098 1025
1099 class DeviceUtilsPullFileTest(DeviceUtilsNewImplTest): 1026 class DeviceUtilsPullFileTest(DeviceUtilsTest):
1100 1027
1101 def testPullFile_existsOnDevice(self): 1028 def testPullFile_existsOnDevice(self):
1102 with mock.patch('os.path.exists', return_value=True): 1029 with mock.patch('os.path.exists', return_value=True):
1103 with self.assertCall( 1030 with self.assertCall(
1104 self.call.adb.Pull('/data/app/test.file.exists', 1031 self.call.adb.Pull('/data/app/test.file.exists',
1105 '/test/file/host/path')): 1032 '/test/file/host/path')):
1106 self.device.PullFile('/data/app/test.file.exists', 1033 self.device.PullFile('/data/app/test.file.exists',
1107 '/test/file/host/path') 1034 '/test/file/host/path')
1108 1035
1109 def testPullFile_doesntExistOnDevice(self): 1036 def testPullFile_doesntExistOnDevice(self):
1110 with mock.patch('os.path.exists', return_value=True): 1037 with mock.patch('os.path.exists', return_value=True):
1111 with self.assertCall( 1038 with self.assertCall(
1112 self.call.adb.Pull('/data/app/test.file.does.not.exist', 1039 self.call.adb.Pull('/data/app/test.file.does.not.exist',
1113 '/test/file/host/path'), 1040 '/test/file/host/path'),
1114 self.CommandError('remote object does not exist')): 1041 self.CommandError('remote object does not exist')):
1115 with self.assertRaises(device_errors.CommandFailedError): 1042 with self.assertRaises(device_errors.CommandFailedError):
1116 self.device.PullFile('/data/app/test.file.does.not.exist', 1043 self.device.PullFile('/data/app/test.file.does.not.exist',
1117 '/test/file/host/path') 1044 '/test/file/host/path')
1118 1045
1119 1046
1120 class DeviceUtilsReadFileTest(DeviceUtilsNewImplTest): 1047 class DeviceUtilsReadFileTest(DeviceUtilsTest):
1121 1048
1122 def testReadFile_exists(self): 1049 def testReadFile_exists(self):
1123 with self.assertCall( 1050 with self.assertCall(
1124 self.call.adb.Shell('cat /read/this/test/file'), 1051 self.call.adb.Shell('cat /read/this/test/file'),
1125 'this is a test file\r\n'): 1052 'this is a test file\r\n'):
1126 self.assertEqual('this is a test file\n', 1053 self.assertEqual('this is a test file\n',
1127 self.device.ReadFile('/read/this/test/file')) 1054 self.device.ReadFile('/read/this/test/file'))
1128 1055
1129 def testReadFile_doesNotExist(self): 1056 def testReadFile_doesNotExist(self):
1130 with self.assertCall( 1057 with self.assertCall(
1131 self.call.adb.Shell('cat /this/file/does.not.exist'), 1058 self.call.adb.Shell('cat /this/file/does.not.exist'),
1132 self.ShellError('/system/bin/sh: cat: /this/file/does.not.exist: ' 1059 self.ShellError('/system/bin/sh: cat: /this/file/does.not.exist: '
1133 'No such file or directory')): 1060 'No such file or directory')):
1134 with self.assertRaises(device_errors.AdbCommandFailedError): 1061 with self.assertRaises(device_errors.AdbCommandFailedError):
1135 self.device.ReadFile('/this/file/does.not.exist') 1062 self.device.ReadFile('/this/file/does.not.exist')
1136 1063
1137 def testReadFile_withSU(self): 1064 def testReadFile_withSU(self):
1138 with self.assertCalls( 1065 with self.assertCalls(
1139 (self.call.device.NeedsSU(), True), 1066 (self.call.device.NeedsSU(), True),
1140 (self.call.adb.Shell("su -c sh -c 'cat /this/file/can.be.read.with.su'"), 1067 (self.call.adb.Shell("su -c sh -c 'cat /this/file/can.be.read.with.su'"),
1141 'this is a test file\nread with su')): 1068 'this is a test file\nread with su')):
1142 self.assertEqual( 1069 self.assertEqual(
1143 'this is a test file\nread with su\n', 1070 'this is a test file\nread with su\n',
1144 self.device.ReadFile('/this/file/can.be.read.with.su', 1071 self.device.ReadFile('/this/file/can.be.read.with.su',
1145 as_root=True)) 1072 as_root=True))
1146 1073
1147 1074
1148 class DeviceUtilsWriteFileTest(DeviceUtilsNewImplTest): 1075 class DeviceUtilsWriteFileTest(DeviceUtilsTest):
1149 1076
1150 def testWriteFileWithPush_success(self): 1077 def testWriteFileWithPush_success(self):
1151 tmp_host = MockTempFile('/tmp/file/on.host') 1078 tmp_host = MockTempFile('/tmp/file/on.host')
1152 contents = 'some interesting contents' 1079 contents = 'some interesting contents'
1153 with self.assertCalls( 1080 with self.assertCalls(
1154 (mock.call.tempfile.NamedTemporaryFile(), tmp_host), 1081 (mock.call.tempfile.NamedTemporaryFile(), tmp_host),
1155 self.call.adb.Push('/tmp/file/on.host', '/path/to/device/file')): 1082 self.call.adb.Push('/tmp/file/on.host', '/path/to/device/file')):
1156 self.device._WriteFileWithPush('/path/to/device/file', contents) 1083 self.device._WriteFileWithPush('/path/to/device/file', contents)
1157 tmp_host.file.write.assert_called_once_with(contents) 1084 tmp_host.file.write.assert_called_once_with(contents)
1158 1085
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after
1201 self.device.WriteFile('/test/file/to write', 'the contents') 1128 self.device.WriteFile('/test/file/to write', 'the contents')
1202 1129
1203 def testWriteFile_withEchoAndSU(self): 1130 def testWriteFile_withEchoAndSU(self):
1204 with self.assertCalls( 1131 with self.assertCalls(
1205 (self.call.device.NeedsSU(), True), 1132 (self.call.device.NeedsSU(), True),
1206 (self.call.adb.Shell("su -c sh -c 'echo -n contents > /test/file'"), 1133 (self.call.adb.Shell("su -c sh -c 'echo -n contents > /test/file'"),
1207 '')): 1134 '')):
1208 self.device.WriteFile('/test/file', 'contents', as_root=True) 1135 self.device.WriteFile('/test/file', 'contents', as_root=True)
1209 1136
1210 1137
1211 class DeviceUtilsLsTest(DeviceUtilsNewImplTest): 1138 class DeviceUtilsLsTest(DeviceUtilsTest):
1212 1139
1213 def testLs_directory(self): 1140 def testLs_directory(self):
1214 result = [('.', adb_wrapper.DeviceStat(16889, 4096, 1417436123)), 1141 result = [('.', adb_wrapper.DeviceStat(16889, 4096, 1417436123)),
1215 ('..', adb_wrapper.DeviceStat(16873, 4096, 12382237)), 1142 ('..', adb_wrapper.DeviceStat(16873, 4096, 12382237)),
1216 ('testfile.txt', adb_wrapper.DeviceStat(33206, 3, 1417436122))] 1143 ('testfile.txt', adb_wrapper.DeviceStat(33206, 3, 1417436122))]
1217 with self.assertCalls( 1144 with self.assertCalls(
1218 (self.call.adb.Ls('/data/local/tmp'), result)): 1145 (self.call.adb.Ls('/data/local/tmp'), result)):
1219 self.assertEquals(result, 1146 self.assertEquals(result,
1220 self.device.Ls('/data/local/tmp')) 1147 self.device.Ls('/data/local/tmp'))
1221 1148
1222 def testLs_nothing(self): 1149 def testLs_nothing(self):
1223 with self.assertCalls( 1150 with self.assertCalls(
1224 (self.call.adb.Ls('/data/local/tmp/testfile.txt'), [])): 1151 (self.call.adb.Ls('/data/local/tmp/testfile.txt'), [])):
1225 self.assertEquals([], 1152 self.assertEquals([],
1226 self.device.Ls('/data/local/tmp/testfile.txt')) 1153 self.device.Ls('/data/local/tmp/testfile.txt'))
1227 1154
1228 1155
1229 class DeviceUtilsStatTest(DeviceUtilsNewImplTest): 1156 class DeviceUtilsStatTest(DeviceUtilsTest):
1230 1157
1231 def testStat_file(self): 1158 def testStat_file(self):
1232 result = [('.', adb_wrapper.DeviceStat(16889, 4096, 1417436123)), 1159 result = [('.', adb_wrapper.DeviceStat(16889, 4096, 1417436123)),
1233 ('..', adb_wrapper.DeviceStat(16873, 4096, 12382237)), 1160 ('..', adb_wrapper.DeviceStat(16873, 4096, 12382237)),
1234 ('testfile.txt', adb_wrapper.DeviceStat(33206, 3, 1417436122))] 1161 ('testfile.txt', adb_wrapper.DeviceStat(33206, 3, 1417436122))]
1235 with self.assertCalls( 1162 with self.assertCalls(
1236 (self.call.adb.Ls('/data/local/tmp'), result)): 1163 (self.call.adb.Ls('/data/local/tmp'), result)):
1237 self.assertEquals(adb_wrapper.DeviceStat(33206, 3, 1417436122), 1164 self.assertEquals(adb_wrapper.DeviceStat(33206, 3, 1417436122),
1238 self.device.Stat('/data/local/tmp/testfile.txt')) 1165 self.device.Stat('/data/local/tmp/testfile.txt'))
1239 1166
1240 def testStat_directory(self): 1167 def testStat_directory(self):
1241 result = [('.', adb_wrapper.DeviceStat(16873, 4096, 12382237)), 1168 result = [('.', adb_wrapper.DeviceStat(16873, 4096, 12382237)),
1242 ('..', adb_wrapper.DeviceStat(16873, 4096, 12382237)), 1169 ('..', adb_wrapper.DeviceStat(16873, 4096, 12382237)),
1243 ('tmp', adb_wrapper.DeviceStat(16889, 4096, 1417436123))] 1170 ('tmp', adb_wrapper.DeviceStat(16889, 4096, 1417436123))]
1244 with self.assertCalls( 1171 with self.assertCalls(
1245 (self.call.adb.Ls('/data/local'), result)): 1172 (self.call.adb.Ls('/data/local'), result)):
1246 self.assertEquals(adb_wrapper.DeviceStat(16889, 4096, 1417436123), 1173 self.assertEquals(adb_wrapper.DeviceStat(16889, 4096, 1417436123),
1247 self.device.Stat('/data/local/tmp')) 1174 self.device.Stat('/data/local/tmp'))
1248 1175
1249 def testStat_doesNotExist(self): 1176 def testStat_doesNotExist(self):
1250 result = [('.', adb_wrapper.DeviceStat(16889, 4096, 1417436123)), 1177 result = [('.', adb_wrapper.DeviceStat(16889, 4096, 1417436123)),
1251 ('..', adb_wrapper.DeviceStat(16873, 4096, 12382237)), 1178 ('..', adb_wrapper.DeviceStat(16873, 4096, 12382237)),
1252 ('testfile.txt', adb_wrapper.DeviceStat(33206, 3, 1417436122))] 1179 ('testfile.txt', adb_wrapper.DeviceStat(33206, 3, 1417436122))]
1253 with self.assertCalls( 1180 with self.assertCalls(
1254 (self.call.adb.Ls('/data/local/tmp'), result)): 1181 (self.call.adb.Ls('/data/local/tmp'), result)):
1255 with self.assertRaises(device_errors.CommandFailedError): 1182 with self.assertRaises(device_errors.CommandFailedError):
1256 self.device.Stat('/data/local/tmp/does.not.exist.txt') 1183 self.device.Stat('/data/local/tmp/does.not.exist.txt')
1257 1184
1258 1185
1259 class DeviceUtilsSetJavaAssertsTest(DeviceUtilsNewImplTest): 1186 class DeviceUtilsSetJavaAssertsTest(DeviceUtilsTest):
1260 1187
1261 def testSetJavaAsserts_enable(self): 1188 def testSetJavaAsserts_enable(self):
1262 with self.assertCalls( 1189 with self.assertCalls(
1263 (self.call.device.ReadFile(constants.DEVICE_LOCAL_PROPERTIES_PATH), 1190 (self.call.device.ReadFile(constants.DEVICE_LOCAL_PROPERTIES_PATH),
1264 'some.example.prop=with an example value\n' 1191 'some.example.prop=with an example value\n'
1265 'some.other.prop=value_ok\n'), 1192 'some.other.prop=value_ok\n'),
1266 self.call.device.WriteFile( 1193 self.call.device.WriteFile(
1267 constants.DEVICE_LOCAL_PROPERTIES_PATH, 1194 constants.DEVICE_LOCAL_PROPERTIES_PATH,
1268 'some.example.prop=with an example value\n' 1195 'some.example.prop=with an example value\n'
1269 'some.other.prop=value_ok\n' 1196 'some.other.prop=value_ok\n'
(...skipping 19 matching lines...) Expand all
1289 def testSetJavaAsserts_alreadyEnabled(self): 1216 def testSetJavaAsserts_alreadyEnabled(self):
1290 with self.assertCalls( 1217 with self.assertCalls(
1291 (self.call.device.ReadFile(constants.DEVICE_LOCAL_PROPERTIES_PATH), 1218 (self.call.device.ReadFile(constants.DEVICE_LOCAL_PROPERTIES_PATH),
1292 'some.example.prop=with an example value\n' 1219 'some.example.prop=with an example value\n'
1293 'dalvik.vm.enableassertions=all\n' 1220 'dalvik.vm.enableassertions=all\n'
1294 'some.other.prop=value_ok\n'), 1221 'some.other.prop=value_ok\n'),
1295 (self.call.device.GetProp('dalvik.vm.enableassertions'), 'all')): 1222 (self.call.device.GetProp('dalvik.vm.enableassertions'), 'all')):
1296 self.assertFalse(self.device.SetJavaAsserts(True)) 1223 self.assertFalse(self.device.SetJavaAsserts(True))
1297 1224
1298 1225
1299 class DeviceUtilsGetPropTest(DeviceUtilsNewImplTest): 1226 class DeviceUtilsGetPropTest(DeviceUtilsTest):
1300 1227
1301 def testGetProp_exists(self): 1228 def testGetProp_exists(self):
1302 with self.assertCall( 1229 with self.assertCall(
1303 self.call.adb.Shell('getprop test.property'), 'property_value\n'): 1230 self.call.adb.Shell('getprop test.property'), 'property_value\n'):
1304 self.assertEqual('property_value', 1231 self.assertEqual('property_value',
1305 self.device.GetProp('test.property')) 1232 self.device.GetProp('test.property'))
1306 1233
1307 def testGetProp_doesNotExist(self): 1234 def testGetProp_doesNotExist(self):
1308 with self.assertCall( 1235 with self.assertCall(
1309 self.call.adb.Shell('getprop property.does.not.exist'), '\n'): 1236 self.call.adb.Shell('getprop property.does.not.exist'), '\n'):
(...skipping 13 matching lines...) Expand all
1323 (self.call.adb.Shell('getprop ro.build.type'), self.ShellError()), 1250 (self.call.adb.Shell('getprop ro.build.type'), self.ShellError()),
1324 (self.call.adb.Shell('getprop ro.build.type'), 'userdebug\n')): 1251 (self.call.adb.Shell('getprop ro.build.type'), 'userdebug\n')):
1325 self.assertEqual('userdebug', 1252 self.assertEqual('userdebug',
1326 self.device.GetProp('ro.build.type', 1253 self.device.GetProp('ro.build.type',
1327 cache=True, retries=3)) 1254 cache=True, retries=3))
1328 self.assertEqual('userdebug', 1255 self.assertEqual('userdebug',
1329 self.device.GetProp('ro.build.type', 1256 self.device.GetProp('ro.build.type',
1330 cache=True, retries=3)) 1257 cache=True, retries=3))
1331 1258
1332 1259
1333 class DeviceUtilsSetPropTest(DeviceUtilsNewImplTest): 1260 class DeviceUtilsSetPropTest(DeviceUtilsTest):
1334 1261
1335 def testSetProp(self): 1262 def testSetProp(self):
1336 with self.assertCall( 1263 with self.assertCall(
1337 self.call.adb.Shell("setprop test.property 'test value'"), ''): 1264 self.call.adb.Shell("setprop test.property 'test value'"), ''):
1338 self.device.SetProp('test.property', 'test value') 1265 self.device.SetProp('test.property', 'test value')
1339 1266
1340 def testSetProp_check_succeeds(self): 1267 def testSetProp_check_succeeds(self):
1341 with self.assertCalls( 1268 with self.assertCalls(
1342 (self.call.adb.Shell('setprop test.property new_value'), ''), 1269 (self.call.adb.Shell('setprop test.property new_value'), ''),
1343 (self.call.adb.Shell('getprop test.property'), 'new_value')): 1270 (self.call.adb.Shell('getprop test.property'), 'new_value')):
1344 self.device.SetProp('test.property', 'new_value', check=True) 1271 self.device.SetProp('test.property', 'new_value', check=True)
1345 1272
1346 def testSetProp_check_fails(self): 1273 def testSetProp_check_fails(self):
1347 with self.assertCalls( 1274 with self.assertCalls(
1348 (self.call.adb.Shell('setprop test.property new_value'), ''), 1275 (self.call.adb.Shell('setprop test.property new_value'), ''),
1349 (self.call.adb.Shell('getprop test.property'), 'old_value')): 1276 (self.call.adb.Shell('getprop test.property'), 'old_value')):
1350 with self.assertRaises(device_errors.CommandFailedError): 1277 with self.assertRaises(device_errors.CommandFailedError):
1351 self.device.SetProp('test.property', 'new_value', check=True) 1278 self.device.SetProp('test.property', 'new_value', check=True)
1352 1279
1353 1280
1354 class DeviceUtilsGetPidsTest(DeviceUtilsNewImplTest): 1281 class DeviceUtilsGetPidsTest(DeviceUtilsTest):
1355 1282
1356 def testGetPids_noMatches(self): 1283 def testGetPids_noMatches(self):
1357 with self.assertCall(self.call.adb.Shell('ps'), 1284 with self.assertCall(self.call.adb.Shell('ps'),
1358 'USER PID PPID VSIZE RSS WCHAN PC NAME\n' 1285 'USER PID PPID VSIZE RSS WCHAN PC NAME\n'
1359 'user 1000 100 1024 1024 ffffffff 00000000 no.match\n'): 1286 'user 1000 100 1024 1024 ffffffff 00000000 no.match\n'):
1360 self.assertEqual({}, self.device.GetPids('does.not.match')) 1287 self.assertEqual({}, self.device.GetPids('does.not.match'))
1361 1288
1362 def testGetPids_oneMatch(self): 1289 def testGetPids_oneMatch(self):
1363 with self.assertCall(self.call.adb.Shell('ps'), 1290 with self.assertCall(self.call.adb.Shell('ps'),
1364 'USER PID PPID VSIZE RSS WCHAN PC NAME\n' 1291 'USER PID PPID VSIZE RSS WCHAN PC NAME\n'
(...skipping 15 matching lines...) Expand all
1380 def testGetPids_exactMatch(self): 1307 def testGetPids_exactMatch(self):
1381 with self.assertCall(self.call.adb.Shell('ps'), 1308 with self.assertCall(self.call.adb.Shell('ps'),
1382 'USER PID PPID VSIZE RSS WCHAN PC NAME\n' 1309 'USER PID PPID VSIZE RSS WCHAN PC NAME\n'
1383 'user 1000 100 1024 1024 ffffffff 00000000 not.exact.match\n' 1310 'user 1000 100 1024 1024 ffffffff 00000000 not.exact.match\n'
1384 'user 1234 100 1024 1024 ffffffff 00000000 exact.match\n'): 1311 'user 1234 100 1024 1024 ffffffff 00000000 exact.match\n'):
1385 self.assertEqual( 1312 self.assertEqual(
1386 {'not.exact.match': '1000', 'exact.match': '1234'}, 1313 {'not.exact.match': '1000', 'exact.match': '1234'},
1387 self.device.GetPids('exact.match')) 1314 self.device.GetPids('exact.match'))
1388 1315
1389 1316
1390 class DeviceUtilsTakeScreenshotTest(DeviceUtilsNewImplTest): 1317 class DeviceUtilsTakeScreenshotTest(DeviceUtilsTest):
1391 1318
1392 def testTakeScreenshot_fileNameProvided(self): 1319 def testTakeScreenshot_fileNameProvided(self):
1393 with self.assertCalls( 1320 with self.assertCalls(
1394 (mock.call.pylib.utils.device_temp_file.DeviceTempFile( 1321 (mock.call.pylib.utils.device_temp_file.DeviceTempFile(
1395 self.adb, suffix='.png'), 1322 self.adb, suffix='.png'),
1396 MockTempFile('/tmp/path/temp-123.png')), 1323 MockTempFile('/tmp/path/temp-123.png')),
1397 (self.call.adb.Shell('/system/bin/screencap -p /tmp/path/temp-123.png'), 1324 (self.call.adb.Shell('/system/bin/screencap -p /tmp/path/temp-123.png'),
1398 ''), 1325 ''),
1399 self.call.device.PullFile('/tmp/path/temp-123.png', 1326 self.call.device.PullFile('/tmp/path/temp-123.png',
1400 '/test/host/screenshot.png')): 1327 '/test/host/screenshot.png')):
1401 self.device.TakeScreenshot('/test/host/screenshot.png') 1328 self.device.TakeScreenshot('/test/host/screenshot.png')
1402 1329
1403 1330
1404 class DeviceUtilsGetMemoryUsageForPidTest(DeviceUtilsOldImplTest): 1331 class DeviceUtilsGetMemoryUsageForPidTest(DeviceUtilsTest):
1405 1332
1406 def setUp(self): 1333 def setUp(self):
1407 super(DeviceUtilsGetMemoryUsageForPidTest, self).setUp() 1334 super(DeviceUtilsGetMemoryUsageForPidTest, self).setUp()
1408 self.device.old_interface._privileged_command_runner = (
1409 self.device.old_interface.RunShellCommand)
1410 self.device.old_interface._protected_file_access_method_initialized = True
1411 1335
1412 def testGetMemoryUsageForPid_validPid(self): 1336 def testGetMemoryUsageForPid_validPid(self):
1413 with self.assertCallsSequence([ 1337 with self.assertCalls(
1414 ("adb -s 0123456789abcdef shell 'showmap 1234'", 1338 (self.call.device.RunShellCommand(
1415 '100 101 102 103 104 105 106 107 TOTAL\r\n'), 1339 ['showmap', '1234'], as_root=True, check_return=True),
1416 ("adb -s 0123456789abcdef shell " 1340 ['100 101 102 103 104 105 106 107 TOTAL']),
1417 "'cat \"/proc/1234/status\" 2> /dev/null'", 1341 (self.call.device.ReadFile('/proc/1234/status', as_root=True),
1418 'VmHWM: 1024 kB') 1342 'VmHWM: 1024 kB\n')):
1419 ]):
1420 self.assertEqual( 1343 self.assertEqual(
1421 { 1344 {
1422 'Size': 100, 1345 'Size': 100,
1423 'Rss': 101, 1346 'Rss': 101,
1424 'Pss': 102, 1347 'Pss': 102,
1425 'Shared_Clean': 103, 1348 'Shared_Clean': 103,
1426 'Shared_Dirty': 104, 1349 'Shared_Dirty': 104,
1427 'Private_Clean': 105, 1350 'Private_Clean': 105,
1428 'Private_Dirty': 106, 1351 'Private_Dirty': 106,
1429 'VmHWM': 1024 1352 'VmHWM': 1024
1430 }, 1353 },
1431 self.device.GetMemoryUsageForPid(1234)) 1354 self.device.GetMemoryUsageForPid(1234))
1432 1355
1433 def testGetMemoryUsageForPid_invalidPid(self): 1356 def testGetMemoryUsageForPid_noSmaps(self):
1434 with self.assertCalls( 1357 with self.assertCalls(
1435 "adb -s 0123456789abcdef shell 'showmap 4321'", 1358 (self.call.device.RunShellCommand(
1436 'cannot open /proc/4321/smaps: No such file or directory\r\n'): 1359 ['showmap', '4321'], as_root=True, check_return=True),
1437 self.assertEqual({}, self.device.GetMemoryUsageForPid(4321)) 1360 ['cannot open /proc/4321/smaps: No such file or directory']),
1361 (self.call.device.ReadFile('/proc/4321/status', as_root=True),
1362 'VmHWM: 1024 kb\n')):
1363 self.assertEquals({'VmHWM': 1024}, self.device.GetMemoryUsageForPid(4321))
1364
1365 def testGetMemoryUsageForPid_noStatus(self):
1366 with self.assertCalls(
1367 (self.call.device.RunShellCommand(
1368 ['showmap', '4321'], as_root=True, check_return=True),
1369 ['100 101 102 103 104 105 106 107 TOTAL']),
1370 (self.call.device.ReadFile('/proc/4321/status', as_root=True),
1371 self.CommandError())):
1372 self.assertEquals(
1373 {
1374 'Size': 100,
1375 'Rss': 101,
1376 'Pss': 102,
1377 'Shared_Clean': 103,
1378 'Shared_Dirty': 104,
1379 'Private_Clean': 105,
1380 'Private_Dirty': 106,
1381 },
1382 self.device.GetMemoryUsageForPid(4321))
1438 1383
1439 1384
1440 class DeviceUtilsStrTest(DeviceUtilsNewImplTest): 1385 class DeviceUtilsStrTest(DeviceUtilsTest):
1441 1386
1442 def testStr_returnsSerial(self): 1387 def testStr_returnsSerial(self):
1443 with self.assertCalls( 1388 with self.assertCalls(
1444 (self.call.adb.GetDeviceSerial(), '0123456789abcdef')): 1389 (self.call.adb.GetDeviceSerial(), '0123456789abcdef')):
1445 self.assertEqual('0123456789abcdef', str(self.device)) 1390 self.assertEqual('0123456789abcdef', str(self.device))
1446 1391
1447 1392
1448 class DeviceUtilsParallelTest(mock_calls.TestCase): 1393 class DeviceUtilsParallelTest(mock_calls.TestCase):
1449 1394
1450 def testParallel_default(self): 1395 def testParallel_default(self):
1451 test_serials = ['0123456789abcdef', 'fedcba9876543210'] 1396 test_serials = ['0123456789abcdef', 'fedcba9876543210']
1452 with self.assertCall( 1397 with self.assertCall(
1453 mock.call.pylib.device.adb_wrapper.AdbWrapper.GetDevices(), 1398 mock.call.pylib.device.adb_wrapper.AdbWrapper.GetDevices(),
1454 [_AdbWrapperMock(serial) for serial in test_serials]): 1399 [_AdbWrapperMock(serial) for serial in test_serials]):
1455 parallel_devices = device_utils.DeviceUtils.parallel() 1400 parallel_devices = device_utils.DeviceUtils.parallel()
1456 for serial, device in zip(test_serials, parallel_devices.pGet(None)): 1401 for serial, device in zip(test_serials, parallel_devices.pGet(None)):
1457 self.assertTrue( 1402 self.assertTrue(
1458 isinstance(device, device_utils.DeviceUtils) 1403 isinstance(device, device_utils.DeviceUtils)
1459 and serial == str(device), 1404 and serial == str(device),
1460 'Expected a DeviceUtils object with serial %s' % serial) 1405 'Expected a DeviceUtils object with serial %s' % serial)
1461 1406
1407 def testParallel_noDevices(self):
1408 with self.assertCall(
1409 mock.call.pylib.device.adb_wrapper.AdbWrapper.GetDevices(), []):
1410 with self.assertRaises(device_errors.NoDevicesError):
1411 device_utils.DeviceUtils.parallel()
1412
1462 1413
1463 if __name__ == '__main__': 1414 if __name__ == '__main__':
1464 logging.getLogger().setLevel(logging.DEBUG) 1415 logging.getLogger().setLevel(logging.DEBUG)
1465 unittest.main(verbosity=2) 1416 unittest.main(verbosity=2)
1466 1417
OLDNEW
« no previous file with comments | « build/android/pylib/device/device_utils.py ('k') | build/android/pylib/device/logcat_monitor.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698