def test_restore_snapshot_should_success_on_existing_snapshot(self, mock_get_vm_snapshots):
        vm = Mock()

        pyvmomi_service = Mock()
        pyvmomi_service.find_by_uuid = Mock(return_value=vm)

        snapshot_restore_command = SnapshotRestoreCommand(pyvmomi_service=pyvmomi_service, task_waiter=Mock())
        si = Mock()

        snapshot = Mock()
        mock_get_vm_snapshots.return_value = {"snap1": snapshot}
        session = MagicMock()
        session.SetResourceLiveStatus = MagicMock()

        # Act
        snapshot_restore_command.restore_snapshot(
            si=si,
            logger=Mock(),
            session=session,
            vm_uuid="machine1",
            resource_fullname="vm_machine1",
            snapshot_name="snap1",
        )

        # Assert
        self.assertTrue(snapshot.RevertToSnapshot_Task.called)
        session.SetResourceLiveStatus.assert_called_with("vm_machine1", "Offline", "Powered Off")
    def test_restore_snapshot_should_throw_exception_on_none_existing_snapshot(self, mock_get_vm_snapshots):
        vm = Mock()

        pyvmomi_service = Mock()
        pyvmomi_service.find_by_uuid = Mock(return_value=vm)

        snapshot_restore_command = SnapshotRestoreCommand(pyvmomi_service=pyvmomi_service, task_waiter=Mock())
        si = Mock()

        mock_get_vm_snapshots.return_value = {"snap1": Mock()}

        session = MagicMock()
        session.SetResourceLiveStatus = MagicMock()

        # Act + Assert
        self.assertRaises(
            SnapshotNotFoundException,
            snapshot_restore_command.restore_snapshot,
            si,
            Mock(),
            session,
            "machine1",
            "vm_machine1",
            "NOT_EXISTING_SNAPSHOT",
        )

        session.SetResourceLiveStatus.assert_not_called()
    def test_destroyVirtualMachineCommand(self):
        # arrange
        pv_service = Mock()
        resource_remover = Mock()
        disconnector = Mock()
        si = create_autospec(spec=vim.ServiceInstance)
        resource_name = "this/is the name of the template"
        uuid = "uuid"
        vm = Mock()

        pv_service.destory_mv = Mock(return_value=True)
        disconnector.remove_interfaces_from_vm = Mock(return_value=True)
        resource_remover.remove_resource = Mock(return_value=True)
        pv_service.find_by_uuid = Mock(return_value=vm)

        destroyer = DestroyVirtualMachineCommand(pv_service, resource_remover, disconnector)

        # act
        res = destroyer.destroy(si, uuid, resource_name)

        # assert
        self.assertTrue(res)
        self.assertTrue(pv_service.destory_mv.called_with(vm))
        self.assertTrue(disconnector.remove_interfaces_from_vm.called_with(si, vm))
        self.assertTrue(resource_remover.remove_resource.called_with(resource_name))
        self.assertTrue(pv_service.find_by_uuid.called_with(si, uuid))
    def test_refresh_ip(self):

        resource_model_parser = Mock()

        qualipy_helpers = MagicMock()

        session = MagicMock()

        qualipy_helpers.get_api_session = Mock(return_value=session)

        nic = Mock()
        nic.network = "A Network"
        nic.ipAddress = ["192.168.1.1"]

        guest = Mock()
        guest.net = [nic]

        vm = Mock()
        vm.guest = guest

        pyvmomi_service = Mock()
        pyvmomi_service.find_by_uuid = Mock(return_value=vm)

        refresh_ip_command = RefreshIpCommand(pyvmomi_service, Mock(), qualipy_helpers, resource_model_parser)

        si = Mock()

        # Act
        refresh_ip_command.refresh_ip(si, "1234-5678", "machine1")

        # Assert
        session.UpdateResourceAddress.assert_called_with("machine1", "192.168.1.1")
    def test_power_on(self):
        # arrange
        vm_uuid = "uuid"
        si = Mock(spec=vim.ServiceInstance)
        vm = Mock(spec=vim.VirtualMachine)
        session = Mock()
        pv_service = Mock()
        pv_service.find_by_uuid = Mock(return_value=vm)

        task = Mock()

        vm.PowerOn = Mock(return_value=task)

        synchronous_task_waiter = Mock()
        synchronous_task_waiter.wait_for_task = Mock(return_value=True)

        power_manager = VirtualMachinePowerManagementCommand(pv_service, synchronous_task_waiter)

        # act
        res = power_manager.power_on(si=si, logger=Mock(), session=session, vm_uuid=vm_uuid, resource_fullname=None)

        # assert
        self.assertTrue(res)
        self.assertTrue(synchronous_task_waiter.wait_for_task.called_with(task))
        self.assertTrue(vm.PowerOn.called)
    def test_power_off(self):
        # arrange
        vcenter_name = "vcenter name"
        vm_uuid = "uuid"
        si = Mock(spec=vim.ServiceInstance)
        vm = Mock(spec=vim.VirtualMachine)
        task = Mock()
        pv_service = Mock()
        pv_service.find_by_uuid = Mock(return_value=vm)

        vm.PowerOff = Mock(return_value=task)

        synchronous_task_waiter = Mock()
        synchronous_task_waiter.wait_for_task = Mock(return_value=True)

        power_manager = VirtualMachinePowerManagementCommand(pv_service, synchronous_task_waiter)
        power_manager._connect_to_vcenter = Mock(return_value=si)
        power_manager._get_vm = Mock(return_value=vm)

        # act
        res = power_manager.power_off(si, vm_uuid, None)

        # assert
        self.assertTrue(res)
        self.assertTrue(power_manager._connect_to_vcenter.called_with(vcenter_name))
        self.assertTrue(power_manager._get_vm.called_with(si, vm_uuid))
        self.assertTrue(synchronous_task_waiter.wait_for_task.called_with(task))
        self.assertTrue(vm.PowerOff.called)
    def test_delete_all(self):
        # arrange
        uuid = "uuid"
        si = Mock()
        vm = Mock()

        connection_detail = Mock()
        connection_detail.host = Mock()
        connection_detail.username = Mock()
        connection_detail.password = Mock()
        connection_detail.port = Mock()

        pv_service = Mock()
        pv_service.connect = Mock(return_value=si)
        pv_service.find_by_uuid = Mock(return_value=vm)

        connector = VirtualSwitchToMachineDisconnectCommand(pv_service, Mock(), "anetwork")
        # virtual_switch_to_machine_connector.remove_interfaces_from_vm = Mock(return_value=True)
        connector.get_network_by_name = lambda x, y: Mock()

        vcenter_data_model = VMwarevCenterResourceModel()

        # act
        res = connector.disconnect(
            si=si, logger=Mock(), vcenter_data_model=vcenter_data_model, vm_uuid=uuid, network_name=None, vm=None
        )
        # assert
        self.assertTrue(
            pv_service.connect.called_with(
                connection_detail.host, connection_detail.username, connection_detail.password, connection_detail.port
            )
        )
        self.assertTrue(pv_service.find_by_uuid.called_with(si, uuid))
        # self.assertTrue(virtual_switch_to_machine_connector.remove_interfaces_from_vm.called_with(vm))
        self.assertTrue(res)
    def test_power_off_soft(self):
        # arrange
        vcenter_name = "vcenter name"
        vm_uuid = "uuid"
        session = Mock()
        si = Mock(spec=vim.ServiceInstance)
        vm = Mock(spec=vim.VirtualMachine)
        task = Mock()
        pv_service = Mock()
        pv_service.find_by_uuid = Mock(return_value=vm)

        vm.PowerOff = Mock(return_value=task)

        synchronous_task_waiter = Mock()
        synchronous_task_waiter.wait_for_task = Mock(return_value=True)

        power_manager = VirtualMachinePowerManagementCommand(pv_service, synchronous_task_waiter)
        power_manager._connect_to_vcenter = Mock(return_value=si)
        power_manager._get_vm = Mock(return_value=vm)

        vcenter = Mock()
        vcenter.shutdown_method = "soft"
        # act
        res = power_manager.power_off(
            si=si, logger=Mock(), session=session, vcenter_data_model=vcenter, vm_uuid=vm_uuid, resource_fullname=None
        )

        # assert
        self.assertTrue(res)
        self.assertTrue(vm.ShutdownGuest.called)
        self.assertTrue(power_manager._connect_to_vcenter.called_with(vcenter_name))
        self.assertTrue(power_manager._get_vm.called_with(si, vm_uuid))
        self.assertTrue(synchronous_task_waiter.wait_for_task.called_with(task))
    def test_delete(self):
        # arrange
        uuid = "uuid"
        network_name = "network_name"

        network = Mock()
        network.name = network_name
        si = Mock()
        vm = Mock()
        vm.network = [network]

        connection_detail = Mock()
        connection_detail.host = Mock()
        connection_detail.username = Mock()
        connection_detail.password = Mock()
        connection_detail.port = Mock()

        pv_service = Mock()
        pv_service.connect = Mock(return_value=si)
        pv_service.find_by_uuid = Mock(return_value=vm)

        connector = VirtualSwitchToMachineDisconnectCommand(pv_service, Mock(), "anetwork")

        # act
        res = connector.disconnect(si, uuid, network_name)

        # assert
        self.assertTrue(
            pv_service.connect.called_with(
                connection_detail.host, connection_detail.username, connection_detail.password, connection_detail.port
            )
        )
        self.assertTrue(pv_service.find_by_uuid.called_with(si, uuid))
        self.assertTrue(res)
    def test_refresh_ip_choose_ipv4(self):
        nic1 = Mock()
        nic1.network = "A Network"
        nic1.ipAddress = ["192.168.1.1"]

        nic2 = Mock()
        nic2.network = "A Network"
        nic2.ipAddress = ["2001:0db8:0a0b:12f0:0000:0000:0000:0001"]

        guest = Mock()
        guest.toolsStatus = "toolsOk"
        guest.net = [nic1, nic2]

        vm = Mock()
        vm.guest = guest

        pyvmomi_service = Mock()
        pyvmomi_service.find_by_uuid = Mock(return_value=vm)

        ip_regex = self._create_custom_param("ip_regex", "")
        refresh_ip_timeout = self._create_custom_param("refresh_ip_timeout", "10")

        resource_instance = create_autospec(ResourceInfo)
        resource_instance.ResourceModelName = "Generic Deployed App"
        resource_instance.ResourceAttributes = {"vm_uuis": "123", "cloud_provider": "vCenter"}
        resource_instance.VmDetails = create_autospec(ResourceInfoVmDetails)
        resource_instance.VmDetails.VmCustomParams = [ip_regex, refresh_ip_timeout]

        refresh_ip_command = RefreshIpCommand(pyvmomi_service, ResourceModelParser(), Mock())
        session = Mock()
        session.UpdateResourceAddress = Mock(return_value=True)
        session.GetResourceDetails = Mock(return_value=resource_instance)
        si = Mock()

        center_resource_model = VMwarevCenterResourceModel()
        center_resource_model.default_datacenter = "QualiSB"
        center_resource_model.holding_network = "anetwork"
        cancellation_context = Mock()

        # Act
        refresh_ip_command.refresh_ip(
            si=si,
            session=session,
            vcenter_data_model=center_resource_model,
            vm_uuid="machine1",
            resource_name="default_network",
            cancellation_context=cancellation_context,
            logger=Mock(),
            app_request_json=Mock(),
        )

        # Assert
        self.assertTrue(session.UpdateResourceAddress.called_with("machine1", "192.168.1.1"))
    def test_restore_snapshot_should_success_on_existing_snapshot(self, mock_get_vm_snapshots):
        vm = Mock()

        pyvmomi_service = Mock()
        pyvmomi_service.find_by_uuid = Mock(return_value=vm)

        snapshot_restore_command = RetrieveSnapshotsCommand(pyvmomi_service=pyvmomi_service)
        si = Mock()

        mock_get_vm_snapshots.return_value = {"snap1": Mock()}

        # Act
        snapshots = snapshot_restore_command.get_snapshots(si=si, logger=Mock(), vm_uuid="machine1")

        # Assert
        self.assertSequenceEqual(snapshots, ["snap1"])
    def test_power_on_already(self):
        vm_uuid = "uuid"
        si = Mock(spec=vim.ServiceInstance)
        vm = Mock(spec=vim.VirtualMachine)
        vm.summary = Mock()
        vm.summary.runtime = Mock()
        vm.summary.runtime.powerState = "poweredOn"
        session = Mock()
        pv_service = Mock()
        pv_service.find_by_uuid = Mock(return_value=vm)

        power_manager = VirtualMachinePowerManagementCommand(pv_service, Mock())

        # act
        res = power_manager.power_on(si=si, logger=Mock(), session=session, vm_uuid=vm_uuid, resource_fullname=None)

        # assert
        self.assertTrue(res, "already powered on")
        self.assertFalse(vm.PowerOn.called)
    def test_save_snapshot_should_fail_if_snaphost_exists(self):
        vm = Mock()

        pyvmomi_service = Mock()
        pyvmomi_service.find_by_uuid = Mock(return_value=vm)

        save_snapshot_command = SaveSnapshotCommand(pyvmomi_service, Mock())
        si = Mock()

        with patch(GET_CURRENT_SNAPSHOT_NAME) as get_current_snapshot_name:
            with patch(GET_VM_SNAPSHOTS) as get_vm_snapshots:
                get_current_snapshot_name.return_value = "snapshot1"
                get_vm_snapshots.return_value = {"snapshot1": None, "snapshot1/snapshot2": None}

                # Act + Assert
                with self.assertRaises(SnapshotAlreadyExistsException):
                    save_snapshot_command.save_snapshot(
                        si=si, logger=Mock(), vm_uuid="machine1", snapshot_name="snapshot2"
                    )
    def test_save_snapshot_should_succeed_when_snapshot_with_the_same_name_does_not_exists(self):
        vm = Mock()

        pyvmomi_service = Mock()
        pyvmomi_service.find_by_uuid = Mock(return_value=vm)

        save_snapshot_command = SaveSnapshotCommand(pyvmomi_service, Mock())
        si = Mock()

        # Act
        with patch(GET_CURRENT_SNAPSHOT_NAME) as get_current_snapshot_name:
            with patch(GET_VM_SNAPSHOTS) as get_vm_snapshots:
                get_current_snapshot_name.return_value = "snapshot1/snapshot2"
                get_vm_snapshots.return_value = {"snapshot1/snapshot2": None, "snapshot1": None}
                save_snapshot_command.save_snapshot(
                    si=si, logger=Mock(), vm_uuid="machine1", snapshot_name="new_snapshot"
                )

        # Assert
        vm.CreateSnapshot.called_with("new_snapshot", "Created by CloudShell vCenterShell", False, True)
    def test_destroyVirtualMachineCommand(self):
        # arrange
        pv_service = Mock()
        resource_remover = Mock()
        disconnector = Mock()
        si = create_autospec(spec=vim.ServiceInstance)
        resource_name = "this/is the name of the template"
        uuid = "uuid"
        vm = Mock()

        pv_service.destory_vm = Mock(return_value=True)
        disconnector.remove_interfaces_from_vm = Mock(return_value=True)
        resource_remover.remove_resource = Mock(return_value=True)
        pv_service.find_by_uuid = Mock(return_value=vm)

        reservation_details = Mock()
        reservation_details.ReservationDescription = Mock()
        reservation_details.ReservationDescription.Connectors = []

        session = Mock()
        session.GetReservationDetails = Mock(return_value=reservation_details)
        vcenter_data_model = Mock()
        destroyer = DestroyVirtualMachineCommand(pv_service, resource_remover, disconnector)

        # act
        res = destroyer.destroy(
            si=si,
            logger=Mock(),
            session=session,
            vcenter_data_model=vcenter_data_model,
            vm_uuid=uuid,
            vm_name=resource_name,
            reservation_id="reservation_id",
        )

        # assert
        self.assertTrue(res)
        self.assertTrue(pv_service.destory_vm.called_with(vm))
        self.assertTrue(disconnector.remove_interfaces_from_vm.called_with(si, vm))
        self.assertTrue(resource_remover.remove_resource.called_with(resource_name))
        self.assertTrue(pv_service.find_by_uuid.called_with(si, uuid))