test_adb.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. #!/usr/bin/env python3
  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. This differs from things in test_device.py in that there is no API for these
  19. things. Most of these tests involve specific error messages or the help text.
  20. """
  21. import contextlib
  22. import os
  23. import random
  24. import select
  25. import socket
  26. import struct
  27. import subprocess
  28. import sys
  29. import threading
  30. import time
  31. import unittest
  32. import warnings
  33. @contextlib.contextmanager
  34. def fake_adbd(protocol=socket.AF_INET, port=0):
  35. """Creates a fake ADB daemon that just replies with a CNXN packet."""
  36. serversock = socket.socket(protocol, socket.SOCK_STREAM)
  37. serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  38. if protocol == socket.AF_INET:
  39. serversock.bind(("127.0.0.1", port))
  40. else:
  41. serversock.bind(("::1", port))
  42. serversock.listen(1)
  43. # A pipe that is used to signal the thread that it should terminate.
  44. readsock, writesock = socket.socketpair()
  45. def _adb_packet(command: bytes, arg0: int, arg1: int, data: bytes) -> bytes:
  46. bin_command = struct.unpack("I", command)[0]
  47. buf = struct.pack("IIIIII", bin_command, arg0, arg1, len(data), 0,
  48. bin_command ^ 0xffffffff)
  49. buf += data
  50. return buf
  51. def _handle(sock):
  52. with contextlib.closing(sock) as serversock:
  53. rlist = [readsock, serversock]
  54. cnxn_sent = {}
  55. while True:
  56. read_ready, _, _ = select.select(rlist, [], [])
  57. for ready in read_ready:
  58. if ready == readsock:
  59. # Closure pipe
  60. for f in rlist:
  61. f.close()
  62. return
  63. elif ready == serversock:
  64. # Server socket
  65. conn, _ = ready.accept()
  66. rlist.append(conn)
  67. else:
  68. # Client socket
  69. data = ready.recv(1024)
  70. if not data or data.startswith(b"OPEN"):
  71. if ready in cnxn_sent:
  72. del cnxn_sent[ready]
  73. ready.shutdown(socket.SHUT_RDWR)
  74. ready.close()
  75. rlist.remove(ready)
  76. continue
  77. if ready in cnxn_sent:
  78. continue
  79. cnxn_sent[ready] = True
  80. ready.sendall(_adb_packet(b"CNXN", 0x01000001, 1024 * 1024,
  81. b"device::ro.product.name=fakeadb"))
  82. port = serversock.getsockname()[1]
  83. server_thread = threading.Thread(target=_handle, args=(serversock,))
  84. server_thread.start()
  85. try:
  86. yield port, writesock
  87. finally:
  88. writesock.close()
  89. server_thread.join()
  90. @contextlib.contextmanager
  91. def adb_connect(unittest, serial):
  92. """Context manager for an ADB connection.
  93. This automatically disconnects when done with the connection.
  94. """
  95. output = subprocess.check_output(["adb", "connect", serial])
  96. unittest.assertEqual(output.strip(),
  97. "connected to {}".format(serial).encode("utf8"))
  98. try:
  99. yield
  100. finally:
  101. # Perform best-effort disconnection. Discard the output.
  102. subprocess.Popen(["adb", "disconnect", serial],
  103. stdout=subprocess.PIPE,
  104. stderr=subprocess.PIPE).communicate()
  105. @contextlib.contextmanager
  106. def adb_server():
  107. """Context manager for an ADB server.
  108. This creates an ADB server and returns the port it's listening on.
  109. """
  110. port = 5038
  111. # Kill any existing server on this non-default port.
  112. subprocess.check_output(["adb", "-P", str(port), "kill-server"],
  113. stderr=subprocess.STDOUT)
  114. read_pipe, write_pipe = os.pipe()
  115. if sys.platform == "win32":
  116. import msvcrt
  117. write_handle = msvcrt.get_osfhandle(write_pipe)
  118. os.set_handle_inheritable(write_handle, True)
  119. reply_fd = str(write_handle)
  120. else:
  121. os.set_inheritable(write_pipe, True)
  122. reply_fd = str(write_pipe)
  123. proc = subprocess.Popen(["adb", "-L", "tcp:localhost:{}".format(port),
  124. "fork-server", "server",
  125. "--reply-fd", reply_fd], close_fds=False)
  126. try:
  127. os.close(write_pipe)
  128. greeting = os.read(read_pipe, 1024)
  129. assert greeting == b"OK\n", repr(greeting)
  130. yield port
  131. finally:
  132. proc.terminate()
  133. proc.wait()
  134. class CommandlineTest(unittest.TestCase):
  135. """Tests for the ADB commandline."""
  136. def test_help(self):
  137. """Make sure we get _something_ out of help."""
  138. out = subprocess.check_output(
  139. ["adb", "help"], stderr=subprocess.STDOUT)
  140. self.assertGreater(len(out), 0)
  141. def test_version(self):
  142. """Get a version number out of the output of adb."""
  143. lines = subprocess.check_output(["adb", "version"]).splitlines()
  144. version_line = lines[0]
  145. self.assertRegex(
  146. version_line, rb"^Android Debug Bridge version \d+\.\d+\.\d+$")
  147. if len(lines) == 2:
  148. # Newer versions of ADB have a second line of output for the
  149. # version that includes a specific revision (git SHA).
  150. revision_line = lines[1]
  151. self.assertRegex(
  152. revision_line, rb"^Revision [0-9a-f]{12}-android$")
  153. def test_tcpip_error_messages(self):
  154. """Make sure 'adb tcpip' parsing is sane."""
  155. proc = subprocess.Popen(["adb", "tcpip"],
  156. stdout=subprocess.PIPE,
  157. stderr=subprocess.STDOUT)
  158. out, _ = proc.communicate()
  159. self.assertEqual(1, proc.returncode)
  160. self.assertIn(b"requires an argument", out)
  161. proc = subprocess.Popen(["adb", "tcpip", "foo"],
  162. stdout=subprocess.PIPE,
  163. stderr=subprocess.STDOUT)
  164. out, _ = proc.communicate()
  165. self.assertEqual(1, proc.returncode)
  166. self.assertIn(b"invalid port", out)
  167. class ServerTest(unittest.TestCase):
  168. """Tests for the ADB server."""
  169. @staticmethod
  170. def _read_pipe_and_set_event(pipe, event):
  171. """Reads a pipe until it is closed, then sets the event."""
  172. pipe.read()
  173. event.set()
  174. def test_handle_inheritance(self):
  175. """Test that launch_server() does not inherit handles.
  176. launch_server() should not let the adb server inherit
  177. stdin/stdout/stderr handles, which can cause callers of adb.exe to hang.
  178. This test also runs fine on unix even though the impetus is an issue
  179. unique to Windows.
  180. """
  181. # This test takes 5 seconds to run on Windows: if there is no adb server
  182. # running on the the port used below, adb kill-server tries to make a
  183. # TCP connection to a closed port and that takes 1 second on Windows;
  184. # adb start-server does the same TCP connection which takes another
  185. # second, and it waits 3 seconds after starting the server.
  186. # Start adb client with redirected stdin/stdout/stderr to check if it
  187. # passes those redirections to the adb server that it starts. To do
  188. # this, run an instance of the adb server on a non-default port so we
  189. # don't conflict with a pre-existing adb server that may already be
  190. # setup with adb TCP/emulator connections. If there is a pre-existing
  191. # adb server, this also tests whether multiple instances of the adb
  192. # server conflict on adb.log.
  193. port = 5038
  194. # Kill any existing server on this non-default port.
  195. subprocess.check_output(["adb", "-P", str(port), "kill-server"],
  196. stderr=subprocess.STDOUT)
  197. try:
  198. # We get warnings for unclosed files for the subprocess's pipes,
  199. # and it's somewhat cumbersome to close them, so just ignore this.
  200. warnings.simplefilter("ignore", ResourceWarning)
  201. # Run the adb client and have it start the adb server.
  202. proc = subprocess.Popen(["adb", "-P", str(port), "start-server"],
  203. stdin=subprocess.PIPE,
  204. stdout=subprocess.PIPE,
  205. stderr=subprocess.PIPE)
  206. # Start threads that set events when stdout/stderr are closed.
  207. stdout_event = threading.Event()
  208. stdout_thread = threading.Thread(
  209. target=ServerTest._read_pipe_and_set_event,
  210. args=(proc.stdout, stdout_event))
  211. stdout_thread.start()
  212. stderr_event = threading.Event()
  213. stderr_thread = threading.Thread(
  214. target=ServerTest._read_pipe_and_set_event,
  215. args=(proc.stderr, stderr_event))
  216. stderr_thread.start()
  217. # Wait for the adb client to finish. Once that has occurred, if
  218. # stdin/stderr/stdout are still open, it must be open in the adb
  219. # server.
  220. proc.wait()
  221. # Try to write to stdin which we expect is closed. If it isn't
  222. # closed, we should get an IOError. If we don't get an IOError,
  223. # stdin must still be open in the adb server. The adb client is
  224. # probably letting the adb server inherit stdin which would be
  225. # wrong.
  226. with self.assertRaises(IOError):
  227. proc.stdin.write(b"x")
  228. proc.stdin.flush()
  229. # Wait a few seconds for stdout/stderr to be closed (in the success
  230. # case, this won't wait at all). If there is a timeout, that means
  231. # stdout/stderr were not closed and and they must be open in the adb
  232. # server, suggesting that the adb client is letting the adb server
  233. # inherit stdout/stderr which would be wrong.
  234. self.assertTrue(stdout_event.wait(5), "adb stdout not closed")
  235. self.assertTrue(stderr_event.wait(5), "adb stderr not closed")
  236. stdout_thread.join()
  237. stderr_thread.join()
  238. finally:
  239. # If we started a server, kill it.
  240. subprocess.check_output(["adb", "-P", str(port), "kill-server"],
  241. stderr=subprocess.STDOUT)
  242. class EmulatorTest(unittest.TestCase):
  243. """Tests for the emulator connection."""
  244. def _reset_socket_on_close(self, sock):
  245. """Use SO_LINGER to cause TCP RST segment to be sent on socket close."""
  246. # The linger structure is two shorts on Windows, but two ints on Unix.
  247. linger_format = "hh" if os.name == "nt" else "ii"
  248. l_onoff = 1
  249. l_linger = 0
  250. sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
  251. struct.pack(linger_format, l_onoff, l_linger))
  252. # Verify that we set the linger structure properly by retrieving it.
  253. linger = sock.getsockopt(socket.SOL_SOCKET, socket.SO_LINGER, 16)
  254. self.assertEqual((l_onoff, l_linger),
  255. struct.unpack_from(linger_format, linger))
  256. def test_emu_kill(self):
  257. """Ensure that adb emu kill works.
  258. Bug: https://code.google.com/p/android/issues/detail?id=21021
  259. """
  260. with contextlib.closing(
  261. socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as listener:
  262. # Use SO_REUSEADDR so subsequent runs of the test can grab the port
  263. # even if it is in TIME_WAIT.
  264. listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  265. listener.bind(("127.0.0.1", 0))
  266. listener.listen(4)
  267. port = listener.getsockname()[1]
  268. # Now that listening has started, start adb emu kill, telling it to
  269. # connect to our mock emulator.
  270. proc = subprocess.Popen(
  271. ["adb", "-s", "emulator-" + str(port), "emu", "kill"],
  272. stderr=subprocess.STDOUT)
  273. accepted_connection, addr = listener.accept()
  274. with contextlib.closing(accepted_connection) as conn:
  275. # If WSAECONNABORTED (10053) is raised by any socket calls,
  276. # then adb probably isn't reading the data that we sent it.
  277. conn.sendall(("Android Console: type 'help' for a list "
  278. "of commands\r\n").encode("utf8"))
  279. conn.sendall(b"OK\r\n")
  280. with contextlib.closing(conn.makefile()) as connf:
  281. line = connf.readline()
  282. if line.startswith("auth"):
  283. # Ignore the first auth line.
  284. line = connf.readline()
  285. self.assertEqual("kill\n", line)
  286. self.assertEqual("quit\n", connf.readline())
  287. conn.sendall(b"OK: killing emulator, bye bye\r\n")
  288. # Use SO_LINGER to send TCP RST segment to test whether adb
  289. # ignores WSAECONNRESET on Windows. This happens with the
  290. # real emulator because it just calls exit() without closing
  291. # the socket or calling shutdown(SD_SEND). At process
  292. # termination, Windows sends a TCP RST segment for every
  293. # open socket that shutdown(SD_SEND) wasn't used on.
  294. self._reset_socket_on_close(conn)
  295. # Wait for adb to finish, so we can check return code.
  296. proc.communicate()
  297. # If this fails, adb probably isn't ignoring WSAECONNRESET when
  298. # reading the response from the adb emu kill command (on Windows).
  299. self.assertEqual(0, proc.returncode)
  300. def test_emulator_connect(self):
  301. """Ensure that the emulator can connect.
  302. Bug: http://b/78991667
  303. """
  304. with adb_server() as server_port:
  305. with fake_adbd() as (port, _):
  306. serial = "emulator-{}".format(port - 1)
  307. # Ensure that the emulator is not there.
  308. try:
  309. subprocess.check_output(["adb", "-P", str(server_port),
  310. "-s", serial, "get-state"],
  311. stderr=subprocess.STDOUT)
  312. self.fail("Device should not be available")
  313. except subprocess.CalledProcessError as err:
  314. self.assertEqual(
  315. err.output.strip(),
  316. "error: device '{}' not found".format(serial).encode("utf8"))
  317. # Let the ADB server know that the emulator has started.
  318. with contextlib.closing(
  319. socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
  320. sock.connect(("localhost", server_port))
  321. command = "host:emulator:{}".format(port).encode("utf8")
  322. sock.sendall(b"%04x%s" % (len(command), command))
  323. # Ensure the emulator is there.
  324. subprocess.check_call(["adb", "-P", str(server_port),
  325. "-s", serial, "wait-for-device"])
  326. output = subprocess.check_output(["adb", "-P", str(server_port),
  327. "-s", serial, "get-state"])
  328. self.assertEqual(output.strip(), b"device")
  329. class ConnectionTest(unittest.TestCase):
  330. """Tests for adb connect."""
  331. def test_connect_ipv4_ipv6(self):
  332. """Ensure that `adb connect localhost:1234` will try both IPv4 and IPv6.
  333. Bug: http://b/30313466
  334. """
  335. for protocol in (socket.AF_INET, socket.AF_INET6):
  336. try:
  337. with fake_adbd(protocol=protocol) as (port, _):
  338. serial = "localhost:{}".format(port)
  339. with adb_connect(self, serial):
  340. pass
  341. except socket.error:
  342. print("IPv6 not available, skipping")
  343. continue
  344. def test_already_connected(self):
  345. """Ensure that an already-connected device stays connected."""
  346. with fake_adbd() as (port, _):
  347. serial = "localhost:{}".format(port)
  348. with adb_connect(self, serial):
  349. # b/31250450: this always returns 0 but probably shouldn't.
  350. output = subprocess.check_output(["adb", "connect", serial])
  351. self.assertEqual(
  352. output.strip(),
  353. "already connected to {}".format(serial).encode("utf8"))
  354. @unittest.skip("Currently failing b/123247844")
  355. def test_reconnect(self):
  356. """Ensure that a disconnected device reconnects."""
  357. with fake_adbd() as (port, _):
  358. serial = "localhost:{}".format(port)
  359. with adb_connect(self, serial):
  360. # Wait a bit to give adb some time to connect.
  361. time.sleep(0.25)
  362. output = subprocess.check_output(["adb", "-s", serial,
  363. "get-state"])
  364. self.assertEqual(output.strip(), b"device")
  365. # This will fail.
  366. proc = subprocess.Popen(["adb", "-s", serial, "shell", "true"],
  367. stdout=subprocess.PIPE,
  368. stderr=subprocess.STDOUT)
  369. output, _ = proc.communicate()
  370. self.assertEqual(output.strip(), b"error: closed")
  371. subprocess.check_call(["adb", "-s", serial, "wait-for-device"])
  372. output = subprocess.check_output(["adb", "-s", serial,
  373. "get-state"])
  374. self.assertEqual(output.strip(), b"device")
  375. # Once we explicitly kick a device, it won't attempt to
  376. # reconnect.
  377. output = subprocess.check_output(["adb", "disconnect", serial])
  378. self.assertEqual(
  379. output.strip(),
  380. "disconnected {}".format(serial).encode("utf8"))
  381. try:
  382. subprocess.check_output(["adb", "-s", serial, "get-state"],
  383. stderr=subprocess.STDOUT)
  384. self.fail("Device should not be available")
  385. except subprocess.CalledProcessError as err:
  386. self.assertEqual(
  387. err.output.strip(),
  388. "error: device '{}' not found".format(serial).encode("utf8"))
  389. class DisconnectionTest(unittest.TestCase):
  390. """Tests for adb disconnect."""
  391. def test_disconnect(self):
  392. """Ensure that `adb disconnect` takes effect immediately."""
  393. def _devices(port):
  394. output = subprocess.check_output(["adb", "-P", str(port), "devices"])
  395. return [x.split("\t") for x in output.decode("utf8").strip().splitlines()[1:]]
  396. with adb_server() as server_port:
  397. with fake_adbd() as (port, sock):
  398. device_name = "localhost:{}".format(port)
  399. output = subprocess.check_output(["adb", "-P", str(server_port),
  400. "connect", device_name])
  401. self.assertEqual(output.strip(),
  402. "connected to {}".format(device_name).encode("utf8"))
  403. self.assertEqual(_devices(server_port), [[device_name, "device"]])
  404. # Send a deliberately malformed packet to make the device go offline.
  405. packet = struct.pack("IIIIII", 0, 0, 0, 0, 0, 0)
  406. sock.sendall(packet)
  407. # Wait a bit.
  408. time.sleep(0.1)
  409. self.assertEqual(_devices(server_port), [[device_name, "offline"]])
  410. # Disconnect the device.
  411. output = subprocess.check_output(["adb", "-P", str(server_port),
  412. "disconnect", device_name])
  413. # Wait a bit.
  414. time.sleep(0.1)
  415. self.assertEqual(_devices(server_port), [])
  416. @unittest.skipUnless(sys.platform == "win32", "requires Windows")
  417. class PowerTest(unittest.TestCase):
  418. def test_resume_usb_kick(self):
  419. """Resuming from sleep/hibernate should kick USB devices."""
  420. try:
  421. usb_serial = subprocess.check_output(["adb", "-d", "get-serialno"]).strip()
  422. except subprocess.CalledProcessError:
  423. # If there are multiple USB devices, we don't have a way to check whether the selected
  424. # device is USB.
  425. raise unittest.SkipTest('requires single USB device')
  426. try:
  427. serial = subprocess.check_output(["adb", "get-serialno"]).strip()
  428. except subprocess.CalledProcessError:
  429. # Did you forget to select a device with $ANDROID_SERIAL?
  430. raise unittest.SkipTest('requires $ANDROID_SERIAL set to a USB device')
  431. # Test only works with USB devices because adb _power_notification_thread does not kick
  432. # non-USB devices on resume event.
  433. if serial != usb_serial:
  434. raise unittest.SkipTest('requires USB device')
  435. # Run an adb shell command in the background that takes a while to complete.
  436. proc = subprocess.Popen(['adb', 'shell', 'sleep', '5'])
  437. # Wait for startup of adb server's _power_notification_thread.
  438. time.sleep(0.1)
  439. # Simulate resuming from sleep/hibernation by sending Windows message.
  440. import ctypes
  441. from ctypes import wintypes
  442. HWND_BROADCAST = 0xffff
  443. WM_POWERBROADCAST = 0x218
  444. PBT_APMRESUMEAUTOMATIC = 0x12
  445. PostMessageW = ctypes.windll.user32.PostMessageW
  446. PostMessageW.restype = wintypes.BOOL
  447. PostMessageW.argtypes = (wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM)
  448. result = PostMessageW(HWND_BROADCAST, WM_POWERBROADCAST, PBT_APMRESUMEAUTOMATIC, 0)
  449. if not result:
  450. raise ctypes.WinError()
  451. # Wait for connection to adb shell to be broken by _power_notification_thread detecting the
  452. # Windows message.
  453. start = time.time()
  454. proc.wait()
  455. end = time.time()
  456. # If the power event was detected, the adb shell command should be broken very quickly.
  457. self.assertLess(end - start, 2)
  458. def main():
  459. """Main entrypoint."""
  460. random.seed(0)
  461. unittest.main(verbosity=3)
  462. if __name__ == "__main__":
  463. main()