blob: 8003eaaeaa59e5e70cc9373b25e8eb39cf84f0a6 [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')
58 del os.environ['ANDROID_SERIAL']
59
60 def tearDown(self):
61 os.environ['ANDROID_SERIAL'] = self.android_serial
62
63 @mock.patch('adb.device.get_devices')
64 def test_explicit(self, mock_get_devices):
65 mock_get_devices.return_value = ['foo', 'bar']
66 device = adb.get_device('foo')
67 self.assertEqual(device.serial, 'foo')
68
69 @mock.patch('adb.device.get_devices')
70 def test_from_env(self, mock_get_devices):
71 mock_get_devices.return_value = ['foo', 'bar']
72 os.environ['ANDROID_SERIAL'] = 'foo'
73 device = adb.get_device()
74 self.assertEqual(device.serial, 'foo')
75
76 @mock.patch('adb.device.get_devices')
77 def test_arg_beats_env(self, mock_get_devices):
78 mock_get_devices.return_value = ['foo', 'bar']
79 os.environ['ANDROID_SERIAL'] = 'bar'
80 device = adb.get_device('foo')
81 self.assertEqual(device.serial, 'foo')
82
83 @mock.patch('adb.device.get_devices')
84 def test_no_such_device(self, mock_get_devices):
85 mock_get_devices.return_value = ['foo', 'bar']
86 self.assertRaises(adb.DeviceNotFoundError, adb.get_device, ['baz'])
87
88 os.environ['ANDROID_SERIAL'] = 'baz'
89 self.assertRaises(adb.DeviceNotFoundError, adb.get_device)
90
91 @mock.patch('adb.device.get_devices')
92 def test_unique_device(self, mock_get_devices):
93 mock_get_devices.return_value = ['foo']
94 device = adb.get_device()
95 self.assertEqual(device.serial, 'foo')
96
97 @mock.patch('adb.device.get_devices')
98 def test_no_unique_device(self, mock_get_devices):
99 mock_get_devices.return_value = ['foo', 'bar']
100 self.assertRaises(adb.NoUniqueDeviceError, adb.get_device)
101
102
103class DeviceTest(unittest.TestCase):
104 def setUp(self):
105 self.device = adb.get_device()
106
107
108class ShellTest(DeviceTest):
109 def test_cat(self):
110 """Check that we can at least cat a file."""
111 out = self.device.shell(['cat', '/proc/uptime']).strip()
112 elements = out.split()
113 self.assertEqual(len(elements), 2)
114
115 uptime, idle = elements
116 self.assertGreater(float(uptime), 0.0)
117 self.assertGreater(float(idle), 0.0)
118
119 def test_throws_on_failure(self):
120 self.assertRaises(subprocess.CalledProcessError,
121 self.device.shell, ['false'])
122
123 def test_output_not_stripped(self):
124 out = self.device.shell(['echo', 'foo'])
125 self.assertEqual(out, 'foo' + self.device.linesep)
126
127 def test_shell_nocheck_failure(self):
128 rc, out = self.device.shell_nocheck(['false'])
129 self.assertNotEqual(rc, 0)
130 self.assertEqual(out, '')
131
132 def test_shell_nocheck_output_not_stripped(self):
133 rc, out = self.device.shell_nocheck(['echo', 'foo'])
134 self.assertEqual(rc, 0)
135 self.assertEqual(out, 'foo' + self.device.linesep)
136
137 def test_can_distinguish_tricky_results(self):
138 # If result checking on ADB shell is naively implemented as
139 # `adb shell <cmd>; echo $?`, we would be unable to distinguish the
140 # output from the result for a cmd of `echo -n 1`.
141 rc, out = self.device.shell_nocheck(['echo', '-n', '1'])
142 self.assertEqual(rc, 0)
143 self.assertEqual(out, '1')
144
145 def test_line_endings(self):
146 """Ensure that line ending translation is not happening in the pty.
147
148 Bug: http://b/19735063
149 """
150 output = self.device.shell(['uname'])
151 self.assertEqual(output, 'Linux' + self.device.linesep)
152
153
154class ArgumentEscapingTest(DeviceTest):
155 def test_shell_escaping(self):
156 """Make sure that argument escaping is somewhat sane."""
157
158 # http://b/19734868
159 # Note that this actually matches ssh(1)'s behavior --- it's
160 # converted to `sh -c echo hello; echo world` which sh interprets
161 # as `sh -c echo` (with an argument to that shell of "hello"),
162 # and then `echo world` back in the first shell.
163 result = self.device.shell(
164 shlex.split("sh -c 'echo hello; echo world'"))
165 result = result.splitlines()
166 self.assertEqual(['', 'world'], result)
167 # If you really wanted "hello" and "world", here's what you'd do:
168 result = self.device.shell(
169 shlex.split(r'echo hello\;echo world')).splitlines()
170 self.assertEqual(['hello', 'world'], result)
171
172 # http://b/15479704
173 result = self.device.shell(shlex.split("'true && echo t'")).strip()
174 self.assertEqual('t', result)
175 result = self.device.shell(
176 shlex.split("sh -c 'true && echo t'")).strip()
177 self.assertEqual('t', result)
178
179 # http://b/20564385
180 result = self.device.shell(shlex.split('FOO=a BAR=b echo t')).strip()
181 self.assertEqual('t', result)
182 result = self.device.shell(shlex.split(r'echo -n 123\;uname')).strip()
183 self.assertEqual('123Linux', result)
184
185 def test_install_argument_escaping(self):
186 """Make sure that install argument escaping works."""
187 # http://b/20323053
188 tf = tempfile.NamedTemporaryFile('wb', suffix='-text;ls;1.apk')
189 self.assertIn("-text;ls;1.apk", self.device.install(tf.name))
190
191 # http://b/3090932
192 tf = tempfile.NamedTemporaryFile('wb', suffix="-Live Hold'em.apk")
193 self.assertIn("-Live Hold'em.apk", self.device.install(tf.name))
194
195
196class RootUnrootTest(DeviceTest):
197 def _test_root(self):
198 message = self.device.root()
199 if 'adbd cannot run as root in production builds' in message:
200 return
201 self.device.wait()
202 self.assertEqual('root', self.device.shell(['id', '-un']).strip())
203
204 def _test_unroot(self):
205 self.device.unroot()
206 self.device.wait()
207 self.assertEqual('shell', self.device.shell(['id', '-un']).strip())
208
209 def test_root_unroot(self):
210 """Make sure that adb root and adb unroot work, using id(1)."""
Dan Alberte2b4a5f2015-07-28 14:53:03 -0700211 if self.device.get_prop('ro.debuggable') != '1':
212 raise unittest.SkipTest('requires rootable build')
213
Dan Albert8e1fdd72015-07-24 17:08:33 -0700214 original_user = self.device.shell(['id', '-un']).strip()
215 try:
216 if original_user == 'root':
217 self._test_unroot()
218 self._test_root()
219 elif original_user == 'shell':
220 self._test_root()
221 self._test_unroot()
222 finally:
223 if original_user == 'root':
224 self.device.root()
225 else:
226 self.device.unroot()
227 self.device.wait()
228
229
230class TcpIpTest(DeviceTest):
231 def test_tcpip_failure_raises(self):
232 """adb tcpip requires a port.
233
234 Bug: http://b/22636927
235 """
236 self.assertRaises(
237 subprocess.CalledProcessError, self.device.tcpip, '')
238 self.assertRaises(
239 subprocess.CalledProcessError, self.device.tcpip, 'foo')
240
241
Dan Alberte2b4a5f2015-07-28 14:53:03 -0700242class SystemPropertiesTest(DeviceTest):
243 def test_get_prop(self):
244 self.assertEqual(self.device.get_prop('init.svc.adbd'), 'running')
245
246 @requires_root
247 def test_set_prop(self):
248 prop_name = 'foo.bar'
249 self.device.shell(['setprop', prop_name, '""'])
250
251 self.device.set_prop(prop_name, 'qux')
252 self.assertEqual(
253 self.device.shell(['getprop', prop_name]).strip(), 'qux')
254
255
Dan Albert8e1fdd72015-07-24 17:08:33 -0700256def compute_md5(string):
257 hsh = hashlib.md5()
258 hsh.update(string)
259 return hsh.hexdigest()
260
261
262def get_md5_prog(device):
263 """Older platforms (pre-L) had the name md5 rather than md5sum."""
264 try:
265 device.shell(['md5sum', '/proc/uptime'])
266 return 'md5sum'
267 except subprocess.CalledProcessError:
268 return 'md5'
269
270
271class HostFile(object):
272 def __init__(self, handle, checksum):
273 self.handle = handle
274 self.checksum = checksum
275 self.full_path = handle.name
276 self.base_name = os.path.basename(self.full_path)
277
278
279class DeviceFile(object):
280 def __init__(self, checksum, full_path):
281 self.checksum = checksum
282 self.full_path = full_path
283 self.base_name = posixpath.basename(self.full_path)
284
285
286def make_random_host_files(in_dir, num_files):
287 min_size = 1 * (1 << 10)
288 max_size = 16 * (1 << 10)
289
290 files = []
291 for _ in xrange(num_files):
292 file_handle = tempfile.NamedTemporaryFile(dir=in_dir, delete=False)
293
294 size = random.randrange(min_size, max_size, 1024)
295 rand_str = os.urandom(size)
296 file_handle.write(rand_str)
297 file_handle.flush()
298 file_handle.close()
299
300 md5 = compute_md5(rand_str)
301 files.append(HostFile(file_handle, md5))
302 return files
303
304
305def make_random_device_files(device, in_dir, num_files):
306 min_size = 1 * (1 << 10)
307 max_size = 16 * (1 << 10)
308
309 files = []
310 for file_num in xrange(num_files):
311 size = random.randrange(min_size, max_size, 1024)
312
313 base_name = 'device_tmpfile' + str(file_num)
314 full_path = os.path.join(in_dir, base_name)
315
316 device.shell(['dd', 'if=/dev/urandom', 'of={}'.format(full_path),
317 'bs={}'.format(size), 'count=1'])
318 dev_md5, _ = device.shell([get_md5_prog(device), full_path]).split()
319
320 files.append(DeviceFile(dev_md5, full_path))
321 return files
322
323
324class FileOperationsTest(DeviceTest):
325 SCRATCH_DIR = '/data/local/tmp'
326 DEVICE_TEMP_FILE = SCRATCH_DIR + '/adb_test_file'
327 DEVICE_TEMP_DIR = SCRATCH_DIR + '/adb_test_dir'
328
329 def _test_push(self, local_file, checksum):
330 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_FILE])
331 try:
332 self.device.push(
333 local=local_file, remote=self.DEVICE_TEMP_FILE)
334 dev_md5, _ = self.device.shell(
335 [get_md5_prog(self.device), self.DEVICE_TEMP_FILE]).split()
336 self.assertEqual(checksum, dev_md5)
337 finally:
338 self.device.shell(['rm', '-f', self.DEVICE_TEMP_FILE])
339
340 def test_push(self):
341 """Push a randomly generated file to specified device."""
342 kbytes = 512
343 tmp = tempfile.NamedTemporaryFile(mode='wb', delete=False)
344 try:
345 rand_str = os.urandom(1024 * kbytes)
346 tmp.write(rand_str)
347 tmp.close()
348 self._test_push(tmp.name, compute_md5(rand_str))
349 finally:
350 os.remove(tmp.name)
351
352 # TODO: write push directory test.
353
354 def _test_pull(self, remote_file, checksum):
355 tmp_write = tempfile.NamedTemporaryFile(mode='wb', delete=False)
356 try:
357 tmp_write.close()
358 self.device.pull(remote=remote_file, local=tmp_write.name)
359 with open(tmp_write.name, 'rb') as tmp_read:
360 host_contents = tmp_read.read()
361 host_md5 = compute_md5(host_contents)
362 self.assertEqual(checksum, host_md5)
363 finally:
364 os.remove(tmp_write.name)
365
366 def test_pull(self):
367 """Pull a randomly generated file from specified device."""
368 kbytes = 512
369 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_FILE])
370 try:
371 cmd = ['dd', 'if=/dev/urandom',
372 'of={}'.format(self.DEVICE_TEMP_FILE), 'bs=1024',
373 'count={}'.format(kbytes)]
374 self.device.shell(cmd)
375 dev_md5, _ = self.device.shell(
376 [get_md5_prog(self.device), self.DEVICE_TEMP_FILE]).split()
377 self._test_pull(self.DEVICE_TEMP_FILE, dev_md5)
378 finally:
379 self.device.shell_nocheck(['rm', self.DEVICE_TEMP_FILE])
380
381 def test_pull_dir(self):
382 """Pull a randomly generated directory of files from the device."""
383 host_dir = tempfile.mkdtemp()
384 try:
385 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
386 self.device.shell(['mkdir', '-p', self.DEVICE_TEMP_DIR])
387
388 # Populate device directory with random files.
389 temp_files = make_random_device_files(
390 self.device, in_dir=self.DEVICE_TEMP_DIR, num_files=32)
391
392 self.device.pull(remote=self.DEVICE_TEMP_DIR, local=host_dir)
393
394 for temp_file in temp_files:
395 host_path = os.path.join(host_dir, temp_file.base_name)
396 with open(host_path, 'rb') as host_file:
397 host_md5 = compute_md5(host_file.read())
398 self.assertEqual(host_md5, temp_file.checksum)
399 finally:
400 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
401 if host_dir is not None:
402 shutil.rmtree(host_dir)
403
404 def test_sync(self):
405 """Sync a randomly generated directory of files to specified device."""
406 base_dir = tempfile.mkdtemp()
407 try:
408 # Create mirror device directory hierarchy within base_dir.
409 full_dir_path = base_dir + self.DEVICE_TEMP_DIR
410 os.makedirs(full_dir_path)
411
412 # Create 32 random files within the host mirror.
413 temp_files = make_random_host_files(in_dir=full_dir_path,
414 num_files=32)
415
416 # Clean up any trash on the device.
417 device = adb.get_device(product=base_dir)
418 device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
419
420 device.sync('data')
421
422 # Confirm that every file on the device mirrors that on the host.
423 for temp_file in temp_files:
424 device_full_path = posixpath.join(
425 self.DEVICE_TEMP_DIR, temp_file.base_name)
426 dev_md5, _ = device.shell(
427 [get_md5_prog(self.device), device_full_path]).split()
428 self.assertEqual(temp_file.checksum, dev_md5)
429 finally:
430 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
431 shutil.rmtree(base_dir + self.DEVICE_TEMP_DIR)
432
Dan Albert8e1fdd72015-07-24 17:08:33 -0700433 def test_unicode_paths(self):
434 """Ensure that we can support non-ASCII paths, even on Windows."""
435 name = u'로보카 폴리'.encode('utf-8')
436
437 ## push.
438 tf = tempfile.NamedTemporaryFile('wb', suffix=name)
439 self.device.push(tf.name, '/data/local/tmp/adb-test-{}'.format(name))
440 self.device.shell(['rm', '-f', '/data/local/tmp/adb-test-*'])
441
442 # pull.
443 cmd = ['touch', '"/data/local/tmp/adb-test-{}"'.format(name)]
444 self.device.shell(cmd)
445
446 tf = tempfile.NamedTemporaryFile('wb', suffix=name)
447 self.device.pull('/data/local/tmp/adb-test-{}'.format(name), tf.name)
448
449
450def main():
451 random.seed(0)
452 if len(adb.get_devices()) > 0:
453 suite = unittest.TestLoader().loadTestsFromName(__name__)
454 unittest.TextTestRunner(verbosity=3).run(suite)
455 else:
456 print('Test suite must be run with attached devices')
457
458
459if __name__ == '__main__':
460 main()