blob: 48a3f6c30b1f10b27a0c9c3885461e8caa132b82 [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
158
159class ArgumentEscapingTest(DeviceTest):
160 def test_shell_escaping(self):
161 """Make sure that argument escaping is somewhat sane."""
162
163 # http://b/19734868
164 # Note that this actually matches ssh(1)'s behavior --- it's
165 # converted to `sh -c echo hello; echo world` which sh interprets
166 # as `sh -c echo` (with an argument to that shell of "hello"),
167 # and then `echo world` back in the first shell.
168 result = self.device.shell(
169 shlex.split("sh -c 'echo hello; echo world'"))
170 result = result.splitlines()
171 self.assertEqual(['', 'world'], result)
172 # If you really wanted "hello" and "world", here's what you'd do:
173 result = self.device.shell(
174 shlex.split(r'echo hello\;echo world')).splitlines()
175 self.assertEqual(['hello', 'world'], result)
176
177 # http://b/15479704
178 result = self.device.shell(shlex.split("'true && echo t'")).strip()
179 self.assertEqual('t', result)
180 result = self.device.shell(
181 shlex.split("sh -c 'true && echo t'")).strip()
182 self.assertEqual('t', result)
183
184 # http://b/20564385
185 result = self.device.shell(shlex.split('FOO=a BAR=b echo t')).strip()
186 self.assertEqual('t', result)
187 result = self.device.shell(shlex.split(r'echo -n 123\;uname')).strip()
188 self.assertEqual('123Linux', result)
189
190 def test_install_argument_escaping(self):
191 """Make sure that install argument escaping works."""
192 # http://b/20323053
193 tf = tempfile.NamedTemporaryFile('wb', suffix='-text;ls;1.apk')
194 self.assertIn("-text;ls;1.apk", self.device.install(tf.name))
195
196 # http://b/3090932
197 tf = tempfile.NamedTemporaryFile('wb', suffix="-Live Hold'em.apk")
198 self.assertIn("-Live Hold'em.apk", self.device.install(tf.name))
199
200
201class RootUnrootTest(DeviceTest):
202 def _test_root(self):
203 message = self.device.root()
204 if 'adbd cannot run as root in production builds' in message:
205 return
206 self.device.wait()
207 self.assertEqual('root', self.device.shell(['id', '-un']).strip())
208
209 def _test_unroot(self):
210 self.device.unroot()
211 self.device.wait()
212 self.assertEqual('shell', self.device.shell(['id', '-un']).strip())
213
214 def test_root_unroot(self):
215 """Make sure that adb root and adb unroot work, using id(1)."""
Dan Alberte2b4a5f2015-07-28 14:53:03 -0700216 if self.device.get_prop('ro.debuggable') != '1':
217 raise unittest.SkipTest('requires rootable build')
218
Dan Albert8e1fdd72015-07-24 17:08:33 -0700219 original_user = self.device.shell(['id', '-un']).strip()
220 try:
221 if original_user == 'root':
222 self._test_unroot()
223 self._test_root()
224 elif original_user == 'shell':
225 self._test_root()
226 self._test_unroot()
227 finally:
228 if original_user == 'root':
229 self.device.root()
230 else:
231 self.device.unroot()
232 self.device.wait()
233
234
235class TcpIpTest(DeviceTest):
236 def test_tcpip_failure_raises(self):
237 """adb tcpip requires a port.
238
239 Bug: http://b/22636927
240 """
241 self.assertRaises(
242 subprocess.CalledProcessError, self.device.tcpip, '')
243 self.assertRaises(
244 subprocess.CalledProcessError, self.device.tcpip, 'foo')
245
246
Dan Alberte2b4a5f2015-07-28 14:53:03 -0700247class SystemPropertiesTest(DeviceTest):
248 def test_get_prop(self):
249 self.assertEqual(self.device.get_prop('init.svc.adbd'), 'running')
250
251 @requires_root
252 def test_set_prop(self):
253 prop_name = 'foo.bar'
254 self.device.shell(['setprop', prop_name, '""'])
255
256 self.device.set_prop(prop_name, 'qux')
257 self.assertEqual(
258 self.device.shell(['getprop', prop_name]).strip(), 'qux')
259
260
Dan Albert8e1fdd72015-07-24 17:08:33 -0700261def compute_md5(string):
262 hsh = hashlib.md5()
263 hsh.update(string)
264 return hsh.hexdigest()
265
266
267def get_md5_prog(device):
268 """Older platforms (pre-L) had the name md5 rather than md5sum."""
269 try:
270 device.shell(['md5sum', '/proc/uptime'])
271 return 'md5sum'
272 except subprocess.CalledProcessError:
273 return 'md5'
274
275
276class HostFile(object):
277 def __init__(self, handle, checksum):
278 self.handle = handle
279 self.checksum = checksum
280 self.full_path = handle.name
281 self.base_name = os.path.basename(self.full_path)
282
283
284class DeviceFile(object):
285 def __init__(self, checksum, full_path):
286 self.checksum = checksum
287 self.full_path = full_path
288 self.base_name = posixpath.basename(self.full_path)
289
290
291def make_random_host_files(in_dir, num_files):
292 min_size = 1 * (1 << 10)
293 max_size = 16 * (1 << 10)
294
295 files = []
296 for _ in xrange(num_files):
297 file_handle = tempfile.NamedTemporaryFile(dir=in_dir, delete=False)
298
299 size = random.randrange(min_size, max_size, 1024)
300 rand_str = os.urandom(size)
301 file_handle.write(rand_str)
302 file_handle.flush()
303 file_handle.close()
304
305 md5 = compute_md5(rand_str)
306 files.append(HostFile(file_handle, md5))
307 return files
308
309
310def make_random_device_files(device, in_dir, num_files):
311 min_size = 1 * (1 << 10)
312 max_size = 16 * (1 << 10)
313
314 files = []
315 for file_num in xrange(num_files):
316 size = random.randrange(min_size, max_size, 1024)
317
318 base_name = 'device_tmpfile' + str(file_num)
Spencer Low3e7feda2015-07-30 01:19:52 -0700319 full_path = posixpath.join(in_dir, base_name)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700320
321 device.shell(['dd', 'if=/dev/urandom', 'of={}'.format(full_path),
322 'bs={}'.format(size), 'count=1'])
323 dev_md5, _ = device.shell([get_md5_prog(device), full_path]).split()
324
325 files.append(DeviceFile(dev_md5, full_path))
326 return files
327
328
329class FileOperationsTest(DeviceTest):
330 SCRATCH_DIR = '/data/local/tmp'
331 DEVICE_TEMP_FILE = SCRATCH_DIR + '/adb_test_file'
332 DEVICE_TEMP_DIR = SCRATCH_DIR + '/adb_test_dir'
333
334 def _test_push(self, local_file, checksum):
335 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_FILE])
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700336 self.device.push(local=local_file, remote=self.DEVICE_TEMP_FILE)
337 dev_md5, _ = self.device.shell([get_md5_prog(self.device),
338 self.DEVICE_TEMP_FILE]).split()
339 self.assertEqual(checksum, dev_md5)
340 self.device.shell(['rm', '-f', self.DEVICE_TEMP_FILE])
Dan Albert8e1fdd72015-07-24 17:08:33 -0700341
342 def test_push(self):
343 """Push a randomly generated file to specified device."""
344 kbytes = 512
345 tmp = tempfile.NamedTemporaryFile(mode='wb', delete=False)
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700346 rand_str = os.urandom(1024 * kbytes)
347 tmp.write(rand_str)
348 tmp.close()
349 self._test_push(tmp.name, compute_md5(rand_str))
350 os.remove(tmp.name)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700351
352 # TODO: write push directory test.
353
354 def _test_pull(self, remote_file, checksum):
355 tmp_write = tempfile.NamedTemporaryFile(mode='wb', delete=False)
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700356 tmp_write.close()
357 self.device.pull(remote=remote_file, local=tmp_write.name)
358 with open(tmp_write.name, 'rb') as tmp_read:
359 host_contents = tmp_read.read()
360 host_md5 = compute_md5(host_contents)
361 self.assertEqual(checksum, host_md5)
362 os.remove(tmp_write.name)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700363
364 def test_pull(self):
365 """Pull a randomly generated file from specified device."""
366 kbytes = 512
367 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_FILE])
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700368 cmd = ['dd', 'if=/dev/urandom',
369 'of={}'.format(self.DEVICE_TEMP_FILE), 'bs=1024',
370 'count={}'.format(kbytes)]
371 self.device.shell(cmd)
372 dev_md5, _ = self.device.shell(
373 [get_md5_prog(self.device), self.DEVICE_TEMP_FILE]).split()
374 self._test_pull(self.DEVICE_TEMP_FILE, dev_md5)
375 self.device.shell_nocheck(['rm', self.DEVICE_TEMP_FILE])
Dan Albert8e1fdd72015-07-24 17:08:33 -0700376
377 def test_pull_dir(self):
378 """Pull a randomly generated directory of files from the device."""
379 host_dir = tempfile.mkdtemp()
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700380 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
381 self.device.shell(['mkdir', '-p', self.DEVICE_TEMP_DIR])
Dan Albert8e1fdd72015-07-24 17:08:33 -0700382
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700383 # Populate device directory with random files.
384 temp_files = make_random_device_files(
385 self.device, in_dir=self.DEVICE_TEMP_DIR, num_files=32)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700386
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700387 self.device.pull(remote=self.DEVICE_TEMP_DIR, local=host_dir)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700388
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700389 for temp_file in temp_files:
390 host_path = os.path.join(host_dir, temp_file.base_name)
391 with open(host_path, 'rb') as host_file:
392 host_md5 = compute_md5(host_file.read())
393 self.assertEqual(host_md5, temp_file.checksum)
394
395 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
396 if host_dir is not None:
397 shutil.rmtree(host_dir)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700398
399 def test_sync(self):
400 """Sync a randomly generated directory of files to specified device."""
401 base_dir = tempfile.mkdtemp()
Dan Albert8e1fdd72015-07-24 17:08:33 -0700402
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700403 # Create mirror device directory hierarchy within base_dir.
404 full_dir_path = base_dir + self.DEVICE_TEMP_DIR
405 os.makedirs(full_dir_path)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700406
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700407 # Create 32 random files within the host mirror.
408 temp_files = make_random_host_files(in_dir=full_dir_path, num_files=32)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700409
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700410 # Clean up any trash on the device.
411 device = adb.get_device(product=base_dir)
412 device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
Dan Albert8e1fdd72015-07-24 17:08:33 -0700413
Elliott Hughes3841a9f2015-08-03 13:58:49 -0700414 device.sync('data')
415
416 # Confirm that every file on the device mirrors that on the host.
417 for temp_file in temp_files:
418 device_full_path = posixpath.join(self.DEVICE_TEMP_DIR,
419 temp_file.base_name)
420 dev_md5, _ = device.shell(
421 [get_md5_prog(self.device), device_full_path]).split()
422 self.assertEqual(temp_file.checksum, dev_md5)
423
424 self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
425 shutil.rmtree(base_dir + self.DEVICE_TEMP_DIR)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700426
Dan Albert8e1fdd72015-07-24 17:08:33 -0700427 def test_unicode_paths(self):
428 """Ensure that we can support non-ASCII paths, even on Windows."""
429 name = u'로보카 폴리'.encode('utf-8')
430
431 ## push.
432 tf = tempfile.NamedTemporaryFile('wb', suffix=name)
433 self.device.push(tf.name, '/data/local/tmp/adb-test-{}'.format(name))
434 self.device.shell(['rm', '-f', '/data/local/tmp/adb-test-*'])
435
436 # pull.
437 cmd = ['touch', '"/data/local/tmp/adb-test-{}"'.format(name)]
438 self.device.shell(cmd)
439
440 tf = tempfile.NamedTemporaryFile('wb', suffix=name)
441 self.device.pull('/data/local/tmp/adb-test-{}'.format(name), tf.name)
442
443
444def main():
445 random.seed(0)
446 if len(adb.get_devices()) > 0:
447 suite = unittest.TestLoader().loadTestsFromName(__name__)
448 unittest.TextTestRunner(verbosity=3).run(suite)
449 else:
450 print('Test suite must be run with attached devices')
451
452
453if __name__ == '__main__':
454 main()