Ejemplo n.º 1
0
    def testIPAddress(self):
        """Test IP class to get ip address."""
        # Internal ip case.
        ssh_object = ssh.Ssh(
            ip=ssh.IP(external="1.1.1.1", internal="10.1.1.1"),
            user=self.FAKE_SSH_USER,
            ssh_private_key_path=self.FAKE_SSH_PRIVATE_KEY_PATH,
            report_internal_ip=True)
        expected_ip = "10.1.1.1"
        self.assertEqual(ssh_object._ip, expected_ip)

        # External ip case.
        ssh_object = ssh.Ssh(
            ip=ssh.IP(external="1.1.1.1", internal="10.1.1.1"),
            user=self.FAKE_SSH_USER,
            ssh_private_key_path=self.FAKE_SSH_PRIVATE_KEY_PATH)
        expected_ip = "1.1.1.1"
        self.assertEqual(ssh_object._ip, expected_ip)

        # Only one ip case.
        ssh_object = ssh.Ssh(
            ip=ssh.IP(ip="1.1.1.1"),
            user=self.FAKE_SSH_USER,
            ssh_private_key_path=self.FAKE_SSH_PRIVATE_KEY_PATH)
        expected_ip = "1.1.1.1"
        self.assertEqual(ssh_object._ip, expected_ip)
Ejemplo n.º 2
0
def _IsWebrtcEnable(instance, host_user, host_ssh_private_key_path,
                    extra_args_ssh_tunnel):
    """Check local/remote instance webRTC is enable.

    Args:
        instance: Local/Remote Instance object.
        host_user: String of user login into the instance.
        host_ssh_private_key_path: String of host key for logging in to the
                                   host.
        extra_args_ssh_tunnel: String, extra args for ssh tunnel connection.

    Returns:
        Boolean: True if cf_runtime_cfg.enable_webrtc is True.
    """
    if instance.islocal:
        return instance.cf_runtime_cfg.enable_webrtc
    ssh = ssh_object.Ssh(ip=ssh_object.IP(ip=instance.ip),
                         user=host_user,
                         ssh_private_key_path=host_ssh_private_key_path,
                         extra_args_ssh_tunnel=extra_args_ssh_tunnel)
    remote_cuttlefish_config = os.path.join(constants.REMOTE_LOG_FOLDER,
                                            constants.CUTTLEFISH_CONFIG_FILE)
    raw_data = ssh.GetCmdOutput("cat " + remote_cuttlefish_config)
    try:
        cf_runtime_cfg = cvd_runtime_config.CvdRuntimeConfig(
            raw_data=raw_data.strip())
        return cf_runtime_cfg.enable_webrtc
    except errors.ConfigError:
        logger.debug("No cuttlefish config[%s] found!",
                     remote_cuttlefish_config)
    return False
Ejemplo n.º 3
0
    def testCreateGCETypeAVDInternalIP(self):
        """Test CreateGCETypeAVD with internal IP."""
        cfg = _CreateCfg()
        fake_ip = ssh.IP(external="140.1.1.1", internal="10.1.1.1")
        fake_instance = "fake-instance"
        fake_build_target = "fake_target"
        fake_build_id = "12345"

        self.compute_client.GetInstanceIP.return_value = fake_ip
        self.compute_client.GenerateInstanceName.return_value = fake_instance

        report = device_driver.CreateGCETypeAVD(cfg,
                                                fake_build_target,
                                                fake_build_id,
                                                report_internal_ip=True,
                                                avd_spec=self.fake_avd_spec)

        self.assertEqual(
            report.data, {
                "devices": [
                    {
                        "instance_name": fake_instance,
                        "ip": fake_ip.internal,
                    },
                ],
            })
Ejemplo n.º 4
0
    def testCreateGCETypeAVD(self):
        """Test CreateGCETypeAVD."""
        cfg = _CreateCfg()
        fake_gs_url = "fake_gs_url"
        fake_ip = ssh.IP(external="140.1.1.1", internal="10.1.1.1")
        fake_instance = "fake-instance"
        fake_image = "fake-image"
        fake_build_target = "fake_target"
        fake_build_id = "12345"

        # Mock uuid
        fake_uuid = mock.MagicMock(hex="1234")
        self.Patch(uuid, "uuid4", return_value=fake_uuid)
        fake_gs_object = fake_uuid.hex + "-" + cfg.disk_image_name
        self.storage_client.GetUrl.return_value = fake_gs_url

        # Mock compute client methods
        disk_name = "extradisk-image-4gb"
        self.compute_client.GetInstanceIP.return_value = fake_ip
        self.compute_client.GenerateImageName.return_value = fake_image
        self.compute_client.GenerateInstanceName.return_value = fake_instance
        self.compute_client.GetDataDiskName.return_value = disk_name

        # Verify
        report = device_driver.CreateGCETypeAVD(cfg,
                                                fake_build_target,
                                                fake_build_id,
                                                avd_spec=self.fake_avd_spec)
        self.build_client.CopyTo.assert_called_with(
            fake_build_target,
            fake_build_id,
            artifact_name=cfg.disk_image_name,
            destination_bucket=cfg.storage_bucket_name,
            destination_path=fake_gs_object)
        self.compute_client.CreateImage.assert_called_with(
            image_name=fake_image, source_uri=fake_gs_url)
        self.compute_client.CreateInstance.assert_called_with(
            instance=fake_instance,
            image_name=fake_image,
            extra_disk_name=disk_name,
            avd_spec=self.fake_avd_spec,
            extra_scopes=None)
        self.compute_client.DeleteImage.assert_called_with(fake_image)
        self.storage_client.Delete(cfg.storage_bucket_name, fake_gs_object)

        self.assertEqual(
            report.data, {
                "devices": [
                    {
                        "instance_name": fake_instance,
                        "ip": fake_ip.external,
                    },
                ],
            })
        self.assertEqual(report.command, "create")
        self.assertEqual(report.status, "SUCCESS")
Ejemplo n.º 5
0
 def testDisplayLog(self, mock_ssh_run):
     """Test DisplayLog."""
     fake_ip = ssh.IP(external="1.1.1.1", internal="10.1.1.1")
     _ssh = ssh.Ssh(ip=fake_ip,
                    user=constants.GCE_USER,
                    ssh_private_key_path="/fake/acloud_rea")
     self.Patch(utils, "GetUserAnswerYes", return_value="Y")
     log_file = "file1.log"
     pull.DisplayLog(_ssh, log_file)
     expected_cmd = "tail -f -n +1 %s" % log_file
     mock_ssh_run.assert_has_calls(
         [mock.call(expected_cmd, show_output=True)])
    def testUploadArtifacts(self, mock_ssh_run, mock_shell):
        """Test UploadArtifacts."""
        fake_host_package = "/fake/host_package.tar.gz"
        fake_image = "/fake/aosp_cf_x86_phone-img-eng.username.zip"
        fake_local_image_dir = "/fake_image"
        fake_ip = ssh.IP(external="1.1.1.1", internal="10.1.1.1")
        args = mock.MagicMock()
        # Test local image extract from image zip case.
        args.config_file = ""
        args.avd_type = constants.TYPE_CF
        args.flavor = "phone"
        args.local_image = "fake_local_image"
        args.adb_port = None
        avd_spec_local_image = avd_spec.AVDSpec(args)
        factory = remote_instance_cf_device_factory.RemoteInstanceDeviceFactory(
            avd_spec_local_image,
            fake_image,
            fake_host_package)
        factory._ssh = ssh.Ssh(ip=fake_ip,
                               user=constants.GCE_USER,
                               ssh_private_key_path="/fake/acloud_rea")
        factory._UploadArtifacts(fake_image, fake_host_package, fake_local_image_dir)
        expected_cmd1 = ("/usr/bin/install_zip.sh . < %s" % fake_image)
        expected_cmd2 = ("tar -x -z -f - < %s" % fake_host_package)
        mock_ssh_run.assert_has_calls([
            mock.call(expected_cmd1),
            mock.call(expected_cmd2)])

        # Test local image get from local folder case.
        fake_image = None
        self.Patch(glob, "glob", return_value=["fake.img"])
        factory._UploadArtifacts(fake_image, fake_host_package, fake_local_image_dir)
        expected_cmd = (
            "tar -cf - --lzop -S -C %s fake.img | "
            "%s -- tar -xf - --lzop -S" %
            (fake_local_image_dir, factory._ssh.GetBaseCmd(constants.SSH_BIN)))
        mock_shell.assert_called_once_with(expected_cmd)

        mock_shell.reset_mock()
        m = mock.mock_open(read_data = (
            "boot.img\n"
            "cache.img\n"
            "super.img\n"
            "userdata.img\n"
            "vendor_boot.img\n"))
        with mock.patch.object(six.moves.builtins, "open", m):
            factory._UploadArtifacts(fake_image, fake_host_package, fake_local_image_dir)
            expected_cmd = (
                "tar -cf - --lzop -S -C %s boot.img cache.img super.img userdata.img vendor_boot.img | "
                "%s -- tar -xf - --lzop -S" %
                (fake_local_image_dir, factory._ssh.GetBaseCmd(constants.SSH_BIN)))
            mock_shell.assert_called_once_with(expected_cmd)
Ejemplo n.º 7
0
    def testCreateInstance(self, mock_shell, mock_create_gce):
        fake_host_package = "/fake/host_package.tar.gz"
        fake_ip = ssh.IP(external="1.1.1.1", internal="10.1.1.1")
        args = mock.MagicMock()
        # Test local image extract from image zip case.
        args.config_file = ""
        args.avd_type = constants.TYPE_FVP
        args.flavor = "phone"
        args.local_image = "fake_local_image"
        args.local_image_dir = "fake_local_image_dir"
        args.adb_port = None
        avd_spec_local_image = avd_spec.AVDSpec(args)
        factory = remote_instance_fvp_device_factory.RemoteInstanceDeviceFactory(
            avd_spec_local_image)
        factory._ssh = ssh.Ssh(ip=fake_ip,
                               user=constants.GCE_USER,
                               ssh_private_key_path="/fake/acloud_rea")
        m = mock.mock_open(read_data=("bl1.bin\n"
                                      "boot.img\n"
                                      "fip.bin\n"
                                      "system-qemu.img\n"
                                      "userdata.img\n"))
        with mock.patch.object(six.moves.builtins, "open", m):
            factory.CreateInstance()

        mock_create_gce.assert_called_once()

        expected_cmds = [
            ("tar -cf - --lzop -S -C /path/to/product/out bl1.bin boot.img "
             "fip.bin system-qemu.img userdata.img | "
             "%s -- tar -xf - --lzop -S" %
             factory._ssh.GetBaseCmd(constants.SSH_BIN)),
            ("tar -cf - --lzop -S -C /path/to/model . | "
             "%s -- tar -xf - --lzop -S" %
             factory._ssh.GetBaseCmd(constants.SSH_BIN)),
            ("%s device/generic/goldfish/fvpbase/run_model_only "
             "[email protected]:run_model_only" %
             factory._ssh.GetBaseCmd(constants.SCP_BIN)),
            ("%s -- mkdir -p lib64" %
             factory._ssh.GetBaseCmd(constants.SSH_BIN)),
            ("%s /path/to/host/out/lib64/bind_to_localhost.so "
             "[email protected]:lib64/bind_to_localhost.so" %
             factory._ssh.GetBaseCmd(constants.SCP_BIN)),
            ("%s -- sh -c \"'ANDROID_HOST_OUT=. ANDROID_PRODUCT_OUT=. "
             "MODEL_BIN=./FVP_Base_RevC-2xAEMv8A "
             "./run_model_only > /dev/null 2> /dev/null &'\"" %
             factory._ssh.GetBaseCmd(constants.SSH_BIN)),
        ]
        mock_shell.assert_has_calls([mock.call(cmd) for cmd in expected_cmds])
    def _InitRemotehost(self):
        """Initialize remote host.

        Determine the remote host instance name, and activate ssh. It need to
        get the IP address in the common_operation. So need to pass the IP and
        ssh to compute_client.

        build_target: The format is like "aosp_cf_x86_phone". We only get info
                      from the user build image file name. If the file name is
                      not custom format (no "-"), we will use $TARGET_PRODUCT
                      from environment variable as build_target.

        Returns:
            A string, representing instance name.
        """
        image_name = os.path.basename(
            self._local_image_artifact) if self._local_image_artifact else ""
        build_target = (os.environ.get(constants.ENV_BUILD_TARGET) if "-" not
                        in image_name else image_name.split("-")[0])
        build_id = self._USER_BUILD
        if self._avd_spec.image_source == constants.IMAGE_SRC_REMOTE:
            build_id = self._avd_spec.remote_image[constants.BUILD_ID]

        instance = "%s-%s-%s-%s" % (constants.INSTANCE_TYPE_HOST,
                                    self._avd_spec.remote_host,
                                    build_id, build_target)
        ip = ssh.IP(ip=self._avd_spec.remote_host)
        self._ssh = ssh.Ssh(
            ip=ip,
            user=self._avd_spec.host_user,
            ssh_private_key_path=(self._avd_spec.host_ssh_private_key_path or
                                  self._cfg.ssh_private_key_path),
            extra_args_ssh_tunnel=self._cfg.extra_args_ssh_tunnel,
            report_internal_ip=self._report_internal_ip)
        self._compute_client.InitRemoteHost(
            self._ssh, ip, self._avd_spec.host_user)
        return instance
Ejemplo n.º 9
0
def CleanUpRemoteHost(cfg, remote_host, host_user,
                      host_ssh_private_key_path=None):
    """Clean up the remote host.

    Args:
        cfg: An AcloudConfig instance.
        remote_host : String, ip address or host name of the remote host.
        host_user: String of user login into the instance.
        host_ssh_private_key_path: String of host key for logging in to the
                                   host.

    Returns:
        A Report instance.
    """
    delete_report = report.Report(command="delete")
    credentials = auth.CreateCredentials(cfg)
    compute_client = cvd_compute_client_multi_stage.CvdComputeClient(
        acloud_config=cfg,
        oauth2_credentials=credentials)
    ssh = ssh_object.Ssh(
        ip=ssh_object.IP(ip=remote_host),
        user=host_user,
        ssh_private_key_path=(
            host_ssh_private_key_path or cfg.ssh_private_key_path))
    try:
        compute_client.InitRemoteHost(ssh, remote_host, host_user)
        delete_report.SetStatus(report.Status.SUCCESS)
        device_driver.AddDeletionResultToReport(
            delete_report, [remote_host], failed=[],
            error_msgs=[],
            resource_name="remote host")
    except subprocess.CalledProcessError as e:
        delete_report.AddError(str(e))
        delete_report.SetStatus(report.Status.FAIL)

    return delete_report
class CheepsRemoteImageRemoteInstanceTest(driver_test_lib.BaseDriverTest):
    """Test cheeps_remote_image_remote_instance."""

    IP = ssh.IP(external="127.0.0.1", internal="10.0.0.1")
    INSTANCE = "fake-instance"
    IMAGE = "fake-image"
    GPU = "nvidia-tesla-k80"
    CHEEPS_HOST_IMAGE_NAME = "fake-stable-host-image-name"
    CHEEPS_HOST_IMAGE_PROJECT = "fake-stable-host-image-project"
    ANDROID_BUILD_ID = 12345
    ANDROID_BUILD_TARGET = "fake-target"

    def setUp(self):
        """Set up the test."""
        super(CheepsRemoteImageRemoteInstanceTest, self).setUp()
        self.build_client = mock.MagicMock()
        self.Patch(
            android_build_client,
            "AndroidBuildClient",
            return_value=self.build_client)
        self.compute_client = mock.MagicMock()
        self.Patch(
            cheeps_compute_client,
            "CheepsComputeClient",
            return_value=self.compute_client)
        self.Patch(
            android_compute_client,
            "AndroidComputeClient",
            return_value=self.compute_client)
        self.Patch(auth, "CreateCredentials", return_value=mock.MagicMock())

        # Mock uuid
        fake_uuid = mock.MagicMock(hex="1234")
        self.Patch(uuid, "uuid4", return_value=fake_uuid)

        # Mock compute client methods
        self.compute_client.GetInstanceIP.return_value = self.IP
        self.compute_client.GenerateImageName.return_value = self.IMAGE
        self.compute_client.GenerateInstanceName.return_value = self.INSTANCE

    def _CreateCfg(self):
        """A helper method that creates a mock configuration object."""
        cfg = mock.MagicMock()
        cfg.service_account_name = "*****@*****.**"
        cfg.service_account_private_key_path = "/fake/path/to/key"
        cfg.zone = "fake_zone"
        cfg.ssh_private_key_path = ""
        cfg.ssh_public_key_path = ""
        cfg.stable_cheeps_host_image_name = self.CHEEPS_HOST_IMAGE_NAME
        cfg.stable_cheeps_host_image_project = self.CHEEPS_HOST_IMAGE_PROJECT
        return cfg

    def _CreateAvdSpec(self, stable_cheeps_host_image_name=None,
                       stable_cheeps_host_image_project=None):
        avd_spec = mock.MagicMock()
        avd_spec.cfg = self._CreateCfg()
        avd_spec.remote_image = {constants.BUILD_ID: self.ANDROID_BUILD_ID,
                                 constants.BUILD_TARGET: self.ANDROID_BUILD_TARGET}
        avd_spec.autoconnect = False
        avd_spec.report_internal_ip = False
        avd_spec.stable_cheeps_host_image_name = stable_cheeps_host_image_name
        avd_spec.stable_cheeps_host_image_project = stable_cheeps_host_image_project
        return avd_spec

    def testCreate(self):
        """Test CreateDevices."""
        avd_spec = self._CreateAvdSpec()
        instance = cheeps_remote_image_remote_instance.CheepsRemoteImageRemoteInstance()
        report = instance.Create(avd_spec, no_prompts=False)

        # Verify
        self.compute_client.CreateInstance.assert_called_with(
            instance=self.INSTANCE,
            image_name=self.CHEEPS_HOST_IMAGE_NAME,
            image_project=self.CHEEPS_HOST_IMAGE_PROJECT,
            avd_spec=avd_spec)

        self.assertEqual(report.data, {
            "devices": [{
                "build_id": self.ANDROID_BUILD_ID,
                "instance_name": self.INSTANCE,
                "ip": self.IP.external,
            },],
        })
        self.assertEqual(report.command, "create_cheeps")
        self.assertEqual(report.status, "SUCCESS")

    def testStableCheepsHostImageArgsOverrideConfig(self):
        """Test that Cheeps host image specifed through args (which goes into
        avd_spec) override values set in Acloud config."""
        stable_cheeps_host_image_name = 'override-stable-host-image-name'
        stable_cheeps_host_image_project = 'override-stable-host-image-project'
        self.assertNotEqual(stable_cheeps_host_image_name,
                            self.CHEEPS_HOST_IMAGE_NAME)
        self.assertNotEqual(stable_cheeps_host_image_project,
                            self.CHEEPS_HOST_IMAGE_PROJECT)

        avd_spec = self._CreateAvdSpec(stable_cheeps_host_image_name,
                                       stable_cheeps_host_image_project)
        instance = cheeps_remote_image_remote_instance.CheepsRemoteImageRemoteInstance()
        instance.Create(avd_spec, no_prompts=False)

        # Verify
        self.compute_client.CreateInstance.assert_called_with(
            instance=self.INSTANCE,
            image_name=stable_cheeps_host_image_name,
            image_project=stable_cheeps_host_image_project,
            avd_spec=avd_spec)
class CommonOperationsTest(driver_test_lib.BaseDriverTest):
    """Test Common Operations."""
    IP = ssh.IP(external="127.0.0.1", internal="10.0.0.1")
    INSTANCE = "fake-instance"
    CMD = "test-cmd"
    AVD_TYPE = "fake-type"
    BRANCH = "fake-branch"
    BUILD_TARGET = "fake-target"
    BUILD_ID = "fake-build-id"

    # pylint: disable=protected-access
    def setUp(self):
        """Set up the test."""
        super(CommonOperationsTest, self).setUp()
        self.build_client = mock.MagicMock()
        self.device_factory = mock.MagicMock()
        self.Patch(
            android_build_client,
            "AndroidBuildClient",
            return_value=self.build_client)
        self.compute_client = mock.MagicMock()
        self.Patch(
            android_compute_client,
            "AndroidComputeClient",
            return_value=self.compute_client)
        self.Patch(auth, "CreateCredentials", return_value=mock.MagicMock())
        self.Patch(self.compute_client, "GetInstanceIP", return_value=self.IP)
        self.Patch(
            self.device_factory, "CreateInstance", return_value=self.INSTANCE)
        self.Patch(
            self.device_factory,
            "GetComputeClient",
            return_value=self.compute_client)
        self.Patch(self.device_factory, "GetBuildInfoDict",
                   return_value={"branch": self.BRANCH,
                                 "build_id": self.BUILD_ID,
                                 "build_target": self.BUILD_TARGET,
                                 "gcs_bucket_build_id": self.BUILD_ID})
        self.Patch(self.device_factory, "GetBuildInfoDict",
                   return_value={"branch": self.BRANCH,
                                 "build_id": self.BUILD_ID,
                                 "build_target": self.BUILD_TARGET,
                                 "gcs_bucket_build_id": self.BUILD_ID})

    @staticmethod
    def _CreateCfg():
        """A helper method that creates a mock configuration object."""
        cfg = mock.MagicMock()
        cfg.service_account_name = "*****@*****.**"
        cfg.service_account_private_key_path = "/fake/path/to/key"
        cfg.zone = "fake_zone"
        cfg.disk_image_name = "fake_image.tar.gz"
        cfg.disk_image_mime_type = "fake/type"
        cfg.ssh_private_key_path = ""
        cfg.ssh_public_key_path = ""
        return cfg

    def testDevicePoolCreateDevices(self):
        """Test Device Pool Create Devices."""
        pool = common_operations.DevicePool(self.device_factory)
        pool.CreateDevices(5)
        self.assertEqual(self.device_factory.CreateInstance.call_count, 5)
        self.assertEqual(len(pool.devices), 5)

    def testCreateDevices(self):
        """Test Create Devices."""
        cfg = self._CreateCfg()
        _report = common_operations.CreateDevices(self.CMD, cfg,
                                                  self.device_factory, 1,
                                                  self.AVD_TYPE)
        self.assertEqual(_report.command, self.CMD)
        self.assertEqual(_report.status, report.Status.SUCCESS)
        self.assertEqual(
            _report.data,
            {"devices": [{
                "ip": self.IP.external,
                "instance_name": self.INSTANCE,
                "branch": self.BRANCH,
                "build_id": self.BUILD_ID,
                "build_target": self.BUILD_TARGET,
                "gcs_bucket_build_id": self.BUILD_ID,
            }]})

    def testCreateDevicesWithAdbPort(self):
        """Test Create Devices with adb port for cuttlefish avd type."""
        self.Patch(utils, "_ExecuteCommand")
        self.Patch(utils, "PickFreePort", return_value=56789)
        self.Patch(shlex, "split", return_value=[])
        cfg = self._CreateCfg()
        _report = common_operations.CreateDevices(self.CMD, cfg,
                                                  self.device_factory, 1,
                                                  "cuttlefish",
                                                  autoconnect=True,
                                                  client_adb_port=12345)
        self.assertEqual(_report.command, self.CMD)
        self.assertEqual(_report.status, report.Status.SUCCESS)
        self.assertEqual(
            _report.data,
            {"devices": [{
                "ip": self.IP.external,
                "instance_name": self.INSTANCE,
                "branch": self.BRANCH,
                "build_id": self.BUILD_ID,
                "adb_port": 12345,
                "vnc_port": 56789,
                "build_target": self.BUILD_TARGET,
                "gcs_bucket_build_id": self.BUILD_ID,
            }]})

    def testCreateDevicesInternalIP(self):
        """Test Create Devices and report internal IP."""
        cfg = self._CreateCfg()
        _report = common_operations.CreateDevices(self.CMD, cfg,
                                                  self.device_factory, 1,
                                                  self.AVD_TYPE,
                                                  report_internal_ip=True)
        self.assertEqual(_report.command, self.CMD)
        self.assertEqual(_report.status, report.Status.SUCCESS)
        self.assertEqual(
            _report.data,
            {"devices": [{
                "ip": self.IP.internal,
                "instance_name": self.INSTANCE,
                "branch": self.BRANCH,
                "build_id": self.BUILD_ID,
                "build_target": self.BUILD_TARGET,
                "gcs_bucket_build_id": self.BUILD_ID,
            }]})
Ejemplo n.º 12
0
class CreateGoldfishActionTest(driver_test_lib.BaseDriverTest):
    """Tests create_goldfish_action."""

    IP = ssh.IP(external="127.0.0.1", internal="10.0.0.1")
    INSTANCE = "fake-instance"
    IMAGE = "fake-image"
    BUILD_TARGET = "fake-build-target"
    EMULATOR_BUILD_TARGET = "emu-fake-target"
    BUILD_ID = "12345"
    EMULATOR_BUILD_ID = "1234567"
    GPU = "nvidia-tesla-k80"
    BRANCH = "fake-branch"
    EMULATOR_BRANCH = "emu-fake-branch"
    KERNEL_BRANCH = "fake-kernel-branch"
    KERNEL_BUILD_ID = "54321"
    KERNEL_BUILD_TARGET = "kernel"
    GOLDFISH_HOST_IMAGE_NAME = "fake-stable-host-image-name"
    GOLDFISH_HOST_IMAGE_PROJECT = "fake-stable-host-image-project"
    EXTRA_DATA_DISK_GB = 4
    EXTRA_SCOPES = None

    def setUp(self):
        """Sets up the test."""
        super(CreateGoldfishActionTest, self).setUp()
        self.build_client = mock.MagicMock()
        self.Patch(android_build_client,
                   "AndroidBuildClient",
                   return_value=self.build_client)
        self.compute_client = mock.MagicMock()
        self.Patch(goldfish_compute_client,
                   "GoldfishComputeClient",
                   return_value=self.compute_client)
        self.Patch(android_compute_client,
                   "AndroidComputeClient",
                   return_value=self.compute_client)
        self.Patch(auth, "CreateCredentials", return_value=mock.MagicMock())
        #Initialize new avd_spec
        self.avd_spec = mock.MagicMock()
        self.avd_spec.cfg = self._CreateCfg()
        self.avd_spec.remote_image = {
            constants.BUILD_ID: self.BUILD_ID,
            constants.BUILD_BRANCH: self.BRANCH,
            constants.BUILD_TARGET: self.BUILD_TARGET
        }
        self.avd_spec.emulator_build_id = self.EMULATOR_BUILD_ID
        self.avd_spec.gpu = self.GPU
        self.avd_spec.serial_log_file = None
        self.avd_spec.autoconnect = False

    def _CreateCfg(self):
        """A helper method that creates a mock configuration object."""
        cfg = mock.MagicMock()
        cfg.service_account_name = "*****@*****.**"
        cfg.service_account_private_key_path = "/fake/path/to/key"
        cfg.zone = "fake_zone"
        cfg.ssh_private_key_path = ""
        cfg.ssh_public_key_path = ""
        cfg.stable_goldfish_host_image_name = self.GOLDFISH_HOST_IMAGE_NAME
        cfg.stable_goldfish_host_image_project = self.GOLDFISH_HOST_IMAGE_PROJECT
        cfg.emulator_build_target = self.EMULATOR_BUILD_TARGET
        cfg.extra_data_disk_size_gb = self.EXTRA_DATA_DISK_GB
        cfg.extra_scopes = self.EXTRA_SCOPES
        return cfg

    def testCreateDevices(self):
        """Tests CreateDevices."""
        cfg = self._CreateCfg()

        # Mock uuid
        fake_uuid = mock.MagicMock(hex="1234")
        self.Patch(uuid, "uuid4", return_value=fake_uuid)

        # Mock compute client methods
        self.compute_client.GetInstanceIP.return_value = self.IP
        self.compute_client.GenerateImageName.return_value = self.IMAGE
        self.compute_client.GenerateInstanceName.return_value = self.INSTANCE

        # Mock build client method
        self.build_client.GetBuildInfo.side_effect = [
            android_build_client.BuildInfo(self.BRANCH, self.BUILD_ID,
                                           self.BUILD_TARGET, None),
            android_build_client.BuildInfo(self.EMULATOR_BRANCH,
                                           self.EMULATOR_BUILD_ID,
                                           self.EMULATOR_BUILD_TARGET, None),
            android_build_client.BuildInfo(self.KERNEL_BRANCH,
                                           self.KERNEL_BUILD_ID,
                                           self.KERNEL_BUILD_TARGET, None)
        ]

        none_avd_spec = None

        # Call CreateDevices with avd_spec is None
        report = create_goldfish_action.CreateDevices(
            none_avd_spec,
            cfg,
            build_target=self.BUILD_TARGET,
            build_id=self.BUILD_ID,
            emulator_build_id=self.EMULATOR_BUILD_ID,
            gpu=self.GPU,
            kernel_branch=self.KERNEL_BRANCH,
            kernel_build_id=self.KERNEL_BUILD_ID,
            kernel_build_target=self.KERNEL_BUILD_TARGET)

        # Verify
        self.compute_client.CreateInstance.assert_called_with(
            instance=self.INSTANCE,
            blank_data_disk_size_gb=self.EXTRA_DATA_DISK_GB,
            image_name=self.GOLDFISH_HOST_IMAGE_NAME,
            image_project=self.GOLDFISH_HOST_IMAGE_PROJECT,
            build_target=self.BUILD_TARGET,
            branch=self.BRANCH,
            build_id=self.BUILD_ID,
            emulator_branch=self.EMULATOR_BRANCH,
            emulator_build_id=self.EMULATOR_BUILD_ID,
            kernel_branch=self.KERNEL_BRANCH,
            kernel_build_id=self.KERNEL_BUILD_ID,
            kernel_build_target=self.KERNEL_BUILD_TARGET,
            gpu=self.GPU,
            avd_spec=none_avd_spec,
            extra_scopes=self.EXTRA_SCOPES,
            tags=None)

        self.assertEqual(
            report.data, {
                "devices": [
                    {
                        "instance_name": self.INSTANCE,
                        "ip": self.IP.external,
                        "branch": self.BRANCH,
                        "build_id": self.BUILD_ID,
                        "build_target": self.BUILD_TARGET,
                        "emulator_branch": self.EMULATOR_BRANCH,
                        "emulator_build_id": self.EMULATOR_BUILD_ID,
                        "emulator_build_target": self.EMULATOR_BUILD_TARGET,
                        "kernel_branch": self.KERNEL_BRANCH,
                        "kernel_build_id": self.KERNEL_BUILD_ID,
                        "kernel_build_target": self.KERNEL_BUILD_TARGET,
                    },
                ],
            })
        self.assertEqual(report.command, "create_gf")
        self.assertEqual(report.status, "SUCCESS")

        # Call CreateDevices with avd_spec
        self.build_client.GetBranch.side_effect = [
            self.BRANCH, self.EMULATOR_BRANCH
        ]
        # TODO: Break out avd spec testing into its own testcase.
        # Mock build client method
        self.build_client.GetBuildInfo.side_effect = [
            android_build_client.BuildInfo(self.BRANCH, self.BUILD_ID,
                                           self.BUILD_TARGET, None),
            android_build_client.BuildInfo(self.EMULATOR_BRANCH,
                                           self.EMULATOR_BUILD_ID,
                                           self.EMULATOR_BUILD_TARGET, None),
            android_build_client.BuildInfo(self.KERNEL_BRANCH,
                                           self.KERNEL_BUILD_ID,
                                           self.KERNEL_BUILD_TARGET, None)
        ]

        report = create_goldfish_action.CreateDevices(avd_spec=self.avd_spec)
        # Verify
        self.compute_client.CreateInstance.assert_called_with(
            instance=self.INSTANCE,
            blank_data_disk_size_gb=self.EXTRA_DATA_DISK_GB,
            image_name=self.GOLDFISH_HOST_IMAGE_NAME,
            image_project=self.GOLDFISH_HOST_IMAGE_PROJECT,
            build_target=self.BUILD_TARGET,
            branch=self.BRANCH,
            build_id=self.BUILD_ID,
            emulator_branch=self.EMULATOR_BRANCH,
            emulator_build_id=self.EMULATOR_BUILD_ID,
            kernel_branch=self.KERNEL_BRANCH,
            kernel_build_id=self.KERNEL_BUILD_ID,
            kernel_build_target=self.KERNEL_BUILD_TARGET,
            gpu=self.GPU,
            avd_spec=self.avd_spec,
            extra_scopes=self.EXTRA_SCOPES,
            tags=None)

    def testCreateDevicesWithoutBuildId(self):
        """Test CreateDevices when emulator sysimage buildid is not provided."""
        cfg = self._CreateCfg()

        # Mock uuid
        fake_uuid = mock.MagicMock(hex="1234")
        self.Patch(uuid, "uuid4", return_value=fake_uuid)

        # Mock compute client methods
        self.compute_client.GetInstanceIP.return_value = self.IP
        self.compute_client.GenerateImageName.return_value = self.IMAGE
        self.compute_client.GenerateInstanceName.return_value = self.INSTANCE

        # Mock build client method
        self.build_client.GetBuildInfo.side_effect = [
            android_build_client.BuildInfo(self.BRANCH, self.BUILD_ID,
                                           self.BUILD_TARGET, None),
            android_build_client.BuildInfo(self.EMULATOR_BRANCH,
                                           self.EMULATOR_BUILD_ID,
                                           self.EMULATOR_BUILD_TARGET, None),
            android_build_client.BuildInfo(self.KERNEL_BRANCH,
                                           self.KERNEL_BUILD_ID,
                                           self.KERNEL_BUILD_TARGET, None)
        ]

        # Mock _FetchBuildIdFromFile method
        self.Patch(create_goldfish_action,
                   "_FetchBuildIdFromFile",
                   return_value=self.BUILD_ID)

        none_avd_spec = None
        # Call CreateDevices with no avd_spec
        report = create_goldfish_action.CreateDevices(
            none_avd_spec,
            cfg,
            build_target=self.BUILD_TARGET,
            build_id=None,
            emulator_build_id=self.EMULATOR_BUILD_ID,
            emulator_branch=None,
            gpu=self.GPU,
            branch=None,
            kernel_branch=self.KERNEL_BRANCH,
            kernel_build_id=self.KERNEL_BUILD_ID,
            kernel_build_target=self.KERNEL_BUILD_TARGET)

        # Verify
        self.compute_client.CreateInstance.assert_called_with(
            instance=self.INSTANCE,
            blank_data_disk_size_gb=self.EXTRA_DATA_DISK_GB,
            image_name=self.GOLDFISH_HOST_IMAGE_NAME,
            image_project=self.GOLDFISH_HOST_IMAGE_PROJECT,
            build_target=self.BUILD_TARGET,
            branch=self.BRANCH,
            build_id=self.BUILD_ID,
            emulator_branch=self.EMULATOR_BRANCH,
            emulator_build_id=self.EMULATOR_BUILD_ID,
            kernel_branch=self.KERNEL_BRANCH,
            kernel_build_id=self.KERNEL_BUILD_ID,
            kernel_build_target=self.KERNEL_BUILD_TARGET,
            gpu=self.GPU,
            avd_spec=none_avd_spec,
            extra_scopes=self.EXTRA_SCOPES,
            tags=None)

        self.assertEqual(
            report.data, {
                "devices": [
                    {
                        "instance_name": self.INSTANCE,
                        "ip": self.IP.external,
                        "branch": self.BRANCH,
                        "build_id": self.BUILD_ID,
                        "build_target": self.BUILD_TARGET,
                        "emulator_branch": self.EMULATOR_BRANCH,
                        "emulator_build_id": self.EMULATOR_BUILD_ID,
                        "emulator_build_target": self.EMULATOR_BUILD_TARGET,
                        "kernel_branch": self.KERNEL_BRANCH,
                        "kernel_build_id": self.KERNEL_BUILD_ID,
                        "kernel_build_target": self.KERNEL_BUILD_TARGET,
                    },
                ],
            })
        self.assertEqual(report.command, "create_gf")
        self.assertEqual(report.status, "SUCCESS")

        # Call CreateDevices with avd_spec
        self.build_client.GetBranch.side_effect = [
            self.BRANCH, self.EMULATOR_BRANCH
        ]
        # TODO: Break out avd spec testing into its own testcase.
        # Mock build client method
        self.build_client.GetBuildInfo.side_effect = [
            android_build_client.BuildInfo(self.BRANCH, self.BUILD_ID,
                                           self.BUILD_TARGET, None),
            android_build_client.BuildInfo(self.EMULATOR_BRANCH,
                                           self.EMULATOR_BUILD_ID,
                                           self.EMULATOR_BUILD_TARGET, None),
            android_build_client.BuildInfo(self.KERNEL_BRANCH,
                                           self.KERNEL_BUILD_ID,
                                           self.KERNEL_BUILD_TARGET, None)
        ]

        report = create_goldfish_action.CreateDevices(avd_spec=self.avd_spec)
        # Verify
        self.compute_client.CreateInstance.assert_called_with(
            instance=self.INSTANCE,
            blank_data_disk_size_gb=self.EXTRA_DATA_DISK_GB,
            image_name=self.GOLDFISH_HOST_IMAGE_NAME,
            image_project=self.GOLDFISH_HOST_IMAGE_PROJECT,
            build_target=self.BUILD_TARGET,
            branch=self.BRANCH,
            build_id=self.BUILD_ID,
            emulator_branch=self.EMULATOR_BRANCH,
            emulator_build_id=self.EMULATOR_BUILD_ID,
            kernel_branch=self.KERNEL_BRANCH,
            kernel_build_id=self.KERNEL_BUILD_ID,
            kernel_build_target=self.KERNEL_BUILD_TARGET,
            gpu=self.GPU,
            avd_spec=self.avd_spec,
            extra_scopes=self.EXTRA_SCOPES,
            tags=None)

    #pylint: disable=invalid-name
    def testCreateDevicesWithoutEmulatorBuildId(self):
        """Test CreateDevices when emulator build id is not provided."""
        cfg = self._CreateCfg()

        # Mock uuid
        fake_uuid = mock.MagicMock(hex="1234")
        self.Patch(uuid, "uuid4", return_value=fake_uuid)

        # Mock compute client methods
        self.compute_client.GetInstanceIP.return_value = self.IP
        self.compute_client.GenerateImageName.return_value = self.IMAGE
        self.compute_client.GenerateInstanceName.return_value = self.INSTANCE

        # Mock build client method
        self.build_client.GetBuildInfo.side_effect = [
            android_build_client.BuildInfo(self.BRANCH, self.BUILD_ID,
                                           self.BUILD_TARGET, None),
            android_build_client.BuildInfo(self.EMULATOR_BRANCH,
                                           self.EMULATOR_BUILD_ID,
                                           self.EMULATOR_BUILD_TARGET, None),
            android_build_client.BuildInfo(self.KERNEL_BRANCH,
                                           self.KERNEL_BUILD_ID,
                                           self.KERNEL_BUILD_TARGET, None)
        ]

        # Mock _FetchBuildIdFromFile method
        self.Patch(create_goldfish_action,
                   "_FetchBuildIdFromFile",
                   return_value=self.EMULATOR_BUILD_ID)

        none_avd_spec = None
        # Call CreateDevices
        report = create_goldfish_action.CreateDevices(
            none_avd_spec,
            cfg,
            build_target=self.BUILD_TARGET,
            build_id=self.BUILD_ID,
            emulator_build_id=None,
            gpu=self.GPU)

        # Verify
        self.compute_client.CreateInstance.assert_called_with(
            instance=self.INSTANCE,
            blank_data_disk_size_gb=self.EXTRA_DATA_DISK_GB,
            image_name=self.GOLDFISH_HOST_IMAGE_NAME,
            image_project=self.GOLDFISH_HOST_IMAGE_PROJECT,
            build_target=self.BUILD_TARGET,
            branch=self.BRANCH,
            build_id=self.BUILD_ID,
            emulator_branch=self.EMULATOR_BRANCH,
            emulator_build_id=self.EMULATOR_BUILD_ID,
            kernel_branch=self.KERNEL_BRANCH,
            kernel_build_id=self.KERNEL_BUILD_ID,
            kernel_build_target=self.KERNEL_BUILD_TARGET,
            gpu=self.GPU,
            avd_spec=none_avd_spec,
            extra_scopes=self.EXTRA_SCOPES,
            tags=None)

        self.assertEqual(
            report.data, {
                "devices": [
                    {
                        "instance_name": self.INSTANCE,
                        "ip": self.IP.external,
                        "branch": self.BRANCH,
                        "build_id": self.BUILD_ID,
                        "build_target": self.BUILD_TARGET,
                        "emulator_branch": self.EMULATOR_BRANCH,
                        "emulator_build_id": self.EMULATOR_BUILD_ID,
                        "emulator_build_target": self.EMULATOR_BUILD_TARGET,
                        "kernel_branch": self.KERNEL_BRANCH,
                        "kernel_build_id": self.KERNEL_BUILD_ID,
                        "kernel_build_target": self.KERNEL_BUILD_TARGET,
                    },
                ],
            })
        self.assertEqual(report.command, "create_gf")
        self.assertEqual(report.status, "SUCCESS")

        # Call CreateDevices with avd_spec
        self.build_client.GetBranch.side_effect = [
            self.BRANCH, self.EMULATOR_BRANCH
        ]
        # TODO: Break out avd spec testing into its own testcase.
        # Mock build client method
        self.build_client.GetBuildInfo.side_effect = [
            android_build_client.BuildInfo(self.BRANCH, self.BUILD_ID,
                                           self.BUILD_TARGET, None),
            android_build_client.BuildInfo(self.EMULATOR_BRANCH,
                                           self.EMULATOR_BUILD_ID,
                                           self.EMULATOR_BUILD_TARGET, None),
            android_build_client.BuildInfo(self.KERNEL_BRANCH,
                                           self.KERNEL_BUILD_ID,
                                           self.KERNEL_BUILD_TARGET, None)
        ]

        report = create_goldfish_action.CreateDevices(avd_spec=self.avd_spec)
        # Verify
        self.compute_client.CreateInstance.assert_called_with(
            instance=self.INSTANCE,
            blank_data_disk_size_gb=self.EXTRA_DATA_DISK_GB,
            image_name=self.GOLDFISH_HOST_IMAGE_NAME,
            image_project=self.GOLDFISH_HOST_IMAGE_PROJECT,
            build_target=self.BUILD_TARGET,
            branch=self.BRANCH,
            build_id=self.BUILD_ID,
            emulator_branch=self.EMULATOR_BRANCH,
            emulator_build_id=self.EMULATOR_BUILD_ID,
            kernel_branch=self.KERNEL_BRANCH,
            kernel_build_id=self.KERNEL_BUILD_ID,
            kernel_build_target=self.KERNEL_BUILD_TARGET,
            gpu=self.GPU,
            avd_spec=self.avd_spec,
            extra_scopes=self.EXTRA_SCOPES,
            tags=None)
class CreateCuttlefishActionTest(driver_test_lib.BaseDriverTest):
    """Test create_cuttlefish_action."""

    IP = ssh.IP(external="127.0.0.1", internal="10.0.0.1")
    INSTANCE = "fake-instance"
    IMAGE = "fake-image"
    BUILD_TARGET = "fake-build-target"
    BUILD_ID = "12345"
    KERNEL_BRANCH = "fake-kernel-branch"
    KERNEL_BUILD_ID = "54321"
    KERNEL_BUILD_TARGET = "kernel"
    BRANCH = "fake-branch"
    SYSTEM_BRANCH = "fake-system-branch"
    SYSTEM_BUILD_ID = "23456"
    SYSTEM_BUILD_TARGET = "fake-system-build-target"
    STABLE_HOST_IMAGE_NAME = "fake-stable-host-image-name"
    STABLE_HOST_IMAGE_PROJECT = "fake-stable-host-image-project"
    EXTRA_DATA_DISK_GB = 4
    EXTRA_SCOPES = ["scope1", "scope2"]

    def setUp(self):
        """Set up the test."""
        super(CreateCuttlefishActionTest, self).setUp()
        self.build_client = mock.MagicMock()
        self.Patch(android_build_client,
                   "AndroidBuildClient",
                   return_value=self.build_client)
        self.compute_client = mock.MagicMock()
        self.Patch(cvd_compute_client,
                   "CvdComputeClient",
                   return_value=self.compute_client)
        self.Patch(cvd_compute_client_multi_stage,
                   "CvdComputeClient",
                   return_value=self.compute_client)
        self.Patch(android_compute_client,
                   "AndroidComputeClient",
                   return_value=self.compute_client)
        self.Patch(auth, "CreateCredentials", return_value=mock.MagicMock())

    def _CreateCfg(self):
        """A helper method that creates a mock configuration object."""
        cfg = mock.MagicMock()
        cfg.service_account_name = "*****@*****.**"
        cfg.service_account_private_key_path = "/fake/path/to/key"
        cfg.zone = "fake_zone"
        cfg.disk_image_name = "fake_image.tar.gz"
        cfg.disk_image_mime_type = "fake/type"
        cfg.ssh_private_key_path = ""
        cfg.ssh_public_key_path = ""
        cfg.stable_host_image_name = self.STABLE_HOST_IMAGE_NAME
        cfg.stable_host_image_project = self.STABLE_HOST_IMAGE_PROJECT
        cfg.extra_data_disk_size_gb = self.EXTRA_DATA_DISK_GB
        cfg.kernel_build_target = self.KERNEL_BUILD_TARGET
        cfg.extra_scopes = self.EXTRA_SCOPES
        cfg.enable_multi_stage = False
        return cfg

    def testCreateDevices(self):
        """Test CreateDevices."""
        cfg = self._CreateCfg()

        # Mock uuid
        fake_uuid = mock.MagicMock(hex="1234")
        self.Patch(uuid, "uuid4", return_value=fake_uuid)

        # Mock compute client methods
        self.compute_client.GetInstanceIP.return_value = self.IP
        self.compute_client.GenerateImageName.return_value = self.IMAGE
        self.compute_client.GenerateInstanceName.return_value = self.INSTANCE
        self.compute_client.GetHostImageName.return_value = self.STABLE_HOST_IMAGE_NAME

        # Mock build client method
        self.build_client.GetBuildInfo.side_effect = [
            android_build_client.BuildInfo(self.BRANCH, self.BUILD_ID,
                                           self.BUILD_TARGET, None),
            android_build_client.BuildInfo(self.KERNEL_BRANCH,
                                           self.KERNEL_BUILD_ID,
                                           self.KERNEL_BUILD_TARGET, None),
            android_build_client.BuildInfo(self.SYSTEM_BRANCH,
                                           self.SYSTEM_BUILD_ID,
                                           self.SYSTEM_BUILD_TARGET, None)
        ]

        # Call CreateDevices
        report = create_cuttlefish_action.CreateDevices(
            cfg,
            self.BUILD_TARGET,
            self.BUILD_ID,
            branch=self.BRANCH,
            kernel_build_id=self.KERNEL_BUILD_ID,
            system_build_target=self.SYSTEM_BUILD_TARGET,
            system_branch=self.SYSTEM_BRANCH,
            system_build_id=self.SYSTEM_BUILD_ID)

        # Verify
        self.compute_client.CreateInstance.assert_called_with(
            instance=self.INSTANCE,
            image_name=self.STABLE_HOST_IMAGE_NAME,
            image_project=self.STABLE_HOST_IMAGE_PROJECT,
            build_target=self.BUILD_TARGET,
            branch=self.BRANCH,
            build_id=self.BUILD_ID,
            kernel_branch=self.KERNEL_BRANCH,
            kernel_build_id=self.KERNEL_BUILD_ID,
            kernel_build_target=self.KERNEL_BUILD_TARGET,
            system_branch=self.SYSTEM_BRANCH,
            system_build_id=self.SYSTEM_BUILD_ID,
            system_build_target=self.SYSTEM_BUILD_TARGET,
            blank_data_disk_size_gb=self.EXTRA_DATA_DISK_GB,
            extra_scopes=self.EXTRA_SCOPES)

        self.assertEqual(
            report.data, {
                "devices": [
                    {
                        "branch": self.BRANCH,
                        "build_id": self.BUILD_ID,
                        "build_target": self.BUILD_TARGET,
                        "kernel_branch": self.KERNEL_BRANCH,
                        "kernel_build_id": self.KERNEL_BUILD_ID,
                        "kernel_build_target": self.KERNEL_BUILD_TARGET,
                        "system_branch": self.SYSTEM_BRANCH,
                        "system_build_id": self.SYSTEM_BUILD_ID,
                        "system_build_target": self.SYSTEM_BUILD_TARGET,
                        "instance_name": self.INSTANCE,
                        "ip": self.IP.external,
                    },
                ],
            })
        self.assertEqual(report.command, "create_cf")
        self.assertEqual(report.status, "SUCCESS")
Ejemplo n.º 14
0
class SshTest(driver_test_lib.BaseDriverTest):
    """Test ssh class."""

    FAKE_SSH_PRIVATE_KEY_PATH = "/fake/acloud_rea"
    FAKE_SSH_USER = "******"
    FAKE_IP = ssh.IP(external="1.1.1.1", internal="10.1.1.1")
    FAKE_EXTRA_ARGS_SSH = "-o ProxyCommand='ssh [email protected] Server 22'"
    FAKE_REPORT_INTERNAL_IP = True

    def setUp(self):
        """Set up the test."""
        super(SshTest, self).setUp()
        self.created_subprocess = mock.MagicMock()
        self.created_subprocess.stdout = mock.MagicMock()
        self.created_subprocess.stdout.readline = mock.MagicMock(
            return_value=b"")
        self.created_subprocess.poll = mock.MagicMock(return_value=0)
        self.created_subprocess.returncode = 0
        self.created_subprocess.communicate = mock.MagicMock(return_value=('',
                                                                           ''))

    def testSSHExecuteWithRetry(self):
        """test SSHExecuteWithRetry method."""
        self.Patch(time, "sleep")
        self.Patch(subprocess,
                   "Popen",
                   side_effect=subprocess.CalledProcessError(
                       None, "ssh command fail."))
        self.assertRaises(subprocess.CalledProcessError, ssh.ShellCmdWithRetry,
                          "fake cmd")

    def testGetBaseCmdWithInternalIP(self):
        """Test get base command with internal ip."""
        ssh_object = ssh.Ssh(
            ip=self.FAKE_IP,
            user=self.FAKE_SSH_USER,
            ssh_private_key_path=self.FAKE_SSH_PRIVATE_KEY_PATH,
            report_internal_ip=self.FAKE_REPORT_INTERNAL_IP)
        expected_ssh_cmd = (
            "/usr/bin/ssh -i /fake/acloud_rea -q -o UserKnownHostsFile=/dev/null "
            "-o StrictHostKeyChecking=no -l fake_user 10.1.1.1")
        self.assertEqual(ssh_object.GetBaseCmd(constants.SSH_BIN),
                         expected_ssh_cmd)

    def testGetBaseCmd(self):
        """Test get base command."""
        ssh_object = ssh.Ssh(self.FAKE_IP, self.FAKE_SSH_USER,
                             self.FAKE_SSH_PRIVATE_KEY_PATH)
        expected_ssh_cmd = (
            "/usr/bin/ssh -i /fake/acloud_rea -q -o UserKnownHostsFile=/dev/null "
            "-o StrictHostKeyChecking=no -l fake_user 1.1.1.1")
        self.assertEqual(ssh_object.GetBaseCmd(constants.SSH_BIN),
                         expected_ssh_cmd)

        expected_scp_cmd = (
            "/usr/bin/scp -i /fake/acloud_rea -q -o UserKnownHostsFile=/dev/null "
            "-o StrictHostKeyChecking=no")
        self.assertEqual(ssh_object.GetBaseCmd(constants.SCP_BIN),
                         expected_scp_cmd)

    # pylint: disable=no-member
    def testSshRunCmd(self):
        """Test ssh run command."""
        self.Patch(subprocess, "Popen", return_value=self.created_subprocess)
        ssh_object = ssh.Ssh(self.FAKE_IP, self.FAKE_SSH_USER,
                             self.FAKE_SSH_PRIVATE_KEY_PATH)
        ssh_object.Run("command")
        expected_cmd = (
            "exec /usr/bin/ssh -i /fake/acloud_rea -q -o UserKnownHostsFile=/dev/null "
            "-o StrictHostKeyChecking=no -l fake_user 1.1.1.1 command")
        subprocess.Popen.assert_called_with(expected_cmd,
                                            shell=True,
                                            stderr=-2,
                                            stdin=None,
                                            stdout=-1,
                                            universal_newlines=True)

    def testSshRunCmdwithExtraArgs(self):
        """test ssh rum command with extra command."""
        self.Patch(subprocess, "Popen", return_value=self.created_subprocess)
        ssh_object = ssh.Ssh(self.FAKE_IP, self.FAKE_SSH_USER,
                             self.FAKE_SSH_PRIVATE_KEY_PATH,
                             self.FAKE_EXTRA_ARGS_SSH)
        ssh_object.Run("command")
        expected_cmd = (
            "exec /usr/bin/ssh -i /fake/acloud_rea -q -o UserKnownHostsFile=/dev/null "
            "-o StrictHostKeyChecking=no "
            "-o ProxyCommand='ssh [email protected] Server 22' "
            "-l fake_user 1.1.1.1 command")
        subprocess.Popen.assert_called_with(expected_cmd,
                                            shell=True,
                                            stderr=-2,
                                            stdin=None,
                                            stdout=-1,
                                            universal_newlines=True)

    def testScpPullFileCmd(self):
        """Test scp pull file command."""
        self.Patch(subprocess, "Popen", return_value=self.created_subprocess)
        ssh_object = ssh.Ssh(self.FAKE_IP, self.FAKE_SSH_USER,
                             self.FAKE_SSH_PRIVATE_KEY_PATH)
        ssh_object.ScpPullFile("/tmp/test", "/tmp/test_1.log")
        expected_cmd = (
            "exec /usr/bin/scp -i /fake/acloud_rea -q -o UserKnownHostsFile=/dev/null "
            "-o StrictHostKeyChecking=no [email protected]:/tmp/test /tmp/test_1.log"
        )
        subprocess.Popen.assert_called_with(expected_cmd,
                                            shell=True,
                                            stderr=-2,
                                            stdin=None,
                                            stdout=-1,
                                            universal_newlines=True)

    def testScpPullFileCmdwithExtraArgs(self):
        """Test scp pull file command."""
        self.Patch(subprocess, "Popen", return_value=self.created_subprocess)
        ssh_object = ssh.Ssh(self.FAKE_IP, self.FAKE_SSH_USER,
                             self.FAKE_SSH_PRIVATE_KEY_PATH,
                             self.FAKE_EXTRA_ARGS_SSH)
        ssh_object.ScpPullFile("/tmp/test", "/tmp/test_1.log")
        expected_cmd = (
            "exec /usr/bin/scp -i /fake/acloud_rea -q -o UserKnownHostsFile=/dev/null "
            "-o StrictHostKeyChecking=no "
            "-o ProxyCommand='ssh [email protected] Server 22' "
            "[email protected]:/tmp/test /tmp/test_1.log")
        subprocess.Popen.assert_called_with(expected_cmd,
                                            shell=True,
                                            stderr=-2,
                                            stdin=None,
                                            stdout=-1,
                                            universal_newlines=True)

    def testScpPushFileCmd(self):
        """Test scp push file command."""
        self.Patch(subprocess, "Popen", return_value=self.created_subprocess)
        ssh_object = ssh.Ssh(self.FAKE_IP, self.FAKE_SSH_USER,
                             self.FAKE_SSH_PRIVATE_KEY_PATH)
        ssh_object.ScpPushFile("/tmp/test", "/tmp/test_1.log")
        expected_cmd = (
            "exec /usr/bin/scp -i /fake/acloud_rea -q -o UserKnownHostsFile=/dev/null "
            "-o StrictHostKeyChecking=no /tmp/test [email protected]:/tmp/test_1.log"
        )
        subprocess.Popen.assert_called_with(expected_cmd,
                                            shell=True,
                                            stderr=-2,
                                            stdin=None,
                                            stdout=-1,
                                            universal_newlines=True)

    def testScpPushFileCmdwithExtraArgs(self):
        """Test scp pull file command."""
        self.Patch(subprocess, "Popen", return_value=self.created_subprocess)
        ssh_object = ssh.Ssh(self.FAKE_IP, self.FAKE_SSH_USER,
                             self.FAKE_SSH_PRIVATE_KEY_PATH,
                             self.FAKE_EXTRA_ARGS_SSH)
        ssh_object.ScpPushFile("/tmp/test", "/tmp/test_1.log")
        expected_cmd = (
            "exec /usr/bin/scp -i /fake/acloud_rea -q -o UserKnownHostsFile=/dev/null "
            "-o StrictHostKeyChecking=no "
            "-o ProxyCommand='ssh [email protected] Server 22' "
            "/tmp/test [email protected]:/tmp/test_1.log")
        subprocess.Popen.assert_called_with(expected_cmd,
                                            shell=True,
                                            stderr=-2,
                                            stdin=None,
                                            stdout=-1,
                                            universal_newlines=True)

    # pylint: disable=protected-access
    def testIPAddress(self):
        """Test IP class to get ip address."""
        # Internal ip case.
        ssh_object = ssh.Ssh(
            ip=ssh.IP(external="1.1.1.1", internal="10.1.1.1"),
            user=self.FAKE_SSH_USER,
            ssh_private_key_path=self.FAKE_SSH_PRIVATE_KEY_PATH,
            report_internal_ip=True)
        expected_ip = "10.1.1.1"
        self.assertEqual(ssh_object._ip, expected_ip)

        # External ip case.
        ssh_object = ssh.Ssh(
            ip=ssh.IP(external="1.1.1.1", internal="10.1.1.1"),
            user=self.FAKE_SSH_USER,
            ssh_private_key_path=self.FAKE_SSH_PRIVATE_KEY_PATH)
        expected_ip = "1.1.1.1"
        self.assertEqual(ssh_object._ip, expected_ip)

        # Only one ip case.
        ssh_object = ssh.Ssh(
            ip=ssh.IP(ip="1.1.1.1"),
            user=self.FAKE_SSH_USER,
            ssh_private_key_path=self.FAKE_SSH_PRIVATE_KEY_PATH)
        expected_ip = "1.1.1.1"
        self.assertEqual(ssh_object._ip, expected_ip)

    def testWaitForSsh(self):
        """Test WaitForSsh."""
        ssh_object = ssh.Ssh(
            ip=self.FAKE_IP,
            user=self.FAKE_SSH_USER,
            ssh_private_key_path=self.FAKE_SSH_PRIVATE_KEY_PATH,
            report_internal_ip=self.FAKE_REPORT_INTERNAL_IP)
        self.Patch(ssh, "_SshCall", return_value=-1)
        self.assertRaises(errors.DeviceConnectionError,
                          ssh_object.WaitForSsh,
                          timeout=1,
                          max_retry=1)

    def testSshCallWait(self):
        """Test SshCallWait."""
        self.Patch(subprocess, "Popen", return_value=self.created_subprocess)
        self.Patch(threading, "Timer")
        fake_cmd = "fake command"
        ssh._SshCallWait(fake_cmd)
        threading.Timer.assert_not_called()

    def testSshCallWaitTimeout(self):
        """Test SshCallWait with timeout."""
        self.Patch(subprocess, "Popen", return_value=self.created_subprocess)
        self.Patch(threading, "Timer")
        fake_cmd = "fake command"
        fake_timeout = 30
        ssh._SshCallWait(fake_cmd, fake_timeout)
        threading.Timer.assert_called_once()

    def testSshCall(self):
        """Test _SshCall."""
        self.Patch(subprocess, "Popen", return_value=self.created_subprocess)
        self.Patch(threading, "Timer")
        fake_cmd = "fake command"
        ssh._SshCall(fake_cmd)
        threading.Timer.assert_not_called()

    def testSshCallTimeout(self):
        """Test SshCallWait with timeout."""
        self.Patch(subprocess, "Popen", return_value=self.created_subprocess)
        self.Patch(threading, "Timer")
        fake_cmd = "fake command"
        fake_timeout = 30
        ssh._SshCall(fake_cmd, fake_timeout)
        threading.Timer.assert_called_once()

    def testSshLogOutput(self):
        """Test _SshCall."""
        self.Patch(subprocess, "Popen", return_value=self.created_subprocess)
        self.Patch(threading, "Timer")
        fake_cmd = "fake command"
        ssh._SshLogOutput(fake_cmd)
        threading.Timer.assert_not_called()

    def testSshLogOutputTimeout(self):
        """Test SshCallWait with timeout."""
        self.Patch(subprocess, "Popen", return_value=self.created_subprocess)
        self.Patch(threading, "Timer")
        fake_cmd = "fake command"
        fake_timeout = 30
        ssh._SshLogOutput(fake_cmd, fake_timeout)
        threading.Timer.assert_called_once()