blob: c893ad42ddded053ee20a2a869b026ca68283dcc [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
218 tf = tempfile.NamedTemporaryFile('wb', suffix='-text;ls;1.apk')
219 self.assertIn("-text;ls;1.apk", self.device.install(tf.name))
220
221 # http://b/3090932
222 tf = tempfile.NamedTemporaryFile('wb', suffix="-Live Hold'em.apk")
223 self.assertIn("-Live Hold'em.apk", self.device.install(tf.name))
224
225
226class RootUnrootTest(DeviceTest):
227 def _test_root(self):
228 message = self.device.root()
229 if 'adbd cannot run as root in production builds' in message:
230 return
231 self.device.wait()
232 self.assertEqual('root', self.device.shell(['id', '-un']).strip())
233
234 def _test_unroot(self):
235 self.device.unroot()
236 self.device.wait()
237 self.assertEqual('shell', self.device.shell(['id', '-un']).strip())
238
239 def test_root_unroot(self):
240 """Make sure that adb root and adb unroot work, using id(1)."""
Dan Alberte2b4a5f2015-07-28 14:53:03 -0700241 if self.device.get_prop('ro.debuggable') != '1':
242 raise unittest.SkipTest('requires rootable build')
243
Dan Albert8e1fdd72015-07-24 17:08:33 -0700244 original_user = self.device.shell(['id', '-un']).strip()
245 try:
246 if original_user == 'root':
247 self._test_unroot()
248 self._test_root()
249 elif original_user == 'shell':
250 self._test_root()
251 self._test_unroot()
252 finally:
253 if original_user == 'root':
254 self.device.root()
255 else:
256 self.device.unroot()
257 self.device.wait()
258
259
260class TcpIpTest(DeviceTest):
261 def test_tcpip_failure_raises(self):
262 """adb tcpip requires a port.
263
264 Bug: http://b/22636927
265 """
266 self.assertRaises(
267 subprocess.CalledProcessError, self.device.tcpip, '')
268 self.assertRaises(
269 subprocess.CalledProcessError, self.device.tcpip, 'foo')
270
271
Dan Alberte2b4a5f2015-07-28 14:53:03 -0700272class SystemPropertiesTest(DeviceTest):
273 def test_get_prop(self):
274 self.assertEqual(self.device.get_prop('init.svc.adbd'), 'running')
275
276 @requires_root
277 def test_set_prop(self):
278 prop_name = 'foo.bar'
279 self.device.shell(['setprop', prop_name, '""'])
280
281 self.device.set_prop(prop_name, 'qux')
282 self.assertEqual(
283 self.device.shell(['getprop', prop_name]).strip(), 'qux')
284
285
Dan Albert8e1fdd72015-07-24 17:08:33 -0700286def compute_md5(string):
287 hsh = hashlib.md5()
288 hsh.update(string)
289 return hsh.hexdigest()
290
291
292def get_md5_prog(device):
293 """Older platforms (pre-L) had the name md5 rather than md5sum."""
294 try:
295 device.shell(['md5sum', '/proc/uptime'])
296 return 'md5sum'
297 except subprocess.CalledProcessError:
298 return 'md5'
299
300
301class HostFile(object):
302 def __init__(self, handle, checksum):
303 self.handle = handle
304 self.checksum = checksum
305 self.full_path = handle.name
306 self.base_name = os.path.basename(self.full_path)
307
308
309class DeviceFile(object):
310 def __init__(self, checksum, full_path):
311 self.checksum = checksum
312 self.full_path = full_path
313 self.base_name = posixpath.basename(self.full_path)
314
315
316def make_random_host_files(in_dir, num_files):
317 min_size = 1 * (1 << 10)
318 max_size = 16 * (1 << 10)
319
320 files = []
321 for _ in xrange(num_files):
322 file_handle = tempfile.NamedTemporaryFile(dir=in_dir, delete=False)
323
324 size = random.randrange(min_size, max_size, 1024)
325 rand_str = os.urandom(size)
326 file_handle.write(rand_str)
327 file_handle.flush()
328 file_handle.close()
329
330 md5 = compute_md5(rand_str)
331 files.append(HostFile(file_handle, md5))
332 return files
333
334
335def make_random_device_files(device, in_dir, num_files):
336 min_size = 1 * (1 << 10)
337 max_size = 16 * (1 << 10)
338
339 files = []
340 for file_num in xrange(num_files):
341 size = random.randrange(min_size, max_size, 1024)
342
343 base_name = 'device_tmpfile' + str(file_num)
Spencer Low3e7feda2015-07-30 01:19:52 -0700344 full_path = posixpath.join(in_dir, base_name)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700345
346 device.shell(['dd', 'if=/dev/urandom', 'of={}'.format(full_path),
347 'bs={}'.format(size), 'count=1'])
348 dev_md5, _ = device.shell([get_md5_prog(device), full_path]).split()
349
350 files.append(DeviceFile(dev_md5, full_path))
351 return files
352
353
354class FileOperationsTest(DeviceTest):
355 SCRATCH_DIR = '/data/local/tmp'
356 DEVICE_TEMP_FILE = SCRATCH_DIR + '/adb_test_file'
357 DEVICE_TEMP_DIR = SCRATCH_DIR + '/adb_test_dir'
358
359 def _test_push(self, local_file, checksum):
360 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_FILE])
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700361 self.device.push(local=local_file, remote=self.DEVICE_TEMP_FILE)
362 dev_md5, _ = self.device.shell([get_md5_prog(self.device),
363 self.DEVICE_TEMP_FILE]).split()
364 self.assertEqual(checksum, dev_md5)
365 self.device.shell(['rm', '-f', self.DEVICE_TEMP_FILE])
Dan Albert8e1fdd72015-07-24 17:08:33 -0700366
367 def test_push(self):
368 """Push a randomly generated file to specified device."""
369 kbytes = 512
370 tmp = tempfile.NamedTemporaryFile(mode='wb', delete=False)
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700371 rand_str = os.urandom(1024 * kbytes)
372 tmp.write(rand_str)
373 tmp.close()
374 self._test_push(tmp.name, compute_md5(rand_str))
375 os.remove(tmp.name)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700376
377 # TODO: write push directory test.
378
379 def _test_pull(self, remote_file, checksum):
380 tmp_write = tempfile.NamedTemporaryFile(mode='wb', delete=False)
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700381 tmp_write.close()
382 self.device.pull(remote=remote_file, local=tmp_write.name)
383 with open(tmp_write.name, 'rb') as tmp_read:
384 host_contents = tmp_read.read()
385 host_md5 = compute_md5(host_contents)
386 self.assertEqual(checksum, host_md5)
387 os.remove(tmp_write.name)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700388
389 def test_pull(self):
390 """Pull a randomly generated file from specified device."""
391 kbytes = 512
392 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_FILE])
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700393 cmd = ['dd', 'if=/dev/urandom',
394 'of={}'.format(self.DEVICE_TEMP_FILE), 'bs=1024',
395 'count={}'.format(kbytes)]
396 self.device.shell(cmd)
397 dev_md5, _ = self.device.shell(
398 [get_md5_prog(self.device), self.DEVICE_TEMP_FILE]).split()
399 self._test_pull(self.DEVICE_TEMP_FILE, dev_md5)
400 self.device.shell_nocheck(['rm', self.DEVICE_TEMP_FILE])
Dan Albert8e1fdd72015-07-24 17:08:33 -0700401
402 def test_pull_dir(self):
403 """Pull a randomly generated directory of files from the device."""
404 host_dir = tempfile.mkdtemp()
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700405 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
406 self.device.shell(['mkdir', '-p', self.DEVICE_TEMP_DIR])
Dan Albert8e1fdd72015-07-24 17:08:33 -0700407
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700408 # Populate device directory with random files.
409 temp_files = make_random_device_files(
410 self.device, in_dir=self.DEVICE_TEMP_DIR, num_files=32)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700411
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700412 self.device.pull(remote=self.DEVICE_TEMP_DIR, local=host_dir)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700413
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700414 for temp_file in temp_files:
415 host_path = os.path.join(host_dir, temp_file.base_name)
416 with open(host_path, 'rb') as host_file:
417 host_md5 = compute_md5(host_file.read())
418 self.assertEqual(host_md5, temp_file.checksum)
419
420 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
421 if host_dir is not None:
422 shutil.rmtree(host_dir)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700423
424 def test_sync(self):
425 """Sync a randomly generated directory of files to specified device."""
426 base_dir = tempfile.mkdtemp()
Dan Albert8e1fdd72015-07-24 17:08:33 -0700427
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700428 # Create mirror device directory hierarchy within base_dir.
429 full_dir_path = base_dir + self.DEVICE_TEMP_DIR
430 os.makedirs(full_dir_path)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700431
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700432 # Create 32 random files within the host mirror.
433 temp_files = make_random_host_files(in_dir=full_dir_path, num_files=32)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700434
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700435 # Clean up any trash on the device.
436 device = adb.get_device(product=base_dir)
437 device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
Dan Albert8e1fdd72015-07-24 17:08:33 -0700438
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700439 device.sync('data')
440
441 # Confirm that every file on the device mirrors that on the host.
442 for temp_file in temp_files:
443 device_full_path = posixpath.join(self.DEVICE_TEMP_DIR,
444 temp_file.base_name)
445 dev_md5, _ = device.shell(
446 [get_md5_prog(self.device), device_full_path]).split()
447 self.assertEqual(temp_file.checksum, dev_md5)
448
449 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
450 shutil.rmtree(base_dir + self.DEVICE_TEMP_DIR)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700451
Dan Albert8e1fdd72015-07-24 17:08:33 -0700452 def test_unicode_paths(self):
453 """Ensure that we can support non-ASCII paths, even on Windows."""
454 name = u'로보카 폴리'.encode('utf-8')
455
456 ## push.
457 tf = tempfile.NamedTemporaryFile('wb', suffix=name)
458 self.device.push(tf.name, '/data/local/tmp/adb-test-{}'.format(name))
459 self.device.shell(['rm', '-f', '/data/local/tmp/adb-test-*'])
460
461 # pull.
462 cmd = ['touch', '"/data/local/tmp/adb-test-{}"'.format(name)]
463 self.device.shell(cmd)
464
465 tf = tempfile.NamedTemporaryFile('wb', suffix=name)
466 self.device.pull('/data/local/tmp/adb-test-{}'.format(name), tf.name)
467
468
469def main():
470 random.seed(0)
471 if len(adb.get_devices()) > 0:
472 suite = unittest.TestLoader().loadTestsFromName(__name__)
473 unittest.TextTestRunner(verbosity=3).run(suite)
474 else:
475 print('Test suite must be run with attached devices')
476
477
478if __name__ == '__main__':
479 main()