blob: aed70f9d10a5ded7b368984560616baba7b8f5c5 [file] [log] [blame]
Dan Albert8e1fdd72015-07-24 17:08:33 -07001#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3#
4# Copyright (C) 2015 The Android Open Source Project
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18from __future__ import print_function
19
20import hashlib
21import os
22import posixpath
23import random
24import shlex
25import shutil
26import subprocess
27import tempfile
28import unittest
29
30import mock
31
32import adb
33
34
Dan Alberte2b4a5f2015-07-28 14:53:03 -070035def requires_root(func):
36 def wrapper(self, *args):
37 if self.device.get_prop('ro.debuggable') != '1':
38 raise unittest.SkipTest('requires rootable build')
39
40 was_root = self.device.shell(['id', '-un']).strip() == 'root'
41 if not was_root:
42 self.device.root()
43 self.device.wait()
44
45 try:
46 func(self, *args)
47 finally:
48 if not was_root:
49 self.device.unroot()
50 self.device.wait()
51
52 return wrapper
53
54
Dan Albert8e1fdd72015-07-24 17:08:33 -070055class GetDeviceTest(unittest.TestCase):
56 def setUp(self):
57 self.android_serial = os.getenv('ANDROID_SERIAL')
Spencer Low3e7feda2015-07-30 01:19:52 -070058 if 'ANDROID_SERIAL' in os.environ:
59 del os.environ['ANDROID_SERIAL']
Dan Albert8e1fdd72015-07-24 17:08:33 -070060
61 def tearDown(self):
Spencer Low3e7feda2015-07-30 01:19:52 -070062 if self.android_serial is not None:
63 os.environ['ANDROID_SERIAL'] = self.android_serial
64 else:
65 if 'ANDROID_SERIAL' in os.environ:
66 del os.environ['ANDROID_SERIAL']
Dan Albert8e1fdd72015-07-24 17:08:33 -070067
68 @mock.patch('adb.device.get_devices')
69 def test_explicit(self, mock_get_devices):
70 mock_get_devices.return_value = ['foo', 'bar']
71 device = adb.get_device('foo')
72 self.assertEqual(device.serial, 'foo')
73
74 @mock.patch('adb.device.get_devices')
75 def test_from_env(self, mock_get_devices):
76 mock_get_devices.return_value = ['foo', 'bar']
77 os.environ['ANDROID_SERIAL'] = 'foo'
78 device = adb.get_device()
79 self.assertEqual(device.serial, 'foo')
80
81 @mock.patch('adb.device.get_devices')
82 def test_arg_beats_env(self, mock_get_devices):
83 mock_get_devices.return_value = ['foo', 'bar']
84 os.environ['ANDROID_SERIAL'] = 'bar'
85 device = adb.get_device('foo')
86 self.assertEqual(device.serial, 'foo')
87
88 @mock.patch('adb.device.get_devices')
89 def test_no_such_device(self, mock_get_devices):
90 mock_get_devices.return_value = ['foo', 'bar']
91 self.assertRaises(adb.DeviceNotFoundError, adb.get_device, ['baz'])
92
93 os.environ['ANDROID_SERIAL'] = 'baz'
94 self.assertRaises(adb.DeviceNotFoundError, adb.get_device)
95
96 @mock.patch('adb.device.get_devices')
97 def test_unique_device(self, mock_get_devices):
98 mock_get_devices.return_value = ['foo']
99 device = adb.get_device()
100 self.assertEqual(device.serial, 'foo')
101
102 @mock.patch('adb.device.get_devices')
103 def test_no_unique_device(self, mock_get_devices):
104 mock_get_devices.return_value = ['foo', 'bar']
105 self.assertRaises(adb.NoUniqueDeviceError, adb.get_device)
106
107
108class DeviceTest(unittest.TestCase):
109 def setUp(self):
110 self.device = adb.get_device()
111
112
113class ShellTest(DeviceTest):
114 def test_cat(self):
115 """Check that we can at least cat a file."""
116 out = self.device.shell(['cat', '/proc/uptime']).strip()
117 elements = out.split()
118 self.assertEqual(len(elements), 2)
119
120 uptime, idle = elements
121 self.assertGreater(float(uptime), 0.0)
122 self.assertGreater(float(idle), 0.0)
123
124 def test_throws_on_failure(self):
125 self.assertRaises(subprocess.CalledProcessError,
126 self.device.shell, ['false'])
127
128 def test_output_not_stripped(self):
129 out = self.device.shell(['echo', 'foo'])
130 self.assertEqual(out, 'foo' + self.device.linesep)
131
132 def test_shell_nocheck_failure(self):
133 rc, out = self.device.shell_nocheck(['false'])
134 self.assertNotEqual(rc, 0)
135 self.assertEqual(out, '')
136
137 def test_shell_nocheck_output_not_stripped(self):
138 rc, out = self.device.shell_nocheck(['echo', 'foo'])
139 self.assertEqual(rc, 0)
140 self.assertEqual(out, 'foo' + self.device.linesep)
141
142 def test_can_distinguish_tricky_results(self):
143 # If result checking on ADB shell is naively implemented as
144 # `adb shell <cmd>; echo $?`, we would be unable to distinguish the
145 # output from the result for a cmd of `echo -n 1`.
146 rc, out = self.device.shell_nocheck(['echo', '-n', '1'])
147 self.assertEqual(rc, 0)
148 self.assertEqual(out, '1')
149
150 def test_line_endings(self):
151 """Ensure that line ending translation is not happening in the pty.
152
153 Bug: http://b/19735063
154 """
155 output = self.device.shell(['uname'])
156 self.assertEqual(output, 'Linux' + self.device.linesep)
157
David Purselld4093f12015-08-10 12:52:16 -0700158 def test_pty_logic(self):
159 """Verify PTY logic for shells.
160
161 Interactive shells should use a PTY, non-interactive should not.
162
163 Bug: http://b/21215503
164 """
165 proc = subprocess.Popen(
166 self.device.adb_cmd + ['shell'], stdin=subprocess.PIPE,
167 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
168 # [ -t 0 ] is used (rather than `tty`) to provide portability. This
169 # gives an exit code of 0 iff stdin is connected to a terminal.
170 #
171 # Closing host-side stdin doesn't currently trigger the interactive
172 # shell to exit so we need to explicitly add an exit command to
173 # close the session from the device side, and append \n to complete
174 # the interactive command.
175 result = proc.communicate('[ -t 0 ]; echo x$?; exit 0\n')[0]
176 partition = result.rpartition('x')
177 self.assertEqual(partition[1], 'x')
178 self.assertEqual(int(partition[2]), 0)
179
180 exit_code = self.device.shell_nocheck(['[ -t 0 ]'])[0]
181 self.assertEqual(exit_code, 1)
182
Dan Albert8e1fdd72015-07-24 17:08:33 -0700183
184class ArgumentEscapingTest(DeviceTest):
185 def test_shell_escaping(self):
186 """Make sure that argument escaping is somewhat sane."""
187
188 # http://b/19734868
189 # Note that this actually matches ssh(1)'s behavior --- it's
190 # converted to `sh -c echo hello; echo world` which sh interprets
191 # as `sh -c echo` (with an argument to that shell of "hello"),
192 # and then `echo world` back in the first shell.
193 result = self.device.shell(
194 shlex.split("sh -c 'echo hello; echo world'"))
195 result = result.splitlines()
196 self.assertEqual(['', 'world'], result)
197 # If you really wanted "hello" and "world", here's what you'd do:
198 result = self.device.shell(
199 shlex.split(r'echo hello\;echo world')).splitlines()
200 self.assertEqual(['hello', 'world'], result)
201
202 # http://b/15479704
203 result = self.device.shell(shlex.split("'true && echo t'")).strip()
204 self.assertEqual('t', result)
205 result = self.device.shell(
206 shlex.split("sh -c 'true && echo t'")).strip()
207 self.assertEqual('t', result)
208
209 # http://b/20564385
210 result = self.device.shell(shlex.split('FOO=a BAR=b echo t')).strip()
211 self.assertEqual('t', result)
212 result = self.device.shell(shlex.split(r'echo -n 123\;uname')).strip()
213 self.assertEqual('123Linux', result)
214
215 def test_install_argument_escaping(self):
216 """Make sure that install argument escaping works."""
217 # http://b/20323053
Spencer Lowd8cce182015-08-28 01:07:30 -0700218 tf = tempfile.NamedTemporaryFile('wb', suffix='-text;ls;1.apk',
219 delete=False)
220 tf.close()
Dan Albert8e1fdd72015-07-24 17:08:33 -0700221 self.assertIn("-text;ls;1.apk", self.device.install(tf.name))
Spencer Lowd8cce182015-08-28 01:07:30 -0700222 os.remove(tf.name)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700223
224 # http://b/3090932
Spencer Lowd8cce182015-08-28 01:07:30 -0700225 tf = tempfile.NamedTemporaryFile('wb', suffix="-Live Hold'em.apk",
226 delete=False)
227 tf.close()
Dan Albert8e1fdd72015-07-24 17:08:33 -0700228 self.assertIn("-Live Hold'em.apk", self.device.install(tf.name))
Spencer Lowd8cce182015-08-28 01:07:30 -0700229 os.remove(tf.name)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700230
231
232class RootUnrootTest(DeviceTest):
233 def _test_root(self):
234 message = self.device.root()
235 if 'adbd cannot run as root in production builds' in message:
236 return
237 self.device.wait()
238 self.assertEqual('root', self.device.shell(['id', '-un']).strip())
239
240 def _test_unroot(self):
241 self.device.unroot()
242 self.device.wait()
243 self.assertEqual('shell', self.device.shell(['id', '-un']).strip())
244
245 def test_root_unroot(self):
246 """Make sure that adb root and adb unroot work, using id(1)."""
Dan Alberte2b4a5f2015-07-28 14:53:03 -0700247 if self.device.get_prop('ro.debuggable') != '1':
248 raise unittest.SkipTest('requires rootable build')
249
Dan Albert8e1fdd72015-07-24 17:08:33 -0700250 original_user = self.device.shell(['id', '-un']).strip()
251 try:
252 if original_user == 'root':
253 self._test_unroot()
254 self._test_root()
255 elif original_user == 'shell':
256 self._test_root()
257 self._test_unroot()
258 finally:
259 if original_user == 'root':
260 self.device.root()
261 else:
262 self.device.unroot()
263 self.device.wait()
264
265
266class TcpIpTest(DeviceTest):
267 def test_tcpip_failure_raises(self):
268 """adb tcpip requires a port.
269
270 Bug: http://b/22636927
271 """
272 self.assertRaises(
273 subprocess.CalledProcessError, self.device.tcpip, '')
274 self.assertRaises(
275 subprocess.CalledProcessError, self.device.tcpip, 'foo')
276
277
Dan Alberte2b4a5f2015-07-28 14:53:03 -0700278class SystemPropertiesTest(DeviceTest):
279 def test_get_prop(self):
280 self.assertEqual(self.device.get_prop('init.svc.adbd'), 'running')
281
282 @requires_root
283 def test_set_prop(self):
284 prop_name = 'foo.bar'
285 self.device.shell(['setprop', prop_name, '""'])
286
287 self.device.set_prop(prop_name, 'qux')
288 self.assertEqual(
289 self.device.shell(['getprop', prop_name]).strip(), 'qux')
290
291
Dan Albert8e1fdd72015-07-24 17:08:33 -0700292def compute_md5(string):
293 hsh = hashlib.md5()
294 hsh.update(string)
295 return hsh.hexdigest()
296
297
298def get_md5_prog(device):
299 """Older platforms (pre-L) had the name md5 rather than md5sum."""
300 try:
301 device.shell(['md5sum', '/proc/uptime'])
302 return 'md5sum'
303 except subprocess.CalledProcessError:
304 return 'md5'
305
306
307class HostFile(object):
308 def __init__(self, handle, checksum):
309 self.handle = handle
310 self.checksum = checksum
311 self.full_path = handle.name
312 self.base_name = os.path.basename(self.full_path)
313
314
315class DeviceFile(object):
316 def __init__(self, checksum, full_path):
317 self.checksum = checksum
318 self.full_path = full_path
319 self.base_name = posixpath.basename(self.full_path)
320
321
322def make_random_host_files(in_dir, num_files):
323 min_size = 1 * (1 << 10)
324 max_size = 16 * (1 << 10)
325
326 files = []
327 for _ in xrange(num_files):
328 file_handle = tempfile.NamedTemporaryFile(dir=in_dir, delete=False)
329
330 size = random.randrange(min_size, max_size, 1024)
331 rand_str = os.urandom(size)
332 file_handle.write(rand_str)
333 file_handle.flush()
334 file_handle.close()
335
336 md5 = compute_md5(rand_str)
337 files.append(HostFile(file_handle, md5))
338 return files
339
340
341def make_random_device_files(device, in_dir, num_files):
342 min_size = 1 * (1 << 10)
343 max_size = 16 * (1 << 10)
344
345 files = []
346 for file_num in xrange(num_files):
347 size = random.randrange(min_size, max_size, 1024)
348
349 base_name = 'device_tmpfile' + str(file_num)
Spencer Low3e7feda2015-07-30 01:19:52 -0700350 full_path = posixpath.join(in_dir, base_name)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700351
352 device.shell(['dd', 'if=/dev/urandom', 'of={}'.format(full_path),
353 'bs={}'.format(size), 'count=1'])
354 dev_md5, _ = device.shell([get_md5_prog(device), full_path]).split()
355
356 files.append(DeviceFile(dev_md5, full_path))
357 return files
358
359
360class FileOperationsTest(DeviceTest):
361 SCRATCH_DIR = '/data/local/tmp'
362 DEVICE_TEMP_FILE = SCRATCH_DIR + '/adb_test_file'
363 DEVICE_TEMP_DIR = SCRATCH_DIR + '/adb_test_dir'
364
365 def _test_push(self, local_file, checksum):
366 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_FILE])
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700367 self.device.push(local=local_file, remote=self.DEVICE_TEMP_FILE)
368 dev_md5, _ = self.device.shell([get_md5_prog(self.device),
369 self.DEVICE_TEMP_FILE]).split()
370 self.assertEqual(checksum, dev_md5)
371 self.device.shell(['rm', '-f', self.DEVICE_TEMP_FILE])
Dan Albert8e1fdd72015-07-24 17:08:33 -0700372
373 def test_push(self):
374 """Push a randomly generated file to specified device."""
375 kbytes = 512
376 tmp = tempfile.NamedTemporaryFile(mode='wb', delete=False)
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700377 rand_str = os.urandom(1024 * kbytes)
378 tmp.write(rand_str)
379 tmp.close()
380 self._test_push(tmp.name, compute_md5(rand_str))
381 os.remove(tmp.name)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700382
383 # TODO: write push directory test.
384
385 def _test_pull(self, remote_file, checksum):
386 tmp_write = tempfile.NamedTemporaryFile(mode='wb', delete=False)
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700387 tmp_write.close()
388 self.device.pull(remote=remote_file, local=tmp_write.name)
389 with open(tmp_write.name, 'rb') as tmp_read:
390 host_contents = tmp_read.read()
391 host_md5 = compute_md5(host_contents)
392 self.assertEqual(checksum, host_md5)
393 os.remove(tmp_write.name)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700394
395 def test_pull(self):
396 """Pull a randomly generated file from specified device."""
397 kbytes = 512
398 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_FILE])
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700399 cmd = ['dd', 'if=/dev/urandom',
400 'of={}'.format(self.DEVICE_TEMP_FILE), 'bs=1024',
401 'count={}'.format(kbytes)]
402 self.device.shell(cmd)
403 dev_md5, _ = self.device.shell(
404 [get_md5_prog(self.device), self.DEVICE_TEMP_FILE]).split()
405 self._test_pull(self.DEVICE_TEMP_FILE, dev_md5)
406 self.device.shell_nocheck(['rm', self.DEVICE_TEMP_FILE])
Dan Albert8e1fdd72015-07-24 17:08:33 -0700407
408 def test_pull_dir(self):
409 """Pull a randomly generated directory of files from the device."""
410 host_dir = tempfile.mkdtemp()
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700411 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
412 self.device.shell(['mkdir', '-p', self.DEVICE_TEMP_DIR])
Dan Albert8e1fdd72015-07-24 17:08:33 -0700413
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700414 # Populate device directory with random files.
415 temp_files = make_random_device_files(
416 self.device, in_dir=self.DEVICE_TEMP_DIR, num_files=32)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700417
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700418 self.device.pull(remote=self.DEVICE_TEMP_DIR, local=host_dir)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700419
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700420 for temp_file in temp_files:
421 host_path = os.path.join(host_dir, temp_file.base_name)
422 with open(host_path, 'rb') as host_file:
423 host_md5 = compute_md5(host_file.read())
424 self.assertEqual(host_md5, temp_file.checksum)
425
426 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
427 if host_dir is not None:
428 shutil.rmtree(host_dir)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700429
430 def test_sync(self):
431 """Sync a randomly generated directory of files to specified device."""
432 base_dir = tempfile.mkdtemp()
Dan Albert8e1fdd72015-07-24 17:08:33 -0700433
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700434 # Create mirror device directory hierarchy within base_dir.
435 full_dir_path = base_dir + self.DEVICE_TEMP_DIR
436 os.makedirs(full_dir_path)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700437
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700438 # Create 32 random files within the host mirror.
439 temp_files = make_random_host_files(in_dir=full_dir_path, num_files=32)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700440
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700441 # Clean up any trash on the device.
442 device = adb.get_device(product=base_dir)
443 device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
Dan Albert8e1fdd72015-07-24 17:08:33 -0700444
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700445 device.sync('data')
446
447 # Confirm that every file on the device mirrors that on the host.
448 for temp_file in temp_files:
449 device_full_path = posixpath.join(self.DEVICE_TEMP_DIR,
450 temp_file.base_name)
451 dev_md5, _ = device.shell(
452 [get_md5_prog(self.device), device_full_path]).split()
453 self.assertEqual(temp_file.checksum, dev_md5)
454
455 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
456 shutil.rmtree(base_dir + self.DEVICE_TEMP_DIR)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700457
Dan Albert8e1fdd72015-07-24 17:08:33 -0700458 def test_unicode_paths(self):
459 """Ensure that we can support non-ASCII paths, even on Windows."""
460 name = u'로보카 폴리'.encode('utf-8')
461
462 ## push.
463 tf = tempfile.NamedTemporaryFile('wb', suffix=name)
464 self.device.push(tf.name, '/data/local/tmp/adb-test-{}'.format(name))
465 self.device.shell(['rm', '-f', '/data/local/tmp/adb-test-*'])
466
467 # pull.
468 cmd = ['touch', '"/data/local/tmp/adb-test-{}"'.format(name)]
469 self.device.shell(cmd)
470
471 tf = tempfile.NamedTemporaryFile('wb', suffix=name)
472 self.device.pull('/data/local/tmp/adb-test-{}'.format(name), tf.name)
473
474
475def main():
476 random.seed(0)
477 if len(adb.get_devices()) > 0:
478 suite = unittest.TestLoader().loadTestsFromName(__name__)
479 unittest.TextTestRunner(verbosity=3).run(suite)
480 else:
481 print('Test suite must be run with attached devices')
482
483
484if __name__ == '__main__':
485 main()