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

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

Issue 924003003: [Android] Migrate DeviceUtils.GetMemoryUsageForPid to adb_wrapper. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: 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
« no previous file with comments | « build/android/pylib/device/device_utils.py ('k') | no next file » | 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
(...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):
jbudorick 2015/02/17 16:59:15 After rebasing, this had no more clients, so I rem
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 110 matching lines...) Expand 10 before | Expand all | Expand 10 after
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 @mock.patch('time.sleep', mock.Mock()) 586 @mock.patch('time.sleep', mock.Mock())
660 class DeviceUtilsKillAllTest(DeviceUtilsNewImplTest): 587 class DeviceUtilsKillAllTest(DeviceUtilsTest):
661 588
662 def testKillAll_noMatchingProcesses(self): 589 def testKillAll_noMatchingProcesses(self):
663 with self.assertCall(self.call.adb.Shell('ps'), 590 with self.assertCall(self.call.adb.Shell('ps'),
664 'USER PID PPID VSIZE RSS WCHAN PC NAME\n'): 591 'USER PID PPID VSIZE RSS WCHAN PC NAME\n'):
665 with self.assertRaises(device_errors.CommandFailedError): 592 with self.assertRaises(device_errors.CommandFailedError):
666 self.device.KillAll('test_process') 593 self.device.KillAll('test_process')
667 594
668 def testKillAll_nonblocking(self): 595 def testKillAll_nonblocking(self):
669 with self.assertCalls( 596 with self.assertCalls(
670 (self.call.adb.Shell('ps'), 597 (self.call.adb.Shell('ps'),
(...skipping 30 matching lines...) Expand all
701 def testKillAll_sigterm(self): 628 def testKillAll_sigterm(self):
702 with self.assertCalls( 629 with self.assertCalls(
703 (self.call.adb.Shell('ps'), 630 (self.call.adb.Shell('ps'),
704 'USER PID PPID VSIZE RSS WCHAN PC NAME\n' 631 'USER PID PPID VSIZE RSS WCHAN PC NAME\n'
705 'u0_a1 1234 174 123456 54321 ffffffff 456789ab some.process\n'), 632 'u0_a1 1234 174 123456 54321 ffffffff 456789ab some.process\n'),
706 (self.call.adb.Shell('kill -15 1234'), '')): 633 (self.call.adb.Shell('kill -15 1234'), '')):
707 self.assertEquals(1, 634 self.assertEquals(1,
708 self.device.KillAll('some.process', signum=signal.SIGTERM)) 635 self.device.KillAll('some.process', signum=signal.SIGTERM))
709 636
710 637
711 class DeviceUtilsStartActivityTest(DeviceUtilsNewImplTest): 638 class DeviceUtilsStartActivityTest(DeviceUtilsTest):
712 639
713 def testStartActivity_actionOnly(self): 640 def testStartActivity_actionOnly(self):
714 test_intent = intent.Intent(action='android.intent.action.VIEW') 641 test_intent = intent.Intent(action='android.intent.action.VIEW')
715 with self.assertCall( 642 with self.assertCall(
716 self.call.adb.Shell('am start ' 643 self.call.adb.Shell('am start '
717 '-a android.intent.action.VIEW'), 644 '-a android.intent.action.VIEW'),
718 'Starting: Intent { act=android.intent.action.VIEW }'): 645 'Starting: Intent { act=android.intent.action.VIEW }'):
719 self.device.StartActivity(test_intent) 646 self.device.StartActivity(test_intent)
720 647
721 def testStartActivity_success(self): 648 def testStartActivity_success(self):
(...skipping 143 matching lines...) Expand 10 before | Expand all | Expand 10 after
865 flags='0x10000000') 792 flags='0x10000000')
866 with self.assertCall( 793 with self.assertCall(
867 self.call.adb.Shell('am start ' 794 self.call.adb.Shell('am start '
868 '-a android.intent.action.VIEW ' 795 '-a android.intent.action.VIEW '
869 '-n this.is.a.test.package/.Main ' 796 '-n this.is.a.test.package/.Main '
870 '-f 0x10000000'), 797 '-f 0x10000000'),
871 'Starting: Intent { act=android.intent.action.VIEW }'): 798 'Starting: Intent { act=android.intent.action.VIEW }'):
872 self.device.StartActivity(test_intent) 799 self.device.StartActivity(test_intent)
873 800
874 801
875 class DeviceUtilsStartInstrumentationTest(DeviceUtilsNewImplTest): 802 class DeviceUtilsStartInstrumentationTest(DeviceUtilsTest):
876 803
877 def testStartInstrumentation_nothing(self): 804 def testStartInstrumentation_nothing(self):
878 with self.assertCalls( 805 with self.assertCalls(
879 self.call.device.RunShellCommand( 806 self.call.device.RunShellCommand(
880 ['am', 'instrument', 'test.package/.TestInstrumentation'], 807 ['am', 'instrument', 'test.package/.TestInstrumentation'],
881 check_return=True)): 808 check_return=True)):
882 self.device.StartInstrumentation( 809 self.device.StartInstrumentation(
883 'test.package/.TestInstrumentation', 810 'test.package/.TestInstrumentation',
884 finish=False, raw=False, extras=None) 811 finish=False, raw=False, extras=None)
885 812
(...skipping 21 matching lines...) Expand all
907 with self.assertCalls( 834 with self.assertCalls(
908 self.call.device.RunShellCommand( 835 self.call.device.RunShellCommand(
909 ['am', 'instrument', '-e', 'foo', 'Foo', '-e', 'bar', 'Bar', 836 ['am', 'instrument', '-e', 'foo', 'Foo', '-e', 'bar', 'Bar',
910 'test.package/.TestInstrumentation'], 837 'test.package/.TestInstrumentation'],
911 check_return=True)): 838 check_return=True)):
912 self.device.StartInstrumentation( 839 self.device.StartInstrumentation(
913 'test.package/.TestInstrumentation', 840 'test.package/.TestInstrumentation',
914 finish=False, raw=False, extras={'foo': 'Foo', 'bar': 'Bar'}) 841 finish=False, raw=False, extras={'foo': 'Foo', 'bar': 'Bar'})
915 842
916 843
917 class DeviceUtilsBroadcastIntentTest(DeviceUtilsNewImplTest): 844 class DeviceUtilsBroadcastIntentTest(DeviceUtilsTest):
918 845
919 def testBroadcastIntent_noExtras(self): 846 def testBroadcastIntent_noExtras(self):
920 test_intent = intent.Intent(action='test.package.with.an.INTENT') 847 test_intent = intent.Intent(action='test.package.with.an.INTENT')
921 with self.assertCall( 848 with self.assertCall(
922 self.call.adb.Shell('am broadcast -a test.package.with.an.INTENT'), 849 self.call.adb.Shell('am broadcast -a test.package.with.an.INTENT'),
923 'Broadcasting: Intent { act=test.package.with.an.INTENT } '): 850 'Broadcasting: Intent { act=test.package.with.an.INTENT } '):
924 self.device.BroadcastIntent(test_intent) 851 self.device.BroadcastIntent(test_intent)
925 852
926 def testBroadcastIntent_withExtra(self): 853 def testBroadcastIntent_withExtra(self):
927 test_intent = intent.Intent(action='test.package.with.an.INTENT', 854 test_intent = intent.Intent(action='test.package.with.an.INTENT',
928 extras={'foo': 'bar value'}) 855 extras={'foo': 'bar value'})
929 with self.assertCall( 856 with self.assertCall(
930 self.call.adb.Shell( 857 self.call.adb.Shell(
931 "am broadcast -a test.package.with.an.INTENT --es foo 'bar value'"), 858 "am broadcast -a test.package.with.an.INTENT --es foo 'bar value'"),
932 'Broadcasting: Intent { act=test.package.with.an.INTENT } '): 859 'Broadcasting: Intent { act=test.package.with.an.INTENT } '):
933 self.device.BroadcastIntent(test_intent) 860 self.device.BroadcastIntent(test_intent)
934 861
935 def testBroadcastIntent_withExtra_noValue(self): 862 def testBroadcastIntent_withExtra_noValue(self):
936 test_intent = intent.Intent(action='test.package.with.an.INTENT', 863 test_intent = intent.Intent(action='test.package.with.an.INTENT',
937 extras={'foo': None}) 864 extras={'foo': None})
938 with self.assertCall( 865 with self.assertCall(
939 self.call.adb.Shell( 866 self.call.adb.Shell(
940 'am broadcast -a test.package.with.an.INTENT --esn foo'), 867 'am broadcast -a test.package.with.an.INTENT --esn foo'),
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 871
945 class DeviceUtilsGoHomeTest(DeviceUtilsNewImplTest): 872 class DeviceUtilsGoHomeTest(DeviceUtilsTest):
946 873
947 def testGoHome(self): 874 def testGoHome(self):
948 with self.assertCall( 875 with self.assertCall(
949 self.call.adb.Shell('am start -W -a android.intent.action.MAIN ' 876 self.call.adb.Shell('am start -W -a android.intent.action.MAIN '
950 '-c android.intent.category.HOME'), 877 '-c android.intent.category.HOME'),
951 'Starting: Intent { act=android.intent.action.MAIN }\r\n'): 878 'Starting: Intent { act=android.intent.action.MAIN }\r\n'):
952 self.device.GoHome() 879 self.device.GoHome()
953 880
954 881
955 class DeviceUtilsForceStopTest(DeviceUtilsNewImplTest): 882 class DeviceUtilsForceStopTest(DeviceUtilsTest):
956 883
957 def testForceStop(self): 884 def testForceStop(self):
958 with self.assertCall( 885 with self.assertCall(
959 self.call.adb.Shell('am force-stop this.is.a.test.package'), 886 self.call.adb.Shell('am force-stop this.is.a.test.package'),
960 ''): 887 ''):
961 self.device.ForceStop('this.is.a.test.package') 888 self.device.ForceStop('this.is.a.test.package')
962 889
963 890
964 class DeviceUtilsClearApplicationStateTest(DeviceUtilsNewImplTest): 891 class DeviceUtilsClearApplicationStateTest(DeviceUtilsTest):
965 892
966 def testClearApplicationState_packageDoesntExist(self): 893 def testClearApplicationState_packageDoesntExist(self):
967 with self.assertCalls( 894 with self.assertCalls(
968 (self.call.adb.Shell('getprop ro.build.version.sdk'), '17\n'), 895 (self.call.adb.Shell('getprop ro.build.version.sdk'), '17\n'),
969 (self.call.device.GetApplicationPath('this.package.does.not.exist'), 896 (self.call.device.GetApplicationPath('this.package.does.not.exist'),
970 None)): 897 None)):
971 self.device.ClearApplicationState('this.package.does.not.exist') 898 self.device.ClearApplicationState('this.package.does.not.exist')
972 899
973 def testClearApplicationState_packageDoesntExistOnAndroidJBMR2OrAbove(self): 900 def testClearApplicationState_packageDoesntExistOnAndroidJBMR2OrAbove(self):
974 with self.assertCalls( 901 with self.assertCalls(
(...skipping 12 matching lines...) Expand all
987 self.device.ClearApplicationState('this.package.exists') 914 self.device.ClearApplicationState('this.package.exists')
988 915
989 def testClearApplicationState_packageExistsOnAndroidJBMR2OrAbove(self): 916 def testClearApplicationState_packageExistsOnAndroidJBMR2OrAbove(self):
990 with self.assertCalls( 917 with self.assertCalls(
991 (self.call.adb.Shell('getprop ro.build.version.sdk'), '18\n'), 918 (self.call.adb.Shell('getprop ro.build.version.sdk'), '18\n'),
992 (self.call.adb.Shell('pm clear this.package.exists'), 919 (self.call.adb.Shell('pm clear this.package.exists'),
993 'Success\r\n')): 920 'Success\r\n')):
994 self.device.ClearApplicationState('this.package.exists') 921 self.device.ClearApplicationState('this.package.exists')
995 922
996 923
997 class DeviceUtilsSendKeyEventTest(DeviceUtilsNewImplTest): 924 class DeviceUtilsSendKeyEventTest(DeviceUtilsTest):
998 925
999 def testSendKeyEvent(self): 926 def testSendKeyEvent(self):
1000 with self.assertCall(self.call.adb.Shell('input keyevent 66'), ''): 927 with self.assertCall(self.call.adb.Shell('input keyevent 66'), ''):
1001 self.device.SendKeyEvent(66) 928 self.device.SendKeyEvent(66)
1002 929
1003 930
1004 class DeviceUtilsPushChangedFilesIndividuallyTest(DeviceUtilsNewImplTest): 931 class DeviceUtilsPushChangedFilesIndividuallyTest(DeviceUtilsTest):
1005 932
1006 def testPushChangedFilesIndividually_empty(self): 933 def testPushChangedFilesIndividually_empty(self):
1007 test_files = [] 934 test_files = []
1008 with self.assertCalls(): 935 with self.assertCalls():
1009 self.device._PushChangedFilesIndividually(test_files) 936 self.device._PushChangedFilesIndividually(test_files)
1010 937
1011 def testPushChangedFilesIndividually_single(self): 938 def testPushChangedFilesIndividually_single(self):
1012 test_files = [('/test/host/path', '/test/device/path')] 939 test_files = [('/test/host/path', '/test/device/path')]
1013 with self.assertCalls(self.call.adb.Push(*test_files[0])): 940 with self.assertCalls(self.call.adb.Push(*test_files[0])):
1014 self.device._PushChangedFilesIndividually(test_files) 941 self.device._PushChangedFilesIndividually(test_files)
1015 942
1016 def testPushChangedFilesIndividually_multiple(self): 943 def testPushChangedFilesIndividually_multiple(self):
1017 test_files = [ 944 test_files = [
1018 ('/test/host/path/file1', '/test/device/path/file1'), 945 ('/test/host/path/file1', '/test/device/path/file1'),
1019 ('/test/host/path/file2', '/test/device/path/file2')] 946 ('/test/host/path/file2', '/test/device/path/file2')]
1020 with self.assertCalls( 947 with self.assertCalls(
1021 self.call.adb.Push(*test_files[0]), 948 self.call.adb.Push(*test_files[0]),
1022 self.call.adb.Push(*test_files[1])): 949 self.call.adb.Push(*test_files[1])):
1023 self.device._PushChangedFilesIndividually(test_files) 950 self.device._PushChangedFilesIndividually(test_files)
1024 951
1025 952
1026 class DeviceUtilsPushChangedFilesZippedTest(DeviceUtilsNewImplTest): 953 class DeviceUtilsPushChangedFilesZippedTest(DeviceUtilsTest):
1027 954
1028 def testPushChangedFilesZipped_empty(self): 955 def testPushChangedFilesZipped_empty(self):
1029 test_files = [] 956 test_files = []
1030 with self.assertCalls(): 957 with self.assertCalls():
1031 self.device._PushChangedFilesZipped(test_files) 958 self.device._PushChangedFilesZipped(test_files)
1032 959
1033 def _testPushChangedFilesZipped_spec(self, test_files): 960 def _testPushChangedFilesZipped_spec(self, test_files):
1034 mock_zip_temp = mock.mock_open() 961 mock_zip_temp = mock.mock_open()
1035 mock_zip_temp.return_value.name = '/test/temp/file/tmp.zip' 962 mock_zip_temp.return_value.name = '/test/temp/file/tmp.zip'
1036 with self.assertCalls( 963 with self.assertCalls(
(...skipping 18 matching lines...) Expand all
1055 def testPushChangedFilesZipped_single(self): 982 def testPushChangedFilesZipped_single(self):
1056 self._testPushChangedFilesZipped_spec( 983 self._testPushChangedFilesZipped_spec(
1057 [('/test/host/path/file1', '/test/device/path/file1')]) 984 [('/test/host/path/file1', '/test/device/path/file1')])
1058 985
1059 def testPushChangedFilesZipped_multiple(self): 986 def testPushChangedFilesZipped_multiple(self):
1060 self._testPushChangedFilesZipped_spec( 987 self._testPushChangedFilesZipped_spec(
1061 [('/test/host/path/file1', '/test/device/path/file1'), 988 [('/test/host/path/file1', '/test/device/path/file1'),
1062 ('/test/host/path/file2', '/test/device/path/file2')]) 989 ('/test/host/path/file2', '/test/device/path/file2')])
1063 990
1064 991
1065 class DeviceUtilsFileExistsTest(DeviceUtilsNewImplTest): 992 class DeviceUtilsFileExistsTest(DeviceUtilsTest):
1066 993
1067 def testFileExists_usingTest_fileExists(self): 994 def testFileExists_usingTest_fileExists(self):
1068 with self.assertCall( 995 with self.assertCall(
1069 self.call.device.RunShellCommand( 996 self.call.device.RunShellCommand(
1070 ['test', '-e', '/path/file.exists'], check_return=True), ''): 997 ['test', '-e', '/path/file.exists'], check_return=True), ''):
1071 self.assertTrue(self.device.FileExists('/path/file.exists')) 998 self.assertTrue(self.device.FileExists('/path/file.exists'))
1072 999
1073 def testFileExists_usingTest_fileDoesntExist(self): 1000 def testFileExists_usingTest_fileDoesntExist(self):
1074 with self.assertCall( 1001 with self.assertCall(
1075 self.call.device.RunShellCommand( 1002 self.call.device.RunShellCommand(
1076 ['test', '-e', '/does/not/exist'], check_return=True), 1003 ['test', '-e', '/does/not/exist'], check_return=True),
1077 self.ShellError('', 1)): 1004 self.ShellError('', 1)):
1078 self.assertFalse(self.device.FileExists('/does/not/exist')) 1005 self.assertFalse(self.device.FileExists('/does/not/exist'))
1079 1006
1080 1007
1081 class DeviceUtilsPullFileTest(DeviceUtilsNewImplTest): 1008 class DeviceUtilsPullFileTest(DeviceUtilsTest):
1082 1009
1083 def testPullFile_existsOnDevice(self): 1010 def testPullFile_existsOnDevice(self):
1084 with mock.patch('os.path.exists', return_value=True): 1011 with mock.patch('os.path.exists', return_value=True):
1085 with self.assertCall( 1012 with self.assertCall(
1086 self.call.adb.Pull('/data/app/test.file.exists', 1013 self.call.adb.Pull('/data/app/test.file.exists',
1087 '/test/file/host/path')): 1014 '/test/file/host/path')):
1088 self.device.PullFile('/data/app/test.file.exists', 1015 self.device.PullFile('/data/app/test.file.exists',
1089 '/test/file/host/path') 1016 '/test/file/host/path')
1090 1017
1091 def testPullFile_doesntExistOnDevice(self): 1018 def testPullFile_doesntExistOnDevice(self):
1092 with mock.patch('os.path.exists', return_value=True): 1019 with mock.patch('os.path.exists', return_value=True):
1093 with self.assertCall( 1020 with self.assertCall(
1094 self.call.adb.Pull('/data/app/test.file.does.not.exist', 1021 self.call.adb.Pull('/data/app/test.file.does.not.exist',
1095 '/test/file/host/path'), 1022 '/test/file/host/path'),
1096 self.CommandError('remote object does not exist')): 1023 self.CommandError('remote object does not exist')):
1097 with self.assertRaises(device_errors.CommandFailedError): 1024 with self.assertRaises(device_errors.CommandFailedError):
1098 self.device.PullFile('/data/app/test.file.does.not.exist', 1025 self.device.PullFile('/data/app/test.file.does.not.exist',
1099 '/test/file/host/path') 1026 '/test/file/host/path')
1100 1027
1101 1028
1102 class DeviceUtilsReadFileTest(DeviceUtilsNewImplTest): 1029 class DeviceUtilsReadFileTest(DeviceUtilsTest):
1103 1030
1104 def testReadFile_exists(self): 1031 def testReadFile_exists(self):
1105 with self.assertCall( 1032 with self.assertCall(
1106 self.call.adb.Shell('cat /read/this/test/file'), 1033 self.call.adb.Shell('cat /read/this/test/file'),
1107 'this is a test file\r\n'): 1034 'this is a test file\r\n'):
1108 self.assertEqual('this is a test file\n', 1035 self.assertEqual('this is a test file\n',
1109 self.device.ReadFile('/read/this/test/file')) 1036 self.device.ReadFile('/read/this/test/file'))
1110 1037
1111 def testReadFile_doesNotExist(self): 1038 def testReadFile_doesNotExist(self):
1112 with self.assertCall( 1039 with self.assertCall(
1113 self.call.adb.Shell('cat /this/file/does.not.exist'), 1040 self.call.adb.Shell('cat /this/file/does.not.exist'),
1114 self.ShellError('/system/bin/sh: cat: /this/file/does.not.exist: ' 1041 self.ShellError('/system/bin/sh: cat: /this/file/does.not.exist: '
1115 'No such file or directory')): 1042 'No such file or directory')):
1116 with self.assertRaises(device_errors.AdbCommandFailedError): 1043 with self.assertRaises(device_errors.AdbCommandFailedError):
1117 self.device.ReadFile('/this/file/does.not.exist') 1044 self.device.ReadFile('/this/file/does.not.exist')
1118 1045
1119 def testReadFile_withSU(self): 1046 def testReadFile_withSU(self):
1120 with self.assertCalls( 1047 with self.assertCalls(
1121 (self.call.device.NeedsSU(), True), 1048 (self.call.device.NeedsSU(), True),
1122 (self.call.adb.Shell("su -c sh -c 'cat /this/file/can.be.read.with.su'"), 1049 (self.call.adb.Shell("su -c sh -c 'cat /this/file/can.be.read.with.su'"),
1123 'this is a test file\nread with su')): 1050 'this is a test file\nread with su')):
1124 self.assertEqual( 1051 self.assertEqual(
1125 'this is a test file\nread with su\n', 1052 'this is a test file\nread with su\n',
1126 self.device.ReadFile('/this/file/can.be.read.with.su', 1053 self.device.ReadFile('/this/file/can.be.read.with.su',
1127 as_root=True)) 1054 as_root=True))
1128 1055
1129 1056
1130 class DeviceUtilsWriteFileTest(DeviceUtilsNewImplTest): 1057 class DeviceUtilsWriteFileTest(DeviceUtilsTest):
1131 1058
1132 def testWriteFileWithPush_success(self): 1059 def testWriteFileWithPush_success(self):
1133 tmp_host = MockTempFile('/tmp/file/on.host') 1060 tmp_host = MockTempFile('/tmp/file/on.host')
1134 contents = 'some interesting contents' 1061 contents = 'some interesting contents'
1135 with self.assertCalls( 1062 with self.assertCalls(
1136 (mock.call.tempfile.NamedTemporaryFile(), tmp_host), 1063 (mock.call.tempfile.NamedTemporaryFile(), tmp_host),
1137 self.call.adb.Push('/tmp/file/on.host', '/path/to/device/file')): 1064 self.call.adb.Push('/tmp/file/on.host', '/path/to/device/file')):
1138 self.device._WriteFileWithPush('/path/to/device/file', contents) 1065 self.device._WriteFileWithPush('/path/to/device/file', contents)
1139 tmp_host.file.write.assert_called_once_with(contents) 1066 tmp_host.file.write.assert_called_once_with(contents)
1140 1067
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after
1183 self.device.WriteFile('/test/file/to write', 'the contents') 1110 self.device.WriteFile('/test/file/to write', 'the contents')
1184 1111
1185 def testWriteFile_withEchoAndSU(self): 1112 def testWriteFile_withEchoAndSU(self):
1186 with self.assertCalls( 1113 with self.assertCalls(
1187 (self.call.device.NeedsSU(), True), 1114 (self.call.device.NeedsSU(), True),
1188 (self.call.adb.Shell("su -c sh -c 'echo -n contents > /test/file'"), 1115 (self.call.adb.Shell("su -c sh -c 'echo -n contents > /test/file'"),
1189 '')): 1116 '')):
1190 self.device.WriteFile('/test/file', 'contents', as_root=True) 1117 self.device.WriteFile('/test/file', 'contents', as_root=True)
1191 1118
1192 1119
1193 class DeviceUtilsLsTest(DeviceUtilsNewImplTest): 1120 class DeviceUtilsLsTest(DeviceUtilsTest):
1194 1121
1195 def testLs_directory(self): 1122 def testLs_directory(self):
1196 result = [('.', adb_wrapper.DeviceStat(16889, 4096, 1417436123)), 1123 result = [('.', adb_wrapper.DeviceStat(16889, 4096, 1417436123)),
1197 ('..', adb_wrapper.DeviceStat(16873, 4096, 12382237)), 1124 ('..', adb_wrapper.DeviceStat(16873, 4096, 12382237)),
1198 ('testfile.txt', adb_wrapper.DeviceStat(33206, 3, 1417436122))] 1125 ('testfile.txt', adb_wrapper.DeviceStat(33206, 3, 1417436122))]
1199 with self.assertCalls( 1126 with self.assertCalls(
1200 (self.call.adb.Ls('/data/local/tmp'), result)): 1127 (self.call.adb.Ls('/data/local/tmp'), result)):
1201 self.assertEquals(result, 1128 self.assertEquals(result,
1202 self.device.Ls('/data/local/tmp')) 1129 self.device.Ls('/data/local/tmp'))
1203 1130
1204 def testLs_nothing(self): 1131 def testLs_nothing(self):
1205 with self.assertCalls( 1132 with self.assertCalls(
1206 (self.call.adb.Ls('/data/local/tmp/testfile.txt'), [])): 1133 (self.call.adb.Ls('/data/local/tmp/testfile.txt'), [])):
1207 self.assertEquals([], 1134 self.assertEquals([],
1208 self.device.Ls('/data/local/tmp/testfile.txt')) 1135 self.device.Ls('/data/local/tmp/testfile.txt'))
1209 1136
1210 1137
1211 class DeviceUtilsStatTest(DeviceUtilsNewImplTest): 1138 class DeviceUtilsStatTest(DeviceUtilsTest):
1212 1139
1213 def testStat_file(self): 1140 def testStat_file(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(adb_wrapper.DeviceStat(33206, 3, 1417436122), 1146 self.assertEquals(adb_wrapper.DeviceStat(33206, 3, 1417436122),
1220 self.device.Stat('/data/local/tmp/testfile.txt')) 1147 self.device.Stat('/data/local/tmp/testfile.txt'))
1221 1148
1222 def testStat_directory(self): 1149 def testStat_directory(self):
1223 result = [('.', adb_wrapper.DeviceStat(16873, 4096, 12382237)), 1150 result = [('.', adb_wrapper.DeviceStat(16873, 4096, 12382237)),
1224 ('..', adb_wrapper.DeviceStat(16873, 4096, 12382237)), 1151 ('..', adb_wrapper.DeviceStat(16873, 4096, 12382237)),
1225 ('tmp', adb_wrapper.DeviceStat(16889, 4096, 1417436123))] 1152 ('tmp', adb_wrapper.DeviceStat(16889, 4096, 1417436123))]
1226 with self.assertCalls( 1153 with self.assertCalls(
1227 (self.call.adb.Ls('/data/local'), result)): 1154 (self.call.adb.Ls('/data/local'), result)):
1228 self.assertEquals(adb_wrapper.DeviceStat(16889, 4096, 1417436123), 1155 self.assertEquals(adb_wrapper.DeviceStat(16889, 4096, 1417436123),
1229 self.device.Stat('/data/local/tmp')) 1156 self.device.Stat('/data/local/tmp'))
1230 1157
1231 def testStat_doesNotExist(self): 1158 def testStat_doesNotExist(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 with self.assertRaises(device_errors.CommandFailedError): 1164 with self.assertRaises(device_errors.CommandFailedError):
1238 self.device.Stat('/data/local/tmp/does.not.exist.txt') 1165 self.device.Stat('/data/local/tmp/does.not.exist.txt')
1239 1166
1240 1167
1241 class DeviceUtilsSetJavaAssertsTest(DeviceUtilsNewImplTest): 1168 class DeviceUtilsSetJavaAssertsTest(DeviceUtilsTest):
1242 1169
1243 def testSetJavaAsserts_enable(self): 1170 def testSetJavaAsserts_enable(self):
1244 with self.assertCalls( 1171 with self.assertCalls(
1245 (self.call.device.ReadFile(constants.DEVICE_LOCAL_PROPERTIES_PATH), 1172 (self.call.device.ReadFile(constants.DEVICE_LOCAL_PROPERTIES_PATH),
1246 'some.example.prop=with an example value\n' 1173 'some.example.prop=with an example value\n'
1247 'some.other.prop=value_ok\n'), 1174 'some.other.prop=value_ok\n'),
1248 self.call.device.WriteFile( 1175 self.call.device.WriteFile(
1249 constants.DEVICE_LOCAL_PROPERTIES_PATH, 1176 constants.DEVICE_LOCAL_PROPERTIES_PATH,
1250 'some.example.prop=with an example value\n' 1177 'some.example.prop=with an example value\n'
1251 'some.other.prop=value_ok\n' 1178 'some.other.prop=value_ok\n'
(...skipping 19 matching lines...) Expand all
1271 def testSetJavaAsserts_alreadyEnabled(self): 1198 def testSetJavaAsserts_alreadyEnabled(self):
1272 with self.assertCalls( 1199 with self.assertCalls(
1273 (self.call.device.ReadFile(constants.DEVICE_LOCAL_PROPERTIES_PATH), 1200 (self.call.device.ReadFile(constants.DEVICE_LOCAL_PROPERTIES_PATH),
1274 'some.example.prop=with an example value\n' 1201 'some.example.prop=with an example value\n'
1275 'dalvik.vm.enableassertions=all\n' 1202 'dalvik.vm.enableassertions=all\n'
1276 'some.other.prop=value_ok\n'), 1203 'some.other.prop=value_ok\n'),
1277 (self.call.device.GetProp('dalvik.vm.enableassertions'), 'all')): 1204 (self.call.device.GetProp('dalvik.vm.enableassertions'), 'all')):
1278 self.assertFalse(self.device.SetJavaAsserts(True)) 1205 self.assertFalse(self.device.SetJavaAsserts(True))
1279 1206
1280 1207
1281 class DeviceUtilsGetPropTest(DeviceUtilsNewImplTest): 1208 class DeviceUtilsGetPropTest(DeviceUtilsTest):
1282 1209
1283 def testGetProp_exists(self): 1210 def testGetProp_exists(self):
1284 with self.assertCall( 1211 with self.assertCall(
1285 self.call.adb.Shell('getprop test.property'), 'property_value\n'): 1212 self.call.adb.Shell('getprop test.property'), 'property_value\n'):
1286 self.assertEqual('property_value', 1213 self.assertEqual('property_value',
1287 self.device.GetProp('test.property')) 1214 self.device.GetProp('test.property'))
1288 1215
1289 def testGetProp_doesNotExist(self): 1216 def testGetProp_doesNotExist(self):
1290 with self.assertCall( 1217 with self.assertCall(
1291 self.call.adb.Shell('getprop property.does.not.exist'), '\n'): 1218 self.call.adb.Shell('getprop property.does.not.exist'), '\n'):
(...skipping 13 matching lines...) Expand all
1305 (self.call.adb.Shell('getprop ro.build.type'), self.ShellError()), 1232 (self.call.adb.Shell('getprop ro.build.type'), self.ShellError()),
1306 (self.call.adb.Shell('getprop ro.build.type'), 'userdebug\n')): 1233 (self.call.adb.Shell('getprop ro.build.type'), 'userdebug\n')):
1307 self.assertEqual('userdebug', 1234 self.assertEqual('userdebug',
1308 self.device.GetProp('ro.build.type', 1235 self.device.GetProp('ro.build.type',
1309 cache=True, retries=3)) 1236 cache=True, retries=3))
1310 self.assertEqual('userdebug', 1237 self.assertEqual('userdebug',
1311 self.device.GetProp('ro.build.type', 1238 self.device.GetProp('ro.build.type',
1312 cache=True, retries=3)) 1239 cache=True, retries=3))
1313 1240
1314 1241
1315 class DeviceUtilsSetPropTest(DeviceUtilsNewImplTest): 1242 class DeviceUtilsSetPropTest(DeviceUtilsTest):
1316 1243
1317 def testSetProp(self): 1244 def testSetProp(self):
1318 with self.assertCall( 1245 with self.assertCall(
1319 self.call.adb.Shell("setprop test.property 'test value'"), ''): 1246 self.call.adb.Shell("setprop test.property 'test value'"), ''):
1320 self.device.SetProp('test.property', 'test value') 1247 self.device.SetProp('test.property', 'test value')
1321 1248
1322 def testSetProp_check_succeeds(self): 1249 def testSetProp_check_succeeds(self):
1323 with self.assertCalls( 1250 with self.assertCalls(
1324 (self.call.adb.Shell('setprop test.property new_value'), ''), 1251 (self.call.adb.Shell('setprop test.property new_value'), ''),
1325 (self.call.adb.Shell('getprop test.property'), 'new_value')): 1252 (self.call.adb.Shell('getprop test.property'), 'new_value')):
1326 self.device.SetProp('test.property', 'new_value', check=True) 1253 self.device.SetProp('test.property', 'new_value', check=True)
1327 1254
1328 def testSetProp_check_fails(self): 1255 def testSetProp_check_fails(self):
1329 with self.assertCalls( 1256 with self.assertCalls(
1330 (self.call.adb.Shell('setprop test.property new_value'), ''), 1257 (self.call.adb.Shell('setprop test.property new_value'), ''),
1331 (self.call.adb.Shell('getprop test.property'), 'old_value')): 1258 (self.call.adb.Shell('getprop test.property'), 'old_value')):
1332 with self.assertRaises(device_errors.CommandFailedError): 1259 with self.assertRaises(device_errors.CommandFailedError):
1333 self.device.SetProp('test.property', 'new_value', check=True) 1260 self.device.SetProp('test.property', 'new_value', check=True)
1334 1261
1335 1262
1336 class DeviceUtilsGetPidsTest(DeviceUtilsNewImplTest): 1263 class DeviceUtilsGetPidsTest(DeviceUtilsTest):
1337 1264
1338 def testGetPids_noMatches(self): 1265 def testGetPids_noMatches(self):
1339 with self.assertCall(self.call.adb.Shell('ps'), 1266 with self.assertCall(self.call.adb.Shell('ps'),
1340 'USER PID PPID VSIZE RSS WCHAN PC NAME\n' 1267 'USER PID PPID VSIZE RSS WCHAN PC NAME\n'
1341 'user 1000 100 1024 1024 ffffffff 00000000 no.match\n'): 1268 'user 1000 100 1024 1024 ffffffff 00000000 no.match\n'):
1342 self.assertEqual({}, self.device.GetPids('does.not.match')) 1269 self.assertEqual({}, self.device.GetPids('does.not.match'))
1343 1270
1344 def testGetPids_oneMatch(self): 1271 def testGetPids_oneMatch(self):
1345 with self.assertCall(self.call.adb.Shell('ps'), 1272 with self.assertCall(self.call.adb.Shell('ps'),
1346 'USER PID PPID VSIZE RSS WCHAN PC NAME\n' 1273 'USER PID PPID VSIZE RSS WCHAN PC NAME\n'
(...skipping 15 matching lines...) Expand all
1362 def testGetPids_exactMatch(self): 1289 def testGetPids_exactMatch(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'
1365 'user 1000 100 1024 1024 ffffffff 00000000 not.exact.match\n' 1292 'user 1000 100 1024 1024 ffffffff 00000000 not.exact.match\n'
1366 'user 1234 100 1024 1024 ffffffff 00000000 exact.match\n'): 1293 'user 1234 100 1024 1024 ffffffff 00000000 exact.match\n'):
1367 self.assertEqual( 1294 self.assertEqual(
1368 {'not.exact.match': '1000', 'exact.match': '1234'}, 1295 {'not.exact.match': '1000', 'exact.match': '1234'},
1369 self.device.GetPids('exact.match')) 1296 self.device.GetPids('exact.match'))
1370 1297
1371 1298
1372 class DeviceUtilsTakeScreenshotTest(DeviceUtilsNewImplTest): 1299 class DeviceUtilsTakeScreenshotTest(DeviceUtilsTest):
1373 1300
1374 def testTakeScreenshot_fileNameProvided(self): 1301 def testTakeScreenshot_fileNameProvided(self):
1375 with self.assertCalls( 1302 with self.assertCalls(
1376 (mock.call.pylib.utils.device_temp_file.DeviceTempFile( 1303 (mock.call.pylib.utils.device_temp_file.DeviceTempFile(
1377 self.adb, suffix='.png'), 1304 self.adb, suffix='.png'),
1378 MockTempFile('/tmp/path/temp-123.png')), 1305 MockTempFile('/tmp/path/temp-123.png')),
1379 (self.call.adb.Shell('/system/bin/screencap -p /tmp/path/temp-123.png'), 1306 (self.call.adb.Shell('/system/bin/screencap -p /tmp/path/temp-123.png'),
1380 ''), 1307 ''),
1381 self.call.device.PullFile('/tmp/path/temp-123.png', 1308 self.call.device.PullFile('/tmp/path/temp-123.png',
1382 '/test/host/screenshot.png')): 1309 '/test/host/screenshot.png')):
1383 self.device.TakeScreenshot('/test/host/screenshot.png') 1310 self.device.TakeScreenshot('/test/host/screenshot.png')
1384 1311
1385 1312
1386 class DeviceUtilsGetMemoryUsageForPidTest(DeviceUtilsOldImplTest): 1313 class DeviceUtilsGetMemoryUsageForPidTest(DeviceUtilsTest):
1387 1314
1388 def setUp(self): 1315 def setUp(self):
1389 super(DeviceUtilsGetMemoryUsageForPidTest, self).setUp() 1316 super(DeviceUtilsGetMemoryUsageForPidTest, self).setUp()
1390 self.device.old_interface._privileged_command_runner = (
1391 self.device.old_interface.RunShellCommand)
1392 self.device.old_interface._protected_file_access_method_initialized = True
1393 1317
1394 def testGetMemoryUsageForPid_validPid(self): 1318 def testGetMemoryUsageForPid_validPid(self):
1395 with self.assertCallsSequence([ 1319 with self.assertCalls(
1396 ("adb -s 0123456789abcdef shell 'showmap 1234'", 1320 (self.call.device.RunShellCommand(
1397 '100 101 102 103 104 105 106 107 TOTAL\r\n'), 1321 ['showmap', '1234'], as_root=True, check_return=True),
1398 ("adb -s 0123456789abcdef shell " 1322 ['100 101 102 103 104 105 106 107 TOTAL']),
1399 "'cat \"/proc/1234/status\" 2> /dev/null'", 1323 (self.call.device.ReadFile('/proc/1234/status', as_root=True),
1400 'VmHWM: 1024 kB') 1324 'VmHWM: 1024 kB\n')):
1401 ]):
1402 self.assertEqual( 1325 self.assertEqual(
1403 { 1326 {
1404 'Size': 100, 1327 'Size': 100,
1405 'Rss': 101, 1328 'Rss': 101,
1406 'Pss': 102, 1329 'Pss': 102,
1407 'Shared_Clean': 103, 1330 'Shared_Clean': 103,
1408 'Shared_Dirty': 104, 1331 'Shared_Dirty': 104,
1409 'Private_Clean': 105, 1332 'Private_Clean': 105,
1410 'Private_Dirty': 106, 1333 'Private_Dirty': 106,
1411 'VmHWM': 1024 1334 'VmHWM': 1024
1412 }, 1335 },
1413 self.device.GetMemoryUsageForPid(1234)) 1336 self.device.GetMemoryUsageForPid(1234))
1414 1337
1415 def testGetMemoryUsageForPid_invalidPid(self): 1338 def testGetMemoryUsageForPid_noSmaps(self):
1416 with self.assertCalls( 1339 with self.assertCalls(
1417 "adb -s 0123456789abcdef shell 'showmap 4321'", 1340 (self.call.device.RunShellCommand(
1418 'cannot open /proc/4321/smaps: No such file or directory\r\n'): 1341 ['showmap', '4321'], as_root=True, check_return=True),
1419 self.assertEqual({}, self.device.GetMemoryUsageForPid(4321)) 1342 ['cannot open /proc/4321/smaps: No such file or directory']),
1343 (self.call.device.ReadFile('/proc/4321/status', as_root=True),
1344 'VmHWM: 1024 kb\n')):
1345 self.assertEquals({'VmHWM': 1024}, self.device.GetMemoryUsageForPid(4321))
1346
1347 def testGetMemoryUsageForPid_noStatus(self):
1348 with self.assertCalls(
1349 (self.call.device.RunShellCommand(
1350 ['showmap', '4321'], as_root=True, check_return=True),
1351 ['100 101 102 103 104 105 106 107 TOTAL']),
1352 (self.call.device.ReadFile('/proc/4321/status', as_root=True),
1353 self.CommandError())):
1354 self.assertEquals(
1355 {
1356 'Size': 100,
1357 'Rss': 101,
1358 'Pss': 102,
1359 'Shared_Clean': 103,
1360 'Shared_Dirty': 104,
1361 'Private_Clean': 105,
1362 'Private_Dirty': 106,
1363 },
1364 self.device.GetMemoryUsageForPid(4321))
1420 1365
1421 1366
1422 class DeviceUtilsStrTest(DeviceUtilsNewImplTest): 1367 class DeviceUtilsStrTest(DeviceUtilsTest):
1423 1368
1424 def testStr_returnsSerial(self): 1369 def testStr_returnsSerial(self):
1425 with self.assertCalls( 1370 with self.assertCalls(
1426 (self.call.adb.GetDeviceSerial(), '0123456789abcdef')): 1371 (self.call.adb.GetDeviceSerial(), '0123456789abcdef')):
1427 self.assertEqual('0123456789abcdef', str(self.device)) 1372 self.assertEqual('0123456789abcdef', str(self.device))
1428 1373
1429 1374
1430 class DeviceUtilsParallelTest(mock_calls.TestCase): 1375 class DeviceUtilsParallelTest(mock_calls.TestCase):
1431 1376
1432 def testParallel_default(self): 1377 def testParallel_default(self):
1433 test_serials = ['0123456789abcdef', 'fedcba9876543210'] 1378 test_serials = ['0123456789abcdef', 'fedcba9876543210']
1434 with self.assertCall( 1379 with self.assertCall(
1435 mock.call.pylib.device.adb_wrapper.AdbWrapper.GetDevices(), 1380 mock.call.pylib.device.adb_wrapper.AdbWrapper.GetDevices(),
1436 [_AdbWrapperMock(serial) for serial in test_serials]): 1381 [_AdbWrapperMock(serial) for serial in test_serials]):
1437 parallel_devices = device_utils.DeviceUtils.parallel() 1382 parallel_devices = device_utils.DeviceUtils.parallel()
1438 for serial, device in zip(test_serials, parallel_devices.pGet(None)): 1383 for serial, device in zip(test_serials, parallel_devices.pGet(None)):
1439 self.assertTrue( 1384 self.assertTrue(
1440 isinstance(device, device_utils.DeviceUtils) 1385 isinstance(device, device_utils.DeviceUtils)
1441 and serial == str(device), 1386 and serial == str(device),
1442 'Expected a DeviceUtils object with serial %s' % serial) 1387 'Expected a DeviceUtils object with serial %s' % serial)
1443 1388
1444 1389
1445 if __name__ == '__main__': 1390 if __name__ == '__main__':
1446 logging.getLogger().setLevel(logging.DEBUG) 1391 logging.getLogger().setLevel(logging.DEBUG)
1447 unittest.main(verbosity=2) 1392 unittest.main(verbosity=2)
1448 1393
OLDNEW
« no previous file with comments | « build/android/pylib/device/device_utils.py ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698