blob: ce4d4ecfe0c2f0caab751c0f17e9bacec7583892 [file] [log] [blame]
Dan Albert8e1fdd72015-07-24 17:08:33 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2015 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17"""Tests for the adb program itself.
18
19This differs from things in test_device.py in that there is no API for these
20things. Most of these tests involve specific error messages or the help text.
21"""
22from __future__ import print_function
23
Luis Hector Chavez8b67c522018-04-17 19:25:33 -070024import binascii
Spencer Low351ecd12015-10-14 17:32:44 -070025import contextlib
Spencer Low1ce06082015-09-16 20:45:53 -070026import os
Dan Albert8e1fdd72015-07-24 17:08:33 -070027import random
Luis Hector Chavez8b67c522018-04-17 19:25:33 -070028import select
Spencer Low351ecd12015-10-14 17:32:44 -070029import socket
30import struct
Dan Albert8e1fdd72015-07-24 17:08:33 -070031import subprocess
Spencer Low1ce06082015-09-16 20:45:53 -070032import threading
Dan Albert8e1fdd72015-07-24 17:08:33 -070033import unittest
34
35import adb
36
37
Luis Hector Chavez8b67c522018-04-17 19:25:33 -070038@contextlib.contextmanager
39def fake_adb_server(protocol=socket.AF_INET, port=0):
40 """Creates a fake ADB server that just replies with a CNXN packet."""
41
42 serversock = socket.socket(protocol, socket.SOCK_STREAM)
43 if protocol == socket.AF_INET:
44 serversock.bind(('127.0.0.1', port))
45 else:
46 serversock.bind(('::1', port))
47 serversock.listen(1)
48
49 # A pipe that is used to signal the thread that it should terminate.
50 readpipe, writepipe = os.pipe()
51
Luis Hector Chavez56fe7532018-04-17 14:25:04 -070052 def _adb_packet(command, arg0, arg1, data):
53 bin_command = struct.unpack('I', command)[0]
54 buf = struct.pack('IIIIII', bin_command, arg0, arg1, len(data), 0,
55 bin_command ^ 0xffffffff)
56 buf += data
57 return buf
58
Luis Hector Chavez8b67c522018-04-17 19:25:33 -070059 def _handle():
60 rlist = [readpipe, serversock]
Luis Hector Chavez56fe7532018-04-17 14:25:04 -070061 cnxn_sent = {}
Luis Hector Chavez8b67c522018-04-17 19:25:33 -070062 while True:
63 ready, _, _ = select.select(rlist, [], [])
64 for r in ready:
65 if r == readpipe:
66 # Closure pipe
67 os.close(r)
68 serversock.shutdown(socket.SHUT_RDWR)
69 serversock.close()
70 return
71 elif r == serversock:
72 # Server socket
73 conn, _ = r.accept()
74 rlist.append(conn)
75 else:
76 # Client socket
77 data = r.recv(1024)
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070078 if not data or data.startswith('OPEN'):
Luis Hector Chavez56fe7532018-04-17 14:25:04 -070079 if r in cnxn_sent:
80 del cnxn_sent[r]
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070081 r.shutdown(socket.SHUT_RDWR)
82 r.close()
Luis Hector Chavez8b67c522018-04-17 19:25:33 -070083 rlist.remove(r)
Luis Hector Chavez56fe7532018-04-17 14:25:04 -070084 continue
85 if r in cnxn_sent:
86 continue
87 cnxn_sent[r] = True
88 r.sendall(_adb_packet('CNXN', 0x01000001, 1024 * 1024,
89 'device::ro.product.name=fakeadb'))
Luis Hector Chavez8b67c522018-04-17 19:25:33 -070090
91 port = serversock.getsockname()[1]
92 server_thread = threading.Thread(target=_handle)
93 server_thread.start()
94
95 try:
96 yield port
97 finally:
98 os.close(writepipe)
99 server_thread.join()
100
101
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700102@contextlib.contextmanager
103def adb_connect(unittest, serial):
104 """Context manager for an ADB connection.
105
106 This automatically disconnects when done with the connection.
107 """
108
109 output = subprocess.check_output(['adb', 'connect', serial])
110 unittest.assertEqual(output.strip(), 'connected to {}'.format(serial))
111
112 try:
113 yield
114 finally:
115 # Perform best-effort disconnection. Discard the output.
116 p = subprocess.Popen(['adb', 'disconnect', serial],
117 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
118 p.communicate()
119
120
Dan Albert8e1fdd72015-07-24 17:08:33 -0700121class NonApiTest(unittest.TestCase):
122 """Tests for ADB that aren't a part of the AndroidDevice API."""
123
124 def test_help(self):
125 """Make sure we get _something_ out of help."""
126 out = subprocess.check_output(
127 ['adb', 'help'], stderr=subprocess.STDOUT)
128 self.assertGreater(len(out), 0)
129
130 def test_version(self):
131 """Get a version number out of the output of adb."""
132 lines = subprocess.check_output(['adb', 'version']).splitlines()
133 version_line = lines[0]
134 self.assertRegexpMatches(
135 version_line, r'^Android Debug Bridge version \d+\.\d+\.\d+$')
136 if len(lines) == 2:
137 # Newer versions of ADB have a second line of output for the
138 # version that includes a specific revision (git SHA).
139 revision_line = lines[1]
140 self.assertRegexpMatches(
141 revision_line, r'^Revision [0-9a-f]{12}-android$')
142
143 def test_tcpip_error_messages(self):
144 p = subprocess.Popen(['adb', 'tcpip'], stdout=subprocess.PIPE,
145 stderr=subprocess.STDOUT)
146 out, _ = p.communicate()
147 self.assertEqual(1, p.returncode)
Elliott Hughese1632982017-08-23 15:42:28 -0700148 self.assertIn('requires an argument', out)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700149
150 p = subprocess.Popen(['adb', 'tcpip', 'foo'], stdout=subprocess.PIPE,
151 stderr=subprocess.STDOUT)
152 out, _ = p.communicate()
153 self.assertEqual(1, p.returncode)
Elliott Hughese1632982017-08-23 15:42:28 -0700154 self.assertIn('invalid port', out)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700155
Spencer Low1ce06082015-09-16 20:45:53 -0700156 # Helper method that reads a pipe until it is closed, then sets the event.
157 def _read_pipe_and_set_event(self, pipe, event):
158 x = pipe.read()
159 event.set()
160
161 # Test that launch_server() does not let the adb server inherit
162 # stdin/stdout/stderr handles which can cause callers of adb.exe to hang.
163 # This test also runs fine on unix even though the impetus is an issue
164 # unique to Windows.
165 def test_handle_inheritance(self):
166 # This test takes 5 seconds to run on Windows: if there is no adb server
167 # running on the the port used below, adb kill-server tries to make a
168 # TCP connection to a closed port and that takes 1 second on Windows;
169 # adb start-server does the same TCP connection which takes another
170 # second, and it waits 3 seconds after starting the server.
171
172 # Start adb client with redirected stdin/stdout/stderr to check if it
173 # passes those redirections to the adb server that it starts. To do
174 # this, run an instance of the adb server on a non-default port so we
175 # don't conflict with a pre-existing adb server that may already be
176 # setup with adb TCP/emulator connections. If there is a pre-existing
177 # adb server, this also tests whether multiple instances of the adb
178 # server conflict on adb.log.
179
180 port = 5038
181 # Kill any existing server on this non-default port.
182 subprocess.check_output(['adb', '-P', str(port), 'kill-server'],
183 stderr=subprocess.STDOUT)
184
185 try:
186 # Run the adb client and have it start the adb server.
187 p = subprocess.Popen(['adb', '-P', str(port), 'start-server'],
188 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
189 stderr=subprocess.PIPE)
190
191 # Start threads that set events when stdout/stderr are closed.
192 stdout_event = threading.Event()
193 stdout_thread = threading.Thread(
194 target=self._read_pipe_and_set_event,
195 args=(p.stdout, stdout_event))
196 stdout_thread.daemon = True
197 stdout_thread.start()
198
199 stderr_event = threading.Event()
200 stderr_thread = threading.Thread(
201 target=self._read_pipe_and_set_event,
202 args=(p.stderr, stderr_event))
203 stderr_thread.daemon = True
204 stderr_thread.start()
205
206 # Wait for the adb client to finish. Once that has occurred, if
207 # stdin/stderr/stdout are still open, it must be open in the adb
208 # server.
209 p.wait()
210
211 # Try to write to stdin which we expect is closed. If it isn't
212 # closed, we should get an IOError. If we don't get an IOError,
213 # stdin must still be open in the adb server. The adb client is
214 # probably letting the adb server inherit stdin which would be
215 # wrong.
216 with self.assertRaises(IOError):
217 p.stdin.write('x')
218
219 # Wait a few seconds for stdout/stderr to be closed (in the success
220 # case, this won't wait at all). If there is a timeout, that means
221 # stdout/stderr were not closed and and they must be open in the adb
222 # server, suggesting that the adb client is letting the adb server
223 # inherit stdout/stderr which would be wrong.
224 self.assertTrue(stdout_event.wait(5), "adb stdout not closed")
225 self.assertTrue(stderr_event.wait(5), "adb stderr not closed")
226 finally:
227 # If we started a server, kill it.
228 subprocess.check_output(['adb', '-P', str(port), 'kill-server'],
229 stderr=subprocess.STDOUT)
Dan Albert8e1fdd72015-07-24 17:08:33 -0700230
Spencer Low351ecd12015-10-14 17:32:44 -0700231 # Use SO_LINGER to cause TCP RST segment to be sent on socket close.
232 def _reset_socket_on_close(self, sock):
233 # The linger structure is two shorts on Windows, but two ints on Unix.
234 linger_format = 'hh' if os.name == 'nt' else 'ii'
235 l_onoff = 1
236 l_linger = 0
237
238 sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
239 struct.pack(linger_format, l_onoff, l_linger))
240 # Verify that we set the linger structure properly by retrieving it.
241 linger = sock.getsockopt(socket.SOL_SOCKET, socket.SO_LINGER, 16)
242 self.assertEqual((l_onoff, l_linger),
243 struct.unpack_from(linger_format, linger))
244
245 def test_emu_kill(self):
246 """Ensure that adb emu kill works.
247
248 Bug: https://code.google.com/p/android/issues/detail?id=21021
249 """
Spencer Low351ecd12015-10-14 17:32:44 -0700250 with contextlib.closing(
251 socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as listener:
252 # Use SO_REUSEADDR so subsequent runs of the test can grab the port
253 # even if it is in TIME_WAIT.
254 listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Josh Gaoc251ec52018-04-03 12:55:18 -0700255 listener.bind(('127.0.0.1', 0))
Spencer Low351ecd12015-10-14 17:32:44 -0700256 listener.listen(4)
Josh Gaoc251ec52018-04-03 12:55:18 -0700257 port = listener.getsockname()[1]
Spencer Low351ecd12015-10-14 17:32:44 -0700258
259 # Now that listening has started, start adb emu kill, telling it to
260 # connect to our mock emulator.
261 p = subprocess.Popen(
262 ['adb', '-s', 'emulator-' + str(port), 'emu', 'kill'],
263 stderr=subprocess.STDOUT)
264
265 accepted_connection, addr = listener.accept()
266 with contextlib.closing(accepted_connection) as conn:
267 # If WSAECONNABORTED (10053) is raised by any socket calls,
268 # then adb probably isn't reading the data that we sent it.
269 conn.sendall('Android Console: type \'help\' for a list ' +
270 'of commands\r\n')
271 conn.sendall('OK\r\n')
272
273 with contextlib.closing(conn.makefile()) as f:
274 self.assertEqual('kill\n', f.readline())
275 self.assertEqual('quit\n', f.readline())
276
277 conn.sendall('OK: killing emulator, bye bye\r\n')
278
279 # Use SO_LINGER to send TCP RST segment to test whether adb
280 # ignores WSAECONNRESET on Windows. This happens with the
281 # real emulator because it just calls exit() without closing
282 # the socket or calling shutdown(SD_SEND). At process
283 # termination, Windows sends a TCP RST segment for every
284 # open socket that shutdown(SD_SEND) wasn't used on.
285 self._reset_socket_on_close(conn)
286
287 # Wait for adb to finish, so we can check return code.
288 p.communicate()
289
290 # If this fails, adb probably isn't ignoring WSAECONNRESET when
291 # reading the response from the adb emu kill command (on Windows).
292 self.assertEqual(0, p.returncode)
293
Josh Gao78cc20f2016-09-01 14:54:18 -0700294 def test_connect_ipv4_ipv6(self):
295 """Ensure that `adb connect localhost:1234` will try both IPv4 and IPv6.
296
297 Bug: http://b/30313466
298 """
Luis Hector Chavez8b67c522018-04-17 19:25:33 -0700299 for protocol in (socket.AF_INET, socket.AF_INET6):
300 try:
301 with fake_adb_server(protocol=protocol) as port:
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700302 serial = 'localhost:{}'.format(port)
303 with adb_connect(self, serial):
304 pass
Luis Hector Chavez8b67c522018-04-17 19:25:33 -0700305 except socket.error:
306 print("IPv6 not available, skipping")
307 continue
Josh Gao78cc20f2016-09-01 14:54:18 -0700308
Luis Hector Chavez8b67c522018-04-17 19:25:33 -0700309 def test_already_connected(self):
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700310 """Ensure that an already-connected device stays connected."""
311
Luis Hector Chavez8b67c522018-04-17 19:25:33 -0700312 with fake_adb_server() as port:
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700313 serial = 'localhost:{}'.format(port)
314 with adb_connect(self, serial):
315 # b/31250450: this always returns 0 but probably shouldn't.
316 output = subprocess.check_output(['adb', 'connect', serial])
317 self.assertEqual(
318 output.strip(), 'already connected to {}'.format(serial))
Josh Gao78cc20f2016-09-01 14:54:18 -0700319
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700320 def test_reconnect(self):
321 """Ensure that a disconnected device reconnects."""
Josh Gao78cc20f2016-09-01 14:54:18 -0700322
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700323 with fake_adb_server() as port:
324 serial = 'localhost:{}'.format(port)
325 with adb_connect(self, serial):
326 output = subprocess.check_output(['adb', '-s', serial,
327 'get-state'])
328 self.assertEqual(output.strip(), 'device')
Josh Gaoc251ec52018-04-03 12:55:18 -0700329
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700330 # This will fail.
331 p = subprocess.Popen(['adb', '-s', serial, 'shell', 'true'],
332 stdout=subprocess.PIPE,
333 stderr=subprocess.STDOUT)
334 output, _ = p.communicate()
335 self.assertEqual(output.strip(), 'error: closed')
336
337 subprocess.check_call(['adb', '-s', serial, 'wait-for-device'])
338
339 output = subprocess.check_output(['adb', '-s', serial,
340 'get-state'])
341 self.assertEqual(output.strip(), 'device')
342
343 # Once we explicitly kick a device, it won't attempt to
344 # reconnect.
345 output = subprocess.check_output(['adb', 'disconnect', serial])
346 self.assertEqual(
347 output.strip(), 'disconnected {}'.format(serial))
348 try:
349 subprocess.check_output(['adb', '-s', serial, 'get-state'],
350 stderr=subprocess.STDOUT)
351 self.fail('Device should not be available')
352 except subprocess.CalledProcessError as e:
353 self.assertEqual(
354 e.output.strip(),
355 'error: device \'{}\' not found'.format(serial))
Spencer Low351ecd12015-10-14 17:32:44 -0700356
Dan Albert8e1fdd72015-07-24 17:08:33 -0700357def main():
358 random.seed(0)
359 if len(adb.get_devices()) > 0:
360 suite = unittest.TestLoader().loadTestsFromName(__name__)
361 unittest.TextTestRunner(verbosity=3).run(suite)
362 else:
363 print('Test suite must be run with attached devices')
364
365
366if __name__ == '__main__':
367 main()