Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 90ff5d67 authored by Josh Gao's avatar Josh Gao Committed by android-build-merger
Browse files

Merge changes If7c8d38f,I7117dd19,Iaa5006e3,I3a568361,I37df06e4, ... am: 18eae78c am: da23544c

am: aca37b9a

Change-Id: I7699126e481eabdbe145bc90754e83cb361dbb42
parents 7add7e7f aca37b9a
Loading
Loading
Loading
Loading
+2 −5
Original line number Original line Diff line number Diff line
@@ -455,17 +455,14 @@ python_test_host {
    srcs: [
    srcs: [
        "test_adb.py",
        "test_adb.py",
    ],
    ],
    libs: [
        "adb_py",
    ],
    test_config: "adb_integration_test_adb.xml",
    test_config: "adb_integration_test_adb.xml",
    test_suites: ["general-tests"],
    test_suites: ["general-tests"],
    version: {
    version: {
        py2: {
        py2: {
            enabled: true,
            enabled: false,
        },
        },
        py3: {
        py3: {
            enabled: false,
            enabled: true,
        },
        },
    },
    },
}
}
+1 −0
Original line number Original line Diff line number Diff line
@@ -465,6 +465,7 @@ void send_auth_response(const char* token, size_t token_size, atransport* t) {
    if (key == nullptr) {
    if (key == nullptr) {
        // No more private keys to try, send the public key.
        // No more private keys to try, send the public key.
        t->SetConnectionState(kCsUnauthorized);
        t->SetConnectionState(kCsUnauthorized);
        t->SetConnectionEstablished(true);
        send_auth_publickey(t);
        send_auth_publickey(t);
        return;
        return;
    }
    }

adb/test_adb.py

100644 → 100755
+115 −112
Original line number Original line Diff line number Diff line
#!/usr/bin/env python
#!/usr/bin/env python3
#
#
# Copyright (C) 2015 The Android Open Source Project
# Copyright (C) 2015 The Android Open Source Project
#
#
@@ -19,9 +19,7 @@
This differs from things in test_device.py in that there is no API for these
This differs from things in test_device.py in that there is no API for these
things. Most of these tests involve specific error messages or the help text.
things. Most of these tests involve specific error messages or the help text.
"""
"""
from __future__ import print_function


import binascii
import contextlib
import contextlib
import os
import os
import random
import random
@@ -32,8 +30,6 @@ import subprocess
import threading
import threading
import unittest
import unittest


import adb



@contextlib.contextmanager
@contextlib.contextmanager
def fake_adbd(protocol=socket.AF_INET, port=0):
def fake_adbd(protocol=socket.AF_INET, port=0):
@@ -42,32 +38,32 @@ def fake_adbd(protocol=socket.AF_INET, port=0):
    serversock = socket.socket(protocol, socket.SOCK_STREAM)
    serversock = socket.socket(protocol, socket.SOCK_STREAM)
    serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    if protocol == socket.AF_INET:
    if protocol == socket.AF_INET:
        serversock.bind(('127.0.0.1', port))
        serversock.bind(("127.0.0.1", port))
    else:
    else:
        serversock.bind(('::1', port))
        serversock.bind(("::1", port))
    serversock.listen(1)
    serversock.listen(1)


    # A pipe that is used to signal the thread that it should terminate.
    # A pipe that is used to signal the thread that it should terminate.
    readpipe, writepipe = os.pipe()
    readsock, writesock = socket.socketpair()


    def _adb_packet(command, arg0, arg1, data):
    def _adb_packet(command: bytes, arg0: int, arg1: int, data: bytes) -> bytes:
        bin_command = struct.unpack('I', command)[0]
        bin_command = struct.unpack("I", command)[0]
        buf = struct.pack('IIIIII', bin_command, arg0, arg1, len(data), 0,
        buf = struct.pack("IIIIII", bin_command, arg0, arg1, len(data), 0,
                          bin_command ^ 0xffffffff)
                          bin_command ^ 0xffffffff)
        buf += data
        buf += data
        return buf
        return buf


    def _handle():
    def _handle(sock):
        rlist = [readpipe, serversock]
        with contextlib.closing(sock) as serversock:
            rlist = [readsock, serversock]
            cnxn_sent = {}
            cnxn_sent = {}
            while True:
            while True:
                read_ready, _, _ = select.select(rlist, [], [])
                read_ready, _, _ = select.select(rlist, [], [])
                for ready in read_ready:
                for ready in read_ready:
                if ready == readpipe:
                    if ready == readsock:
                        # Closure pipe
                        # Closure pipe
                    os.close(ready)
                        for f in rlist:
                    serversock.shutdown(socket.SHUT_RDWR)
                            f.close()
                    serversock.close()
                        return
                        return
                    elif ready == serversock:
                    elif ready == serversock:
                        # Server socket
                        # Server socket
@@ -76,7 +72,7 @@ def fake_adbd(protocol=socket.AF_INET, port=0):
                    else:
                    else:
                        # Client socket
                        # Client socket
                        data = ready.recv(1024)
                        data = ready.recv(1024)
                    if not data or data.startswith('OPEN'):
                        if not data or data.startswith(b"OPEN"):
                            if ready in cnxn_sent:
                            if ready in cnxn_sent:
                                del cnxn_sent[ready]
                                del cnxn_sent[ready]
                            ready.shutdown(socket.SHUT_RDWR)
                            ready.shutdown(socket.SHUT_RDWR)
@@ -86,17 +82,17 @@ def fake_adbd(protocol=socket.AF_INET, port=0):
                        if ready in cnxn_sent:
                        if ready in cnxn_sent:
                            continue
                            continue
                        cnxn_sent[ready] = True
                        cnxn_sent[ready] = True
                    ready.sendall(_adb_packet('CNXN', 0x01000001, 1024 * 1024,
                        ready.sendall(_adb_packet(b"CNXN", 0x01000001, 1024 * 1024,
                                              'device::ro.product.name=fakeadb'))
                                                  b"device::ro.product.name=fakeadb"))


    port = serversock.getsockname()[1]
    port = serversock.getsockname()[1]
    server_thread = threading.Thread(target=_handle)
    server_thread = threading.Thread(target=_handle, args=(serversock,))
    server_thread.start()
    server_thread.start()


    try:
    try:
        yield port
        yield port
    finally:
    finally:
        os.close(writepipe)
        writesock.close()
        server_thread.join()
        server_thread.join()




@@ -107,14 +103,15 @@ def adb_connect(unittest, serial):
    This automatically disconnects when done with the connection.
    This automatically disconnects when done with the connection.
    """
    """


    output = subprocess.check_output(['adb', 'connect', serial])
    output = subprocess.check_output(["adb", "connect", serial])
    unittest.assertEqual(output.strip(), 'connected to {}'.format(serial))
    unittest.assertEqual(output.strip(),
                        "connected to {}".format(serial).encode("utf8"))


    try:
    try:
        yield
        yield
    finally:
    finally:
        # Perform best-effort disconnection. Discard the output.
        # Perform best-effort disconnection. Discard the output.
        subprocess.Popen(['adb', 'disconnect', serial],
        subprocess.Popen(["adb", "disconnect", serial],
                         stdout=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE).communicate()
                         stderr=subprocess.PIPE).communicate()


@@ -123,21 +120,22 @@ def adb_connect(unittest, serial):
def adb_server():
def adb_server():
    """Context manager for an ADB server.
    """Context manager for an ADB server.


    This creates an ADB server and returns the port it's listening on.
    This creates an ADB server and returns the port it"s listening on.
    """
    """


    port = 5038
    port = 5038
    # Kill any existing server on this non-default port.
    # Kill any existing server on this non-default port.
    subprocess.check_output(['adb', '-P', str(port), 'kill-server'],
    subprocess.check_output(["adb", "-P", str(port), "kill-server"],
                            stderr=subprocess.STDOUT)
                            stderr=subprocess.STDOUT)
    read_pipe, write_pipe = os.pipe()
    read_pipe, write_pipe = os.pipe()
    proc = subprocess.Popen(['adb', '-L', 'tcp:localhost:{}'.format(port),
    os.set_inheritable(write_pipe, True)
                             'fork-server', 'server',
    proc = subprocess.Popen(["adb", "-L", "tcp:localhost:{}".format(port),
                             '--reply-fd', str(write_pipe)])
                             "fork-server", "server",
                             "--reply-fd", str(write_pipe)], close_fds=False)
    try:
    try:
        os.close(write_pipe)
        os.close(write_pipe)
        greeting = os.read(read_pipe, 1024)
        greeting = os.read(read_pipe, 1024)
        assert greeting == 'OK\n', repr(greeting)
        assert greeting == b"OK\n", repr(greeting)
        yield port
        yield port
    finally:
    finally:
        proc.terminate()
        proc.terminate()
@@ -150,35 +148,37 @@ class CommandlineTest(unittest.TestCase):
    def test_help(self):
    def test_help(self):
        """Make sure we get _something_ out of help."""
        """Make sure we get _something_ out of help."""
        out = subprocess.check_output(
        out = subprocess.check_output(
            ['adb', 'help'], stderr=subprocess.STDOUT)
            ["adb", "help"], stderr=subprocess.STDOUT)
        self.assertGreater(len(out), 0)
        self.assertGreater(len(out), 0)


    def test_version(self):
    def test_version(self):
        """Get a version number out of the output of adb."""
        """Get a version number out of the output of adb."""
        lines = subprocess.check_output(['adb', 'version']).splitlines()
        lines = subprocess.check_output(["adb", "version"]).splitlines()
        version_line = lines[0]
        version_line = lines[0]
        self.assertRegexpMatches(
        self.assertRegex(
            version_line, r'^Android Debug Bridge version \d+\.\d+\.\d+$')
            version_line, rb"^Android Debug Bridge version \d+\.\d+\.\d+$")
        if len(lines) == 2:
        if len(lines) == 2:
            # Newer versions of ADB have a second line of output for the
            # Newer versions of ADB have a second line of output for the
            # version that includes a specific revision (git SHA).
            # version that includes a specific revision (git SHA).
            revision_line = lines[1]
            revision_line = lines[1]
            self.assertRegexpMatches(
            self.assertRegex(
                revision_line, r'^Revision [0-9a-f]{12}-android$')
                revision_line, rb"^Revision [0-9a-f]{12}-android$")


    def test_tcpip_error_messages(self):
    def test_tcpip_error_messages(self):
        """Make sure 'adb tcpip' parsing is sane."""
        """Make sure 'adb tcpip' parsing is sane."""
        proc = subprocess.Popen(['adb', 'tcpip'], stdout=subprocess.PIPE,
        proc = subprocess.Popen(["adb", "tcpip"],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
                                stderr=subprocess.STDOUT)
        out, _ = proc.communicate()
        out, _ = proc.communicate()
        self.assertEqual(1, proc.returncode)
        self.assertEqual(1, proc.returncode)
        self.assertIn('requires an argument', out)
        self.assertIn(b"requires an argument", out)


        proc = subprocess.Popen(['adb', 'tcpip', 'foo'], stdout=subprocess.PIPE,
        proc = subprocess.Popen(["adb", "tcpip", "foo"],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
                                stderr=subprocess.STDOUT)
        out, _ = proc.communicate()
        out, _ = proc.communicate()
        self.assertEqual(1, proc.returncode)
        self.assertEqual(1, proc.returncode)
        self.assertIn('invalid port', out)
        self.assertIn(b"invalid port", out)




class ServerTest(unittest.TestCase):
class ServerTest(unittest.TestCase):
@@ -214,12 +214,12 @@ class ServerTest(unittest.TestCase):


        port = 5038
        port = 5038
        # Kill any existing server on this non-default port.
        # Kill any existing server on this non-default port.
        subprocess.check_output(['adb', '-P', str(port), 'kill-server'],
        subprocess.check_output(["adb", "-P", str(port), "kill-server"],
                                stderr=subprocess.STDOUT)
                                stderr=subprocess.STDOUT)


        try:
        try:
            # Run the adb client and have it start the adb server.
            # Run the adb client and have it start the adb server.
            proc = subprocess.Popen(['adb', '-P', str(port), 'start-server'],
            proc = subprocess.Popen(["adb", "-P", str(port), "start-server"],
                                    stdin=subprocess.PIPE,
                                    stdin=subprocess.PIPE,
                                    stdout=subprocess.PIPE,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
                                    stderr=subprocess.PIPE)
@@ -229,14 +229,12 @@ class ServerTest(unittest.TestCase):
            stdout_thread = threading.Thread(
            stdout_thread = threading.Thread(
                target=ServerTest._read_pipe_and_set_event,
                target=ServerTest._read_pipe_and_set_event,
                args=(proc.stdout, stdout_event))
                args=(proc.stdout, stdout_event))
            stdout_thread.daemon = True
            stdout_thread.start()
            stdout_thread.start()


            stderr_event = threading.Event()
            stderr_event = threading.Event()
            stderr_thread = threading.Thread(
            stderr_thread = threading.Thread(
                target=ServerTest._read_pipe_and_set_event,
                target=ServerTest._read_pipe_and_set_event,
                args=(proc.stderr, stderr_event))
                args=(proc.stderr, stderr_event))
            stderr_thread.daemon = True
            stderr_thread.start()
            stderr_thread.start()


            # Wait for the adb client to finish. Once that has occurred, if
            # Wait for the adb client to finish. Once that has occurred, if
@@ -250,7 +248,8 @@ class ServerTest(unittest.TestCase):
            # probably letting the adb server inherit stdin which would be
            # probably letting the adb server inherit stdin which would be
            # wrong.
            # wrong.
            with self.assertRaises(IOError):
            with self.assertRaises(IOError):
                proc.stdin.write('x')
                proc.stdin.write(b"x")
                proc.stdin.flush()


            # Wait a few seconds for stdout/stderr to be closed (in the success
            # Wait a few seconds for stdout/stderr to be closed (in the success
            # case, this won't wait at all). If there is a timeout, that means
            # case, this won't wait at all). If there is a timeout, that means
@@ -259,9 +258,11 @@ class ServerTest(unittest.TestCase):
            # inherit stdout/stderr which would be wrong.
            # inherit stdout/stderr which would be wrong.
            self.assertTrue(stdout_event.wait(5), "adb stdout not closed")
            self.assertTrue(stdout_event.wait(5), "adb stdout not closed")
            self.assertTrue(stderr_event.wait(5), "adb stderr not closed")
            self.assertTrue(stderr_event.wait(5), "adb stderr not closed")
            stdout_thread.join()
            stderr_thread.join()
        finally:
        finally:
            # If we started a server, kill it.
            # If we started a server, kill it.
            subprocess.check_output(['adb', '-P', str(port), 'kill-server'],
            subprocess.check_output(["adb", "-P", str(port), "kill-server"],
                                    stderr=subprocess.STDOUT)
                                    stderr=subprocess.STDOUT)




@@ -271,7 +272,7 @@ class EmulatorTest(unittest.TestCase):
    def _reset_socket_on_close(self, sock):
    def _reset_socket_on_close(self, sock):
        """Use SO_LINGER to cause TCP RST segment to be sent on socket close."""
        """Use SO_LINGER to cause TCP RST segment to be sent on socket close."""
        # The linger structure is two shorts on Windows, but two ints on Unix.
        # The linger structure is two shorts on Windows, but two ints on Unix.
        linger_format = 'hh' if os.name == 'nt' else 'ii'
        linger_format = "hh" if os.name == "nt" else "ii"
        l_onoff = 1
        l_onoff = 1
        l_linger = 0
        l_linger = 0


@@ -292,33 +293,33 @@ class EmulatorTest(unittest.TestCase):
            # Use SO_REUSEADDR so subsequent runs of the test can grab the port
            # Use SO_REUSEADDR so subsequent runs of the test can grab the port
            # even if it is in TIME_WAIT.
            # even if it is in TIME_WAIT.
            listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            listener.bind(('127.0.0.1', 0))
            listener.bind(("127.0.0.1", 0))
            listener.listen(4)
            listener.listen(4)
            port = listener.getsockname()[1]
            port = listener.getsockname()[1]


            # Now that listening has started, start adb emu kill, telling it to
            # Now that listening has started, start adb emu kill, telling it to
            # connect to our mock emulator.
            # connect to our mock emulator.
            proc = subprocess.Popen(
            proc = subprocess.Popen(
                ['adb', '-s', 'emulator-' + str(port), 'emu', 'kill'],
                ["adb", "-s", "emulator-" + str(port), "emu", "kill"],
                stderr=subprocess.STDOUT)
                stderr=subprocess.STDOUT)


            accepted_connection, addr = listener.accept()
            accepted_connection, addr = listener.accept()
            with contextlib.closing(accepted_connection) as conn:
            with contextlib.closing(accepted_connection) as conn:
                # If WSAECONNABORTED (10053) is raised by any socket calls,
                # If WSAECONNABORTED (10053) is raised by any socket calls,
                # then adb probably isn't reading the data that we sent it.
                # then adb probably isn't reading the data that we sent it.
                conn.sendall('Android Console: type \'help\' for a list ' +
                conn.sendall(("Android Console: type 'help' for a list "
                             'of commands\r\n')
                             "of commands\r\n").encode("utf8"))
                conn.sendall('OK\r\n')
                conn.sendall(b"OK\r\n")


                with contextlib.closing(conn.makefile()) as connf:
                with contextlib.closing(conn.makefile()) as connf:
                    line = connf.readline()
                    line = connf.readline()
                    if line.startswith('auth'):
                    if line.startswith("auth"):
                        # Ignore the first auth line.
                        # Ignore the first auth line.
                        line = connf.readline()
                        line = connf.readline()
                    self.assertEqual('kill\n', line)
                    self.assertEqual("kill\n", line)
                    self.assertEqual('quit\n', connf.readline())
                    self.assertEqual("quit\n", connf.readline())


                conn.sendall('OK: killing emulator, bye bye\r\n')
                conn.sendall(b"OK: killing emulator, bye bye\r\n")


                # Use SO_LINGER to send TCP RST segment to test whether adb
                # Use SO_LINGER to send TCP RST segment to test whether adb
                # ignores WSAECONNRESET on Windows. This happens with the
                # ignores WSAECONNRESET on Windows. This happens with the
@@ -342,31 +343,31 @@ class EmulatorTest(unittest.TestCase):
        """
        """
        with adb_server() as server_port:
        with adb_server() as server_port:
            with fake_adbd() as port:
            with fake_adbd() as port:
                serial = 'emulator-{}'.format(port - 1)
                serial = "emulator-{}".format(port - 1)
                # Ensure that the emulator is not there.
                # Ensure that the emulator is not there.
                try:
                try:
                    subprocess.check_output(['adb', '-P', str(server_port),
                    subprocess.check_output(["adb", "-P", str(server_port),
                                             '-s', serial, 'get-state'],
                                             "-s", serial, "get-state"],
                                            stderr=subprocess.STDOUT)
                                            stderr=subprocess.STDOUT)
                    self.fail('Device should not be available')
                    self.fail("Device should not be available")
                except subprocess.CalledProcessError as err:
                except subprocess.CalledProcessError as err:
                    self.assertEqual(
                    self.assertEqual(
                        err.output.strip(),
                        err.output.strip(),
                        'error: device \'{}\' not found'.format(serial))
                        "error: device '{}' not found".format(serial).encode("utf8"))


                # Let the ADB server know that the emulator has started.
                # Let the ADB server know that the emulator has started.
                with contextlib.closing(
                with contextlib.closing(
                        socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
                        socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
                    sock.connect(('localhost', server_port))
                    sock.connect(("localhost", server_port))
                    command = 'host:emulator:{}'.format(port)
                    command = "host:emulator:{}".format(port).encode("utf8")
                    sock.sendall('%04x%s' % (len(command), command))
                    sock.sendall(b"%04x%s" % (len(command), command))


                # Ensure the emulator is there.
                # Ensure the emulator is there.
                subprocess.check_call(['adb', '-P', str(server_port),
                subprocess.check_call(["adb", "-P", str(server_port),
                                       '-s', serial, 'wait-for-device'])
                                       "-s", serial, "wait-for-device"])
                output = subprocess.check_output(['adb', '-P', str(server_port),
                output = subprocess.check_output(["adb", "-P", str(server_port),
                                                  '-s', serial, 'get-state'])
                                                  "-s", serial, "get-state"])
                self.assertEqual(output.strip(), 'device')
                self.assertEqual(output.strip(), b"device")




class ConnectionTest(unittest.TestCase):
class ConnectionTest(unittest.TestCase):
@@ -380,7 +381,7 @@ class ConnectionTest(unittest.TestCase):
        for protocol in (socket.AF_INET, socket.AF_INET6):
        for protocol in (socket.AF_INET, socket.AF_INET6):
            try:
            try:
                with fake_adbd(protocol=protocol) as port:
                with fake_adbd(protocol=protocol) as port:
                    serial = 'localhost:{}'.format(port)
                    serial = "localhost:{}".format(port)
                    with adb_connect(self, serial):
                    with adb_connect(self, serial):
                        pass
                        pass
            except socket.error:
            except socket.error:
@@ -391,49 +392,51 @@ class ConnectionTest(unittest.TestCase):
        """Ensure that an already-connected device stays connected."""
        """Ensure that an already-connected device stays connected."""


        with fake_adbd() as port:
        with fake_adbd() as port:
            serial = 'localhost:{}'.format(port)
            serial = "localhost:{}".format(port)
            with adb_connect(self, serial):
            with adb_connect(self, serial):
                # b/31250450: this always returns 0 but probably shouldn't.
                # b/31250450: this always returns 0 but probably shouldn't.
                output = subprocess.check_output(['adb', 'connect', serial])
                output = subprocess.check_output(["adb", "connect", serial])
                self.assertEqual(
                self.assertEqual(
                    output.strip(), 'already connected to {}'.format(serial))
                    output.strip(),
                    "already connected to {}".format(serial).encode("utf8"))


    def test_reconnect(self):
    def test_reconnect(self):
        """Ensure that a disconnected device reconnects."""
        """Ensure that a disconnected device reconnects."""


        with fake_adbd() as port:
        with fake_adbd() as port:
            serial = 'localhost:{}'.format(port)
            serial = "localhost:{}".format(port)
            with adb_connect(self, serial):
            with adb_connect(self, serial):
                output = subprocess.check_output(['adb', '-s', serial,
                output = subprocess.check_output(["adb", "-s", serial,
                                                  'get-state'])
                                                  "get-state"])
                self.assertEqual(output.strip(), 'device')
                self.assertEqual(output.strip(), b"device")


                # This will fail.
                # This will fail.
                proc = subprocess.Popen(['adb', '-s', serial, 'shell', 'true'],
                proc = subprocess.Popen(["adb", "-s", serial, "shell", "true"],
                                        stdout=subprocess.PIPE,
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.STDOUT)
                                        stderr=subprocess.STDOUT)
                output, _ = proc.communicate()
                output, _ = proc.communicate()
                self.assertEqual(output.strip(), 'error: closed')
                self.assertEqual(output.strip(), b"error: closed")


                subprocess.check_call(['adb', '-s', serial, 'wait-for-device'])
                subprocess.check_call(["adb", "-s", serial, "wait-for-device"])


                output = subprocess.check_output(['adb', '-s', serial,
                output = subprocess.check_output(["adb", "-s", serial,
                                                  'get-state'])
                                                  "get-state"])
                self.assertEqual(output.strip(), 'device')
                self.assertEqual(output.strip(), b"device")


                # Once we explicitly kick a device, it won't attempt to
                # Once we explicitly kick a device, it won't attempt to
                # reconnect.
                # reconnect.
                output = subprocess.check_output(['adb', 'disconnect', serial])
                output = subprocess.check_output(["adb", "disconnect", serial])
                self.assertEqual(
                self.assertEqual(
                    output.strip(), 'disconnected {}'.format(serial))
                    output.strip(),
                    "disconnected {}".format(serial).encode("utf8"))
                try:
                try:
                    subprocess.check_output(['adb', '-s', serial, 'get-state'],
                    subprocess.check_output(["adb", "-s", serial, "get-state"],
                                            stderr=subprocess.STDOUT)
                                            stderr=subprocess.STDOUT)
                    self.fail('Device should not be available')
                    self.fail("Device should not be available")
                except subprocess.CalledProcessError as err:
                except subprocess.CalledProcessError as err:
                    self.assertEqual(
                    self.assertEqual(
                        err.output.strip(),
                        err.output.strip(),
                        'error: device \'{}\' not found'.format(serial))
                        "error: device '{}' not found".format(serial).encode("utf8"))




def main():
def main():
@@ -442,5 +445,5 @@ def main():
    unittest.main(verbosity=3)
    unittest.main(verbosity=3)




if __name__ == '__main__':
if __name__ == "__main__":
    main()
    main()
+5 −3
Original line number Original line Diff line number Diff line
@@ -762,9 +762,10 @@ class FileOperationsTest(DeviceTest):
            os.chmod(host_dir, 0o700)
            os.chmod(host_dir, 0o700)


            # Create an empty directory.
            # Create an empty directory.
            os.mkdir(os.path.join(host_dir, 'empty'))
            empty_dir_path = os.path.join(host_dir, 'empty')
            os.mkdir(empty_dir_path);


            self.device.push(host_dir, self.DEVICE_TEMP_DIR)
            self.device.push(empty_dir_path, self.DEVICE_TEMP_DIR)


            test_empty_cmd = ['[', '-d',
            test_empty_cmd = ['[', '-d',
                              os.path.join(self.DEVICE_TEMP_DIR, 'empty')]
                              os.path.join(self.DEVICE_TEMP_DIR, 'empty')]
@@ -1032,7 +1033,8 @@ class FileOperationsTest(DeviceTest):
            if host_dir is not None:
            if host_dir is not None:
                shutil.rmtree(host_dir)
                shutil.rmtree(host_dir)


    def test_pull_symlink_dir(self):
    # selinux prevents adbd from accessing symlinks on /data/local/tmp.
    def disabled_test_pull_symlink_dir(self):
        """Pull a symlink to a directory of symlinks to files."""
        """Pull a symlink to a directory of symlinks to files."""
        try:
        try:
            host_dir = tempfile.mkdtemp()
            host_dir = tempfile.mkdtemp()
+20 −7
Original line number Original line Diff line number Diff line
@@ -1190,14 +1190,15 @@ void close_usb_devices() {
}
}
#endif  // ADB_HOST
#endif  // ADB_HOST


int register_socket_transport(unique_fd s, std::string serial, int port, int local,
bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
                              atransport::ReconnectCallback reconnect) {
                               atransport::ReconnectCallback reconnect, int* error) {
    atransport* t = new atransport(std::move(reconnect), kCsOffline);
    atransport* t = new atransport(std::move(reconnect), kCsOffline);


    D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
    D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
    if (init_socket_transport(t, std::move(s), port, local) < 0) {
    if (init_socket_transport(t, std::move(s), port, local) < 0) {
        delete t;
        delete t;
        return -1;
        if (error) *error = errno;
        return false;
    }
    }


    std::unique_lock<std::recursive_mutex> lock(transport_lock);
    std::unique_lock<std::recursive_mutex> lock(transport_lock);
@@ -1206,7 +1207,8 @@ int register_socket_transport(unique_fd s, std::string serial, int port, int loc
            VLOG(TRANSPORT) << "socket transport " << transport->serial
            VLOG(TRANSPORT) << "socket transport " << transport->serial
                            << " is already in pending_list and fails to register";
                            << " is already in pending_list and fails to register";
            delete t;
            delete t;
            return -EALREADY;
            if (error) *error = EALREADY;
            return false;
        }
        }
    }
    }


@@ -1215,7 +1217,8 @@ int register_socket_transport(unique_fd s, std::string serial, int port, int loc
            VLOG(TRANSPORT) << "socket transport " << transport->serial
            VLOG(TRANSPORT) << "socket transport " << transport->serial
                            << " is already in transport_list and fails to register";
                            << " is already in transport_list and fails to register";
            delete t;
            delete t;
            return -EALREADY;
            if (error) *error = EALREADY;
            return false;
        }
        }
    }
    }


@@ -1229,10 +1232,20 @@ int register_socket_transport(unique_fd s, std::string serial, int port, int loc


    if (local == 1) {
    if (local == 1) {
        // Do not wait for emulator transports.
        // Do not wait for emulator transports.
        return 0;
        return true;
    }
    }


    return waitable->WaitForConnection(std::chrono::seconds(10)) ? 0 : -1;
    if (!waitable->WaitForConnection(std::chrono::seconds(10))) {
        if (error) *error = ETIMEDOUT;
        return false;
    }

    if (t->GetConnectionState() == kCsUnauthorized) {
        if (error) *error = EPERM;
        return false;
    }

    return true;
}
}


#if ADB_HOST
#if ADB_HOST
Loading