From 7db83e0a973a6deeb3aacadf4d172ee6b30de3ae Mon Sep 17 00:00:00 2001 From: Anthony Poddubny Date: Wed, 5 May 2021 13:35:52 +0300 Subject: [PATCH 1/9] fix 4481 deploy VMs in vCenter inside sandbox folders --- .../cp/vcenter/commands/DeleteInstance.py | 43 +++++- .../vcenter/commands/command_orchestrator.py | 36 ++++- cloudshell/cp/vcenter/commands/deploy_vm.py | 129 +++++++++++++++--- cloudshell/cp/vcenter/common/model_factory.py | 2 + .../vcenter/common/vcenter/folder_manager.py | 22 +++ cloudshell/cp/vcenter/constants.py | 8 ++ .../models/GenericDeployedAppResourceModel.py | 2 + tests/test_commands/test_DeleteInstance.py | 22 ++- .../test_command_orchestrator.py | 38 +++++- tests/test_commands/test_deploy_vm.py | 8 +- version.txt | 2 +- 11 files changed, 269 insertions(+), 43 deletions(-) diff --git a/cloudshell/cp/vcenter/commands/DeleteInstance.py b/cloudshell/cp/vcenter/commands/DeleteInstance.py index e638407..4cdbab0 100644 --- a/cloudshell/cp/vcenter/commands/DeleteInstance.py +++ b/cloudshell/cp/vcenter/commands/DeleteInstance.py @@ -1,20 +1,23 @@ from cloudshell.api.cloudshell_api import CloudShellAPISession + +from cloudshell.cp.vcenter import constants from cloudshell.cp.vcenter.common.utilites.common_utils import ( get_error_message_from_exception, ) -from cloudshell.cp.vcenter.constants import VM_CUSTOMIZATION_SPEC_CUSTOM_PARAM +from cloudshell.cp.vcenter.common.vcenter.vm_location import VMLocation class DestroyVirtualMachineCommand(object): """ Command to Destroy a VM """ - def __init__(self, pv_service, resource_remover, disconnector): + def __init__(self, pv_service, folder_manager, resource_remover, disconnector): """ :param pv_service: pv_service Instance :type pv_service: cloudshell.cp.vcenter.common.vcenter.vmomi_service.pyVmomiService :param resource_remover: CloudshellResourceRemover """ self.pv_service = pv_service + self.folder_manager = folder_manager self.resource_remover = resource_remover self.disconnector = disconnector @@ -63,15 +66,28 @@ def destroy( ) return result - def DeleteInstance(self, si, logger, session, vcenter_data_model, resource_model): + def DeleteInstance( + self, + si, + logger, + session, + vcenter_data_model, + reservation_id, + resource_model, + ): """ + + :param si: :param logger: - :param CloudShellAPISession session: + :param session: + :param vcenter_data_model: + :param reservation_id: :param resource_model: :return: """ # find vm vm = self.pv_service.find_by_uuid(si, resource_model.vm_uuid) + if vm is not None: # destroy vm result = self.pv_service.destroy_vm(vm=vm, logger=logger) @@ -86,12 +102,29 @@ def DeleteInstance(self, si, logger, session, vcenter_data_model, resource_model vm_customization_spec = self._get_custom_param( params=resource_model.vm_custom_params, - name=VM_CUSTOMIZATION_SPEC_CUSTOM_PARAM, + name=constants.VM_CUSTOMIZATION_SPEC_CUSTOM_PARAM, ) if vm_customization_spec: self.pv_service.delete_customization_spec(si=si, name=vm_customization_spec) + vm_folder_path = VMLocation.combine( + [ + resource_model.app_request_model.vm_location + or vcenter_data_model.vm_location, + constants.DEPLOYED_APPS_FOLDER, + reservation_id, + ] + ) + + self.folder_manager.delete_folder_if_empty( + si=si, + folder_full_path=VMLocation.combine( + [vcenter_data_model.default_datacenter, vm_folder_path] + ), + logger=logger, + ) + return result @staticmethod diff --git a/cloudshell/cp/vcenter/commands/command_orchestrator.py b/cloudshell/cp/vcenter/commands/command_orchestrator.py index 989b707..7db0102 100644 --- a/cloudshell/cp/vcenter/commands/command_orchestrator.py +++ b/cloudshell/cp/vcenter/commands/command_orchestrator.py @@ -5,6 +5,7 @@ from cloudshell.cp.core.models import DeployApp, DeployAppResult, SaveApp, SaveAppResult from pyVim.connect import Disconnect, SmartConnect +from cloudshell.cp.vcenter import constants from cloudshell.cp.vcenter.commands.cluster_usage import GetClusterUsageCommand from cloudshell.cp.vcenter.commands.connect_dvswitch import VirtualSwitchConnectCommand from cloudshell.cp.vcenter.commands.connect_orchestrator import ( @@ -123,6 +124,13 @@ def __init__(self): resource_remover = CloudshellResourceRemover() ovf_service = OvfImageDeployerService(self.resource_model_parser) + self.deployment_path_map = { + constants.VM_FROM_VM_DEPLOYMENT_PATH: vCenterCloneVMFromVMResourceModel, + constants.VM_FROM_TEMPLATE_DEPLOYMENT_PATH: vCenterVMFromTemplateResourceModel, + constants.VM_FROM_LINKED_CLONE_DEPLOYMENT_PATH: VCenterDeployVMFromLinkedCloneResourceModel, + constants.VM_FROM_IMAGE_DEPLOYMENT_PATH: vCenterVMFromImageResourceModel, + } + self.vm_loader = VMLoader(pv_service) self.cluster_usage_command = GetClusterUsageCommand(pv_service) @@ -195,6 +203,7 @@ def __init__(self): # Destroy VM Command self.destroy_virtual_machine_command = DestroyVirtualMachineCommand( pv_service=pv_service, + folder_manager=self.folder_manager, resource_remover=resource_remover, disconnector=self.virtual_switch_disconnect_command, ) @@ -576,14 +585,37 @@ def _parse_remote_model(self, context): ) resource = context.remote_endpoints[0] - dictionary = jsonpickle.decode(resource.app_context.deployed_app_json) - holder = DeployDataHolder(dictionary) + deployed_app = jsonpickle.decode(resource.app_context.deployed_app_json) + app_request = jsonpickle.decode(resource.app_context.app_request_json) + + holder = DeployDataHolder(deployed_app) app_resource_detail = GenericDeployedAppResourceModel() app_resource_detail.vm_uuid = holder.vmdetails.uid app_resource_detail.cloud_provider = context.resource.fullname app_resource_detail.fullname = resource.fullname + app_resource_detail.deployment_path = app_request["deploymentService"]["model"] + + if app_resource_detail.deployment_path not in self.deployment_path_map: + raise Exception( + f"Invalid deployment path '{app_resource_detail.deployment_path}'. " + f"Possible values are: {self.deployment_path_map.keys()}" + ) + + app_resource_detail.app_request_model = ( + self.resource_model_parser.convert_to_resource_model( + attributes={ + attribute["name"]: attribute["value"] + for attribute in app_request["deploymentService"]["attributes"] + }, + resource_model_type=self.deployment_path_map[ + app_resource_detail.deployment_path + ], + ) + ) + if hasattr(holder.vmdetails, "vmCustomParams"): app_resource_detail.vm_custom_params = holder.vmdetails.vmCustomParams + return app_resource_detail def power_on_not_roemote(self, context, vm_uuid, resource_fullname): diff --git a/cloudshell/cp/vcenter/commands/deploy_vm.py b/cloudshell/cp/vcenter/commands/deploy_vm.py index b42fd41..4bd1277 100644 --- a/cloudshell/cp/vcenter/commands/deploy_vm.py +++ b/cloudshell/cp/vcenter/commands/deploy_vm.py @@ -3,12 +3,11 @@ from os.path import normpath from cloudshell.cp.vcenter.common.vcenter.vm_location import VMLocation +from cloudshell.cp.vcenter.constants import DEPLOYED_APPS_FOLDER from cloudshell.cp.vcenter.models.DeployFromTemplateDetails import ( DeployFromTemplateDetails, ) -DEPLOYED_APPS = "Deployed Apps" - class DeployCommand(object): """ Command to Create a VM from a template """ @@ -43,7 +42,12 @@ def execute_deploy_from_linked_clone( :return: """ self._prepare_deployed_apps_folder( - deployment_params, si, logger, folder_manager, vcenter_data_model + deployment_params, + si, + logger, + folder_manager, + vcenter_data_model, + reservation_id, ) deploy_result = self.deployer.deploy_from_linked_clone( @@ -81,7 +85,12 @@ def execute_deploy_clone_from_vm( :return: """ self._prepare_deployed_apps_folder( - deployment_params, si, logger, folder_manager, vcenter_data_model + deployment_params, + si, + logger, + folder_manager, + vcenter_data_model, + reservation_id, ) deploy_result = self.deployer.deploy_clone_from_vm( si, @@ -96,33 +105,77 @@ def execute_deploy_clone_from_vm( return deploy_result def _prepare_deployed_apps_folder( - self, data_holder, si, logger, folder_manager, vcenter_resource_model + self, + data_holder, + si, + logger, + folder_manager, + vcenter_resource_model, + reservation_id, ): if isinstance(data_holder, DeployFromImageDetails): self._update_deploy_from_image_vm_location( - data_holder, folder_manager, logger, si, vcenter_resource_model + data_holder, + folder_manager, + logger, + si, + vcenter_resource_model, + reservation_id, ) else: self._update_deploy_from_template_vm_location( - data_holder, folder_manager, logger, si, vcenter_resource_model + data_holder, + folder_manager, + logger, + si, + vcenter_resource_model, + reservation_id, ) def _update_deploy_from_template_vm_location( - self, data_holder, folder_manager, logger, si, vcenter_resource_model + self, + data_holder, + folder_manager, + logger, + si, + vcenter_resource_model, + reservation_id, ): vm_location = ( data_holder.template_resource_model.vm_location or vcenter_resource_model.vm_location ) - folder_path = VMLocation.combine( - [vcenter_resource_model.default_datacenter, vm_location] + + folder_manager.get_or_create_vcenter_folder( + si=si, + logger=logger, + path=VMLocation.combine( + [vcenter_resource_model.default_datacenter, vm_location] + ), + folder_name=DEPLOYED_APPS_FOLDER, ) + folder_manager.get_or_create_vcenter_folder( - si, logger, folder_path, DEPLOYED_APPS + si=si, + logger=logger, + path=VMLocation.combine( + [ + vcenter_resource_model.default_datacenter, + vm_location, + DEPLOYED_APPS_FOLDER, + ] + ), + folder_name=reservation_id, ) + data_holder.template_resource_model.vm_location = VMLocation.combine( - [vm_location, DEPLOYED_APPS] + [ + vm_location, + DEPLOYED_APPS_FOLDER, + reservation_id, + ] ) + logger.info( "VM will be deployed to {0}".format( data_holder.template_resource_model.vm_location @@ -130,20 +183,48 @@ def _update_deploy_from_template_vm_location( ) def _update_deploy_from_image_vm_location( - self, data_holder, folder_manager, logger, si, vcenter_resource_model + self, + data_holder, + folder_manager, + logger, + si, + vcenter_resource_model, + reservation_id, ): vm_location = ( data_holder.image_params.vm_location or vcenter_resource_model.vm_location ) - folder_path = VMLocation.combine( - [vcenter_resource_model.default_datacenter, vm_location] + + folder_manager.get_or_create_vcenter_folder( + si=si, + logger=logger, + path=VMLocation.combine( + [vcenter_resource_model.default_datacenter, vm_location] + ), + folder_name=DEPLOYED_APPS_FOLDER, ) + folder_manager.get_or_create_vcenter_folder( - si, logger, folder_path, DEPLOYED_APPS + si=si, + logger=logger, + path=VMLocation.combine( + [ + vcenter_resource_model.default_datacenter, + vm_location, + DEPLOYED_APPS_FOLDER, + ] + ), + folder_name=reservation_id, ) + data_holder.image_params.vm_location = VMLocation.combine( - [vm_location, DEPLOYED_APPS] + [ + vm_location, + DEPLOYED_APPS_FOLDER, + reservation_id, + ] ) + logger.info( "VM will be deployed to {0}".format(data_holder.image_params.vm_location) ) @@ -170,7 +251,12 @@ def execute_deploy_from_template( :return: """ self._prepare_deployed_apps_folder( - deployment_params, si, logger, folder_manager, vcenter_data_model + deployment_params, + si, + logger, + folder_manager, + vcenter_data_model, + reservation_id, ) deploy_result = self.deployer.deploy_from_template( @@ -210,7 +296,12 @@ def execute_deploy_from_image( :return: """ self._prepare_deployed_apps_folder( - deployment_params, si, logger, folder_manager, vcenter_data_model + deployment_params, + si, + logger, + folder_manager, + vcenter_data_model, + reservation_id, ) deploy_result = self.deployer.deploy_from_image( diff --git a/cloudshell/cp/vcenter/common/model_factory.py b/cloudshell/cp/vcenter/common/model_factory.py index 4d57596..648d8d8 100644 --- a/cloudshell/cp/vcenter/common/model_factory.py +++ b/cloudshell/cp/vcenter/common/model_factory.py @@ -246,6 +246,8 @@ def get_property_name_from_attribute_name(attribute): attribute_name = attribute elif hasattr(attribute, "Name"): attribute_name = attribute.Name + elif hasattr(attribute, "name"): + attribute_name = attribute.name else: raise Exception( "Attribute type {0} is not supported".format(str(type(attribute))) diff --git a/cloudshell/cp/vcenter/common/vcenter/folder_manager.py b/cloudshell/cp/vcenter/common/vcenter/folder_manager.py index 6b6c11e..d79d036 100644 --- a/cloudshell/cp/vcenter/common/vcenter/folder_manager.py +++ b/cloudshell/cp/vcenter/common/vcenter/folder_manager.py @@ -13,6 +13,28 @@ def __init__(self, pv_service, task_waiter): self.locks_lock = Lock() self.task_waiter = task_waiter + def delete_folder_if_empty(self, si, folder_full_path, logger): + logger.info(f"Trying to remove folder '{folder_full_path}' if it's empty ...") + folder = self.pv_service.get_folder(si, folder_full_path) + + if not folder: + logger.warning(f"Could not find folder '{folder_full_path}' to delete") + return + + if folder_full_path not in list(self.locks.keys()): + with self.locks_lock: + if folder_full_path not in list(self.locks.keys()): + self.locks[folder_full_path] = Lock() + + with self.locks[folder_full_path]: + if not folder.childEntity: + result = self.delete_folder(folder, logger) + logger.info(f"Remove result for folder '{folder_full_path}':\n{result}") + else: + logger.info( + f"Skip folder '{folder_full_path}' deletion. It contains objects: {folder.childEntity}" + ) + def delete_folder_with_vm_power_off(self, si, logger, folder_full_path): logger.info( "Trying to remove {0} and all child folders and vms".format( diff --git a/cloudshell/cp/vcenter/constants.py b/cloudshell/cp/vcenter/constants.py index 7252074..aed47f1 100644 --- a/cloudshell/cp/vcenter/constants.py +++ b/cloudshell/cp/vcenter/constants.py @@ -1 +1,9 @@ +SHELL_NAME = "VMware vCenter Cloud Provider 2G" + +VM_FROM_VM_DEPLOYMENT_PATH = f"{SHELL_NAME}.vCenter VM From VM 2G" +VM_FROM_TEMPLATE_DEPLOYMENT_PATH = f"{SHELL_NAME}.vCenter VM From Template 2G" +VM_FROM_LINKED_CLONE_DEPLOYMENT_PATH = f"{SHELL_NAME}.vCenter VM From Linked Clone 2G" +VM_FROM_IMAGE_DEPLOYMENT_PATH = f"{SHELL_NAME}.vCenter VM From Image 2G" + +DEPLOYED_APPS_FOLDER = "Deployed Apps" VM_CUSTOMIZATION_SPEC_CUSTOM_PARAM = "vm_customization_spec" diff --git a/cloudshell/cp/vcenter/models/GenericDeployedAppResourceModel.py b/cloudshell/cp/vcenter/models/GenericDeployedAppResourceModel.py index cc05ffe..37e61b7 100644 --- a/cloudshell/cp/vcenter/models/GenericDeployedAppResourceModel.py +++ b/cloudshell/cp/vcenter/models/GenericDeployedAppResourceModel.py @@ -3,4 +3,6 @@ def __init__(self): self.vm_uuid = "" self.cloud_provider = "" self.fullname = "" + self.deployment_path = "" self.vm_custom_params = None + self.app_request_model = None diff --git a/tests/test_commands/test_DeleteInstance.py b/tests/test_commands/test_DeleteInstance.py index ce1ba61..2f1e35e 100644 --- a/tests/test_commands/test_DeleteInstance.py +++ b/tests/test_commands/test_DeleteInstance.py @@ -10,6 +10,7 @@ class TestDestroyVirtualMachineCommand(unittest.TestCase): def test_destroyVirtualMachineCommand(self): # arrange pv_service = Mock() + folder_manager = Mock() resource_remover = Mock() disconnector = Mock() si = create_autospec(spec=vim.ServiceInstance) @@ -30,7 +31,7 @@ def test_destroyVirtualMachineCommand(self): session.GetReservationDetails = Mock(return_value=reservation_details) vcenter_data_model = Mock() destroyer = DestroyVirtualMachineCommand( - pv_service, resource_remover, disconnector + pv_service, folder_manager, resource_remover, disconnector ) # act @@ -56,6 +57,7 @@ def test_destroyVirtualMachineCommandDeletesResourceWhenTheVMActualllyRemovedInV ): # arrange pv_service = Mock() + folder_manager = Mock() resource_remover = Mock() disconnector = Mock() si = create_autospec(spec=vim.ServiceInstance) @@ -76,7 +78,7 @@ def test_destroyVirtualMachineCommandDeletesResourceWhenTheVMActualllyRemovedInV session.GetReservationDetails = Mock(return_value=reservation_details) vcenter_data_model = Mock() destroyer = DestroyVirtualMachineCommand( - pv_service, resource_remover, disconnector + pv_service, folder_manager, resource_remover, disconnector ) # act @@ -100,14 +102,17 @@ def test_destroyVirtualMachineCommandDeletesResourceWhenTheVMActualllyRemovedInV def test_destroyVirtualMachineOnlyCommand(self): # arrange pv_service = Mock() + folder_manager = 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() + resource_model = MagicMock() - resource_model.vm_uuid = uuid + resource_model.vm_uuid = "uuid" + resource_model.fullname = "this/is the name of the template" + resource_model.app_request_model.vm_location = "vm folder" + reservation_id = "9e5b7004-e62e-4a8d-be1a-96bd1e58cb13" pv_service.destory_mv = Mock(return_value=True) disconnector.remove_interfaces_from_vm = Mock(return_value=True) @@ -121,8 +126,10 @@ def test_destroyVirtualMachineOnlyCommand(self): session = Mock() session.GetReservationDetails = Mock(return_value=reservation_details) vcenter_data_model = Mock() + vcenter_data_model.default_datacenter = "Default Datacenter" + destroyer = DestroyVirtualMachineCommand( - pv_service, resource_remover, disconnector + pv_service, folder_manager, resource_remover, disconnector ) # act @@ -131,6 +138,7 @@ def test_destroyVirtualMachineOnlyCommand(self): logger=Mock(), session=session, vcenter_data_model=vcenter_data_model, + reservation_id=reservation_id, resource_model=resource_model, ) @@ -138,4 +146,4 @@ def test_destroyVirtualMachineOnlyCommand(self): 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(pv_service.find_by_uuid.called_with(si, uuid)) + self.assertTrue(pv_service.find_by_uuid.called_with(si, resource_model.vm_uuid)) diff --git a/tests/test_commands/test_command_orchestrator.py b/tests/test_commands/test_command_orchestrator.py index 0321604..d2c1835 100644 --- a/tests/test_commands/test_command_orchestrator.py +++ b/tests/test_commands/test_command_orchestrator.py @@ -1,3 +1,4 @@ +import json from unittest import TestCase import jsonpickle @@ -242,8 +243,21 @@ def test_orchestration_save_double_quotes_in_snapshot_name_should_be_stripped(se endpoint = create_autospec(ResourceContextDetails) endpoint.fullname = "vm_111" endpoint.app_context = create_autospec(AppContext) - endpoint.app_context.deployed_app_json = ( - '{"vmdetails": {"uid": "vm_uuid1"}}' + endpoint.app_context.deployed_app_json = json.dumps( + {"vmdetails": {"uid": "vm_uuid1"}} + ) + endpoint.app_context.app_request_json = json.dumps( + { + "deploymentService": { + "model": "VMware vCenter Cloud Provider 2G.vCenter VM From Linked Clone 2G", + "attributes": list( + map( + lambda items: {"name": items[0], "value": items[1]}, + self.deploy_action.actionParams.deployment.attributes.items(), + ) + ), + } + } ) remote_command_context.remote_endpoints = [endpoint] @@ -279,16 +293,30 @@ def test_orchestration_save_snapshot_name_should_contain_full_datetime(self): # Arrange with patch(SAVE_SNAPSHOT) as save_snapshot_mock: save_snapshot_mock.return_value = '"new_snapshot"' - + deploy_attributes = [] remote_command_context = create_autospec(ResourceRemoteCommandContext) remote_command_context.resource = create_autospec(ResourceContextDetails) remote_command_context.resource.fullname = "vcenter" endpoint = create_autospec(ResourceContextDetails) endpoint.fullname = "vm_111" endpoint.app_context = create_autospec(AppContext) - endpoint.app_context.deployed_app_json = ( - '{"vmdetails": {"uid": "vm_uuid1"}}' + endpoint.app_context.deployed_app_json = json.dumps( + {"vmdetails": {"uid": "vm_uuid1"}} ) + endpoint.app_context.app_request_json = json.dumps( + { + "deploymentService": { + "model": "VMware vCenter Cloud Provider 2G.vCenter VM From Linked Clone 2G", + "attributes": list( + map( + lambda items: {"name": items[0], "value": items[1]}, + self.deploy_action.actionParams.deployment.attributes.items(), + ) + ), + } + } + ) + remote_command_context.remote_endpoints = [endpoint] # Act diff --git a/tests/test_commands/test_deploy_vm.py b/tests/test_commands/test_deploy_vm.py index 24268dd..988c692 100644 --- a/tests/test_commands/test_deploy_vm.py +++ b/tests/test_commands/test_deploy_vm.py @@ -44,7 +44,7 @@ def test_deploy_execute(self): vcenter_data_model = Mock() vcenter_data_model.default_datacenter = "QualiSB" vcenter_data_model.vm_location = "TargetFolder" - reservation_id = Mock() + reservation_id = "4228128c-fb7e-9b0e-60b8-c3fabd3c624e" cancellation_context = object() # act @@ -86,7 +86,7 @@ def test_deploy_image_execute(self): vcenter_data_model = Mock() vcenter_data_model.default_datacenter = "QualiSB" logger = Mock() - reservation_id = Mock() + reservation_id = "4228128c-fb7e-9b0e-60b8-c3fabd3c624e" deploy_command = DeployCommand(deployer) cancellation_context = object() @@ -133,7 +133,7 @@ def test_deploy_clone_execute(self): template_model.vm_folder = "temp folder" deployer.deploy_from_template = Mock(return_value=deploy_res) - reservation_id = Mock() + reservation_id = "4228128c-fb7e-9b0e-60b8-c3fabd3c624e" logger = Mock() session = Mock() app_resource_model = Mock() @@ -207,7 +207,7 @@ def test_deploy_snapshot_execute(self): vcenter_data_model = Mock() vcenter_data_model.default_datacenter = "QualiSB" vcenter_data_model.vm_location = "TargetFolder" - reservation_id = Mock() + reservation_id = "4228128c-fb7e-9b0e-60b8-c3fabd3c624e" cancellation_context = object() session = Mock() app_resource_model = Mock() diff --git a/version.txt b/version.txt index a0cd9f0..a4f52a5 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -3.1.0 \ No newline at end of file +3.2.0 \ No newline at end of file From fc55ffab4c66fcbbe5cf909d9644b807c5f7834b Mon Sep 17 00:00:00 2001 From: Anthony Poddubny Date: Fri, 30 Apr 2021 12:38:58 +0300 Subject: [PATCH 2/9] fix Save Sandbox App command --- .../vcenter/commands/command_orchestrator.py | 2 + .../vcenter/commands/delete_saved_sandbox.py | 36 ++----------- .../cp/vcenter/commands/save_sandbox.py | 51 +++---------------- .../common/utilites/savers/artifact_saver.py | 44 +++++++--------- .../savers/linked_clone_artifact_saver.py | 11 ++++ version.txt | 2 +- 6 files changed, 44 insertions(+), 102 deletions(-) diff --git a/cloudshell/cp/vcenter/commands/command_orchestrator.py b/cloudshell/cp/vcenter/commands/command_orchestrator.py index 989b707..9c07817 100644 --- a/cloudshell/cp/vcenter/commands/command_orchestrator.py +++ b/cloudshell/cp/vcenter/commands/command_orchestrator.py @@ -281,6 +281,7 @@ def save_sandbox(self, context, save_actions, cancellation_context): connection = self.command_wrapper.execute_command_with_connection( context, self.save_app_command.save_app, + AppResourceModel(), save_actions, cancellation_context, ) @@ -299,6 +300,7 @@ def delete_saved_sandbox(self, context, delete_saved_apps, cancellation_context) context, self.delete_saved_sandbox_command.delete_sandbox, delete_saved_apps, + AppResourceModel(), cancellation_context, ) delete_saved_apps_results = connection diff --git a/cloudshell/cp/vcenter/commands/delete_saved_sandbox.py b/cloudshell/cp/vcenter/commands/delete_saved_sandbox.py index 955672e..93ed54f 100644 --- a/cloudshell/cp/vcenter/commands/delete_saved_sandbox.py +++ b/cloudshell/cp/vcenter/commands/delete_saved_sandbox.py @@ -5,10 +5,7 @@ from cloudshell.cp.core.models import ActionResultBase -from cloudshell.cp.vcenter.common.utilites.savers.artifact_saver import ( - ArtifactHandler, - UnsupportedArtifactHandler, -) +from cloudshell.cp.vcenter.common.utilites.savers.artifact_saver import ArtifactHandler from cloudshell.cp.vcenter.common.vcenter.task_waiter import SynchronousTaskWaiter from cloudshell.cp.vcenter.common.vcenter.vmomi_service import pyVmomiService @@ -49,8 +46,10 @@ def delete_sandbox( self, si, logger, + session, vcenter_data_model, delete_sandbox_actions, + app_resource_model, cancellation_context, ): """ @@ -84,6 +83,8 @@ def delete_sandbox( vcenter_data_model, si, logger, + session, + app_resource_model, self.deployer, None, self.resource_model_parser, @@ -96,10 +97,6 @@ def delete_sandbox( for k, g in actions_grouped_by_save_types } - self._validate_save_deployment_models( - artifactHandlersToActions, delete_sandbox_actions, results - ) - error_results = [r for r in results if not r.success] if not error_results: results = self._execute_delete_saved_sandbox( @@ -108,29 +105,6 @@ def delete_sandbox( return results - def _validate_save_deployment_models( - self, artifactHandlersToActions, delete_sandbox_actions, results - ): - unsupported_save_deployment_models = [ - a.unsupported_save_type - for a in list(artifactHandlersToActions.keys()) - if isinstance(a, UnsupportedArtifactHandler) - ] - if unsupported_save_deployment_models: - for action in delete_sandbox_actions: - unsupported_msg = "Unsupported save deployment models: {0}".format( - ", ".join(unsupported_save_deployment_models) - ) - results.append( - ActionResultBase( - type="DeleteSavedAppResult", - actionId=action.actionId, - success=False, - infoMessage=unsupported_msg, - errorMessage=unsupported_msg, - ) - ) - def _execute_delete_saved_sandbox( self, artifactHandlersToActions, cancellation_context, logger, results ): diff --git a/cloudshell/cp/vcenter/commands/save_sandbox.py b/cloudshell/cp/vcenter/commands/save_sandbox.py index 2a3e9d2..f82bb9f 100644 --- a/cloudshell/cp/vcenter/commands/save_sandbox.py +++ b/cloudshell/cp/vcenter/commands/save_sandbox.py @@ -8,10 +8,7 @@ from cloudshell.cp.core.models import SaveApp, SaveAppResult -from cloudshell.cp.vcenter.common.utilites.savers.artifact_saver import ( - ArtifactHandler, - UnsupportedArtifactHandler, -) +from cloudshell.cp.vcenter.common.utilites.savers.artifact_saver import ArtifactHandler from cloudshell.cp.vcenter.common.vcenter.task_waiter import SynchronousTaskWaiter from cloudshell.cp.vcenter.common.vcenter.vmomi_service import pyVmomiService @@ -51,8 +48,10 @@ def save_app( self, si, logger, + session, vcenter_data_model, reservation_id, + app_resource_model, save_app_actions, cancellation_context, ): @@ -89,6 +88,8 @@ def save_app( vcenter_data_model, si, logger, + session, + app_resource_model, self.deployer, reservation_id, self.resource_model_parser, @@ -101,10 +102,6 @@ def save_app( for k, g in actions_grouped_by_save_types } - self.validate_requested_save_types_supported( - artifactSaversToActions, logger, results - ) - error_results = [r for r in results if not r.success] if not error_results: logger.info("Handling Save App requests") @@ -199,6 +196,7 @@ def _save(self, save_params): logger.exception("Save app action {0} failed".format(action.actionId)) return SaveAppResult( action.actionId, + saveDeploymentModel=artifactSaver.save_deployment_model, success=False, errorMessage=str(ex), infoMessage="\n".join(traceback.format_exception(ex_type, ex, tb)), @@ -209,43 +207,8 @@ def _destroy(self, destroy_params): artifactSaver.destroy(save_action=action) return SaveAppResult( action.actionId, + saveDeploymentModel=artifactSaver.save_deployment_model, success=False, errorMessage="Save app action {0} was rolled back".format(action.actionId), infoMessage="", ) - - def validate_requested_save_types_supported( - self, artifactSaversToActions, logger, results - ): - unsupported_savers = [ - saver - for saver in list(artifactSaversToActions.keys()) - if isinstance(saver, UnsupportedArtifactHandler) - ] - if unsupported_savers: - log_error_message = ( - "Unsupported save type was included in save app request: {0}".format( - ", ".join( - {saver.unsupported_save_type for saver in unsupported_savers} - ) - ) - ) - logger.error(log_error_message) - - for artifactSaver in list(artifactSaversToActions.keys()): - if artifactSaver in unsupported_savers: - result_error_message = ( - "Unsupported save type " + artifactSaver.unsupported_save_type - ) - else: - result_error_message = "" - - save_actions = artifactSaversToActions[artifactSaver] - for action in save_actions: - results.append( - SaveAppResult( - action.actionId, - success=False, - errorMessage=result_error_message, - ) - ) diff --git a/cloudshell/cp/vcenter/common/utilites/savers/artifact_saver.py b/cloudshell/cp/vcenter/common/utilites/savers/artifact_saver.py index cc94e61..5e97c7d 100644 --- a/cloudshell/cp/vcenter/common/utilites/savers/artifact_saver.py +++ b/cloudshell/cp/vcenter/common/utilites/savers/artifact_saver.py @@ -4,11 +4,6 @@ class ArtifactHandler(object): - ALLOWED_DEPLOYMENT_PATHS = [ - "VCenter Deploy VM From Linked Clone", - "VMware vCenter Cloud Provider 2G." "vCenter VM From Linked Clone 2G", - ] - @staticmethod def factory( saveDeploymentModel, @@ -16,6 +11,8 @@ def factory( vcenter_data_model, si, logger, + session, + app_resource_model, deployer, reservation_id, resource_model_parser, @@ -25,24 +22,19 @@ def factory( port_configurer, cancellation_service, ): - if saveDeploymentModel in ArtifactHandler.ALLOWED_DEPLOYMENT_PATHS: - return LinkedCloneArtifactHandler( - pv_service, - vcenter_data_model, - si, - logger, - deployer, - reservation_id, - resource_model_parser, - snapshot_saver, - task_waiter, - folder_manager, - port_configurer, - cancellation_service, - ) - return UnsupportedArtifactHandler(saveDeploymentModel) - - -class UnsupportedArtifactHandler(object): - def __init__(self, saveDeploymentModel): - self.unsupported_save_type = saveDeploymentModel + return LinkedCloneArtifactHandler( + pv_service, + vcenter_data_model, + si, + logger, + session, + app_resource_model, + deployer, + reservation_id, + resource_model_parser, + snapshot_saver, + task_waiter, + folder_manager, + port_configurer, + cancellation_service, + ) diff --git a/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py b/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py index 37d937a..1bfa868 100644 --- a/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py +++ b/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py @@ -21,6 +21,9 @@ from cloudshell.cp.vcenter.vm.vcenter_details_factory import VCenterDetailsFactory SAVED_SANDBOXES = "Saved Sandboxes" +VM_FROM_LINKED_CLONE_DEPLOYMENT_PATH = ( + "VMware vCenter Cloud Provider 2G.vCenter VM From Linked Clone 2G" +) class LinkedCloneArtifactHandler(object): @@ -30,6 +33,8 @@ def __init__( vcenter_data_model, si, logger, + session, + app_resource_model, deployer, reservation_id, resource_model_parser, @@ -46,6 +51,8 @@ def __init__( self.vcenter_data_model = vcenter_data_model self.si = si self.logger = logger + self.session = session + self.app_resource_model = app_resource_model self.deployer = deployer self.reservation_id = reservation_id self.snapshot_saver = snapshot_saver @@ -54,6 +61,7 @@ def __init__( self.folder_manager = folder_manager self.pg_configurer = port_configurer self.cs = cancellation_service + self.save_deployment_model = VM_FROM_LINKED_CLONE_DEPLOYMENT_PATH def save(self, save_action, cancellation_context): thread_id = threading.current_thread().ident @@ -91,7 +99,9 @@ def save(self, save_action, cancellation_context): result = self.deployer.deploy_clone_from_vm( self.si, self.logger, + self.session, data_holder, + self.app_resource_model, self.vcenter_data_model, self.reservation_id, cancellation_context, @@ -142,6 +152,7 @@ def save(self, save_action, cancellation_context): True, artifacts=[save_artifact], savedEntityAttributes=saved_entity_attributes, + saveDeploymentModel=self.save_deployment_model, ) def _get_saved_app_result_vcenter_vm_path(self, data_holder, result): diff --git a/version.txt b/version.txt index a0cd9f0..94ff29c 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -3.1.0 \ No newline at end of file +3.1.1 From e644354553a1bee35ccd2739f2870cf2772857dc Mon Sep 17 00:00:00 2001 From: Costya Date: Mon, 24 May 2021 14:18:09 +0300 Subject: [PATCH 3/9] Added ATTRIBUTES_TO_IGNORE list that should be empty during sandbox restore --- .../utilites/savers/linked_clone_artifact_saver.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py b/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py index 1bfa868..1d4acff 100644 --- a/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py +++ b/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py @@ -1,6 +1,5 @@ import threading from contextlib import contextmanager -from itertools import groupby from threading import Lock from cloudshell.cp.core.models import ( @@ -24,6 +23,14 @@ VM_FROM_LINKED_CLONE_DEPLOYMENT_PATH = ( "VMware vCenter Cloud Provider 2G.vCenter VM From Linked Clone 2G" ) +ATTRIBUTES_TO_IGNORE = [ + Attribute("Customization Spec", ""), + Attribute("Private IP", ""), + Attribute("CPU", ""), + Attribute("RAM", ""), + Attribute("Hostname", ""), + Attribute("HDD", ""), + ] class LinkedCloneArtifactHandler(object): @@ -140,6 +147,7 @@ def save(self, save_action, cancellation_context): Attribute("vCenter VM", vcenter_vm_path), Attribute("vCenter VM Snapshot", self.SNAPSHOT_NAME), ] + saved_entity_attributes.extend(ATTRIBUTES_TO_IGNORE) self.logger.info( "[{1}] Save Action using source type: Linked Clone Successful. Saved Sandbox App with snapshot created: {0}".format( From de11e5a92c855a8bcd8862f259eb8717e4e14311 Mon Sep 17 00:00:00 2001 From: Costya Date: Mon, 24 May 2021 14:24:25 +0300 Subject: [PATCH 4/9] fixed requirements and version --- requirements.txt | 2 +- version.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/requirements.txt b/requirements.txt index 76e3af5..158a213 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,7 +7,7 @@ pyvmomi==6.5.0 jsonpickle==0.9.3 enum34==1.1.6 retrying==1.3.3 -cloudshell-cp-core>=1.1.0,<1.2.0 +cloudshell-cp-core>=1.2.0,<1.3.0 cloudshell-logging>=1.0.0,<1.1.0 cryptography>=2.5,<3.3 pyOpenSSL<20.0.0 diff --git a/version.txt b/version.txt index 6ebad14..a6d5334 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -3.1.2 \ No newline at end of file +3.2.0 From faa604712f3479acfc9e1f3b35a5e1ceaa790f82 Mon Sep 17 00:00:00 2001 From: Costya Date: Mon, 24 May 2021 18:15:35 +0300 Subject: [PATCH 5/9] fix black --- .../utilites/savers/linked_clone_artifact_saver.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py b/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py index 1d4acff..35cebc9 100644 --- a/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py +++ b/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py @@ -24,13 +24,13 @@ "VMware vCenter Cloud Provider 2G.vCenter VM From Linked Clone 2G" ) ATTRIBUTES_TO_IGNORE = [ - Attribute("Customization Spec", ""), - Attribute("Private IP", ""), - Attribute("CPU", ""), - Attribute("RAM", ""), - Attribute("Hostname", ""), - Attribute("HDD", ""), - ] + Attribute("Customization Spec", ""), + Attribute("Private IP", ""), + Attribute("CPU", ""), + Attribute("RAM", ""), + Attribute("Hostname", ""), + Attribute("HDD", ""), +] class LinkedCloneArtifactHandler(object): From b98bed04205f5619f9355861623823fd82d72fa8 Mon Sep 17 00:00:00 2001 From: Alexey Bogoslovskyi Date: Wed, 26 May 2021 14:33:56 +0300 Subject: [PATCH 6/9] Modified tox configuration and fixed unittests --- dev_requirements.txt | 4 +- test_requirements.txt | 13 +- tests/test_commands/test_DeleteInstance.py | 95 +-- .../test_command_orchestrator.py | 26 +- .../test_connect_orchestrator.py | 54 +- tests/test_commands/test_connect_vm.py | 45 +- tests/test_commands/test_delete_saved_app.py | 80 +-- tests/test_commands/test_deploy_vm.py | 90 +-- tests/test_commands/test_disconnect_vm.py | 130 ++-- .../test_commands/test_power_management_vm.py | 127 ++-- tests/test_commands/test_refresh_ip.py | 111 ++-- tests/test_commands/test_restore_snapshot.py | 36 +- tests/test_commands/test_retrieve_snapshot.py | 20 +- tests/test_commands/test_save_app.py | 182 +++--- tests/test_commands/test_save_snapshot.py | 45 +- tests/test_commands/test_vm_details.py | 73 +-- tests/test_commands/test_vm_loader.py | 27 +- .../test_connection_detail_retriever.py | 16 +- .../test_cloudshell/test_resource_remover.py | 15 +- tests/test_common/test_logger/__init__.py | 0 .../test_utilities/test_command_wrapper.py | 27 +- .../test_vcenter/test_ovf_image_tool.py | 41 +- .../test_vcenter/test_task_waiter.py | 24 +- .../test_vcenter_data_model_retriever.py | 16 +- .../test_vcenter/test_vm_snapshots.py | 26 +- .../test_vcenter/test_vmomi_service.py | 605 +++++++++--------- .../test_dvswitch/test_connector.py | 73 ++- .../test_dvswitch/test_creator.py | 37 +- .../test_port_group_configurer.py | 63 +- tests/test_network/vnic/test_network_vnic.py | 85 +-- tests/test_vm/test_deployer.py | 108 ++-- tests/test_vm/test_dvswitch_connector.py | 27 +- tests/test_vm/test_vm_ip_manager.py | 25 +- tests/test_vm/test_vnic_to_network_mapper.py | 15 +- .../test_resourceModelParser.py | 7 - tox.ini | 11 +- 36 files changed, 1223 insertions(+), 1156 deletions(-) delete mode 100644 tests/test_common/test_logger/__init__.py diff --git a/dev_requirements.txt b/dev_requirements.txt index e224937..2f91fb7 100644 --- a/dev_requirements.txt +++ b/dev_requirements.txt @@ -1,6 +1,4 @@ pre-commit tox -tox-factor -r test_requirements.txt -enum34==1.1.6 ---extra-index-url https://test.pypi.org/simple -r requirements.txt +-r requirements.txt \ No newline at end of file diff --git a/test_requirements.txt b/test_requirements.txt index 7640fbf..a5f34ff 100644 --- a/test_requirements.txt +++ b/test_requirements.txt @@ -1,10 +1,3 @@ -mock==2.0.0 -nose==1.3.7 -coverage -cloudshell-automation-api>=9.0.0.0,<9.0.1.0 -lxml==4.6.1 -requests==2.18.4 -pyvmomi==6.5.0 -jsonpickle==0.9.3 -retrying==1.3.3 -freezegun \ No newline at end of file +mock; python_version <= '2.7' +pytest +pytest-cov \ No newline at end of file diff --git a/tests/test_commands/test_DeleteInstance.py b/tests/test_commands/test_DeleteInstance.py index 2f1e35e..eba8611 100644 --- a/tests/test_commands/test_DeleteInstance.py +++ b/tests/test_commands/test_DeleteInstance.py @@ -1,35 +1,40 @@ +import sys import unittest -from mock import MagicMock, Mock, create_autospec from pyVmomi import vim from cloudshell.cp.vcenter.commands.DeleteInstance import DestroyVirtualMachineCommand +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock, create_autospec +else: + from mock import MagicMock, create_autospec + class TestDestroyVirtualMachineCommand(unittest.TestCase): def test_destroyVirtualMachineCommand(self): # arrange - pv_service = Mock() - folder_manager = Mock() - resource_remover = Mock() - disconnector = Mock() + pv_service = MagicMock() + folder_manager = MagicMock() + resource_remover = MagicMock() + disconnector = MagicMock() si = create_autospec(spec=vim.ServiceInstance) resource_name = "this/is the name of the template" uuid = "uuid" - vm = Mock() + vm = MagicMock() - 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) + pv_service.destory_vm = MagicMock(return_value=True) + disconnector.remove_interfaces_from_vm = MagicMock(return_value=True) + resource_remover.remove_resource = MagicMock(return_value=True) + pv_service.find_by_uuid = MagicMock(return_value=vm) - reservation_details = Mock() - reservation_details.ReservationDescription = Mock() + reservation_details = MagicMock() + reservation_details.ReservationDescription = MagicMock() reservation_details.ReservationDescription.Connectors = [] - session = Mock() - session.GetReservationDetails = Mock(return_value=reservation_details) - vcenter_data_model = Mock() + session = MagicMock() + session.GetReservationDetails = MagicMock(return_value=reservation_details) + vcenter_data_model = MagicMock() destroyer = DestroyVirtualMachineCommand( pv_service, folder_manager, resource_remover, disconnector ) @@ -37,7 +42,7 @@ def test_destroyVirtualMachineCommand(self): # act res = destroyer.destroy( si=si, - logger=Mock(), + logger=MagicMock(), session=session, vcenter_data_model=vcenter_data_model, vm_uuid=uuid, @@ -56,27 +61,27 @@ def test_destroyVirtualMachineCommandDeletesResourceWhenTheVMActualllyRemovedInV self, ): # arrange - pv_service = Mock() - folder_manager = Mock() - resource_remover = Mock() - disconnector = Mock() + pv_service = MagicMock() + folder_manager = MagicMock() + resource_remover = MagicMock() + disconnector = MagicMock() si = create_autospec(spec=vim.ServiceInstance) resource_name = "this/is the name of the template" uuid = "uuid" vm = None - 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) + pv_service.destory_vm = MagicMock(return_value=True) + disconnector.remove_interfaces_from_vm = MagicMock(return_value=True) + resource_remover.remove_resource = MagicMock(return_value=True) + pv_service.find_by_uuid = MagicMock(return_value=vm) - reservation_details = Mock() - reservation_details.ReservationDescription = Mock() + reservation_details = MagicMock() + reservation_details.ReservationDescription = MagicMock() reservation_details.ReservationDescription.Connectors = [] - session = Mock() - session.GetReservationDetails = Mock(return_value=reservation_details) - vcenter_data_model = Mock() + session = MagicMock() + session.GetReservationDetails = MagicMock(return_value=reservation_details) + vcenter_data_model = MagicMock() destroyer = DestroyVirtualMachineCommand( pv_service, folder_manager, resource_remover, disconnector ) @@ -84,7 +89,7 @@ def test_destroyVirtualMachineCommandDeletesResourceWhenTheVMActualllyRemovedInV # act res = destroyer.destroy( si=si, - logger=Mock(), + logger=MagicMock(), session=session, vcenter_data_model=vcenter_data_model, vm_uuid=uuid, @@ -101,12 +106,12 @@ def test_destroyVirtualMachineCommandDeletesResourceWhenTheVMActualllyRemovedInV def test_destroyVirtualMachineOnlyCommand(self): # arrange - pv_service = Mock() - folder_manager = Mock() - resource_remover = Mock() - disconnector = Mock() + pv_service = MagicMock() + folder_manager = MagicMock() + resource_remover = MagicMock() + disconnector = MagicMock() si = create_autospec(spec=vim.ServiceInstance) - vm = Mock() + vm = MagicMock() resource_model = MagicMock() resource_model.vm_uuid = "uuid" @@ -114,18 +119,18 @@ def test_destroyVirtualMachineOnlyCommand(self): resource_model.app_request_model.vm_location = "vm folder" reservation_id = "9e5b7004-e62e-4a8d-be1a-96bd1e58cb13" - 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) + pv_service.destory_mv = MagicMock(return_value=True) + disconnector.remove_interfaces_from_vm = MagicMock(return_value=True) + resource_remover.remove_resource = MagicMock(return_value=True) + pv_service.find_by_uuid = MagicMock(return_value=vm) - reservation_details = Mock() - reservation_details.ReservationDescription = Mock() + reservation_details = MagicMock() + reservation_details.ReservationDescription = MagicMock() reservation_details.ReservationDescription.Connectors = [] - session = Mock() - session.GetReservationDetails = Mock(return_value=reservation_details) - vcenter_data_model = Mock() + session = MagicMock() + session.GetReservationDetails = MagicMock(return_value=reservation_details) + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "Default Datacenter" destroyer = DestroyVirtualMachineCommand( @@ -135,7 +140,7 @@ def test_destroyVirtualMachineOnlyCommand(self): # act res = destroyer.DeleteInstance( si=si, - logger=Mock(), + logger=MagicMock(), session=session, vcenter_data_model=vcenter_data_model, reservation_id=reservation_id, diff --git a/tests/test_commands/test_command_orchestrator.py b/tests/test_commands/test_command_orchestrator.py index d2c1835..74b452f 100644 --- a/tests/test_commands/test_command_orchestrator.py +++ b/tests/test_commands/test_command_orchestrator.py @@ -1,4 +1,5 @@ import json +import sys from unittest import TestCase import jsonpickle @@ -16,10 +17,15 @@ ResourceRemoteCommandContext, ) from freezegun import freeze_time -from mock import Mock, create_autospec, patch from cloudshell.cp.vcenter.commands.command_orchestrator import CommandOrchestrator +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock, patch, create_autospec +else: + from mock import MagicMock, patch, create_autospec + + RESTORE_SNAPSHOT = "cloudshell.cp.vcenter.commands.command_orchestrator.CommandOrchestrator.restore_snapshot" SAVE_SNAPSHOT = "cloudshell.cp.vcenter.commands.command_orchestrator.CommandOrchestrator.save_snapshot" @@ -86,22 +92,22 @@ def setUp(self): "Reserved Networks": "vlan65", "Default Datacenter": "QualiSB", } - self.context = Mock() - session = Mock() - remote_resource = Mock() + self.context = MagicMock() + session = MagicMock() + remote_resource = MagicMock() remote_resource.fullname = "this is full name of the remote resource" remote_resource.uuid = "this is full uuis of the remote resource" - self.connection_details = Mock() + self.connection_details = MagicMock() self.context.resource = self.resource - self.context.resource.app_context = Mock() - self.context.remote_endpoints = Mock() + self.context.resource.app_context = MagicMock() + self.context.remote_endpoints = MagicMock() self.context.remote_endpoints = [self.resource] self.command_orchestrator = CommandOrchestrator() self.command_orchestrator.command_wrapper.execute_command_with_connection = ( - Mock(return_value=DeployAppResult()) + MagicMock(return_value=DeployAppResult()) ) - self.ports = [Mock()] - self.command_orchestrator._parse_remote_model = Mock( + self.ports = [MagicMock()] + self.command_orchestrator._parse_remote_model = MagicMock( return_value=remote_resource ) diff --git a/tests/test_commands/test_connect_orchestrator.py b/tests/test_commands/test_connect_orchestrator.py index 327aa5b..6338f34 100644 --- a/tests/test_commands/test_connect_orchestrator.py +++ b/tests/test_commands/test_connect_orchestrator.py @@ -1,7 +1,7 @@ +import sys from unittest import TestCase import jsonpickle -from mock import Mock from cloudshell.cp.vcenter.commands.connect_orchestrator import ( ConnectionCommandOrchestrator, @@ -14,15 +14,20 @@ ) from cloudshell.cp.vcenter.vm.portgroup_configurer import VNicDeviceMapper +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock +else: + from mock import MagicMock + class TestCommandOrchestrator(TestCase): def setUp(self): self.portgroup_name = DvPortGroupNameGenerator() - self.connector = Mock() - self.disconnector = Mock() - self.model_parser = Mock() + self.connector = MagicMock() + self.disconnector = MagicMock() + self.model_parser = MagicMock() - self.vc_data_model = Mock() + self.vc_data_model = MagicMock() self.vc_data_model.reserved_networks = "restricted_network1,restricted_network2" self.vc_data_model.default_dvswitch = "dvSwitch" self.vc_data_model.default_network = "Anetwork" @@ -30,7 +35,7 @@ def setUp(self): self.vc_data_model.holding_network = "Holding Network" self.vc_data_model.promiscuous_mode = "True" - self.si = Mock() + self.si = MagicMock() self.ConnectionCommandOrchestrator = ConnectionCommandOrchestrator( self.connector, self.disconnector, self.model_parser @@ -40,7 +45,7 @@ def test_connect_bulk_dvswitch_is_None(self): """ tests the error by missing dvswitch """ - vc_data_model = Mock() + vc_data_model = MagicMock() vc_data_model.reserved_networks = "restricted_network1,restricted_network2" vc_data_model.default_dvswitch = None vc_data_model.default_network = "Anetwork" @@ -50,7 +55,10 @@ def test_connect_bulk_dvswitch_is_None(self): request, expected = self._get_missing_dv_switch_params() results = self.ConnectionCommandOrchestrator.connect_bulk( - si=self.si, logger=Mock(), vcenter_data_model=vc_data_model, request=request + si=self.si, + logger=MagicMock(), + vcenter_data_model=vc_data_model, + request=request, ) self._assert_as_expected(results, expected) @@ -61,7 +69,7 @@ def test_connect_bulk1(self): request, expected = self._get_test1_params() results = self.ConnectionCommandOrchestrator.connect_bulk( si=self.si, - logger=Mock(), + logger=MagicMock(), vcenter_data_model=self.vc_data_model, request=request, ) @@ -74,7 +82,7 @@ def test_connect_bulk2(self): request, expected = self._get_test2_params() results = self.ConnectionCommandOrchestrator.connect_bulk( si=self.si, - logger=Mock(), + logger=MagicMock(), vcenter_data_model=self.vc_data_model, request=request, ) @@ -87,7 +95,7 @@ def test_connect_bulk3(self): request, expected = self._get_test3_params() results = self.ConnectionCommandOrchestrator.connect_bulk( si=self.si, - logger=Mock(), + logger=MagicMock(), vcenter_data_model=self.vc_data_model, request=request, ) @@ -102,7 +110,7 @@ def test_connect_bulk4(self): ValueError, self.ConnectionCommandOrchestrator.connect_bulk, self.si, - Mock(), + MagicMock(), self.vc_data_model, request, ) @@ -114,7 +122,7 @@ def test_connect_bulk5(self): request, expected = self._get_test5_params() res = self.ConnectionCommandOrchestrator.connect_bulk( si=self.si, - logger=Mock(), + logger=MagicMock(), vcenter_data_model=self.vc_data_model, request=request, ) @@ -127,7 +135,7 @@ def test_connect_bulk6(self): request, expected = self._get_test6_params() res = self.ConnectionCommandOrchestrator.connect_bulk( si=self.si, - logger=Mock(), + logger=MagicMock(), vcenter_data_model=self.vc_data_model, request=request, ) @@ -140,7 +148,7 @@ def test_connect_bulk7(self): request, expected = self._get_test7_params() results = self.ConnectionCommandOrchestrator.connect_bulk( si=self.si, - logger=Mock(), + logger=MagicMock(), vcenter_data_model=self.vc_data_model, request=request, ) @@ -153,7 +161,7 @@ def test_connect_bulk8(self): request, expected = self._get_test8_params() results = self.ConnectionCommandOrchestrator.connect_bulk( si=self.si, - logger=Mock(), + logger=MagicMock(), vcenter_data_model=self.vc_data_model, request=request, ) @@ -166,7 +174,7 @@ def test_connect_bulk9(self): request, expected = self._get_test9_params() results = self.ConnectionCommandOrchestrator.connect_bulk( si=self.si, - logger=Mock(), + logger=MagicMock(), vcenter_data_model=self.vc_data_model, request=request, ) @@ -215,7 +223,7 @@ def _set_connect_to_networks_by_request(self, request): network_key="aa", ) res.append(r) - self.connector.connect_to_networks = Mock(return_value=res) + self.connector.connect_to_networks = MagicMock(return_value=res) def _set_disconnect_from_networks(self, request): a = DeployDataHolder(request["driverRequest"]) @@ -226,14 +234,14 @@ def _set_disconnect_from_networks(self, request): ) interface = self._get_interface_name(action) r = VNicDeviceMapper( - vnic=Mock(), + vnic=MagicMock(), requested_vnic=vnic_name, - network=Mock(), + network=MagicMock(), connect=False, mac=interface, ) res.append(r) - self.disconnector.disconnect_from_networks = Mock(return_value=res) + self.disconnector.disconnect_from_networks = MagicMock(return_value=res) def _get_interface_name_for_result(self, action): interface_attributes = [ @@ -684,7 +692,7 @@ def _get_test5_params(self): ] } } - self.disconnector.disconnect_from_networks = Mock() + self.disconnector.disconnect_from_networks = MagicMock() self.disconnector.disconnect_from_networks.side_effect = ValueError( "vnic not found" ) @@ -727,7 +735,7 @@ def _get_test6_params(self): ] } } - self.connector.connect_to_networks = Mock() + self.connector.connect_to_networks = MagicMock() self.connector.connect_to_networks.side_effect = ValueError("vnic not found") expected = self._get_connect_excepted_results(request, "vnic not found") # here we don't don't get vnic input input diff --git a/tests/test_commands/test_connect_vm.py b/tests/test_commands/test_connect_vm.py index 92cd4ce..dc1a736 100644 --- a/tests/test_commands/test_connect_vm.py +++ b/tests/test_commands/test_connect_vm.py @@ -1,53 +1,62 @@ +import sys from unittest import TestCase -from mock import Mock, create_autospec from pyVmomi import vim from cloudshell.cp.vcenter.commands.connect_dvswitch import VirtualSwitchConnectCommand from cloudshell.cp.vcenter.vm.dvswitch_connector import VmNetworkMapping from cloudshell.cp.vcenter.vm.portgroup_configurer import VNicDeviceMapper +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock, create_autospec +else: + from mock import MagicMock, create_autospec + class TestVirtualSwitchToMachineDisconnectCommand(TestCase): def setUp(self): self.vlan_id_gen = "gen_id" self.name_gen = "gen_name" - self.spec = Mock() + self.spec = MagicMock() self.vm = Fake() - nic = Mock(spec=vim.vm.device.VirtualEthernetCard) + nic = MagicMock(spec=vim.vm.device.VirtualEthernetCard) nic.macAddress = True self.vm.config = Fake() self.vm.config.hardware = Fake() self.vm.config.hardware.device = [nic] - self.pv_service = Mock() + self.pv_service = MagicMock() self.pv_service.find_by_uuid = lambda x, y: self.vm - self.si = Mock() + self.si = MagicMock() self.vm_uuid = "uuid" self.vlan_id = 100 - self.spec_type = Mock() + self.spec_type = MagicMock() vnic_device_mapper = create_autospec(spec=VNicDeviceMapper) vnic_device_mapper.vnic = create_autospec( spec=vim.vm.device.VirtualEthernetCard ) vnic_device_mapper.vnic.macAddress = "AA-BB" - vnic_device_mapper.vnic.deviceInfo = Mock() + vnic_device_mapper.vnic.deviceInfo = MagicMock() vnic_device_mapper.vnic.deviceInfo.label = "AA-BB" - vnic_device_mapper.network = Mock() + vnic_device_mapper.network = MagicMock() vnic_device_mapper.network.name = "the network" vnic_device_mapper.network.key = "keyyyyyey" vnic_device_mapper.requested_vnic = "requested" - self.dv_connector = Mock() - self.dv_connector.connect_by_mapping = Mock(return_value=[vnic_device_mapper]) - self.dv_port_name_gen = Mock() - self.vlan_spec_factory = Mock() - self.vlan_id_range_parser = Mock() - self.vlan_id_range_parser.parse_vlan_id = Mock(return_value=self.vlan_id_gen) - self.dv_port_name_gen.generate_port_group_name = Mock( + self.dv_connector = MagicMock() + self.dv_connector.connect_by_mapping = MagicMock( + return_value=[vnic_device_mapper] + ) + self.dv_port_name_gen = MagicMock() + self.vlan_spec_factory = MagicMock() + self.vlan_id_range_parser = MagicMock() + self.vlan_id_range_parser.parse_vlan_id = MagicMock( + return_value=self.vlan_id_gen + ) + self.dv_port_name_gen.generate_port_group_name = MagicMock( return_value=self.name_gen ) - self.vlan_spec_factory.get_vlan_spec = Mock(return_value=self.spec) + self.vlan_spec_factory.get_vlan_spec = MagicMock(return_value=self.spec) def test_connect_vnic_to_network(self): # arrange @@ -63,8 +72,8 @@ def test_connect_vnic_to_network(self): mapping.vlan_id = "vlan_id" mapping.vlan_spec = "trunc" mapping.dv_port_name = "port_name" - mapping.network = Mock() - logger = Mock() + mapping.network = MagicMock() + logger = MagicMock() # act connect_results = connect_command.connect_to_networks( diff --git a/tests/test_commands/test_delete_saved_app.py b/tests/test_commands/test_delete_saved_app.py index 1c3c282..203bad0 100644 --- a/tests/test_commands/test_delete_saved_app.py +++ b/tests/test_commands/test_delete_saved_app.py @@ -1,3 +1,4 @@ +import sys from unittest import TestCase from uuid import uuid4 as guid @@ -8,17 +9,16 @@ SaveApp, SaveAppParams, ) -from mock import Mock, PropertyMock from cloudshell.cp.vcenter.commands.delete_saved_sandbox import ( DeleteSavedSandboxCommand, ) -from cloudshell.cp.vcenter.commands.save_sandbox import SaveAppCommand from cloudshell.cp.vcenter.common.vcenter.folder_manager import FolderManager -from cloudshell.cp.vcenter.models.DeployFromTemplateDetails import ( - DeployFromTemplateDetails, -) -from cloudshell.cp.vcenter.models.QualiDriverModels import CancellationContext + +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock +else: + from mock import MagicMock class MockResourceParser(object): @@ -29,28 +29,28 @@ def convert_to_resource_model(dummy, callable): class TestDeleteSavedSandboxCommand(TestCase): def setUp(self): - self.pyvmomi_service = Mock() - self.cancellation_context = Mock() + self.pyvmomi_service = MagicMock() + self.cancellation_context = MagicMock() self.cancellation_context.is_cancelled = False - vm = Mock() + vm = MagicMock() vm.name = "some string" - task_waiter = Mock() + task_waiter = MagicMock() self.folder_manager = FolderManager(self.pyvmomi_service, task_waiter) - self.pyvmomi_service.get_vm_by_uuid = Mock(return_value=vm) - self.cancellation_service = Mock() - self.cancellation_service.check_if_cancelled = Mock(return_value=False) - clone_result = Mock(vmName="whatever") - self.deployer = Mock() - self.deployer.deploy_clone_from_vm = Mock(return_value=clone_result) + self.pyvmomi_service.get_vm_by_uuid = MagicMock(return_value=vm) + self.cancellation_service = MagicMock() + self.cancellation_service.check_if_cancelled = MagicMock(return_value=False) + clone_result = MagicMock(vmName="whatever") + self.deployer = MagicMock() + self.deployer.deploy_clone_from_vm = MagicMock(return_value=clone_result) self.delete_command = DeleteSavedSandboxCommand( pyvmomi_service=self.pyvmomi_service, - task_waiter=Mock(), + task_waiter=MagicMock(), deployer=self.deployer, resource_model_parser=MockResourceParser(), - snapshot_saver=Mock(), + snapshot_saver=MagicMock(), folder_manager=self.folder_manager, cancellation_service=self.cancellation_service, - port_group_configurer=Mock(), + port_group_configurer=MagicMock(), ) def test_delete_sandbox_runs_successfully(self): @@ -60,14 +60,16 @@ def test_delete_sandbox_runs_successfully(self): delete_action2 = self._create_arbitrary_delete_saved_app_action() # path to save apps folder and saved sandbox folder uses default datacenter and vm location - vcenter_data_model = Mock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "QualiSB Cluster" vcenter_data_model.vm_location = "QualiFolder" vcenter_data_model.holding_network = "DEFAULT NETWORK" result = self.delete_command.delete_sandbox( - si=Mock(), - logger=Mock(), + si=MagicMock(), + logger=MagicMock(), + session=MagicMock(), + app_resource_model=MagicMock(), vcenter_data_model=vcenter_data_model, delete_sandbox_actions=[delete_action1, delete_action2], cancellation_context=self.cancellation_context, @@ -92,39 +94,15 @@ def test_delete_saved_sandbox_fails_when_actions_empty(self): str(context.exception), ) - def test_delete_saved_sandbox_fails_due_to_unsupported_save_type(self): - # if cloud provider sends an invalid delete save action with unsupported save type - # an exception will be thrown - - delete_action = self._create_arbitrary_delete_saved_app_action() - delete_action.actionParams.saveDeploymentModel = "mass quantum cloning" - - vcenter_data_model = Mock() - vcenter_data_model.default_datacenter = "QualiSB Cluster" - vcenter_data_model.vm_location = "QualiFolder" - result = self.delete_command.delete_sandbox( - si=Mock(), - logger=Mock(), - vcenter_data_model=vcenter_data_model, - delete_sandbox_actions=[delete_action], - cancellation_context=self.cancellation_context, - ) - # Assert - self.assertTrue(not result[0].success) - self.assertTrue( - result[0].errorMessage - == "Unsupported save deployment models: {0}".format( - delete_action.actionParams.saveDeploymentModel - ) - ) - def _delete_saved_sandbox_without_actions(self): - vcenter_data_model = Mock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "QualiSB Cluster" vcenter_data_model.vm_location = "QualiFolder" self.delete_command.delete_sandbox( - si=Mock(), - logger=Mock(), + si=MagicMock(), + logger=MagicMock(), + session=MagicMock(), + app_resource_model=MagicMock(), vcenter_data_model=vcenter_data_model, delete_sandbox_actions=[], cancellation_context=self.cancellation_context, diff --git a/tests/test_commands/test_deploy_vm.py b/tests/test_commands/test_deploy_vm.py index 988c692..646eb85 100644 --- a/tests/test_commands/test_deploy_vm.py +++ b/tests/test_commands/test_deploy_vm.py @@ -1,9 +1,6 @@ -import os -import sys +import sys import unittest -from mock import Mock - from cloudshell.cp.vcenter.commands.deploy_vm import DeployCommand from cloudshell.cp.vcenter.models.DeployFromTemplateDetails import ( DeployFromTemplateDetails, @@ -12,13 +9,18 @@ vCenterVMFromTemplateResourceModel, ) +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock +else: + from mock import MagicMock + class TestDeployFromTemplateCommand(unittest.TestCase): def test_deploy_execute(self): # arrange - deployer = Mock() - si = Mock() - template_model = Mock() + deployer = MagicMock() + si = MagicMock() + template_model = MagicMock() deploy_res = dict() deploy_res["vm_path"] = "path" @@ -27,7 +29,7 @@ def test_deploy_execute(self): template_model.template_name = "temp name" template_model.vm_folder = "temp folder" - deployer.deploy_from_template = Mock(return_value=deploy_res) + deployer.deploy_from_template = MagicMock(return_value=deploy_res) template_resource_model = vCenterVMFromTemplateResourceModel() @@ -37,11 +39,11 @@ def test_deploy_execute(self): deploy_command = DeployCommand(deployer) - resource_context = Mock() - logger = Mock() - session = Mock() - app_resource_model = Mock() - vcenter_data_model = Mock() + resource_context = MagicMock() + logger = MagicMock() + session = MagicMock() + app_resource_model = MagicMock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "QualiSB" vcenter_data_model.vm_location = "TargetFolder" reservation_id = "4228128c-fb7e-9b0e-60b8-c3fabd3c624e" @@ -57,7 +59,7 @@ def test_deploy_execute(self): vcenter_data_model=vcenter_data_model, reservation_id=reservation_id, cancellation_context=cancellation_context, - folder_manager=Mock(), + folder_manager=MagicMock(), ) # assert @@ -74,25 +76,25 @@ def test_deploy_execute(self): ) def test_deploy_image_execute(self): - deployer = Mock() - si = Mock() - deployment_params = Mock() + deployer = MagicMock() + si = MagicMock() + deployment_params = MagicMock() deployment_params.template_resource_model.vm_location = "SomeFolder" - connectivity = Mock() - res = Mock() - deployer.deploy_from_image = Mock(return_value=res) - session = Mock() - vcenter_data_model = Mock() + connectivity = MagicMock() + res = MagicMock() + deployer.deploy_from_image = MagicMock(return_value=res) + session = MagicMock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "QualiSB" - logger = Mock() + logger = MagicMock() reservation_id = "4228128c-fb7e-9b0e-60b8-c3fabd3c624e" deploy_command = DeployCommand(deployer) cancellation_context = object() # act - folder_manager = Mock() + folder_manager = MagicMock() result = deploy_command.execute_deploy_from_image( si=si, logger=logger, @@ -120,9 +122,9 @@ def test_deploy_image_execute(self): def test_deploy_clone_execute(self): # arrange - deployer = Mock() - si = Mock() - template_model = Mock() + deployer = MagicMock() + si = MagicMock() + template_model = MagicMock() deploy_res = dict() deploy_res["vm_path"] = "path" @@ -131,14 +133,14 @@ def test_deploy_clone_execute(self): template_model.template_name = "temp name" template_model.vm_folder = "temp folder" - deployer.deploy_from_template = Mock(return_value=deploy_res) + deployer.deploy_from_template = MagicMock(return_value=deploy_res) reservation_id = "4228128c-fb7e-9b0e-60b8-c3fabd3c624e" - logger = Mock() - session = Mock() - app_resource_model = Mock() + logger = MagicMock() + session = MagicMock() + app_resource_model = MagicMock() - vcenter_data_model = Mock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "QualiSB" vcenter_data_model.vm_location = "TargetFolder" @@ -150,7 +152,7 @@ def test_deploy_clone_execute(self): deploy_command = DeployCommand(deployer) - resource_context = Mock() + resource_context = MagicMock() cancellation_context = object() # act @@ -163,7 +165,7 @@ def test_deploy_clone_execute(self): deployment_params=deploy_params, reservation_id=reservation_id, cancellation_context=cancellation_context, - folder_manager=Mock(), + folder_manager=MagicMock(), ) # assert @@ -181,9 +183,9 @@ def test_deploy_clone_execute(self): def test_deploy_snapshot_execute(self): # arrange - deployer = Mock() - si = Mock() - template_model = Mock() + deployer = MagicMock() + si = MagicMock() + template_model = MagicMock() deploy_res = dict() deploy_res["vm_path"] = "path" @@ -192,7 +194,7 @@ def test_deploy_snapshot_execute(self): template_model.template_name = "temp name" template_model.vm_folder = "temp folder" - deployer.deploy_from_template = Mock(return_value=deploy_res) + deployer.deploy_from_template = MagicMock(return_value=deploy_res) template_resource_model = vCenterVMFromTemplateResourceModel() @@ -202,15 +204,15 @@ def test_deploy_snapshot_execute(self): deploy_command = DeployCommand(deployer) - resource_context = Mock() - logger = Mock() - vcenter_data_model = Mock() + resource_context = MagicMock() + logger = MagicMock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "QualiSB" vcenter_data_model.vm_location = "TargetFolder" reservation_id = "4228128c-fb7e-9b0e-60b8-c3fabd3c624e" cancellation_context = object() - session = Mock() - app_resource_model = Mock() + session = MagicMock() + app_resource_model = MagicMock() # act result = deploy_command.execute_deploy_from_linked_clone( @@ -222,7 +224,7 @@ def test_deploy_snapshot_execute(self): app_resource_model=app_resource_model, reservation_id=reservation_id, cancellation_context=cancellation_context, - folder_manager=Mock(), + folder_manager=MagicMock(), ) # assert diff --git a/tests/test_commands/test_disconnect_vm.py b/tests/test_commands/test_disconnect_vm.py index 80cadc7..1ecb5a3 100644 --- a/tests/test_commands/test_disconnect_vm.py +++ b/tests/test_commands/test_disconnect_vm.py @@ -1,6 +1,6 @@ +import sys from unittest import TestCase -from mock import Mock from pyVmomi import vim from cloudshell.cp.vcenter.commands.disconnect_dvswitch import ( @@ -11,36 +11,40 @@ ) from cloudshell.cp.vcenter.network.vnic.vnic_service import VNicService +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock +else: + from mock import MagicMock + class TestVirtualSwitchToMachineDisconnectCommand(TestCase): def test_delete_all(self): # arrange uuid = "uuid" - si = Mock() - vm = Mock() + si = MagicMock() + vm = MagicMock() - connection_detail = Mock() - connection_detail.host = Mock() - connection_detail.username = Mock() - connection_detail.password = Mock() - connection_detail.port = Mock() + connection_detail = MagicMock() + connection_detail.host = MagicMock() + connection_detail.username = MagicMock() + connection_detail.password = MagicMock() + connection_detail.port = MagicMock() - pv_service = Mock() - pv_service.connect = Mock(return_value=si) - pv_service.find_by_uuid = Mock(return_value=vm) + pv_service = MagicMock() + pv_service.connect = MagicMock(return_value=si) + pv_service.find_by_uuid = MagicMock(return_value=vm) connector = VirtualSwitchToMachineDisconnectCommand( - pv_service, Mock(), "anetwork" + pv_service, MagicMock(), "anetwork" ) - # virtual_switch_to_machine_connector.remove_interfaces_from_vm = Mock(return_value=True) - connector.get_network_by_name = lambda x, y: Mock() + connector.get_network_by_name = lambda x, y: MagicMock() vcenter_data_model = VMwarevCenterResourceModel() # act res = connector.disconnect( si=si, - logger=Mock(), + logger=MagicMock(), vcenter_data_model=vcenter_data_model, vm_uuid=uuid, network_name=None, @@ -64,24 +68,24 @@ def test_delete(self): uuid = "uuid" network_name = "network_name" - network = Mock() + network = MagicMock() network.name = network_name - si = Mock() - vm = Mock() + si = MagicMock() + vm = MagicMock() vm.network = [network] - connection_detail = Mock() - connection_detail.host = Mock() - connection_detail.username = Mock() - connection_detail.password = Mock() - connection_detail.port = Mock() + connection_detail = MagicMock() + connection_detail.host = MagicMock() + connection_detail.username = MagicMock() + connection_detail.password = MagicMock() + connection_detail.port = MagicMock() - pv_service = Mock() - pv_service.connect = Mock(return_value=si) - pv_service.find_by_uuid = Mock(return_value=vm) + pv_service = MagicMock() + pv_service.connect = MagicMock(return_value=si) + pv_service.find_by_uuid = MagicMock(return_value=vm) connector = VirtualSwitchToMachineDisconnectCommand( - pv_service, Mock(), "anetwork" + pv_service, MagicMock(), "anetwork" ) vcenter_data_model = VMwarevCenterResourceModel() @@ -89,7 +93,7 @@ def test_delete(self): # act res = connector.disconnect( si=si, - logger=Mock(), + logger=MagicMock(), vcenter_data_model=vcenter_data_model, vm_uuid=uuid, network_name=network_name, @@ -109,9 +113,9 @@ def test_delete(self): def test_is_device_match_network_port_type(self): # arrange - backing = Mock(spec=[]) - device = Mock() - port = Mock() + backing = MagicMock(spec=[]) + device = MagicMock() + port = MagicMock() device.backing = backing backing.port = port @@ -125,9 +129,9 @@ def test_is_device_match_network_port_type(self): def test_is_device_match_network_other_type(self): # arrange - backing = Mock(spec=[]) - device = Mock() - nerwork = Mock() + backing = MagicMock(spec=[]) + device = MagicMock() + nerwork = MagicMock() device.backing = backing backing.network = nerwork @@ -141,15 +145,14 @@ def test_is_device_match_network_other_type(self): def test_is_device_match_network_not_found(self): # arrange - device = Mock() - device.backing = Mock(spec=[]) + device = MagicMock() + device.backing = MagicMock(spec=[]) virtual_switch_to_machine_connector = VirtualSwitchToMachineDisconnectCommand( - Mock(), Mock(), "anetwork" + MagicMock(), MagicMock(), "anetwork" ) # act - # res = virtual_switch_to_machine_connector.is_device_match_network(device, 'Fake name') res = VNicService.device_is_attached_to_network(device, "Fake name") # assert @@ -157,13 +160,13 @@ def test_is_device_match_network_not_found(self): def test_remove_interfaces_from_vm_no_nic_found(self): # arrange - vm = Mock() - vm.config = Mock() + vm = MagicMock() + vm.config = MagicMock() vm.config.hardware() vm.config.hardware.device = [] virtual_switch_to_machine_connector = VirtualSwitchToMachineDisconnectCommand( - Mock(), Mock(), "anetwork" + MagicMock(), MagicMock(), "anetwork" ) # act @@ -174,15 +177,15 @@ def test_remove_interfaces_from_vm_no_nic_found(self): def test_remove_interfaces_from_vm_no_filter(self): # arrange - device1 = Mock(spec=vim.vm.device.VirtualEthernetCard) - device2 = Mock(spec=vim.vm.device.VirtualSoundCard) - vm = Mock() - vm.config = Mock() + device1 = MagicMock(spec=vim.vm.device.VirtualEthernetCard) + device2 = MagicMock(spec=vim.vm.device.VirtualSoundCard) + vm = MagicMock() + vm.config = MagicMock() vm.config.hardware() vm.config.hardware.device = [device2, device1] virtual_switch_to_machine_connector = VirtualSwitchToMachineDisconnectCommand( - Mock(), Mock(), "anetwork" + MagicMock(), MagicMock(), "anetwork" ) # act @@ -190,25 +193,25 @@ def test_remove_interfaces_from_vm_no_filter(self): # assert self.assertTrue(res) - # self.assertTrue(virtual_switch_to_machine_connector.remove_devices.called) def test_remove_interfaces_from_vm_with_filter(self): # arrange - device1 = Mock(spec=vim.vm.device.VirtualEthernetCard) - device2 = Mock(spec=vim.vm.device.VirtualEthernetCard) - device3 = Mock(spec=vim.vm.device.VirtualSoundCard) + device1 = MagicMock(spec=vim.vm.device.VirtualEthernetCard) + device2 = MagicMock(spec=vim.vm.device.VirtualEthernetCard) + device3 = MagicMock(spec=vim.vm.device.VirtualSoundCard) device1.name = "this is the one" device2.name = "very close" device3.name = "not it" - vm = Mock() - vm.config = Mock() + vm = MagicMock() + vm.config = MagicMock() vm.config.hardware() vm.config.hardware.device = [device3, device2, device1] - connector = VirtualSwitchToMachineDisconnectCommand(Mock(), Mock(), "anetwork") - # connector.remove_devices = Mock(return_value=True) + connector = VirtualSwitchToMachineDisconnectCommand( + MagicMock(), MagicMock(), "anetwork" + ) # act condition = lambda device: device.name == device1.name @@ -216,22 +219,3 @@ def test_remove_interfaces_from_vm_with_filter(self): # assert self.assertTrue(res) - # self.assertTrue(connector.remove_devices.called) - - # def test_remove_devices(self): - # # arrange - # device_config = [Mock(spec=vim.vm.device.VirtualDeviceSpec)] - # task = Mock() - # vm = Mock() - # vm.ReconfigVM_Task = Mock(return_value=task) - # - # virtual_switch_to_machine_connector = VirtualSwitchToMachineDisconnectCommand(Mock(), Mock(), Mock()) - # virtual_switch_to_machine_connector.synchronous_task_waiter = Mock() - # virtual_switch_to_machine_connector.synchronous_task_waiter.wait_for_task = Mock(return_value=True) - # - # # act - # res = virtual_switch_to_machine_connector.remove_devices(device_config, vm) - # - # # assert - # self.assertTrue(res) - # self.assertTrue(virtual_switch_to_machine_connector.synchronous_task_waiter.wait_for_task .called_eith(task)) diff --git a/tests/test_commands/test_power_management_vm.py b/tests/test_commands/test_power_management_vm.py index 9c56f40..b9b138f 100644 --- a/tests/test_commands/test_power_management_vm.py +++ b/tests/test_commands/test_power_management_vm.py @@ -1,33 +1,40 @@ +import sys from unittest import TestCase -from mock import Mock from pyVmomi import vim from cloudshell.cp.vcenter.commands.power_manager_vm import ( VirtualMachinePowerManagementCommand, ) +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock +else: + from mock import MagicMock + class TestVirtualMachinePowerManagementCommand(TestCase): def test_power_off_already(self): vm_uuid = "uuid" - si = Mock(spec=vim.ServiceInstance) - vm = Mock(spec=vim.VirtualMachine) - vm.summary = Mock() - vm.summary.runtime = Mock() + si = MagicMock(spec=vim.ServiceInstance) + vm = MagicMock(spec=vim.VirtualMachine) + vm.summary = MagicMock() + vm.summary.runtime = MagicMock() vm.summary.runtime.powerState = "poweredOff" - session = Mock() - pv_service = Mock() - pv_service.find_by_uuid = Mock(return_value=vm) + session = MagicMock() + pv_service = MagicMock() + pv_service.find_by_uuid = MagicMock(return_value=vm) - power_manager = VirtualMachinePowerManagementCommand(pv_service, Mock(), Mock()) + power_manager = VirtualMachinePowerManagementCommand( + pv_service, MagicMock(), MagicMock() + ) # act res = power_manager.power_off( si=si, - logger=Mock(), + logger=MagicMock(), session=session, - vcenter_data_model=Mock(), + vcenter_data_model=MagicMock(), vm_uuid=vm_uuid, resource_fullname=None, ) @@ -38,21 +45,23 @@ def test_power_off_already(self): 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() + si = MagicMock(spec=vim.ServiceInstance) + vm = MagicMock(spec=vim.VirtualMachine) + vm.summary = MagicMock() + vm.summary.runtime = MagicMock() vm.summary.runtime.powerState = "poweredOn" - session = Mock() - pv_service = Mock() - pv_service.find_by_uuid = Mock(return_value=vm) + session = MagicMock() + pv_service = MagicMock() + pv_service.find_by_uuid = MagicMock(return_value=vm) - power_manager = VirtualMachinePowerManagementCommand(pv_service, Mock(), Mock()) + power_manager = VirtualMachinePowerManagementCommand( + pv_service, MagicMock(), MagicMock() + ) # act res = power_manager.power_on( si=si, - logger=Mock(), + logger=MagicMock(), session=session, vm_uuid=vm_uuid, resource_fullname=None, @@ -65,27 +74,27 @@ def test_power_on_already(self): 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) + si = MagicMock(spec=vim.ServiceInstance) + vm = MagicMock(spec=vim.VirtualMachine) + session = MagicMock() + pv_service = MagicMock() + pv_service.find_by_uuid = MagicMock(return_value=vm) - task = Mock() + task = MagicMock() - vm.PowerOn = Mock(return_value=task) + vm.PowerOn = MagicMock(return_value=task) - synchronous_task_waiter = Mock() - synchronous_task_waiter.wait_for_task = Mock(return_value=True) + synchronous_task_waiter = MagicMock() + synchronous_task_waiter.wait_for_task = MagicMock(return_value=True) power_manager = VirtualMachinePowerManagementCommand( - pv_service, synchronous_task_waiter, Mock() + pv_service, synchronous_task_waiter, MagicMock() ) # act res = power_manager.power_on( si=si, - logger=Mock(), + logger=MagicMock(), session=session, vm_uuid=vm_uuid, resource_fullname=None, @@ -100,30 +109,30 @@ 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) + session = MagicMock() + si = MagicMock(spec=vim.ServiceInstance) + vm = MagicMock(spec=vim.VirtualMachine) + task = MagicMock() + pv_service = MagicMock() + pv_service.find_by_uuid = MagicMock(return_value=vm) - vm.PowerOff = Mock(return_value=task) + vm.PowerOff = MagicMock(return_value=task) - synchronous_task_waiter = Mock() - synchronous_task_waiter.wait_for_task = Mock(return_value=True) + synchronous_task_waiter = MagicMock() + synchronous_task_waiter.wait_for_task = MagicMock(return_value=True) power_manager = VirtualMachinePowerManagementCommand( - pv_service, synchronous_task_waiter, Mock() + pv_service, synchronous_task_waiter, MagicMock() ) - power_manager._connect_to_vcenter = Mock(return_value=si) - power_manager._get_vm = Mock(return_value=vm) + power_manager._connect_to_vcenter = MagicMock(return_value=si) + power_manager._get_vm = MagicMock(return_value=vm) - vcenter = Mock() + vcenter = MagicMock() vcenter.shutdown_method = "soft" # act res = power_manager.power_off( si=si, - logger=Mock(), + logger=MagicMock(), session=session, vcenter_data_model=vcenter, vm_uuid=vm_uuid, @@ -141,30 +150,30 @@ def test_power_off_hard(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) + session = MagicMock() + si = MagicMock(spec=vim.ServiceInstance) + vm = MagicMock(spec=vim.VirtualMachine) + task = MagicMock() + pv_service = MagicMock() + pv_service.find_by_uuid = MagicMock(return_value=vm) - vm.PowerOff = Mock(return_value=task) + vm.PowerOff = MagicMock(return_value=task) - synchronous_task_waiter = Mock() - synchronous_task_waiter.wait_for_task = Mock(return_value=True) + synchronous_task_waiter = MagicMock() + synchronous_task_waiter.wait_for_task = MagicMock(return_value=True) power_manager = VirtualMachinePowerManagementCommand( - pv_service, synchronous_task_waiter, Mock() + pv_service, synchronous_task_waiter, MagicMock() ) - power_manager._connect_to_vcenter = Mock(return_value=si) - power_manager._get_vm = Mock(return_value=vm) + power_manager._connect_to_vcenter = MagicMock(return_value=si) + power_manager._get_vm = MagicMock(return_value=vm) - vcenter = Mock() + vcenter = MagicMock() vcenter.shutdown_method = "hard" # act res = power_manager.power_off( si=si, - logger=Mock(), + logger=MagicMock(), session=session, vcenter_data_model=vcenter, vm_uuid=vm_uuid, diff --git a/tests/test_commands/test_refresh_ip.py b/tests/test_commands/test_refresh_ip.py index 93dd94d..fd79ac4 100644 --- a/tests/test_commands/test_refresh_ip.py +++ b/tests/test_commands/test_refresh_ip.py @@ -1,12 +1,6 @@ +import sys from unittest import TestCase -from cloudshell.api.cloudshell_api import ( - ResourceInfo, - ResourceInfoVmDetails, - VmCustomParam, -) -from mock import Mock, create_autospec - from cloudshell.cp.vcenter.commands.refresh_ip import RefreshIpCommand from cloudshell.cp.vcenter.common.model_factory import ResourceModelParser from cloudshell.cp.vcenter.models import GenericDeployedAppResourceModel @@ -14,26 +8,31 @@ VMwarevCenterResourceModel, ) +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock, create_autospec +else: + from mock import MagicMock, create_autospec + class TestRefreshIpCommand(TestCase): def test_refresh_ip(self): - nic1 = Mock() + nic1 = MagicMock() nic1.network = "A Network" nic1.ipAddress = ["192.168.1.1"] - nic2 = Mock() + nic2 = MagicMock() nic2.network = "A Network" nic2.ipAddress = ["111.111.111.111"] - guest = Mock() + guest = MagicMock() guest.toolsStatus = "toolsOk" guest.net = [nic1, nic2] - vm = Mock() + vm = MagicMock() vm.guest = guest - pyvmomi_service = Mock() - pyvmomi_service.find_by_uuid = Mock(return_value=vm) + pyvmomi_service = MagicMock() + pyvmomi_service.find_by_uuid = MagicMock(return_value=vm) ip_regex = self._create_custom_param("ip_regex", "192\.168\..*") refresh_ip_timeout = self._create_custom_param("refresh_ip_timeout", "10") @@ -45,16 +44,16 @@ def test_refresh_ip(self): resource_model.vm_custom_params = [ip_regex, refresh_ip_timeout] refresh_ip_command = RefreshIpCommand( - pyvmomi_service, ResourceModelParser(), Mock() + pyvmomi_service, ResourceModelParser(), MagicMock() ) - session = Mock() - session.UpdateResourceAddress = Mock(return_value=True) - si = Mock() + session = MagicMock() + session.UpdateResourceAddress = MagicMock(return_value=True) + si = MagicMock() center_resource_model = VMwarevCenterResourceModel() center_resource_model.default_datacenter = "QualiSB" center_resource_model.holding_network = "anetwork" - cancellation_context = Mock() + cancellation_context = MagicMock() # Act refresh_ip_command.refresh_ip( @@ -63,8 +62,8 @@ def test_refresh_ip(self): vcenter_data_model=center_resource_model, resource_model=resource_model, cancellation_context=cancellation_context, - logger=Mock(), - app_request_json=Mock(), + logger=MagicMock(), + app_request_json=MagicMock(), ) # Assert @@ -73,29 +72,29 @@ def test_refresh_ip(self): ) def _create_custom_param(self, name, value): - vm_custom_param = Mock() + vm_custom_param = MagicMock() vm_custom_param.name = name vm_custom_param.value = value return vm_custom_param def test_refresh_ip_choose_ipv4(self): - nic1 = Mock() + nic1 = MagicMock() nic1.network = "A Network" nic1.ipAddress = ["192.168.1.1"] - nic2 = Mock() + nic2 = MagicMock() nic2.network = "A Network" nic2.ipAddress = ["2001:0db8:0a0b:12f0:0000:0000:0000:0001"] - guest = Mock() + guest = MagicMock() guest.toolsStatus = "toolsOk" guest.net = [nic1, nic2] - vm = Mock() + vm = MagicMock() vm.guest = guest - pyvmomi_service = Mock() - pyvmomi_service.find_by_uuid = Mock(return_value=vm) + pyvmomi_service = MagicMock() + pyvmomi_service.find_by_uuid = MagicMock(return_value=vm) ip_regex = self._create_custom_param("ip_regex", "") refresh_ip_timeout = self._create_custom_param("refresh_ip_timeout", "10") @@ -107,17 +106,17 @@ def test_refresh_ip_choose_ipv4(self): resource_model.vm_custom_params = [ip_regex, refresh_ip_timeout] refresh_ip_command = RefreshIpCommand( - pyvmomi_service, ResourceModelParser(), Mock() + pyvmomi_service, ResourceModelParser(), MagicMock() ) - session = Mock() - session.UpdateResourceAddress = Mock(return_value=True) - session.GetResourceDetails = Mock(return_value=resource_model) - si = Mock() + session = MagicMock() + session.UpdateResourceAddress = MagicMock(return_value=True) + session.GetResourceDetails = MagicMock(return_value=resource_model) + si = MagicMock() center_resource_model = VMwarevCenterResourceModel() center_resource_model.default_datacenter = "QualiSB" center_resource_model.holding_network = "anetwork" - cancellation_context = Mock() + cancellation_context = MagicMock() # Act refresh_ip_command.refresh_ip( @@ -126,8 +125,8 @@ def test_refresh_ip_choose_ipv4(self): vcenter_data_model=center_resource_model, resource_model=resource_model, cancellation_context=cancellation_context, - logger=Mock(), - app_request_json=Mock(), + logger=MagicMock(), + app_request_json=MagicMock(), ) # Assert @@ -136,23 +135,23 @@ def test_refresh_ip_choose_ipv4(self): ) def test_refresh_ip_choose_ip_by_regex(self): - nic1 = Mock() + nic1 = MagicMock() nic1.network = "A Network" nic1.ipAddress = ["192.168.1.1"] - nic2 = Mock() + nic2 = MagicMock() nic2.network = "A Network" nic2.ipAddress = ["111.111.111.111"] - guest = Mock() + guest = MagicMock() guest.toolsStatus = "toolsOk" guest.net = [nic1, nic2] - vm = Mock() + vm = MagicMock() vm.guest = guest - pyvmomi_service = Mock() - pyvmomi_service.find_by_uuid = Mock(return_value=vm) + pyvmomi_service = MagicMock() + pyvmomi_service.find_by_uuid = MagicMock(return_value=vm) ip_regex = self._create_custom_param("ip_regex", "192\.168\..*") refresh_ip_timeout = self._create_custom_param("refresh_ip_timeout", "10") @@ -164,17 +163,17 @@ def test_refresh_ip_choose_ip_by_regex(self): resource_model.vm_custom_params = [ip_regex, refresh_ip_timeout] refresh_ip_command = RefreshIpCommand( - pyvmomi_service, ResourceModelParser(), Mock() + pyvmomi_service, ResourceModelParser(), MagicMock() ) - session = Mock() - session.UpdateResourceAddress = Mock(return_value=True) - session.GetResourceDetails = Mock(return_value=resource_model) - si = Mock() + session = MagicMock() + session.UpdateResourceAddress = MagicMock(return_value=True) + session.GetResourceDetails = MagicMock(return_value=resource_model) + si = MagicMock() center_resource_model = VMwarevCenterResourceModel() center_resource_model.default_datacenter = "QualiSB" center_resource_model.holding_network = "anetwork" - cancellation_context = Mock() + cancellation_context = MagicMock() # Act refresh_ip_command.refresh_ip( @@ -183,8 +182,8 @@ def test_refresh_ip_choose_ip_by_regex(self): vcenter_data_model=center_resource_model, resource_model=resource_model, cancellation_context=cancellation_context, - logger=Mock(), - app_request_json=Mock(), + logger=MagicMock(), + app_request_json=MagicMock(), ) # Assert @@ -194,16 +193,16 @@ def test_refresh_ip_choose_ip_by_regex(self): def test_refresh_ip_should_fail_static_vm(self): # Act - refresh_ip_command = RefreshIpCommand(Mock(), Mock(), Mock()) + refresh_ip_command = RefreshIpCommand(MagicMock(), MagicMock(), MagicMock()) # assert self.assertRaises( ValueError, refresh_ip_command.refresh_ip, - Mock(), - Mock(), - Mock(), - Mock(), - Mock(), - Mock(), + MagicMock(), + MagicMock(), + MagicMock(), + MagicMock(), + MagicMock(), + MagicMock(), None, ) diff --git a/tests/test_commands/test_restore_snapshot.py b/tests/test_commands/test_restore_snapshot.py index a3b2fb2..f2ef183 100644 --- a/tests/test_commands/test_restore_snapshot.py +++ b/tests/test_commands/test_restore_snapshot.py @@ -1,12 +1,16 @@ +import sys from unittest import TestCase -from mock import MagicMock, Mock, patch - from cloudshell.cp.vcenter.commands.restore_snapshot import SnapshotRestoreCommand from cloudshell.cp.vcenter.exceptions.snapshot_not_found import ( SnapshotNotFoundException, ) +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock, patch +else: + from mock import MagicMock, patch + class TestSnapshotRestoreCommand(TestCase): @patch( @@ -15,24 +19,24 @@ class TestSnapshotRestoreCommand(TestCase): def test_restore_snapshot_should_success_on_existing_snapshot( self, mock_get_vm_snapshots ): - vm = Mock() + vm = MagicMock() - pyvmomi_service = Mock() - pyvmomi_service.find_by_uuid = Mock(return_value=vm) + pyvmomi_service = MagicMock() + pyvmomi_service.find_by_uuid = MagicMock(return_value=vm) snapshot_restore_command = SnapshotRestoreCommand( - pyvmomi_service=pyvmomi_service, task_waiter=Mock() + pyvmomi_service=pyvmomi_service, task_waiter=MagicMock() ) - si = Mock() + si = MagicMock() - snapshot = Mock() + snapshot = MagicMock() mock_get_vm_snapshots.return_value = {"snap1": snapshot} session = MagicMock() # Act snapshot_restore_command.restore_snapshot( si=si, - logger=Mock(), + logger=MagicMock(), session=session, vm_uuid="machine1", resource_fullname="vm_machine1", @@ -48,17 +52,17 @@ def test_restore_snapshot_should_success_on_existing_snapshot( def test_restore_snapshot_should_throw_exception_on_none_existing_snapshot( self, mock_get_vm_snapshots ): - vm = Mock() + vm = MagicMock() - pyvmomi_service = Mock() - pyvmomi_service.find_by_uuid = Mock(return_value=vm) + pyvmomi_service = MagicMock() + pyvmomi_service.find_by_uuid = MagicMock(return_value=vm) snapshot_restore_command = SnapshotRestoreCommand( - pyvmomi_service=pyvmomi_service, task_waiter=Mock() + pyvmomi_service=pyvmomi_service, task_waiter=MagicMock() ) - si = Mock() + si = MagicMock() - mock_get_vm_snapshots.return_value = {"snap1": Mock()} + mock_get_vm_snapshots.return_value = {"snap1": MagicMock()} session = MagicMock() @@ -67,7 +71,7 @@ def test_restore_snapshot_should_throw_exception_on_none_existing_snapshot( SnapshotNotFoundException, snapshot_restore_command.restore_snapshot, si, - Mock(), + MagicMock(), session, "machine1", "vm_machine1", diff --git a/tests/test_commands/test_retrieve_snapshot.py b/tests/test_commands/test_retrieve_snapshot.py index f28f903..2317d5c 100644 --- a/tests/test_commands/test_retrieve_snapshot.py +++ b/tests/test_commands/test_retrieve_snapshot.py @@ -1,9 +1,13 @@ +import sys from unittest import TestCase -from mock import Mock, patch - from cloudshell.cp.vcenter.commands.retrieve_snapshots import RetrieveSnapshotsCommand +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock, patch +else: + from mock import MagicMock, patch + class TestRetrieveSnapshotCommand(TestCase): @patch( @@ -12,21 +16,21 @@ class TestRetrieveSnapshotCommand(TestCase): def test_restore_snapshot_should_success_on_existing_snapshot( self, mock_get_vm_snapshots ): - vm = Mock() + vm = MagicMock() - pyvmomi_service = Mock() - pyvmomi_service.find_by_uuid = Mock(return_value=vm) + pyvmomi_service = MagicMock() + pyvmomi_service.find_by_uuid = MagicMock(return_value=vm) snapshot_restore_command = RetrieveSnapshotsCommand( pyvmomi_service=pyvmomi_service ) - si = Mock() + si = MagicMock() - mock_get_vm_snapshots.return_value = {"snap1": Mock()} + mock_get_vm_snapshots.return_value = {"snap1": MagicMock()} # Act snapshots = snapshot_restore_command.get_snapshots( - si=si, logger=Mock(), vm_uuid="machine1" + si=si, logger=MagicMock(), vm_uuid="machine1" ) # Assert diff --git a/tests/test_commands/test_save_app.py b/tests/test_commands/test_save_app.py index 057e5ef..69082f4 100644 --- a/tests/test_commands/test_save_app.py +++ b/tests/test_commands/test_save_app.py @@ -1,15 +1,19 @@ +import sys from unittest import TestCase from uuid import uuid4 as guid from cloudshell.cp.core.models import SaveApp, SaveAppParams -from mock import Mock, PropertyMock from cloudshell.cp.vcenter.commands.save_sandbox import SaveAppCommand from cloudshell.cp.vcenter.common.vcenter.folder_manager import FolderManager from cloudshell.cp.vcenter.models.DeployFromTemplateDetails import ( DeployFromTemplateDetails, ) -from cloudshell.cp.vcenter.models.QualiDriverModels import CancellationContext + +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock +else: + from mock import MagicMock class MockResourceParser(object): @@ -20,28 +24,28 @@ def convert_to_resource_model(dummy, callable): class TestSaveAppCommand(TestCase): def setUp(self): - self.pyvmomi_service = Mock() - self.cancellation_context = Mock() + self.pyvmomi_service = MagicMock() + self.cancellation_context = MagicMock() self.cancellation_context.is_cancelled = False - vm = Mock() + vm = MagicMock() vm.name = "some string" - task_waiter = Mock() + task_waiter = MagicMock() self.folder_manager = FolderManager(self.pyvmomi_service, task_waiter) - self.pyvmomi_service.get_vm_by_uuid = Mock(return_value=vm) - self.cancellation_service = Mock() - self.cancellation_service.check_if_cancelled = Mock(return_value=False) - clone_result = Mock(vmName="whatever") - self.deployer = Mock() - self.deployer.deploy_clone_from_vm = Mock(return_value=clone_result) + self.pyvmomi_service.get_vm_by_uuid = MagicMock(return_value=vm) + self.cancellation_service = MagicMock() + self.cancellation_service.check_if_cancelled = MagicMock(return_value=False) + clone_result = MagicMock(vmName="whatever") + self.deployer = MagicMock() + self.deployer.deploy_clone_from_vm = MagicMock(return_value=clone_result) self.save_command = SaveAppCommand( pyvmomi_service=self.pyvmomi_service, - task_waiter=Mock(), + task_waiter=MagicMock(), deployer=self.deployer, resource_model_parser=MockResourceParser(), - snapshot_saver=Mock(), + snapshot_saver=MagicMock(), folder_manager=self.folder_manager, cancellation_service=self.cancellation_service, - port_group_configurer=Mock(), + port_group_configurer=MagicMock(), ) def test_save_runs_successfully(self): @@ -51,14 +55,16 @@ def test_save_runs_successfully(self): save_action2 = self._create_arbitrary_save_app_action() # path to save apps folder and saved sandbox folder uses default datacenter and vm location - vcenter_data_model = Mock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "QualiSB Cluster" vcenter_data_model.vm_location = "QualiFolder" vcenter_data_model.holding_network = "DEFAULT NETWORK" result = self.save_command.save_app( - si=Mock(), - logger=Mock(), + si=MagicMock(), + logger=MagicMock(), + session=MagicMock(), + app_resource_model=MagicMock(), vcenter_data_model=vcenter_data_model, reservation_id="abc", save_app_actions=[save_action1, save_action2], @@ -78,17 +84,19 @@ def test_exception_thrown_if_command_cancelled_before_anything_runs(self): save_action1 = self._create_arbitrary_save_app_action() save_action2 = self._create_arbitrary_save_app_action() - vcenter_data_model = Mock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "QualiSB Cluster" vcenter_data_model.vm_location = "QualiFolder" - cancellation_context = Mock() + cancellation_context = MagicMock() cancellation_context.is_cancelled = True with self.assertRaises(Exception) as context: self.save_command.save_app( - si=Mock(), - logger=Mock(), + si=MagicMock(), + logger=MagicMock(), + session=MagicMock(), + app_resource_model=MagicMock(), vcenter_data_model=vcenter_data_model, reservation_id="abc", save_app_actions=[save_action1, save_action2], @@ -100,29 +108,31 @@ def test_destroy_on_vms_and_folders_if_command_cancelled_during_deploy(self): save_action1 = self._create_arbitrary_save_app_action() save_action2 = self._create_arbitrary_save_app_action() - vcenter_data_model = Mock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "QualiSB Cluster" vcenter_data_model.vm_location = "QualiFolder" return_values = [False, True] - cancellation_service = Mock() - cancellation_service.check_if_cancelled = Mock(side_effect=return_values) + cancellation_service = MagicMock() + cancellation_service.check_if_cancelled = MagicMock(side_effect=return_values) self.save_command = SaveAppCommand( pyvmomi_service=self.pyvmomi_service, - task_waiter=Mock(), + task_waiter=MagicMock(), deployer=self.deployer, resource_model_parser=MockResourceParser(), - snapshot_saver=Mock(), + snapshot_saver=MagicMock(), folder_manager=self.folder_manager, cancellation_service=cancellation_service, - port_group_configurer=Mock(), + port_group_configurer=MagicMock(), ) result = self.save_command.save_app( - si=Mock(), - logger=Mock(), + si=MagicMock(), + logger=MagicMock(), + session=MagicMock(), + app_resource_model=MagicMock(), vcenter_data_model=vcenter_data_model, reservation_id="abc", save_app_actions=[save_action1, save_action2], @@ -152,15 +162,17 @@ def test_nonempty_saved_sandbox_storage_replaces_default_storage(self): save_action1 = self._create_arbitrary_save_app_action() # path to save apps folder and saved sandbox folder uses default datacenter and vm location - vcenter_data_model = Mock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "QualiSB Cluster" vcenter_data_model.vm_location = "QualiFolder" vcenter_data_model.saved_sandbox_storage = "sandbox_storage" vcenter_data_model.vm_storage = "default_storage" self.save_command.save_app( - si=Mock(), - logger=Mock(), + si=MagicMock(), + logger=MagicMock(), + session=MagicMock(), + app_resource_model=MagicMock(), vcenter_data_model=vcenter_data_model, reservation_id="abc", save_app_actions=[save_action1], @@ -185,15 +197,17 @@ def test_empty_saved_sandbox_storage_does_not_replace_default_storage(self): save_action1 = self._create_arbitrary_save_app_action() # path to save apps folder and saved sandbox folder uses default datacenter and vm location - vcenter_data_model = Mock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "QualiSB Cluster" vcenter_data_model.vm_location = "QualiFolder" vcenter_data_model.saved_sandbox_storage = "" vcenter_data_model.vm_storage = "default_storage" self.save_command.save_app( - si=Mock(), - logger=Mock(), + si=MagicMock(), + logger=MagicMock(), + session=MagicMock(), + app_resource_model=MagicMock(), vcenter_data_model=vcenter_data_model, reservation_id="abc", save_app_actions=[save_action1], @@ -222,19 +236,21 @@ def test_behavior_during_save_configured_as_power_off(self): "Behavior during save" ] = "Power Off" - vm = Mock() + vm = MagicMock() vm.summary.runtime.powerState = "poweredOn" vm.name = "some string" - self.save_command.pyvmomi_service.find_by_uuid = Mock(return_value=vm) + self.save_command.pyvmomi_service.find_by_uuid = MagicMock(return_value=vm) - vcenter_data_model = Mock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "QualiSB Cluster" vcenter_data_model.vm_location = "QualiFolder" vcenter_data_model.holding_network = "DEFAULT NETWORK" result = self.save_command.save_app( - si=Mock(), - logger=Mock(), + si=MagicMock(), + logger=MagicMock(), + session=MagicMock(), + app_resource_model=MagicMock(), vcenter_data_model=vcenter_data_model, reservation_id="abc", save_app_actions=[save_action], @@ -253,7 +269,7 @@ def test_behavior_during_save_configured_as_power_off_on_vcenter_model_empty_on_ ): # if behavior during save is empty on deployment, default to vcenter model - vcenter_data_model = Mock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "QualiSB Cluster" vcenter_data_model.vm_location = "QualiFolder" vcenter_data_model.holding_network = "DEFAULT NETWORK" @@ -262,14 +278,16 @@ def test_behavior_during_save_configured_as_power_off_on_vcenter_model_empty_on_ save_action.actionParams.deploymentPathAttributes["Behavior during save"] = "" vcenter_data_model.behavior_during_save = "Power Off" - vm = Mock() + vm = MagicMock() vm.summary.runtime.powerState = "poweredOn" vm.name = "some string" - self.save_command.pyvmomi_service.find_by_uuid = Mock(return_value=vm) + self.save_command.pyvmomi_service.find_by_uuid = MagicMock(return_value=vm) result = self.save_command.save_app( - si=Mock(), - logger=Mock(), + si=MagicMock(), + logger=MagicMock(), + session=MagicMock(), + app_resource_model=MagicMock(), vcenter_data_model=vcenter_data_model, reservation_id="abc", save_app_actions=[save_action], @@ -292,14 +310,14 @@ def test_create_saved_apps_folder_if_not_found_in_vcenter(self): save_action = self._create_arbitrary_save_app_action() - vcenter_data_model = Mock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "QualiSB Cluster" vcenter_data_model.vm_location = "QualiFolder" vcenter_data_model.holding_network = "DEFAULT NETWORK" - vm_location_folder = Mock() + vm_location_folder = MagicMock() - self.save_command.pyvmomi_service.get_folder = Mock( + self.save_command.pyvmomi_service.get_folder = MagicMock( side_effect=[ vm_location_folder, None, @@ -311,8 +329,10 @@ def test_create_saved_apps_folder_if_not_found_in_vcenter(self): ) result = self.save_command.save_app( - si=Mock(), - logger=Mock(), + si=MagicMock(), + logger=MagicMock(), + session=MagicMock(), + app_resource_model=MagicMock(), vcenter_data_model=vcenter_data_model, reservation_id="abc", save_app_actions=[save_action], @@ -330,12 +350,12 @@ def test_create_saved_sandbox_folder_if_not_found_in_vcenter(self): # show the sandbox folder under saved apps folder is created when doesnt exist save_action = self._create_arbitrary_save_app_action() - vcenter_data_model = Mock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "QualiSB Cluster" vcenter_data_model.vm_location = "QualiFolder" vcenter_data_model.holding_network = "DEFAULT NETWORK" - saved_apps_folder = Mock() + saved_apps_folder = MagicMock() def cant_find_saved_apps_folder(si, path): if ( @@ -350,13 +370,15 @@ def cant_find_saved_apps_folder(si, path): return None return saved_apps_folder - self.save_command.pyvmomi_service.get_folder = Mock( + self.save_command.pyvmomi_service.get_folder = MagicMock( side_effect=cant_find_saved_apps_folder ) result = self.save_command.save_app( - si=Mock(), - logger=Mock(), + si=MagicMock(), + logger=MagicMock(), + session=MagicMock(), + app_resource_model=MagicMock(), vcenter_data_model=vcenter_data_model, reservation_id="abc", save_app_actions=[save_action], @@ -388,18 +410,20 @@ def test_error_thrown_during_save(self): save_action = self._create_arbitrary_save_app_action() - self.save_command.deployer = Mock() + self.save_command.deployer = MagicMock() error_message = "Save app action was rolled back" - self.save_command.deployer.deploy_clone_from_vm = Mock( + self.save_command.deployer.deploy_clone_from_vm = MagicMock( side_effect=Exception(error_message) ) - vcenter_data_model = Mock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "QualiSB Cluster" vcenter_data_model.vm_location = "QualiFolder" result = self.save_command.save_app( - si=Mock(), - logger=Mock(), + si=MagicMock(), + logger=MagicMock(), + session=MagicMock(), + app_resource_model=MagicMock(), vcenter_data_model=vcenter_data_model, reservation_id="abc", save_app_actions=[save_action], @@ -411,41 +435,15 @@ def test_error_thrown_during_save(self): self.assertTrue(not result[0].success) self.assertTrue(result[0].errorMessage == error_message) - def test_save_fails_due_to_unsupported_save_type(self): - # if cloud provider sends an invalid save action with unsupported save type - # an exception will be thrown - - save_action = self._create_arbitrary_save_app_action() - save_action.actionParams.saveDeploymentModel = "mass quantum cloning" - - vcenter_data_model = Mock() - vcenter_data_model.default_datacenter = "QualiSB Cluster" - vcenter_data_model.vm_location = "QualiFolder" - result = self.save_command.save_app( - si=Mock(), - logger=Mock(), - vcenter_data_model=vcenter_data_model, - reservation_id="abc", - save_app_actions=[save_action], - cancellation_context=None, - ) - - # Assert - self.assertTrue(not result[0].success) - self.assertTrue( - result[0].errorMessage - == "Unsupported save type {0}".format( - save_action.actionParams.saveDeploymentModel - ) - ) - def _save_app_without_actions(self): - vcenter_data_model = Mock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "QualiSB Cluster" vcenter_data_model.vm_location = "QualiFolder" self.save_command.save_app( - si=Mock(), - logger=Mock(), + si=MagicMock(), + logger=MagicMock(), + session=MagicMock(), + app_resource_model=MagicMock(), vcenter_data_model=vcenter_data_model, reservation_id="abc", save_app_actions=[], diff --git a/tests/test_commands/test_save_snapshot.py b/tests/test_commands/test_save_snapshot.py index a007772..af9fe78 100644 --- a/tests/test_commands/test_save_snapshot.py +++ b/tests/test_commands/test_save_snapshot.py @@ -1,12 +1,17 @@ +import sys from unittest import TestCase -from mock import Mock, patch - from cloudshell.cp.vcenter.commands.save_snapshot import SaveSnapshotCommand from cloudshell.cp.vcenter.exceptions.snapshot_exists import ( SnapshotAlreadyExistsException, ) +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock, patch +else: + from mock import MagicMock, patch + + GET_VM_SNAPSHOTS = ( "cloudshell.cp.vcenter.commands.save_snapshot.SnapshotRetriever.get_vm_snapshots" ) @@ -16,13 +21,13 @@ class TestSaveSnapshotCommand(TestCase): def test_save_snapshot_should_succeed_when_there_is_no_snapshot(self): - vm = Mock() + vm = MagicMock() - pyvmomi_service = Mock() - pyvmomi_service.find_by_uuid = Mock(return_value=vm) + pyvmomi_service = MagicMock() + pyvmomi_service.find_by_uuid = MagicMock(return_value=vm) - save_snapshot_command = SaveSnapshotCommand(pyvmomi_service, Mock()) - si = Mock() + save_snapshot_command = SaveSnapshotCommand(pyvmomi_service, MagicMock()) + si = MagicMock() # Act with patch(GET_CURRENT_SNAPSHOT_NAME) as get_current_snapshot_name: @@ -31,7 +36,7 @@ def test_save_snapshot_should_succeed_when_there_is_no_snapshot(self): get_vm_snapshots.return_value = {} save_snapshot_command.save_snapshot( si=si, - logger=Mock(), + logger=MagicMock(), vm_uuid="machine1", snapshot_name="new_snapshot", save_memory="No", @@ -45,13 +50,13 @@ def test_save_snapshot_should_succeed_when_there_is_no_snapshot(self): def test_save_snapshot_should_succeed_when_snapshot_with_the_same_name_does_not_exists( self, ): - vm = Mock() + vm = MagicMock() - pyvmomi_service = Mock() - pyvmomi_service.find_by_uuid = Mock(return_value=vm) + pyvmomi_service = MagicMock() + pyvmomi_service.find_by_uuid = MagicMock(return_value=vm) - save_snapshot_command = SaveSnapshotCommand(pyvmomi_service, Mock()) - si = Mock() + save_snapshot_command = SaveSnapshotCommand(pyvmomi_service, MagicMock()) + si = MagicMock() # Act with patch(GET_CURRENT_SNAPSHOT_NAME) as get_current_snapshot_name: @@ -63,7 +68,7 @@ def test_save_snapshot_should_succeed_when_snapshot_with_the_same_name_does_not_ } save_snapshot_command.save_snapshot( si=si, - logger=Mock(), + logger=MagicMock(), vm_uuid="machine1", snapshot_name="new_snapshot", save_memory="No", @@ -75,13 +80,13 @@ def test_save_snapshot_should_succeed_when_snapshot_with_the_same_name_does_not_ ) def test_save_snapshot_should_fail_if_snaphost_exists(self): - vm = Mock() + vm = MagicMock() - pyvmomi_service = Mock() - pyvmomi_service.find_by_uuid = Mock(return_value=vm) + pyvmomi_service = MagicMock() + pyvmomi_service.find_by_uuid = MagicMock(return_value=vm) - save_snapshot_command = SaveSnapshotCommand(pyvmomi_service, Mock()) - si = Mock() + save_snapshot_command = SaveSnapshotCommand(pyvmomi_service, MagicMock()) + si = MagicMock() with patch(GET_CURRENT_SNAPSHOT_NAME) as get_current_snapshot_name: with patch(GET_VM_SNAPSHOTS) as get_vm_snapshots: @@ -95,7 +100,7 @@ def test_save_snapshot_should_fail_if_snaphost_exists(self): with self.assertRaises(SnapshotAlreadyExistsException): save_snapshot_command.save_snapshot( si=si, - logger=Mock(), + logger=MagicMock(), vm_uuid="machine1", snapshot_name="snapshot2", save_memory="No", diff --git a/tests/test_commands/test_vm_details.py b/tests/test_commands/test_vm_details.py index e52923a..0035b2a 100644 --- a/tests/test_commands/test_vm_details.py +++ b/tests/test_commands/test_vm_details.py @@ -1,3 +1,4 @@ +import sys from unittest import TestCase from cloudshell.cp.core.models import ( @@ -5,54 +6,59 @@ VmDetailsNetworkInterface, VmDetailsProperty, ) -from mock import Mock, mock from pyVmomi import vim from cloudshell.cp.vcenter.commands.vm_details import VmDetailsCommand -from cloudshell.cp.vcenter.network.vnic.vnic_service import VNicService from cloudshell.cp.vcenter.vm.ip_manager import VMIPManager from cloudshell.cp.vcenter.vm.vm_details_provider import ( VmDetailsData, VmDetailsProvider, ) +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock, patch +else: + from mock import MagicMock, patch + class TestVmDetailsCommand(TestCase): - @mock.patch("tests.test_commands.test_vm_details.VNicService.get_network_by_device") + @patch( + "cloudshell.cp.vcenter.network.vnic.vnic_service.VNicService.get_network_by_device" + ) def test(self, get_network_by_device): # ARRANGE - network = Mock() + network = MagicMock() network.name = "Net1" network.config.defaultPortConfig.vlan.vlanId = "65" get_network_by_device.return_value = network vm = self.mock_vm() - si = Mock() - pyvmomi_service = Mock() - pyvmomi_service.find_by_uuid = Mock(return_value=vm) - ip_regex_param = Mock() + si = MagicMock() + pyvmomi_service = MagicMock() + pyvmomi_service.find_by_uuid = MagicMock(return_value=vm) + ip_regex_param = MagicMock() ip_regex_param.name = "ip_regex" ip_regex_param.value = ".*" - wait_for_ip_param = Mock() + wait_for_ip_param = MagicMock() wait_for_ip_param.name = "wait_for_ip" wait_for_ip_param.value = "True" - request = Mock() + request = MagicMock() request.deployedAppJson.name = "App1" request.deployedAppJson.vmdetails.vmCustomParams = [ ip_regex_param, wait_for_ip_param, ] request.appRequestJson.deploymentService.model = "vCenter Clone VM From VM" - request.appRequestJson.deploymentService.attributes = [Mock()] - resource_context = Mock() + request.appRequestJson.deploymentService.attributes = [MagicMock()] + resource_context = MagicMock() resource_context.attributes = {"Reserved Networks": "Net1;B"} - cancellation_context = Mock(is_cancelled=False) + cancellation_context = MagicMock(is_cancelled=False) ip_manager = VMIPManager() vm_details_provider = VmDetailsProvider(pyvmomi_service, ip_manager) # ACT command = VmDetailsCommand(pyvmomi_service, vm_details_provider) datas = command.get_vm_details( si=si, - logger=Mock(), + logger=MagicMock(), resource_context=resource_context, requests=[request], cancellation_context=cancellation_context, @@ -87,7 +93,7 @@ def test(self, get_network_by_device): self.assertEqual(self._get_value(nic.networkData, "Port Group Name"), "Net1") def mock_vm(self): - vm = Mock() + vm = MagicMock() vm.summary.config.memorySizeMB = 2 * 1024 disk = vim.vm.device.VirtualDisk() disk.capacityInKB = 20 * 1024 * 1024 @@ -99,14 +105,14 @@ def mock_vm(self): vm.config.hardware.device = [disk, nic] vm.summary.config.numCpu = 4 vm.summary.config.guestFullName = "Centos" - node = Mock() - node.snapshot = Mock() + node = MagicMock() + node.snapshot = MagicMock() node.name = "Snap1" vm.snapshot.rootSnapshotList = [ node - ] # [Mock(snapshot=snapshot,name=Mock(return_value='Snap1'))] + ] # [MagicMock(snapshot=snapshot,name=MagicMock(return_value='Snap1'))] vm.snapshot.currentSnapshot = node.snapshot - vm.guest.net = [Mock(deviceConfigId="2", ipAddress=["1.2.3.4"])] + vm.guest.net = [MagicMock(deviceConfigId="2", ipAddress=["1.2.3.4"])] vm.guest.ipAddress = "1.2.3.4" return vm @@ -115,32 +121,3 @@ def _get_value(self, data, key): if item.key == key: return item.value return None - - # def integration(self): - # credentials = TestCredentials() - # py_vmomi_service = pyVmomiService(connect=SmartConnect, disconnect=Disconnect, - # task_waiter=SynchronousTaskWaiter()) - # si = py_vmomi_service.connect(credentials.host, credentials.username, credentials.password) - # - # vm_details_provider = VmDetailsProvider(py_vmomi_service,VMIPManager()) - # cancel = Mock() - # cancel.is_cancelled = False - # logger = Mock() - # resource_context = Mock() - # resource_context.attributes = {'Reserved Networks': 'A'} - # requests = [Mock()] - # requests[0].deployedAppJson = Mock() - # requests[0].deployedAppJson.name = 'SomeApp' - # requests[0].deployedAppJson.vmdetails = Mock() - # requests[0].deployedAppJson.vmdetails.uid = '423283e4-0003-6e04-07bb-7e4c3ebcf993' - # requests[0].deployedAppJson.vmdetails.vmCustomParams = [] - # requests[0].appRequestJson = Mock() - # requests[0].appRequestJson.deploymentService = Mock() - # requests[0].appRequestJson.deploymentService.model = 'vCenter Clone VM From VM' - # requests[0].appRequestJson.deploymentService.attributes = [Mock()] - # - # vm = py_vmomi_service.find_by_uuid(si, '423283e4-0003-6e04-07bb-7e4c3ebcf993') - # - # cmd = VmDetailsCommand(py_vmomi_service, vm_details_provider) - # d = cmd.get_vm_details(si, logger, resource_context, requests, cancel) - # pass diff --git a/tests/test_commands/test_vm_loader.py b/tests/test_commands/test_vm_loader.py index bae3fd8..88dedb1 100644 --- a/tests/test_commands/test_vm_loader.py +++ b/tests/test_commands/test_vm_loader.py @@ -1,24 +1,29 @@ +import sys from unittest import TestCase -from mock import Mock, create_autospec from pyVmomi import vim from cloudshell.cp.vcenter.commands.load_vm import VMLoader +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock +else: + from mock import MagicMock + class TestCommandOrchestrator(TestCase): def setUp(self): - self.vc_model = Mock() + self.vc_model = MagicMock() self.vc_model.default_datacenter = "datacenter" - self.pv_service = Mock() + self.pv_service = MagicMock() self.vm_loader = VMLoader(self.pv_service) - self.si = Mock() + self.si = MagicMock() def test_get_vm_uuid(self): - vm = Mock(spec=vim.VirtualMachine) - vm.config = Mock() + vm = MagicMock(spec=vim.VirtualMachine) + vm.config = MagicMock() vm.config.uuid = "this is the uuid" - self.pv_service.find_vm_by_name = Mock(return_value=vm) + self.pv_service.find_vm_by_name = MagicMock(return_value=vm) path = "raz/abadi\\c" res = self.vm_loader.load_vm_uuid_by_name(self.si, self.vc_model, path) @@ -30,10 +35,10 @@ def test_get_vm_uuid(self): ) def test_get_vm_uuid_not_vm(self): - vm = Mock() - vm.config = Mock() + vm = MagicMock() + vm.config = MagicMock() vm.config.uuid = "this is the uuid" - self.pv_service.find_vm_by_name = Mock(return_value=vm) + self.pv_service.find_vm_by_name = MagicMock(return_value=vm) self.assertRaises( ValueError, @@ -45,7 +50,7 @@ def test_get_vm_uuid_not_vm(self): def test_get_vm_uuid_None(self): vm = None - self.pv_service.find_vm_by_name = Mock(return_value=vm) + self.pv_service.find_vm_by_name = MagicMock(return_value=vm) self.assertRaises( ValueError, diff --git a/tests/test_common/test_cloudshell/test_connection_detail_retriever.py b/tests/test_common/test_cloudshell/test_connection_detail_retriever.py index 9c9a8d4..d286cf7 100644 --- a/tests/test_common/test_cloudshell/test_connection_detail_retriever.py +++ b/tests/test_common/test_cloudshell/test_connection_detail_retriever.py @@ -1,7 +1,6 @@ +import sys from unittest import TestCase -from mock import Mock - from cloudshell.cp.vcenter.common.cloud_shell.conn_details_retriever import ( ResourceConnectionDetailsRetriever, ) @@ -9,14 +8,19 @@ VMwarevCenterResourceModel, ) +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock +else: + from mock import MagicMock + class TestConnectionDetailRetriever(TestCase): def test_connection_detail_retriever(self): - session = Mock() - decrypted_password = Mock() + session = MagicMock() + decrypted_password = MagicMock() decrypted_password.Value = "decrypted password" - session.DecryptPassword = Mock(return_value=decrypted_password) - resource_context = Mock() + session.DecryptPassword = MagicMock(return_value=decrypted_password) + resource_context = MagicMock() resource_context.address = "192.168.1.1" vcenter_data_model = VMwarevCenterResourceModel() diff --git a/tests/test_common/test_cloudshell/test_resource_remover.py b/tests/test_common/test_cloudshell/test_resource_remover.py index 1f6c263..8ea8cf3 100644 --- a/tests/test_common/test_cloudshell/test_resource_remover.py +++ b/tests/test_common/test_cloudshell/test_resource_remover.py @@ -1,21 +1,24 @@ +import sys from unittest import TestCase -from mock import Mock - from cloudshell.cp.vcenter.common.cloud_shell.resource_remover import ( CloudshellResourceRemover, ) +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock +else: + from mock import MagicMock + class TestResourceRemover(TestCase): def test_resource_remover(self): # assert - helpers = Mock() - session = Mock() + session = MagicMock() to_remove = "remove this" - session.DeleteResource = Mock(return_value=True) - session = Mock(return_value=session) + session.DeleteResource = MagicMock(return_value=True) + session = MagicMock(return_value=session) resource_remmover = CloudshellResourceRemover() # act diff --git a/tests/test_common/test_logger/__init__.py b/tests/test_common/test_logger/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/tests/test_common/test_utilities/test_command_wrapper.py b/tests/test_common/test_utilities/test_command_wrapper.py index 9bf1794..da5108f 100644 --- a/tests/test_common/test_utilities/test_command_wrapper.py +++ b/tests/test_common/test_utilities/test_command_wrapper.py @@ -1,3 +1,4 @@ +import sys from unittest import TestCase from cloudshell.shell.core.driver_context import ( @@ -6,19 +7,23 @@ ResourceCommandContext, ResourceContextDetails, ) -from mock import Mock, create_autospec, patch from cloudshell.cp.vcenter.common.wrappers.command_wrapper import CommandWrapper +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock, patch, create_autospec +else: + from mock import MagicMock, patch, create_autospec + class TestCommandWrapper(TestCase): def setUp(self): - self.si = Mock() - self.logger = Mock() - self.pv_service = Mock() - self.pv_service.connect = Mock(return_value=self.si) - self.cloud_shell_helper = Mock() - self.resource_model_parser = Mock() + self.si = MagicMock() + self.logger = MagicMock() + self.pv_service = MagicMock() + self.pv_service.connect = MagicMock(return_value=self.si) + self.cloud_shell_helper = MagicMock() + self.resource_model_parser = MagicMock() def test_execute_command_with_params_and_vcetner_data_model_with_session_inject( self, @@ -40,7 +45,7 @@ def fake_command_with_connection_return_true_2( wrapper = CommandWrapper( pv_service=self.pv_service, resource_model_parser=self.resource_model_parser, - context_based_logger_factory=Mock(), + context_based_logger_factory=MagicMock(), ) context = self._create_resource_command_context() @@ -68,7 +73,7 @@ def fake_command_with_connection_return_true( wrapper = CommandWrapper( pv_service=self.pv_service, resource_model_parser=self.resource_model_parser, - context_based_logger_factory=Mock(), + context_based_logger_factory=MagicMock(), ) context = self._create_resource_command_context() @@ -90,7 +95,7 @@ def fake_command_with_connection_return_true(si, session, fake1, fake2): wrapper = CommandWrapper( pv_service=self.pv_service, resource_model_parser=self.resource_model_parser, - context_based_logger_factory=Mock(), + context_based_logger_factory=MagicMock(), ) context = self._create_resource_command_context() @@ -112,7 +117,7 @@ def fake_command_with_connection_return_true(si, fake1, fake2): wrapper = CommandWrapper( pv_service=self.pv_service, resource_model_parser=self.resource_model_parser, - context_based_logger_factory=Mock(), + context_based_logger_factory=MagicMock(), ) context = self._create_resource_command_context() diff --git a/tests/test_common/test_vcenter/test_ovf_image_tool.py b/tests/test_common/test_vcenter/test_ovf_image_tool.py index c2d9314..f4388b6 100644 --- a/tests/test_common/test_vcenter/test_ovf_image_tool.py +++ b/tests/test_common/test_vcenter/test_ovf_image_tool.py @@ -1,16 +1,21 @@ +import sys import unittest import urllib.error import urllib.parse import urllib.request -from mock import Mock, patch - from cloudshell.cp.vcenter.common.vcenter.ovf_service import OvfImageDeployerService from cloudshell.cp.vcenter.models.VCenterConnectionDetails import ( VCenterConnectionDetails, ) -PROCESS = Mock() +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock, patch +else: + from mock import MagicMock, patch + + +PROCESS = MagicMock() class ProccesMock: @@ -24,7 +29,7 @@ def Popen(*args, **kwargs): class TestOvfImageService(unittest.TestCase): @patch("subprocess.Popen", ProccesMock.Popen) def test_deploy_image_success(self): - PROCESS.communicate = Mock(return_value=["Completed successfully"]) + PROCESS.communicate = MagicMock(return_value=["Completed successfully"]) expected_args = [ "dummypath/ovftool.exe", "--noSSLVerify", @@ -38,7 +43,7 @@ def test_deploy_image_success(self): "vi://vcenter%20user:password%20to%20vcenter@venter.host.com/QualiSB/host/QualiSB%20Cluster/Resources/LiverPool", ] ovf = OvfImageDeployerService("dummypath/ovftool.exe") - image_params = Mock() + image_params = MagicMock() image_params.connectivity = VCenterConnectionDetails( "venter.host.com", "vcenter user", "password to vcenter" ) @@ -54,12 +59,12 @@ def test_deploy_image_success(self): image_params.image_url = "http://192.168.65.88/ovf/Debian 64 - Yoav.ovf" image_params.user_arguments = '--vlan="anetwork"' - vcenter_data_model = Mock() + vcenter_data_model = MagicMock() vcenter_data_model.ovf_tool_path = "dummypath/ovftool.exe" - ovf._validate_url_exists = Mock(return_value=True) + ovf._validate_url_exists = MagicMock(return_value=True) - res = ovf.deploy_image(vcenter_data_model, image_params, logger=Mock()) + res = ovf.deploy_image(vcenter_data_model, image_params, logger=MagicMock()) self.assertTrue(res) self.assertEqual(PROCESS.args, expected_args) @@ -68,9 +73,9 @@ def test_deploy_image_success(self): @patch("subprocess.Popen", ProccesMock.Popen) def test_deploy_image_no_communication(self): - PROCESS.communicate = Mock(return_value=None) + PROCESS.communicate = MagicMock(return_value=None) ovf = OvfImageDeployerService("dummypath/ovftool.exe") - image_params = Mock() + image_params = MagicMock() image_params.connectivity = VCenterConnectionDetails( "venter.host.com", "vcenter user", "password to vcenter" ) @@ -80,22 +85,21 @@ def test_deploy_image_no_communication(self): image_params.vm_name = "raz_deploy_image_integration_test" image_params.resource_pool = "LiverPool" image_params.datastore = "aa" - # image_params.image_url = "C:\\images\\test\\OVAfile121_QS\\OVAfile121_QS.ovf" image_params.image_url = "http://192.168.65.88/ovf/Debian 64 - Yoav.ovf" image_params.user_arguments = '--vlan="anetwork"' - vcenter_data_model = Mock() + vcenter_data_model = MagicMock() vcenter_data_model.ovf_tool_path = "dummypath/ovftool.exe" - ovf._validate_url_exists = Mock(return_value=True) + ovf._validate_url_exists = MagicMock(return_value=True) self.assertRaises(Exception, ovf.deploy_image, vcenter_data_model, image_params) @patch("subprocess.Popen", ProccesMock.Popen) def test_deploy_image_error(self): - PROCESS.communicate = Mock(return_value=["error"]) + PROCESS.communicate = MagicMock(return_value=["error"]) ovf = OvfImageDeployerService("dummypath/ovftool.exe") - image_params = Mock() + image_params = MagicMock() image_params.connectivity = VCenterConnectionDetails( "venter.host.com", "vcenter user", "password to vcenter" ) @@ -104,18 +108,17 @@ def test_deploy_image_error(self): image_params.resource_pool = "LiverPool" image_params.vm_name = "raz_deploy_image_integration_test" image_params.datastore = "aa" - # image_params.image_url = "C:\\images\\test\\OVAfile121_QS\\OVAfile121_QS.ovf" image_params.image_url = "http://192.168.65.88/ovf/Debian 64 - Yoav.ovf" image_params.user_arguments = '--vlan="anetwork"' - ovf._validate_url_exists = Mock(return_value=True) + ovf._validate_url_exists = MagicMock(return_value=True) - vcenter_data_model = Mock() + vcenter_data_model = MagicMock() vcenter_data_model.ovf_tool_path = "dummypath/ovftool.exe" try: - ovf.deploy_image(vcenter_data_model, image_params, logger=Mock()) + ovf.deploy_image(vcenter_data_model, image_params, logger=MagicMock()) # should not reach here self.assertTrue(False) except Exception as inst: diff --git a/tests/test_common/test_vcenter/test_task_waiter.py b/tests/test_common/test_vcenter/test_task_waiter.py index aab45d2..415f0ca 100644 --- a/tests/test_common/test_vcenter/test_task_waiter.py +++ b/tests/test_common/test_vcenter/test_task_waiter.py @@ -1,11 +1,17 @@ +import sys import unittest -from mock import Mock, patch from pyVmomi import vim from cloudshell.cp.vcenter.common.vcenter.task_waiter import SynchronousTaskWaiter -task = Mock(spec=vim.Task) +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock, patch +else: + from mock import MagicMock, patch + + +task = MagicMock(spec=vim.Task) class helper: @@ -23,49 +29,49 @@ def change_to_error(a): class TestTaskWaiter(unittest.TestCase): @patch("time.sleep", helper.change_to_success) def test_wait_for_task(self): - task.info = Mock(spec=vim.TaskInfo) + task.info = MagicMock(spec=vim.TaskInfo) task.info.state = vim.TaskInfo.State.running result = "result" task.info.result = result waiter = SynchronousTaskWaiter() res = waiter.wait_for_task( - task=task, logger=Mock(), action_name="job", hide_result=False + task=task, logger=MagicMock(), action_name="job", hide_result=False ) self.assertEqual(res, result) @patch("time.sleep", helper.change_to_success) def test_wait_for_queued_task(self): - task.info = Mock(spec=vim.TaskInfo) + task.info = MagicMock(spec=vim.TaskInfo) task.info.state = vim.TaskInfo.State.queued result = "result" task.info.result = result waiter = SynchronousTaskWaiter() res = waiter.wait_for_task( - task=task, logger=Mock(), action_name="job", hide_result=False + task=task, logger=MagicMock(), action_name="job", hide_result=False ) self.assertEqual(res, result) @patch("time.sleep", helper.change_to_success) def test_wait_for_task_result_none(self): - task.info = Mock(spec=vim.TaskInfo) + task.info = MagicMock(spec=vim.TaskInfo) task.info.state = vim.TaskInfo.State.running result = "result" task.info.result = None waiter = SynchronousTaskWaiter() res = waiter.wait_for_task( - task=task, logger=Mock(), action_name="job", hide_result=False + task=task, logger=MagicMock(), action_name="job", hide_result=False ) self.assertIsNone(res, result) @patch("time.sleep", helper.change_to_error) def test_wait_for_task_fail(self): - task.info = Mock(spec=vim.TaskInfo) + task.info = MagicMock(spec=vim.TaskInfo) task.info.error = "error" task.info.state = vim.TaskInfo.State.running result = "result" diff --git a/tests/test_common/test_vcenter/test_vcenter_data_model_retriever.py b/tests/test_common/test_vcenter/test_vcenter_data_model_retriever.py index 34e32bf..c23562d 100644 --- a/tests/test_common/test_vcenter/test_vcenter_data_model_retriever.py +++ b/tests/test_common/test_vcenter/test_vcenter_data_model_retriever.py @@ -1,19 +1,23 @@ +import sys import unittest -from mock import Mock, create_autospec - from cloudshell.cp.vcenter.common.model_factory import ResourceModelParser from cloudshell.cp.vcenter.common.vcenter.data_model_retriever import ( VCenterDataModelRetriever, ) from cloudshell.cp.vcenter.models.QualiDriverModels import ResourceContextDetails +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock, create_autospec +else: + from mock import MagicMock, create_autospec + class TestVCenterDataModelRetriever(unittest.TestCase): def test_get_vcenter_data_model(self): # Arrange data_model_retriever = VCenterDataModelRetriever(ResourceModelParser()) - api = Mock() + api = MagicMock() vcenter_resource = create_autospec(ResourceContextDetails) vcenter_resource.model = "VMWare vCenter" @@ -36,7 +40,7 @@ def test_get_vcenter_data_model(self): "saved_sandbox_storage": "", } - api.GetResourceDetails = Mock(return_value=vcenter_resource) + api.GetResourceDetails = MagicMock(return_value=vcenter_resource) # Act vcenter_data_model = data_model_retriever.get_vcenter_data_model( @@ -49,7 +53,7 @@ def test_get_vcenter_data_model(self): def test_get_vcenter_data_model_empty_vcenter_name(self): # Arrange data_model_retriever = VCenterDataModelRetriever(ResourceModelParser()) - api = Mock() + api = MagicMock() vcenter_resource = create_autospec(ResourceContextDetails) vcenter_resource.model = "VMWare vCenter" @@ -70,7 +74,7 @@ def test_get_vcenter_data_model_empty_vcenter_name(self): "promiscuous_mode": "", } - api.GetResourceDetails = Mock(return_value=vcenter_resource) + api.GetResourceDetails = MagicMock(return_value=vcenter_resource) # Act + Assert self.assertRaises( diff --git a/tests/test_common/test_vcenter/test_vm_snapshots.py b/tests/test_common/test_vcenter/test_vm_snapshots.py index 8e78340..d83619f 100644 --- a/tests/test_common/test_vcenter/test_vm_snapshots.py +++ b/tests/test_common/test_vcenter/test_vm_snapshots.py @@ -1,9 +1,13 @@ +import sys import unittest -from mock import Mock - from cloudshell.cp.vcenter.common.vcenter.vm_snapshots import SnapshotRetriever +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock +else: + from mock import MagicMock + class TestSnapshotRetriever(unittest.TestCase): def test_ctor(self): @@ -12,7 +16,7 @@ def test_ctor(self): def test_empty_dict_when_vm_has_no_snapshots(self): # Arrange - vm = Mock() + vm = MagicMock() vm.snapshot = None # Act @@ -23,12 +27,12 @@ def test_empty_dict_when_vm_has_no_snapshots(self): def test_one_snapshot_when_one_snapshot_exists(self): # Arrange - snapshot = Mock() + snapshot = MagicMock() snapshot.name = "snap1" snapshot.childSnapshotList = [] - vm = Mock() - vm.snapshot = Mock() + vm = MagicMock() + vm.snapshot = MagicMock() vm.snapshot.rootSnapshotList = [snapshot] # Act @@ -39,16 +43,16 @@ def test_one_snapshot_when_one_snapshot_exists(self): def test_two_snapshots_when_root_snapshot_has_a_child(self): # Arrange - child = Mock() + child = MagicMock() child.name = "child" child.childSnapshotList = [] - root = Mock() + root = MagicMock() root.name = "root" root.childSnapshotList = [child] - vm = Mock() - vm.snapshot = Mock() + vm = MagicMock() + vm.snapshot = MagicMock() vm.snapshot.rootSnapshotList = [root] # Act @@ -66,7 +70,7 @@ def test_combine_should_combine_base_snapshot_location_with_snapshot_name(self): def test_cet_current_snapshot_returns_none_when_no_snapshot_exists(self): # Arrange - vm = Mock() + vm = MagicMock() vm.snapshot = None # Act diff --git a/tests/test_common/test_vcenter/test_vmomi_service.py b/tests/test_common/test_vcenter/test_vmomi_service.py index 8461f7b..485cc6d 100644 --- a/tests/test_common/test_vcenter/test_vmomi_service.py +++ b/tests/test_common/test_vcenter/test_vmomi_service.py @@ -1,7 +1,7 @@ import unittest +import sys from datetime import datetime -from mock import MagicMock, Mock, create_autospec from pyVim.connect import Disconnect, SmartConnect from pyVmomi import vim @@ -9,6 +9,11 @@ from tests.utils.testing_credentials import TestCredentials +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock, create_autospec +else: + from mock import MagicMock, create_autospec + class TestVmomiService(unittest.TestCase): def setUp(self): @@ -31,7 +36,7 @@ def integration_clone_vm_destory(self): ) "#act" now = datetime.now() - res = pv_service.clone_vm(clone_params=params, logger=Mock()) + res = pv_service.clone_vm(clone_params=params, logger=MagicMock()) "#assert" self.assertTrue(type(res.vm), vim.VirtualMachine) @@ -39,7 +44,7 @@ def integration_clone_vm_destory(self): "#teardown" now = datetime.now() if res.error is None and res.vm is not None: - destroyed = pv_service.destroy_vm(vm=res.vm, logger=Mock()) + destroyed = pv_service.destroy_vm(vm=res.vm, logger=MagicMock()) print(("destroy took: {0}".format(str(datetime.now() - now)))) @@ -50,26 +55,28 @@ def test_clone_vm_power_on_false(self): Checks clone_vm """ "#arrange" - si = Mock(spec=vim.ServiceInstance) - vim_mock = Mock() - vim_mock.vm = Mock() - vim_mock.vm.RelocateSpec = Mock() - vim_mock.vm.CloneSpec = Mock() + si = MagicMock(spec=vim.ServiceInstance) + vim_mock = MagicMock() + vim_mock.vm = MagicMock() + vim_mock.vm.RelocateSpec = MagicMock() + vim_mock.vm.CloneSpec = MagicMock() vim_mock.Datacenter = vim.Datacenter vim_mock.Datastore = vim.Datastore vim_mock.ServiceInstance = vim.ServiceInstance - datacenter = Mock(spec=vim.Datacenter) - template = Mock(spec=vim.VirtualMachine) - template.datastore = [Mock()] - - pv_service = pyVmomiService(None, None, Mock(), vim_import=vim_mock) - pv_service.find_vm_by_name = Mock(return_value=template) - pv_service.get_obj = Mock() - pv_service.get_folder = Mock(return_value=datacenter) - pv_service._get_datastore = Mock(return_value=Mock(spec=vim.Datastore)) - pv_service.get_resource_pool = Mock( - return_value=(Mock(spec=vim.ResourcePool), None) + datacenter = MagicMock(spec=vim.Datacenter) + template = MagicMock(spec=vim.VirtualMachine) + template.datastore = [MagicMock()] + + pv_service = pyVmomiService(None, None, MagicMock(), vim_import=vim_mock) + pv_service.find_vm_by_name = MagicMock(return_value=template) + pv_service.get_obj = MagicMock() + pv_service.get_folder = MagicMock(return_value=datacenter) + pv_service._get_datastore = MagicMock( + return_value=MagicMock(spec=vim.Datastore) + ) + pv_service.get_resource_pool = MagicMock( + return_value=(MagicMock(spec=vim.ResourcePool), None) ) params = pv_service.CloneVmParameters( @@ -82,7 +89,7 @@ def test_clone_vm_power_on_false(self): "#act" res = pv_service.clone_vm( - clone_params=params, logger=Mock(), cancellation_context=Mock() + clone_params=params, logger=MagicMock(), cancellation_context=MagicMock() ) "#assert" @@ -98,26 +105,28 @@ def test_clone_vm_resource_pool_is_not_empty(self): Checks clone_vm """ "#arrange" - si = Mock(spec=vim.ServiceInstance) - vim_mock = Mock() - vim_mock.vm = Mock() - vim_mock.vm.RelocateSpec = Mock() - vim_mock.vm.CloneSpec = Mock() + si = MagicMock(spec=vim.ServiceInstance) + vim_mock = MagicMock() + vim_mock.vm = MagicMock() + vim_mock.vm.RelocateSpec = MagicMock() + vim_mock.vm.CloneSpec = MagicMock() vim_mock.Datacenter = vim.Datacenter vim_mock.Datastore = vim.Datastore vim_mock.ServiceInstance = vim.ServiceInstance - datacenter = Mock(spec=vim.Datacenter) - template = Mock(spec=vim.VirtualMachine) - template.datastore = [Mock()] - - pv_service = pyVmomiService(None, None, Mock(), vim_mock) - pv_service.find_vm_by_name = Mock(return_value=template) - pv_service.get_obj = Mock() - pv_service.get_folder = Mock(return_value=datacenter) - pv_service._get_datastore = Mock(return_value=Mock(spec=vim.Datastore)) - pv_service.get_resource_pool = Mock( - return_value=(Mock(spec=vim.ResourcePool), None) + datacenter = MagicMock(spec=vim.Datacenter) + template = MagicMock(spec=vim.VirtualMachine) + template.datastore = [MagicMock()] + + pv_service = pyVmomiService(None, None, MagicMock(), vim_mock) + pv_service.find_vm_by_name = MagicMock(return_value=template) + pv_service.get_obj = MagicMock() + pv_service.get_folder = MagicMock(return_value=datacenter) + pv_service._get_datastore = MagicMock( + return_value=MagicMock(spec=vim.Datastore) + ) + pv_service.get_resource_pool = MagicMock( + return_value=(MagicMock(spec=vim.ResourcePool), None) ) params = pv_service.CloneVmParameters( @@ -130,7 +139,7 @@ def test_clone_vm_resource_pool_is_not_empty(self): "#act" res = pv_service.clone_vm( - clone_params=params, logger=Mock(), cancellation_context=Mock() + clone_params=params, logger=MagicMock(), cancellation_context=MagicMock() ) "#assert" @@ -146,26 +155,28 @@ def test_clone_vm_datastore_name_is_not_none(self): Checks clone_vm """ "#arrange" - si = Mock(spec=vim.ServiceInstance) - vim_mock = Mock() - vim_mock.vm = Mock() - vim_mock.vm.RelocateSpec = Mock() - vim_mock.vm.CloneSpec = Mock() + si = MagicMock(spec=vim.ServiceInstance) + vim_mock = MagicMock() + vim_mock.vm = MagicMock() + vim_mock.vm.RelocateSpec = MagicMock() + vim_mock.vm.CloneSpec = MagicMock() vim_mock.Datacenter = vim.Datacenter vim_mock.Datastore = vim.Datastore vim_mock.ServiceInstance = vim.ServiceInstance - datacenter = Mock(spec=vim.Datacenter) - template = Mock(spec=vim.VirtualMachine) - template.datastore = [Mock()] - - pv_service = pyVmomiService(None, None, Mock(), vim_mock) - pv_service.find_vm_by_name = Mock(return_value=template) - pv_service.get_obj = Mock() - pv_service.get_folder = Mock(return_value=datacenter) - pv_service._get_datastore = Mock(return_value=Mock(spec=vim.Datastore)) - pv_service.get_resource_pool = Mock( - return_value=(Mock(spec=vim.ResourcePool), None) + datacenter = MagicMock(spec=vim.Datacenter) + template = MagicMock(spec=vim.VirtualMachine) + template.datastore = [MagicMock()] + + pv_service = pyVmomiService(None, None, MagicMock(), vim_mock) + pv_service.find_vm_by_name = MagicMock(return_value=template) + pv_service.get_obj = MagicMock() + pv_service.get_folder = MagicMock(return_value=datacenter) + pv_service._get_datastore = MagicMock( + return_value=MagicMock(spec=vim.Datastore) + ) + pv_service.get_resource_pool = MagicMock( + return_value=(MagicMock(spec=vim.ResourcePool), None) ) params = pv_service.CloneVmParameters( @@ -178,7 +189,7 @@ def test_clone_vm_datastore_name_is_not_none(self): "#act" res = pv_service.clone_vm( - clone_params=params, logger=Mock(), cancellation_context=Mock() + clone_params=params, logger=MagicMock(), cancellation_context=MagicMock() ) "#assert" @@ -194,32 +205,38 @@ def test_clone_vm_destenation_folder_is_unsupported(self): Checks clone_vm """ "#arrange" - si = Mock(spec=vim.ServiceInstance) - vim_mock = Mock() - vim_mock.vm = Mock() - vim_mock.vm.RelocateSpec = Mock() - vim_mock.vm.CloneSpec = Mock() + si = MagicMock(spec=vim.ServiceInstance) + vim_mock = MagicMock() + vim_mock.vm = MagicMock() + vim_mock.vm.RelocateSpec = MagicMock() + vim_mock.vm.CloneSpec = MagicMock() vim_mock.Folder = vim.Folder vim_mock.Datacenter = vim.Datacenter vim_mock.ServiceInstance = vim.ServiceInstance - folder = Mock(spec=vim.VirtualMachine) - template = Mock(spec=vim.VirtualMachine) - template.datastore = [Mock()] + folder = MagicMock(spec=vim.VirtualMachine) + template = MagicMock(spec=vim.VirtualMachine) + template.datastore = [MagicMock()] - pv_service = pyVmomiService(None, None, Mock(), vim_mock) - pv_service.find_vm_by_name = Mock(return_value=template) - pv_service.get_obj = Mock() - pv_service.get_folder = Mock(return_value=folder) - pv_service._get_datastore = Mock(return_value=Mock(spec=vim.Datastore)) - pv_service.get_resource_pool = Mock(return_value=Mock(spec=vim.ResourcePool)) + pv_service = pyVmomiService(None, None, MagicMock(), vim_mock) + pv_service.find_vm_by_name = MagicMock(return_value=template) + pv_service.get_obj = MagicMock() + pv_service.get_folder = MagicMock(return_value=folder) + pv_service._get_datastore = MagicMock( + return_value=MagicMock(spec=vim.Datastore) + ) + pv_service.get_resource_pool = MagicMock( + return_value=MagicMock(spec=vim.ResourcePool) + ) params = pv_service.CloneVmParameters( si=si, template_name="my_temp", vm_name="my_name", vm_folder="my_folder" ) "#assert" - self.assertRaises(ValueError, pv_service.clone_vm, params, Mock(), Mock()) + self.assertRaises( + ValueError, pv_service.clone_vm, params, MagicMock(), MagicMock() + ) self.assertTrue(pv_service.get_folder.called) self.assertFalse(vim_mock.vm.RelocateSpec.called) self.assertFalse(vim_mock.vm.CloneSpec.called) @@ -231,26 +248,28 @@ def test_clone_vm_destenation_folder_is_folder_type(self): Checks clone_vm """ "#arrange" - si = Mock(spec=vim.ServiceInstance) - vim_mock = Mock() - vim_mock.vm = Mock() - vim_mock.vm.RelocateSpec = Mock() - vim_mock.vm.CloneSpec = Mock() + si = MagicMock(spec=vim.ServiceInstance) + vim_mock = MagicMock() + vim_mock.vm = MagicMock() + vim_mock.vm.RelocateSpec = MagicMock() + vim_mock.vm.CloneSpec = MagicMock() vim_mock.Folder = vim.Folder vim_mock.Datacenter = vim.Datacenter vim_mock.ServiceInstance = vim.ServiceInstance - folder = Mock(spec=vim.Folder) - template = Mock(spec=vim.VirtualMachine) - template.datastore = [Mock()] - - pv_service = pyVmomiService(None, None, Mock(), vim_mock) - pv_service.find_vm_by_name = Mock(return_value=template) - pv_service.get_obj = Mock() - pv_service.get_folder = Mock(return_value=folder) - pv_service._get_datastore = Mock(return_value=Mock(spec=vim.Datastore)) - pv_service.get_resource_pool = Mock( - return_value=(Mock(spec=vim.ResourcePool), None) + folder = MagicMock(spec=vim.Folder) + template = MagicMock(spec=vim.VirtualMachine) + template.datastore = [MagicMock()] + + pv_service = pyVmomiService(None, None, MagicMock(), vim_mock) + pv_service.find_vm_by_name = MagicMock(return_value=template) + pv_service.get_obj = MagicMock() + pv_service.get_folder = MagicMock(return_value=folder) + pv_service._get_datastore = MagicMock( + return_value=MagicMock(spec=vim.Datastore) + ) + pv_service.get_resource_pool = MagicMock( + return_value=(MagicMock(spec=vim.ResourcePool), None) ) params = pv_service.CloneVmParameters( @@ -259,7 +278,7 @@ def test_clone_vm_destenation_folder_is_folder_type(self): "#act" res = pv_service.clone_vm( - clone_params=params, logger=Mock(), cancellation_context=Mock() + clone_params=params, logger=MagicMock(), cancellation_context=MagicMock() ) "#assert" @@ -275,25 +294,27 @@ def test_clone_vm_datastore_name_is_none(self): Checks clone_vm """ "#arrange" - si = Mock(spec=vim.ServiceInstance) - vim_mock = Mock() - vim_mock.vm = Mock() - vim_mock.vm.RelocateSpec = Mock() - vim_mock.vm.CloneSpec = Mock() + si = MagicMock(spec=vim.ServiceInstance) + vim_mock = MagicMock() + vim_mock.vm = MagicMock() + vim_mock.vm.RelocateSpec = MagicMock() + vim_mock.vm.CloneSpec = MagicMock() vim_mock.Datacenter = vim.Datacenter vim_mock.ServiceInstance = vim.ServiceInstance - datacenter = Mock(spec=vim.Datacenter) - template = Mock(spec=vim.VirtualMachine) - template.datastore = [Mock()] - - pv_service = pyVmomiService(None, None, Mock(), vim_mock) - pv_service.find_vm_by_name = Mock(return_value=template) - pv_service.get_obj = Mock() - pv_service.get_folder = Mock(return_value=datacenter) - pv_service._get_datastore = Mock(return_value=Mock(spec=vim.Datastore)) - pv_service.get_resource_pool = Mock( - return_value=(Mock(spec=vim.ResourcePool), None) + datacenter = MagicMock(spec=vim.Datacenter) + template = MagicMock(spec=vim.VirtualMachine) + template.datastore = [MagicMock()] + + pv_service = pyVmomiService(None, None, MagicMock(), vim_mock) + pv_service.find_vm_by_name = MagicMock(return_value=template) + pv_service.get_obj = MagicMock() + pv_service.get_folder = MagicMock(return_value=datacenter) + pv_service._get_datastore = MagicMock( + return_value=MagicMock(spec=vim.Datastore) + ) + pv_service.get_resource_pool = MagicMock( + return_value=(MagicMock(spec=vim.ResourcePool), None) ) params = pv_service.CloneVmParameters( @@ -304,7 +325,7 @@ def test_clone_vm_datastore_name_is_none(self): "#act" res = pv_service.clone_vm( clone_params=params, - logger=Mock(), + logger=MagicMock(), cancellation_context=cancellation_context, ) @@ -323,14 +344,14 @@ def test_clone_vm_vm_folder_is_none(self): "#arrange" si = create_autospec(spec=vim.ServiceInstance) - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) params = pv_service.CloneVmParameters( si=si, template_name="my_temp", vm_name="my_name", vm_folder=None ) "#act" res = pv_service.clone_vm( - clone_params=params, logger=Mock(), cancellation_context=Mock() + clone_params=params, logger=MagicMock(), cancellation_context=MagicMock() ) "#assert" @@ -343,14 +364,14 @@ def test_clone_vm_vm_name_is_none(self): "#arrange" si = create_autospec(spec=vim.ServiceInstance) - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) params = pv_service.CloneVmParameters( si=si, template_name="my_temp", vm_name=None, vm_folder=None ) "#act" res = pv_service.clone_vm( - clone_params=params, logger=Mock(), cancellation_context=Mock() + clone_params=params, logger=MagicMock(), cancellation_context=MagicMock() ) "#assert" @@ -363,14 +384,14 @@ def test_clone_vm_template_name_is_none(self): "#arrange" si = create_autospec(spec=vim.ServiceInstance) - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) params = pv_service.CloneVmParameters( si=si, template_name=None, vm_name=None, vm_folder=None ) "#act" res = pv_service.clone_vm( - clone_params=params, logger=Mock(), cancellation_context=Mock() + clone_params=params, logger=MagicMock(), cancellation_context=MagicMock() ) "#assert" @@ -381,14 +402,14 @@ def test_clone_vm_si_is_none(self): Checks clone_vm """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) params = pv_service.CloneVmParameters( si=None, template_name=None, vm_name=None, vm_folder=None ) "#act" res = pv_service.clone_vm( - clone_params=params, logger=Mock(), cancellation_context=Mock() + clone_params=params, logger=MagicMock(), cancellation_context=MagicMock() ) "#assert" @@ -399,19 +420,19 @@ def test_destroy_vm_by_name(self): Checks whether the vm found and call to be destroy """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() + si.content.searchIndex = MagicMock() - pv_service.find_vm_by_name = Mock(return_value=Mock(name="vm")) - pv_service.destroy_vm = Mock(return_value=True) + pv_service.find_vm_by_name = MagicMock(return_value=MagicMock(name="vm")) + pv_service.destroy_vm = MagicMock(return_value=True) "#act" result = pv_service.destroy_vm_by_name( - si=si, vm_name="vm_name:name", vm_path="fake/path", logger=Mock() + si=si, vm_name="vm_name:name", vm_path="fake/path", logger=MagicMock() ) "#assert" @@ -424,22 +445,22 @@ def test_destroy_vm_by_uuid(self): Checks whether the vm found and call to be destroy """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() + si.content.searchIndex = MagicMock() - pv_service.find_by_uuid = Mock(return_value=Mock(name="vm")) - pv_service.destroy_vm = Mock(return_value=True) + pv_service.find_by_uuid = MagicMock(return_value=MagicMock(name="vm")) + pv_service.destroy_vm = MagicMock(return_value=True) "#act" result = pv_service.destroy_vm_by_uuid( si=si, vm_uuid="thisuni-vers-ally-uniq-ueidentifier", vm_path="fake/path", - logger=Mock(), + logger=MagicMock(), ) "#assert" @@ -452,7 +473,7 @@ def test_get_folder_path_not_found(self): Checks when path not found """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) def find_child_mock(*args): root = args[0] @@ -467,30 +488,30 @@ def find_child_mock(*args): return None si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() + si.content.searchIndex = MagicMock() si.content.searchIndex.FindChild = MagicMock(side_effect=find_child_mock) - first_folder = Mock(spec=[], name="first") + first_folder = MagicMock(spec=[], name="first") first_folder.name = "first" - second_folder = Mock(spec=[], name="second") + second_folder = MagicMock(spec=[], name="second") second_folder.name = "second" - third_folder = Mock(spec=[], name="third") + third_folder = MagicMock(spec=[], name="third") third_folder.name = "third" - fourth_folder = Mock(spec=[], name="fourth") + fourth_folder = MagicMock(spec=[], name="fourth") fourth_folder.name = "fourth" - fifth_folder = Mock(spec=[], name="fifth") + fifth_folder = MagicMock(spec=[], name="fifth") fifth_folder.name = "fifth" - sixth_folder = Mock(spec=[], name="sixth") + sixth_folder = MagicMock(spec=[], name="sixth") sixth_folder.name = "sixth" - si.content.rootFolder = Mock(spec=["name", "childEntity"]) + si.content.rootFolder = MagicMock(spec=["name", "childEntity"]) si.content.rootFolder.name = "rootFolder" si.content.rootFolder.childEntity = [first_folder, second_folder] first_folder.vmFolder = [second_folder, sixth_folder] @@ -510,7 +531,7 @@ def test_get_folder_deep_and_complex_path(self): Checks when path is deep and complex, goes through all the folder types """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) def find_child_mock(*args): root = args[0] @@ -525,30 +546,30 @@ def find_child_mock(*args): return None si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() + si.content.searchIndex = MagicMock() si.content.searchIndex.FindChild = MagicMock(side_effect=find_child_mock) - first_folder = Mock(spec=[], name="first") + first_folder = MagicMock(spec=[], name="first") first_folder.name = "first" - second_folder = Mock(spec=[], name="second") + second_folder = MagicMock(spec=[], name="second") second_folder.name = "second" - third_folder = Mock(spec=[], name="third") + third_folder = MagicMock(spec=[], name="third") third_folder.name = "third" - fourth_folder = Mock(spec=[], name="fourth") + fourth_folder = MagicMock(spec=[], name="fourth") fourth_folder.name = "fourth" - fifth_folder = Mock(spec=[], name="fifth") + fifth_folder = MagicMock(spec=[], name="fifth") fifth_folder.name = "fifth" - sixth_folder = Mock(spec=[], name="sixth") + sixth_folder = MagicMock(spec=[], name="sixth") sixth_folder.name = "sixth" - si.content.rootFolder = Mock() + si.content.rootFolder = MagicMock() si.content.rootFolder.name = "rootFolder" si.content.rootFolder.childEntity = [first_folder, second_folder] first_folder.vmFolder = [second_folder, sixth_folder] @@ -568,7 +589,7 @@ def test_get_folder_deep_path(self): Checks when path is deep, more then two """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) def find_child_mock(*args): root = args[0] @@ -578,24 +599,24 @@ def find_child_mock(*args): return None si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() + si.content.searchIndex = MagicMock() si.content.searchIndex.FindChild = MagicMock(side_effect=find_child_mock) - inner_folder = Mock() + inner_folder = MagicMock() inner_folder.name = "inner" - inner_decoy_folder = Mock() + inner_decoy_folder = MagicMock() inner_decoy_folder.name = "decoy" - inner_deep_folder = Mock() + inner_deep_folder = MagicMock() inner_deep_folder.name = "inner_deep_folder" inner_folder.childEntity = [inner_deep_folder, inner_decoy_folder] inner_decoy_folder.childEntity = [inner_folder] - si.content.rootFolder = Mock() + si.content.rootFolder = MagicMock() si.content.rootFolder.childEntity = [inner_decoy_folder, inner_folder] si.content.rootFolder.name = "rootFolder" @@ -611,7 +632,7 @@ def test_get_folder_one_sub_folder(self): """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) def find_child_mock(*args): root = args[0] @@ -621,18 +642,18 @@ def find_child_mock(*args): return None si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() + si.content.searchIndex = MagicMock() si.content.searchIndex.FindChild = MagicMock(side_effect=find_child_mock) - inner_folder = Mock() + inner_folder = MagicMock() inner_folder.name = "inner" - inner_decoy_folder = Mock() + inner_decoy_folder = MagicMock() inner_decoy_folder.name = "decoy" - si.content.rootFolder = Mock() + si.content.rootFolder = MagicMock() si.content.rootFolder.childEntity = [inner_decoy_folder, inner_folder] si.content.rootFolder.name = "rootFolder" @@ -649,13 +670,13 @@ def test_get_folder_path_empty(self): "#arrange" folder_name = "rootFolder" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.rootFolder = Mock() + si.content.rootFolder = MagicMock() si.content.rootFolder.name = folder_name "#act" @@ -669,7 +690,7 @@ def test_get_object_by_path_checks_networkFolder(self): Checks whether the function can grab network folder """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) def search_child(*args, **keys): if args[0].name == pv_service.Network: @@ -679,16 +700,16 @@ def search_child(*args, **keys): class FolderMock: networkFolder = None - folder = Mock(spec=FolderMock()) + folder = MagicMock(spec=FolderMock()) folder.name = "parentFolder" folder.networkFolder.name = pv_service.Network get_folder = MagicMock(return_value=folder) pv_service.get_folder = get_folder si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() + si.content.searchIndex = MagicMock() si.content.searchIndex.FindChild = MagicMock(side_effect=search_child) "#act" @@ -702,7 +723,7 @@ def test_get_object_by_path_checks_hostFolder(self): Checks whether the function can grab host folder """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) def search_child(*args, **keys): if args[0].name == pv_service.Host: @@ -712,16 +733,16 @@ def search_child(*args, **keys): class FolderMock: hostFolder = None - folder = Mock(spec=FolderMock()) + folder = MagicMock(spec=FolderMock()) folder.name = "parentFolder" folder.hostFolder.name = pv_service.Host get_folder = MagicMock(return_value=folder) pv_service.get_folder = get_folder si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() + si.content.searchIndex = MagicMock() si.content.searchIndex.FindChild = MagicMock(side_effect=search_child) "#act" @@ -735,7 +756,7 @@ def test_get_object_by_path_checks_datacenterFolder(self): Checks whether the function can grab datacenter folder """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) def search_child(*args, **keys): if args[0].name == pv_service.Datacenter: @@ -745,16 +766,16 @@ def search_child(*args, **keys): class FolderMock: datacenterFolder = None - folder = Mock(spec=FolderMock()) + folder = MagicMock(spec=FolderMock()) folder.name = "parentFolder" folder.datacenterFolder.name = pv_service.Datacenter get_folder = MagicMock(return_value=folder) pv_service.get_folder = get_folder si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() + si.content.searchIndex = MagicMock() si.content.searchIndex.FindChild = MagicMock(side_effect=search_child) "#act" @@ -768,7 +789,7 @@ def test_get_object_by_path_checks_datastoreFolder(self): Checks whether the function can grab datastore folder """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) def search_child(*args, **keys): if args[0].name == pv_service.Datastore: @@ -778,16 +799,16 @@ def search_child(*args, **keys): class FolderMock: datastoreFolder = None - folder = Mock(spec=FolderMock()) + folder = MagicMock(spec=FolderMock()) folder.name = "parentFolder" folder.datastoreFolder.name = pv_service.Datastore get_folder = MagicMock(return_value=folder) pv_service.get_folder = get_folder si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() + si.content.searchIndex = MagicMock() si.content.searchIndex.FindChild = MagicMock(side_effect=search_child) "#act" @@ -801,7 +822,7 @@ def test_get_object_by_path_checks_vmFolder(self): Checks whether the function can grab vm folder """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) def search_child(*args, **keys): if args[0].name == pv_service.VM: @@ -811,16 +832,16 @@ def search_child(*args, **keys): class FolderMock: vmFolder = None - folder = Mock(spec=FolderMock()) + folder = MagicMock(spec=FolderMock()) folder.name = "parentFolder" folder.vmFolder.name = pv_service.VM get_folder = MagicMock(return_value=folder) pv_service.get_folder = get_folder si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() + si.content.searchIndex = MagicMock() si.content.searchIndex.FindChild = MagicMock(side_effect=search_child) "#act" @@ -834,7 +855,7 @@ def test_get_object_by_path_checks_childEntity(self): Checks whether the function can grab from child entities """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) def search_child(*args, **keys): if args[0].name == pv_service.ChildEntity: @@ -844,15 +865,15 @@ def search_child(*args, **keys): class FolderMock: childEntity = None - folder = Mock(spec=FolderMock()) + folder = MagicMock(spec=FolderMock()) folder.name = pv_service.ChildEntity get_folder = MagicMock(return_value=folder) pv_service.get_folder = get_folder si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() + si.content.searchIndex = MagicMock() si.content.searchIndex.FindChild = MagicMock(side_effect=search_child) "#act" @@ -866,13 +887,13 @@ def test_get_object_by_path_no_nested_objs(self): Checks whether the function returns 'None' if it doesn't find an object """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) - get_folder = MagicMock(return_value=Mock(spec=[])) + get_folder = MagicMock(return_value=MagicMock(spec=[])) pv_service.get_folder = get_folder si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) "#act" @@ -885,15 +906,15 @@ def test_get_object_by_path_no_folder_found(self): "#arrange" folder_name = "rootFolder" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.rootFolder = Mock() + si.content.rootFolder = MagicMock() si.content.rootFolder.name = folder_name - pv_service.get_folder = Mock(return_value=None) + pv_service.get_folder = MagicMock(return_value=None) "#act" self.assertRaises( @@ -921,15 +942,15 @@ def side_eff(*args, **kwargs): counter.i += 1 return "not found" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() - si.content.rootFolder = Mock() - si.content.searchIndex.FindChild = Mock(side_effect=side_eff) + si.content.searchIndex = MagicMock() + si.content.rootFolder = MagicMock() + si.content.searchIndex.FindChild = MagicMock(side_effect=side_eff) "#act" result = pv_service.find_item_in_path_by_type( @@ -955,17 +976,17 @@ def side_eff(*args, **kwargs): return "not yet" else: counter.i = counter.i + 1 - return Mock(spec=vim.Datacenter) + return MagicMock(spec=vim.Datacenter) - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() - si.content.rootFolder = Mock() - si.content.searchIndex.FindChild = Mock(side_effect=side_eff) + si.content.searchIndex = MagicMock() + si.content.rootFolder = MagicMock() + si.content.searchIndex.FindChild = MagicMock(side_effect=side_eff) "#act" result = pv_service.find_item_in_path_by_type( @@ -981,14 +1002,14 @@ def test_find_item_in_path_by_type_type_is_None(self): Checks whether the function can grab object by uuid """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() - si.content.rootFolder = Mock() + si.content.searchIndex = MagicMock() + si.content.rootFolder = MagicMock() "#act" result = pv_service.find_item_in_path_by_type(si, "test", None) @@ -1001,14 +1022,14 @@ def test_find_item_in_path_by_type_path_None(self): Checks whether the function can grab object by uuid """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() - si.content.rootFolder = Mock + si.content.searchIndex = MagicMock() + si.content.rootFolder = MagicMock() "#act" result = pv_service.find_item_in_path_by_type(si, None, "not none") @@ -1021,17 +1042,17 @@ def test_get_vm_by_uuid_vm_with_path(self): Checks whether the function can grab object by uuid """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) - dc = Mock(spec=vim.Datacenter) - pv_service.find_item_in_path_by_type = Mock(return_value=dc) + dc = MagicMock(spec=vim.Datacenter) + pv_service.find_item_in_path_by_type = MagicMock(return_value=dc) si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() - si.content.searchIndex.FindByUuid = Mock( + si.content.searchIndex = MagicMock() + si.content.searchIndex.FindByUuid = MagicMock( return_value="b8e4da4e-a2ff-11e5-bf7f-feff819cdc9f" ) @@ -1053,10 +1074,10 @@ def test_get_vm_by_uuid_vm_without_uuid(self): Checks whether the function can grab object by uuid """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) "#act" @@ -1070,14 +1091,14 @@ def test_get_vm_by_uuid_vm_without_path(self): Checks whether the function can grab object by uuid """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - si.content.searchIndex = Mock() - si.content.searchIndex.FindByUuid = Mock( + si.content.searchIndex = MagicMock() + si.content.searchIndex.FindByUuid = MagicMock( return_value="b8e4da4e-a2ff-11e5-bf7f-feff819cdc9f" ) @@ -1093,16 +1114,16 @@ def test_get_vm_by_name_isVm_VM_type(self): Checks whether the function can passes vm type """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) def find_obj_by_path_mock(*args, **kwargs): return args[3] == pv_service.VM si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - pv_service.find_obj_by_path = Mock(side_effect=find_obj_by_path_mock) + pv_service.find_obj_by_path = MagicMock(side_effect=find_obj_by_path_mock) "#act" result = pv_service.find_vm_by_name(si, "", "") @@ -1115,16 +1136,16 @@ def test_get_datastore_by_name_is_Datastore_type(self): Checks whether the function can passes datastore type """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) def find_obj_by_path_mock(*args, **kwargs): return args[3] == pv_service.Datastore si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - pv_service.find_obj_by_path = Mock(side_effect=find_obj_by_path_mock) + pv_service.find_obj_by_path = MagicMock(side_effect=find_obj_by_path_mock) "#act" result = pv_service.find_datastore_by_name(si, "", "") @@ -1137,16 +1158,16 @@ def test_get_datacenter_by_name_is_Datacenter_type(self): Checks whether the function can passes datascenter type """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) def find_obj_by_path_mock(*args, **kwargs): return args[3] == pv_service.Datacenter si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - pv_service.find_obj_by_path = Mock(side_effect=find_obj_by_path_mock) + pv_service.find_obj_by_path = MagicMock(side_effect=find_obj_by_path_mock) "#act" result = pv_service.find_datacenter_by_name(si, "", "") @@ -1159,16 +1180,16 @@ def test_get_host_by_name_is_Host_type(self): Checks whether the function can passes host type """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) def find_obj_by_path_mock(*args, **kwargs): return args[3] == pv_service.Host si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - pv_service.find_obj_by_path = Mock(side_effect=find_obj_by_path_mock) + pv_service.find_obj_by_path = MagicMock(side_effect=find_obj_by_path_mock) "#act" result = pv_service.find_host_by_name(si, "", "") @@ -1181,16 +1202,16 @@ def test_get_network_by_name_is_network_type(self): Checks whether the function can passes network type """ "#arrange" - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) def find_obj_by_path_mock(*args, **kwargs): return args[3] == pv_service.Network si = create_autospec(spec=vim.ServiceInstance) - si.RetrieveContent = Mock() + si.RetrieveContent = MagicMock() si.content = create_autospec(spec=vim.ServiceInstanceContent()) - pv_service.find_obj_by_path = Mock(side_effect=find_obj_by_path_mock) + pv_service.find_obj_by_path = MagicMock(side_effect=find_obj_by_path_mock) "#act" result = pv_service.find_network_by_name(si, "", "") @@ -1200,11 +1221,11 @@ def find_obj_by_path_mock(*args, **kwargs): def test_connect(self): # arrange - pv_service = pyVmomiService(SmartConnect, Disconnect, Mock()) - address = Mock() - user = Mock() - password = Mock() - pv_service.pyvmomi_connect = Mock() + pv_service = pyVmomiService(SmartConnect, Disconnect, MagicMock()) + address = MagicMock() + user = MagicMock() + password = MagicMock() + pv_service.pyvmomi_connect = MagicMock() # act pv_service.connect(address, user, password) @@ -1214,9 +1235,9 @@ def test_connect(self): def test_disconnect(self): # arrange - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) si = create_autospec(spec=vim.ServiceInstance) - pv_service.pyvmomi_disconnect = Mock() + pv_service.pyvmomi_disconnect = MagicMock() # act pv_service.disconnect(si) @@ -1226,10 +1247,10 @@ def test_disconnect(self): def test_get_network_by_full_name(self): # arrange - pv_service = pyVmomiService(None, None, Mock()) + pv_service = pyVmomiService(None, None, MagicMock()) si = create_autospec(spec=vim.ServiceInstance) default_network_full_name = "Root/Folder/Folder2/Name" - pv_service.find_network_by_name = Mock() + pv_service.find_network_by_name = MagicMock() # act pv_service.get_network_by_full_name(si, default_network_full_name) @@ -1239,16 +1260,16 @@ def test_get_network_by_full_name(self): def test_destroy_vm(self): # arrange - pv_service = pyVmomiService(None, None, Mock()) - pv_service.wait_for_task = Mock() - vm = Mock() - vm.runtime = Mock() + pv_service = pyVmomiService(None, None, MagicMock()) + pv_service.wait_for_task = MagicMock() + vm = MagicMock() + vm.runtime = MagicMock() vm.runtime.powerState = "poweredOn" - vm.PowerOffVM_Task = Mock() - vm.Destroy_Task = Mock() + vm.PowerOffVM_Task = MagicMock() + vm.Destroy_Task = MagicMock() # act - pv_service.destroy_vm(vm=vm, logger=Mock()) + pv_service.destroy_vm(vm=vm, logger=MagicMock()) # assert self.assertTrue(vm.PowerOffVM_Task.called) @@ -1256,26 +1277,26 @@ def test_destroy_vm(self): def test_vm_get_network_by_name(self): # Arrange - pv_service = pyVmomiService(None, None, Mock()) - pv_service.wait_for_task = Mock() + pv_service = pyVmomiService(None, None, MagicMock()) + pv_service.wait_for_task = MagicMock() - network = Mock() + network = MagicMock() network.name = "main_network" - backing = Mock() + backing = MagicMock() backing.network = network virtual_card = create_autospec(vim.vm.device.VirtualEthernetCard) virtual_card.macAddress = "AA-BB" virtual_card.backing = backing - hardware = Mock() + hardware = MagicMock() hardware.device = [virtual_card] - config = Mock() + config = MagicMock() config.hardware = hardware - vm = Mock() + vm = MagicMock() vm.config = config # Act @@ -1286,26 +1307,26 @@ def test_vm_get_network_by_name(self): def test_vm_get_network_by_name_1(self): # Arrange - pv_service = pyVmomiService(None, None, Mock()) - pv_service.wait_for_task = Mock() + pv_service = pyVmomiService(None, None, MagicMock()) + pv_service.wait_for_task = MagicMock() - network = Mock() + network = MagicMock() network.name = "main_network" - backing = Mock() + backing = MagicMock() backing.network = network virtual_card = create_autospec(vim.vm.device.VirtualEthernetCard) virtual_card.macAddress = "AA-BB" virtual_card.backing = backing - hardware = Mock() + hardware = MagicMock() hardware.device = [virtual_card] - config = Mock() + config = MagicMock() config.hardware = hardware - vm = Mock() + vm = MagicMock() vm.config = config # Act @@ -1316,40 +1337,40 @@ def test_vm_get_network_by_name_1(self): def test_get_snapshot_no_snapshot_param(self): # Arrange - pv_service = pyVmomiService(None, None, Mock()) - pv_service.wait_for_task = Mock() + pv_service = pyVmomiService(None, None, MagicMock()) + pv_service.wait_for_task = MagicMock() # Act - actual_network = pv_service._get_snapshot(Mock(spec=[]), Mock) + actual_network = pv_service._get_snapshot(MagicMock(spec=[]), MagicMock) # Assert self.assertIsNone(actual_network) def test_get_snapshot_snapshot_not_found(self): # Arrange - pv_service = pyVmomiService(None, None, Mock()) - pv_service.wait_for_task = Mock() + pv_service = pyVmomiService(None, None, MagicMock()) + pv_service.wait_for_task = MagicMock() - params = Mock() + params = MagicMock() params.snapshot = "aa/bb/ee" - template = Mock(vim.VirtualMachine) - template.snapshot = Mock() - template.snapshot.rootSnapshotList = [Mock()] + template = MagicMock(vim.VirtualMachine) + template.snapshot = MagicMock() + template.snapshot.rootSnapshotList = [MagicMock()] # Act self.assertRaises(ValueError, pv_service._get_snapshot, params, template) def test_get_snapshot_snapshot_has_no_root(self): # Arrange - pv_service = pyVmomiService(None, None, Mock()) - pv_service.wait_for_task = Mock() + pv_service = pyVmomiService(None, None, MagicMock()) + pv_service.wait_for_task = MagicMock() - params = Mock() + params = MagicMock() params.snapshot = "aa/bb/ee" - template = Mock(vim.VirtualMachine) - template.snapshot = Mock() + template = MagicMock(vim.VirtualMachine) + template.snapshot = MagicMock() template.snapshot.rootSnapshotList = None # Act @@ -1357,21 +1378,21 @@ def test_get_snapshot_snapshot_has_no_root(self): def test_get_snapshot_snapshot(self): # Arrange - pv_service = pyVmomiService(None, None, Mock()) - pv_service.wait_for_task = Mock() + pv_service = pyVmomiService(None, None, MagicMock()) + pv_service.wait_for_task = MagicMock() - params = Mock() + params = MagicMock() params.snapshot = "aa/bb/ee" - template = Mock(vim.VirtualMachine) - template.snapshot = Mock() + template = MagicMock(vim.VirtualMachine) + template.snapshot = MagicMock() - aa = Mock(spec=[]) - bb1 = Mock(spec=[]) - bb2 = Mock(spec=[]) - cc = Mock(spec=[]) - dd = Mock(spec=[]) - ee = Mock(spec=[]) + aa = MagicMock(spec=[]) + bb1 = MagicMock(spec=[]) + bb2 = MagicMock(spec=[]) + cc = MagicMock(spec=[]) + dd = MagicMock(spec=[]) + ee = MagicMock(spec=[]) aa.name = "aa" aa.createTime = 1 @@ -1390,7 +1411,7 @@ def test_get_snapshot_snapshot(self): ee.name = "ee" ee.createTime = 1 - ee.snapshot = Mock() + ee.snapshot = MagicMock() aa.childSnapshotList = [dd, bb1, bb2] dd.childSnapshotList = [cc] diff --git a/tests/test_network/test_dvswitch/test_connector.py b/tests/test_network/test_dvswitch/test_connector.py index 9e57f51..63d9d3c 100644 --- a/tests/test_network/test_dvswitch/test_connector.py +++ b/tests/test_network/test_dvswitch/test_connector.py @@ -1,17 +1,18 @@ +import sys from unittest import TestCase -from mock import Mock from pyVmomi import vim -from cloudshell.cp.vcenter.common.cloud_shell.conn_details_retriever import ( - ResourceConnectionDetailsRetriever, -) -from cloudshell.cp.vcenter.common.model_factory import ResourceModelParser from cloudshell.cp.vcenter.common.utilites.common_name import generate_unique_name from cloudshell.cp.vcenter.vm.dvswitch_connector import VirtualSwitchToMachineConnector from cloudshell.cp.vcenter.vm.portgroup_configurer import * from cloudshell.cp.vcenter.vm.vnic_to_network_mapper import VnicToNetworkMapper +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock, patch, create_autospec +else: + from mock import MagicMock, patch, create_autospec + class TestVirtualSwitchToMachineConnector(TestCase): def setUp(self): @@ -27,37 +28,39 @@ def setUp(self): self.dv_switch_name = "dvSwitch-SergiiT" self.dv_port_group_name = "aa-dvPortGroup3B" - self.network = Mock() + self.network = MagicMock() self.network.key = "network-key" self.network.config.distributedVirtualSwitch.uuid = ( "422254d5-5226-946e-26fb-60c21898b73f" ) - self.py_vmomi_service = Mock() + self.py_vmomi_service = MagicMock() - self.vm = Mock() - self.vm.config.hardware = Mock() - self.vnic = Mock(spec=vim.vm.device.VirtualEthernetCard) - self.vnic.deviceInfo = Mock() + self.vm = MagicMock() + self.vm.config.hardware = MagicMock() + self.vnic = MagicMock(spec=vim.vm.device.VirtualEthernetCard) + self.vnic.deviceInfo = MagicMock() self.vm.config.hardware.device = [self.vnic] self.py_vmomi_service.find_by_uuid = lambda a, b, c: self.vm - self.py_vmomi_service.find_network_by_name = Mock(return_value=self.network) + self.py_vmomi_service.find_network_by_name = MagicMock( + return_value=self.network + ) - self.synchronous_task_waiter = Mock() - self.synchronous_task_waiter.wait_for_task = Mock(return_value="TASK OK") - self.si = Mock() + self.synchronous_task_waiter = MagicMock() + self.synchronous_task_waiter.wait_for_task = MagicMock(return_value="TASK OK") + self.si = MagicMock() name_generator = generate_unique_name vnic_to_network_mapper = VnicToNetworkMapper(name_generator) - helpers = Mock() - cs_retriever_service = Mock() - session = Mock() - resource_context = Mock() - connection_details = Mock() - - helpers.get_resource_context_details = Mock(return_value=resource_context) - helpers.get_api_session = Mock(return_value=session) - cs_retriever_service.getVCenterConnectionDetails = Mock( + helpers = MagicMock() + cs_retriever_service = MagicMock() + session = MagicMock() + resource_context = MagicMock() + connection_details = MagicMock() + + helpers.get_resource_context_details = MagicMock(return_value=resource_context) + helpers.get_api_session = MagicMock(return_value=session) + cs_retriever_service.getVCenterConnectionDetails = MagicMock( return_value=connection_details ) @@ -65,8 +68,8 @@ def setUp(self): self.py_vmomi_service, self.synchronous_task_waiter, vnic_to_network_mapper, - Mock(), - Mock(), + MagicMock(), + MagicMock(), ) # pyvmomi_service, synchronous_task_waiter, vnic_to_network_mapper, vnic_common @@ -77,7 +80,7 @@ def setUp(self): self.connector = VirtualSwitchToMachineConnector(self.creator, self.configurer) def test_map_vnc(self): - network_spec = Mock() + network_spec = MagicMock() network_spec.dv_port_name = "" network_spec.dv_switch_name = "" network_spec.dv_switch_path = "" @@ -85,11 +88,11 @@ def test_map_vnc(self): network_spec.vlan_spec = "" mapp = [network_spec] - self.configurer.connect_vnic_to_networks = Mock(return_value="OK") - self.connector.virtual_machine_port_group_configurer.connect_by_mapping = Mock( - return_value="OK" + self.configurer.connect_vnic_to_networks = MagicMock(return_value="OK") + self.connector.virtual_machine_port_group_configurer.connect_by_mapping = ( + MagicMock(return_value="OK") ) - self.connector.connect_and_get_vm = Mock( + self.connector.connect_and_get_vm = MagicMock( return_value=( 1, 1, @@ -97,19 +100,19 @@ def test_map_vnc(self): ) res = self.connector.connect_by_mapping( - self.si, self.vm, [], "default_network", [], Mock(), "True" + self.si, self.vm, [], "default_network", [], MagicMock(), "True" ) self.assertEqual(res, "OK") res = self.connector.connect_by_mapping( - self.si, self.vm, [], None, [], Mock(), "True" + self.si, self.vm, [], None, [], MagicMock(), "True" ) self.assertEqual(res, "OK") res = self.connector.connect_by_mapping( - self.si, self.vm, mapp, "default_network", [], Mock(), "True" + self.si, self.vm, mapp, "default_network", [], MagicMock(), "True" ) self.assertEqual(res, "OK") res = self.connector.connect_by_mapping( - self.si, self.vm, mapp, None, [], Mock(), "True" + self.si, self.vm, mapp, None, [], MagicMock(), "True" ) self.assertEqual(res, "OK") diff --git a/tests/test_network/test_dvswitch/test_creator.py b/tests/test_network/test_dvswitch/test_creator.py index 46a3c5e..0520bc3 100644 --- a/tests/test_network/test_dvswitch/test_creator.py +++ b/tests/test_network/test_dvswitch/test_creator.py @@ -1,17 +1,22 @@ +import sys from unittest import TestCase -from mock import Mock, create_autospec from pyVmomi import vim from cloudshell.cp.vcenter.network.dvswitch.creator import DvPortGroupCreator +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock, create_autospec +else: + from mock import MagicMock, create_autospec + class TestDvPortGroupCreator(TestCase): def test_create_dv_port_group_exception(self): # Arrange - pyvmomy_service = Mock() - pyvmomy_service.find_network_by_name = Mock(return_value=None) - synchronous_task_waiter = Mock() + pyvmomy_service = MagicMock() + pyvmomy_service.find_network_by_name = MagicMock(return_value=None) + synchronous_task_waiter = MagicMock() # Act dv_port_group_creator = DvPortGroupCreator( @@ -25,26 +30,26 @@ def test_create_dv_port_group_exception(self): "port_name", "switch_name", "switch_path", - Mock(), + MagicMock(), None, None, - Mock(), + MagicMock(), ) def test_create_dv_port_group(self): # Arrange dv_switch = create_autospec(spec=vim.DistributedVirtualSwitch) - dv_switch.portgroup = Mock() - pyvmomy_service = Mock() - pyvmomy_service.find_network_by_name = Mock(return_value=dv_switch) - synchronous_task_waiter = Mock() + dv_switch.portgroup = MagicMock() + pyvmomy_service = MagicMock() + pyvmomy_service.find_network_by_name = MagicMock(return_value=dv_switch) + synchronous_task_waiter = MagicMock() dv_port_group_creator = DvPortGroupCreator( pyvmomy_service, synchronous_task_waiter ) dv_port_group_create_task_prev = DvPortGroupCreator.__dict__[ "dv_port_group_create_task" ] - DvPortGroupCreator.dv_port_group_create_task = Mock() + DvPortGroupCreator.dv_port_group_create_task = MagicMock() # Act dv_port_group_creator._create_dv_port_group( @@ -54,7 +59,7 @@ def test_create_dv_port_group(self): create_autospec(spec=vim.ServiceInstance), spec=None, vlan_id=1001, - logger=Mock(), + logger=MagicMock(), promiscuous_mode="True", ) @@ -68,13 +73,13 @@ def test_create_dv_port_group(self): def test_dv_port_group_create_task(self): # arrange - pyvmomy_service = Mock() - synchronous_task_waiter = Mock() + pyvmomy_service = MagicMock() + synchronous_task_waiter = MagicMock() dv_port_group_creator = DvPortGroupCreator( pyvmomy_service, synchronous_task_waiter ) dv_switch = create_autospec(spec=vim.DistributedVirtualSwitch) - dv_switch.AddDVPortgroup_Task = Mock() + dv_switch.AddDVPortgroup_Task = MagicMock() spec = create_autospec(spec=vim.dvs.VmwareDistributedVirtualSwitch.VlanSpec) # act @@ -83,7 +88,7 @@ def test_dv_port_group_create_task(self): dv_switch=dv_switch, spec=spec, vlan_id=1001, - logger=Mock(), + logger=MagicMock(), promiscuous_mode="True", num_ports=32, ) diff --git a/tests/test_network/test_dvswitch/test_port_group_configurer.py b/tests/test_network/test_dvswitch/test_port_group_configurer.py index 24126ba..7f8b17d 100644 --- a/tests/test_network/test_dvswitch/test_port_group_configurer.py +++ b/tests/test_network/test_dvswitch/test_port_group_configurer.py @@ -1,6 +1,6 @@ +import sys from unittest import TestCase -from mock import MagicMock, Mock from pyVmomi import vim from cloudshell.cp.vcenter.network.dvswitch.name_generator import ( @@ -11,6 +11,11 @@ VirtualMachinePortGroupConfigurer, ) +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock +else: + from mock import MagicMock + class TestDvPortGroupConfigurer(TestCase): def setUp(self): @@ -26,43 +31,47 @@ def setUp(self): self.dv_switch_name = "dvSwitch-SergiiT" self.dv_port_group_name = "aa-dvPortGroup3B" - self.network = Mock() + self.network = MagicMock() self.network.key = "network-key" self.network.name = "QS_123" self.network.config.distributedVirtualSwitch.uuid = ( "422254d5-5226-946e-26fb-60c21898b73f" ) - self.py_vmomi_service = Mock() + self.py_vmomi_service = MagicMock() - self.network2 = Mock() + self.network2 = MagicMock() self.network2.key = "network2-key" self.network2.name = "QS_network2" - self.network3 = Mock() + self.network3 = MagicMock() self.network3.key = "network3-key" self.network3.name = "QS_network3" - self.vm = Mock() - self.vm.config.hardware = Mock() - self.vnic = Mock(spec=vim.vm.device.VirtualEthernetCard) + self.vm = MagicMock() + self.vm.config.hardware = MagicMock() + self.vnic = MagicMock(spec=vim.vm.device.VirtualEthernetCard) self.vnic.macAddress = True - self.vnic.deviceInfo = Mock() + self.vnic.deviceInfo = MagicMock() self.vm.config.hardware.device = [self.vnic] self.py_vmomi_service.find_by_uuid = lambda a, b, c: self.vm - self.py_vmomi_service.find_network_by_name = Mock(return_value=self.network) + self.py_vmomi_service.find_network_by_name = MagicMock( + return_value=self.network + ) - self.synchronous_task_waiter = Mock() - self.synchronous_task_waiter.wait_for_task = Mock(return_value="TASK OK") - self.si = Mock() + self.synchronous_task_waiter = MagicMock() + self.synchronous_task_waiter.wait_for_task = MagicMock(return_value="TASK OK") + self.si = MagicMock() - mapping = {"vnic 1": (Mock(spec=vim.Network), None)} - self.vnic_service = Mock() - self.vnic_to_network_mapper = Mock() - self.vnic_to_network_mapper.map_request_to_vnics = Mock(return_value=mapping) + mapping = {"vnic 1": (MagicMock(spec=vim.Network), None)} + self.vnic_service = MagicMock() + self.vnic_to_network_mapper = MagicMock() + self.vnic_to_network_mapper.map_request_to_vnics = MagicMock( + return_value=mapping + ) self.vnics = {"vnic 1": self.vnic} self.port_group_name_generator = DvPortGroupNameGenerator() - self.vnic_service.map_vnics = Mock(return_value=self.vnics) + self.vnic_service.map_vnics = MagicMock(return_value=self.vnics) self.configurer = VirtualMachinePortGroupConfigurer( self.py_vmomi_service, self.synchronous_task_waiter, @@ -72,31 +81,33 @@ def setUp(self): ) def test_get_networks_on_vnics(self): - res = self.configurer.get_networks_on_vnics(self.vm, [self.vnic], logger=Mock()) + res = self.configurer.get_networks_on_vnics( + self.vm, [self.vnic], logger=MagicMock() + ) self.assertIsNotNone(res) def test_erase_network_by_mapping(self): res = self.configurer.erase_network_by_mapping( - [self.network], [], logger=Mock() + [self.network], [], logger=MagicMock() ) self.assertIsNone(res) def test_disconnect_all_networks(self): mapping = self.configurer.disconnect_all_networks( - self.vm, Mock(spec=vim.Network), [], logger=Mock() + self.vm, MagicMock(spec=vim.Network), [], logger=MagicMock() ) self.assertFalse(mapping[0].connect) def test_disconnect_network(self): mapping = self.configurer.disconnect_network( - self.vm, self.network, Mock(spec=vim.Network), "", logger=Mock() + self.vm, self.network, MagicMock(spec=vim.Network), "", logger=MagicMock() ) self.assertFalse(mapping[0].connect) def test_connect_vnic_to_networks(self): - mapping = [ConnectRequest("vnic 1", (Mock(spec=vim.Network), None))] + mapping = [ConnectRequest("vnic 1", (MagicMock(spec=vim.Network), None))] res = self.configurer.connect_vnic_to_networks( - self.vm, mapping, Mock(spec=vim.Network), [], logger=Mock() + self.vm, mapping, MagicMock(spec=vim.Network), [], logger=MagicMock() ) self.assertIsNotNone(res[0].vnic) @@ -108,7 +119,7 @@ def side_effect(*args, **keys): self.port_group_name_generator.is_generated_name = MagicMock(return_value=True) self.configurer.destroy_port_group_task = MagicMock(side_effect=side_effect) self.configurer.erase_network_by_mapping( - [self.network, self.network], [], logger=Mock() + [self.network, self.network], [], logger=MagicMock() ) def test_disconnect_vm_with_three_networks(self): @@ -121,7 +132,7 @@ def side_effect(*args, **keys): self.port_group_name_generator.is_generated_name = MagicMock(return_value=True) self.configurer.destroy_port_group_task = MagicMock(side_effect=side_effect) self.configurer.erase_network_by_mapping( - [self.network, self.network2, self.network3], [], logger=Mock() + [self.network, self.network2, self.network3], [], logger=MagicMock() ) # Assert diff --git a/tests/test_network/vnic/test_network_vnic.py b/tests/test_network/vnic/test_network_vnic.py index 73b81b3..c3bef79 100644 --- a/tests/test_network/vnic/test_network_vnic.py +++ b/tests/test_network/vnic/test_network_vnic.py @@ -1,21 +1,26 @@ +import sys from unittest import TestCase -from mock import MagicMock, Mock, create_autospec from pyVmomi import vim from cloudshell.cp.vcenter.common.vcenter.vmomi_service import pyVmomiService from cloudshell.cp.vcenter.network.vnic.vnic_service import VNicService +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock, create_autospec +else: + from mock import MagicMock, create_autospec + class TestNetwork(TestCase): def setUp(self): pass def test_vnic_reconfig_task(self): - vm = Mock() + vm = MagicMock() vm.ReconfigVM_Task = lambda x: isinstance(x, vim.vm.ConfigSpec) - api_wrapper = pyVmomiService(Mock, Mock(), Mock()) + api_wrapper = pyVmomiService(MagicMock, MagicMock(), MagicMock()) res = api_wrapper.vm_reconfig_task(vm, []) self.assertTrue(res) @@ -34,66 +39,66 @@ def test_device_attahed_to_network_standard(self): self.assertFalse(VNicService.device_is_attached_to_network(None, None)) network_name = "TEST" - device = Mock() - device.backing = Mock() - device.backing.network = Mock() + device = MagicMock() + device.backing = MagicMock() + device.backing.network = MagicMock() device.backing.network.name = network_name self.assertTrue(VNicService.device_is_attached_to_network(device, network_name)) - network = Mock(spec=vim.Network) + network = MagicMock(spec=vim.Network) network.name = "xnet" - nicspec = Mock() + nicspec = MagicMock() nicspec.device = device res = VNicService.vnic_attach_to_network_standard( - nicspec=nicspec, network=network, logger=Mock() + nicspec=nicspec, network=network, logger=MagicMock() ) self.assertEqual(res.device.backing.network.name, "xnet") def test_device_attahed_to_network_distributed(self): network_name = "PORT-GROUP" - device = Mock() + device = MagicMock() device.backing = MagicMock() - device.backing.port = Mock() + device.backing.port = MagicMock() hasattr(device.backing, "network") del device.backing.network device.backing.port.portgroupKey = network_name self.assertTrue(VNicService.device_is_attached_to_network(device, network_name)) - port_group = Mock(spec=vim.dvs.DistributedVirtualPortgroup) + port_group = MagicMock(spec=vim.dvs.DistributedVirtualPortgroup) port_group.key = "group_net" port_group.config.distributedVirtualSwitch.uuid = "6686" - nicspec = Mock() + nicspec = MagicMock() nicspec.device = device res = VNicService.vnic_attach_to_network_distributed( - nicspec=nicspec, port_group=port_group, logger=Mock() + nicspec=nicspec, port_group=port_group, logger=MagicMock() ) self.assertEqual(res.device.backing.port.portgroupKey, "group_net") def test_xx(self): - vm = Mock() + vm = MagicMock() vm.ReconfigVM_Task = lambda x: isinstance(x, vim.vm.ConfigSpec) - nicspec = Mock() + nicspec = MagicMock() res = VNicService.vnic_add_to_vm_task( - nicspec=nicspec, virtual_machine=vm, logger=Mock() + nicspec=nicspec, virtual_machine=vm, logger=MagicMock() ) self.assertIsNone(res) - # nicspec = Mock(spec=vim.vm.device.VirtualDeviceSpec) + # nicspec = MagicMock(spec=vim.vm.device.VirtualDeviceSpec) # res = vnic_add_to_vm_task(nicspec, vm) # pass def test_vnic_add_to_vm_task(self): # arrange nicspec = vim.vm.device.VirtualDeviceSpec() - vm = Mock() - VNicService.vnic_set_connectivity_status = Mock() - pyVmomiService.vm_reconfig_task = Mock() + vm = MagicMock() + VNicService.vnic_set_connectivity_status = MagicMock() + pyVmomiService.vm_reconfig_task = MagicMock() # act res = VNicService.vnic_add_to_vm_task( - nicspec=nicspec, virtual_machine=vm, logger=Mock() + nicspec=nicspec, virtual_machine=vm, logger=MagicMock() ) # assert @@ -101,25 +106,25 @@ def test_vnic_add_to_vm_task(self): self.assertTrue(pyVmomiService.vm_reconfig_task.called) def test_set_connectiv(self): - nicspec = Mock() - nicspec.device = Mock() + nicspec = MagicMock() + nicspec.device = MagicMock() connect_status = True nicspec = VNicService.vnic_set_connectivity_status( - nicspec=nicspec, is_connected=connect_status, logger=Mock() + nicspec=nicspec, is_connected=connect_status, logger=MagicMock() ) self.assertEqual(nicspec.device.connectable.connected, connect_status) def test_vnic_is_attachet_to_network(self): - nicspec = Mock() - nicspec.device = Mock() - res = VNicService.vnic_is_attachet_to_network(nicspec, Mock()) + nicspec = MagicMock() + nicspec.device = MagicMock() + res = VNicService.vnic_is_attachet_to_network(nicspec, MagicMock()) self.assertFalse(res) def test_vnic_remove_from_vm_list(self): # arrange vm = create_autospec(spec=vim.vm) - vm.config = Mock() - vm.config.hardware = Mock() + vm.config = MagicMock() + vm.config.hardware = MagicMock() vm.config.hardware.device = [ create_autospec(spec=vim.vm.device.VirtualEthernetCard) ] @@ -132,9 +137,9 @@ def test_vnic_remove_from_vm_list(self): def test_get_device_spec(self): # arrange - vnic = Mock() - VNicService.create_vnic_spec = Mock() - VNicService.set_vnic_connectivity_status = Mock() + vnic = MagicMock() + VNicService.create_vnic_spec = MagicMock() + VNicService.set_vnic_connectivity_status = MagicMock() # act VNicService.get_device_spec(vnic, True) @@ -147,11 +152,11 @@ def test_vnic_add_new_to_vm_task(self): # arrange vm = create_autospec(spec=vim.vm) - VNicService.vnic_new_attached_to_network = Mock() - # VNicService.vnic_add_to_vm_task = Mock() + VNicService.vnic_new_attached_to_network = MagicMock() + # VNicService.vnic_add_to_vm_task = MagicMock() # act - VNicService.vnic_add_new_to_vm_task(vm=vm, network=None, logger=Mock()) + VNicService.vnic_add_new_to_vm_task(vm=vm, network=None, logger=MagicMock()) # assert self.assertTrue(VNicService.vnic_new_attached_to_network.called) @@ -161,10 +166,10 @@ def test_vnic_attached_to_network_1(self): # arrange network = create_autospec(spec=vim.dvs.DistributedVirtualPortgroup) nicspec = create_autospec(spec=vim.vm.device.VirtualDeviceSpec) - VNicService.vnic_attach_to_network_distributed = Mock() + VNicService.vnic_attach_to_network_distributed = MagicMock() # act - VNicService.vnic_attached_to_network(nicspec, network, logger=Mock()) + VNicService.vnic_attached_to_network(nicspec, network, logger=MagicMock()) # assert self.assertTrue(VNicService.vnic_attach_to_network_distributed.called) @@ -173,10 +178,10 @@ def test_vnic_attached_to_network_2(self): # arrange network = create_autospec(spec=vim.Network) nicspec = create_autospec(spec=vim.vm.device.VirtualDeviceSpec) - VNicService.vnic_attach_to_network_standard = Mock() + VNicService.vnic_attach_to_network_standard = MagicMock() # act - VNicService.vnic_attached_to_network(nicspec, network, logger=Mock()) + VNicService.vnic_attached_to_network(nicspec, network, logger=MagicMock()) # assert self.assertTrue(VNicService.vnic_attach_to_network_standard.called) diff --git a/tests/test_vm/test_deployer.py b/tests/test_vm/test_deployer.py index e8e0949..af944d0 100644 --- a/tests/test_vm/test_deployer.py +++ b/tests/test_vm/test_deployer.py @@ -1,7 +1,6 @@ +import sys from unittest import TestCase -from mock import Mock - from cloudshell.cp.vcenter.common.model_factory import ResourceModelParser from cloudshell.cp.vcenter.models.DeployDataHolder import DeployDataHolder from cloudshell.cp.vcenter.models.DeployFromTemplateDetails import ( @@ -21,31 +20,36 @@ ) from cloudshell.cp.vcenter.vm.deploy import VirtualMachineDeployer +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock +else: + from mock import MagicMock + class TestVirtualMachineDeployer(TestCase): def setUp(self): self.name = "name" self.uuid = "uuid" - self.name_gen = Mock(return_value=self.name) - self.pv_service = Mock() - self.si = Mock() - self.clone_parmas = Mock() - self.clone_res = Mock() + self.name_gen = MagicMock(return_value=self.name) + self.pv_service = MagicMock() + self.si = MagicMock() + self.clone_parmas = MagicMock() + self.clone_res = MagicMock() self.clone_res.error = None - self.clone_res.vm = Mock() - self.clone_res.vm.summary = Mock() - self.clone_res.vm.summary.config = Mock() + self.clone_res.vm = MagicMock() + self.clone_res.vm.summary = MagicMock() + self.clone_res.vm.summary.config = MagicMock() self.clone_res.vm.summary.config.uuid = self.uuid - self.pv_service.CloneVmParameters = Mock(return_value=self.clone_parmas) - self.pv_service.clone_vm = Mock(return_value=self.clone_res) - self.image_deployer = Mock() - self.image_deployer.deploy_image = Mock(return_value=True) - self.vm = Mock() - self.vm.config = Mock() + self.pv_service.CloneVmParameters = MagicMock(return_value=self.clone_parmas) + self.pv_service.clone_vm = MagicMock(return_value=self.clone_res) + self.image_deployer = MagicMock() + self.image_deployer.deploy_image = MagicMock(return_value=True) + self.vm = MagicMock() + self.vm.config = MagicMock() self.vm.config.uuid = self.uuid - self.pv_service.find_vm_by_name = Mock(return_value=self.vm) + self.pv_service.find_vm_by_name = MagicMock(return_value=self.vm) self.model_parser = ResourceModelParser() - self.vm_details_provider = Mock() + self.vm_details_provider = MagicMock() self.deployer = VirtualMachineDeployer( pv_service=self.pv_service, name_generator=self.name_gen, @@ -63,17 +67,17 @@ def test_vm_deployer(self): ) resource_context = self._create_vcenter_resource_context() - cancellation_context = Mock() + cancellation_context = MagicMock() cancellation_context.is_cancelled = False res = self.deployer.deploy_from_template( si=self.si, data_holder=deploy_from_template_details, vcenter_data_model=resource_context, - app_resource_model=Mock(), - logger=Mock(), - session=Mock(), - reservation_id=Mock(), + app_resource_model=MagicMock(), + logger=MagicMock(), + session=MagicMock(), + reservation_id=MagicMock(), cancellation_context=cancellation_context, ) @@ -90,17 +94,17 @@ def test_clone_deployer(self): ) deploy_from_template_details.vcenter_vm = "name" resource_context = self._create_vcenter_resource_context() - reservation_id = Mock() - cancellation_context = Mock() + reservation_id = MagicMock() + cancellation_context = MagicMock() cancellation_context.is_cancelled = False res = self.deployer.deploy_clone_from_vm( si=self.si, data_holder=deploy_from_template_details, - app_resource_model=Mock(), + app_resource_model=MagicMock(), vcenter_data_model=resource_context, - logger=Mock(), - session=Mock(), + logger=MagicMock(), + session=MagicMock(), reservation_id=reservation_id, cancellation_context=cancellation_context, ) @@ -118,17 +122,17 @@ def test_snapshot_deployer(self): ) deploy_from_template_details.vcenter_vm_snapshot = "name/shanpshot" resource_context = self._create_vcenter_resource_context() - cancellation_context = Mock() + cancellation_context = MagicMock() cancellation_context.is_cancelled = False res = self.deployer.deploy_from_linked_clone( si=self.si, data_holder=deploy_from_template_details, - app_resource_model=Mock(), + app_resource_model=MagicMock(), vcenter_data_model=resource_context, - logger=Mock(), - session=Mock(), - reservation_id=Mock(), + logger=MagicMock(), + session=MagicMock(), + reservation_id=MagicMock(), cancellation_context=cancellation_context, ) @@ -155,10 +159,10 @@ def _create_vcenter_resource_context(self): return vc def test_vm_deployer_error(self): - self.clone_res.error = Mock() + self.clone_res.error = MagicMock() - self.pv_service.CloneVmParameters = Mock(return_value=self.clone_parmas) - self.pv_service.clone_vm = Mock(return_value=self.clone_res) + self.pv_service.CloneVmParameters = MagicMock(return_value=self.clone_parmas) + self.pv_service.clone_vm = MagicMock(return_value=self.clone_res) deploy_from_template_details = DeployFromTemplateDetails( vCenterVMFromTemplateResourceModel(), "VM Deployment" ) @@ -172,13 +176,13 @@ def test_vm_deployer_error(self): Exception, self.deployer.deploy_from_template, self.si, - Mock(), - Mock(), + MagicMock(), + MagicMock(), deploy_from_template_details, - Mock(), + MagicMock(), vcenter_data_model, - Mock(), - Mock(), + MagicMock(), + MagicMock(), ) self.pv_service.CloneVmParameters.assert_called() @@ -208,25 +212,25 @@ def test_vm_deployer_image(self): } ) - connectivity = Mock() + connectivity = MagicMock() connectivity.address = "vcenter ip or name" connectivity.user = "user" connectivity.password = "password" - session = Mock() - vcenter_data_model = Mock() + session = MagicMock() + vcenter_data_model = MagicMock() vcenter_data_model.default_datacenter = "qualisb" - resource_context = Mock() - cancellation_context = Mock() + resource_context = MagicMock() + cancellation_context = MagicMock() cancellation_context.is_cancelled = False res = self.deployer.deploy_from_image( si=self.si, - logger=Mock(), + logger=MagicMock(), session=session, vcenter_data_model=vcenter_data_model, data_holder=params, resource_context=resource_context, - reservation_id=Mock(), + reservation_id=MagicMock(), cancellation_context=cancellation_context, ) @@ -234,7 +238,7 @@ def test_vm_deployer_image(self): self.assertEqual(res.vmUuid, self.uuid) def test_vm_deployer_image_no_res(self): - self.image_deployer.deploy_image = Mock(return_value=None) + self.image_deployer.deploy_image = MagicMock(return_value=None) params = DeployDataHolder( { "image_url": "c:\image.ovf", @@ -248,7 +252,7 @@ def test_vm_deployer_image_no_res(self): } ) - connectivity = Mock() + connectivity = MagicMock() connectivity.address = "vcenter ip or name" connectivity.user = "user" connectivity.password = "password" @@ -258,7 +262,7 @@ def test_vm_deployer_image_no_res(self): ) def test_vm_deployer_image_no_vm(self): - self.pv_service.find_vm_by_name = Mock(return_value=None) + self.pv_service.find_vm_by_name = MagicMock(return_value=None) params = DeployDataHolder( { "image_url": "c:\image.ovf", @@ -272,7 +276,7 @@ def test_vm_deployer_image_no_vm(self): } ) - connectivity = Mock() + connectivity = MagicMock() connectivity.address = "vcenter ip or name" connectivity.user = "user" connectivity.password = "password" diff --git a/tests/test_vm/test_dvswitch_connector.py b/tests/test_vm/test_dvswitch_connector.py index 1d0b240..e2fe35f 100644 --- a/tests/test_vm/test_dvswitch_connector.py +++ b/tests/test_vm/test_dvswitch_connector.py @@ -1,6 +1,6 @@ +import sys from unittest import TestCase -from mock import MagicMock, Mock from pyVim.connect import Disconnect, SmartConnect from pyVmomi import vim @@ -19,25 +19,30 @@ from tests.utils.testing_credentials import TestCredentials +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock +else: + from mock import MagicMock + class TestVirtualSwitchToMachineConnector(TestCase): def test_connect(self): # Arrange - si = Mock() + si = MagicMock() - py_vmomi_service = Mock() - py_vmomi_service.connect = Mock(return_value=si) + py_vmomi_service = MagicMock() + py_vmomi_service.connect = MagicMock(return_value=si) dv_port_group_creator = MagicMock() virtual_machine_port_group_configurer = MagicMock() - vlan_spec = Mock() + vlan_spec = MagicMock() virtual_switch_to_machine_connector = VirtualSwitchToMachineConnector( dv_port_group_creator, virtual_machine_port_group_configurer ) - vm = Mock() + vm = MagicMock() - network_map = Mock() + network_map = MagicMock() network_map.dv_port_name = "dv_port_name" network_map.dv_switch_name = "dvSwitch" network_map.dv_switch_path = "QualiSB" @@ -48,16 +53,16 @@ def test_connect(self): si=si, vm=vm, mapping=[network_map], - default_network=Mock(spec=vim.Network), + default_network=MagicMock(spec=vim.Network), reserved_networks=[], - logger=Mock(), + logger=MagicMock(), promiscuous_mode="True", ) def integrationtest(self): - resource_connection_details_retriever = Mock() + resource_connection_details_retriever = MagicMock() credentials = TestCredentials() - resource_connection_details_retriever.connection_details = Mock( + resource_connection_details_retriever.connection_details = MagicMock( return_value=VCenterConnectionDetails( credentials.host, credentials.username, credentials.password ) diff --git a/tests/test_vm/test_vm_ip_manager.py b/tests/test_vm/test_vm_ip_manager.py index b3831e2..1578c71 100644 --- a/tests/test_vm/test_vm_ip_manager.py +++ b/tests/test_vm/test_vm_ip_manager.py @@ -1,11 +1,16 @@ import re +import sys from unittest import TestCase -from mock import Mock, patch - from cloudshell.cp.vcenter.commands.ip_result import IpReason, IpResult from cloudshell.cp.vcenter.vm.ip_manager import VMIPManager +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock +else: + from mock import MagicMock + + counter = 0 @@ -15,12 +20,12 @@ def setUp(self): self.ip_manager.INTERVAL = 0.001 self.default_net = "aa" self.function = re.compile(".*").match - self.cancel = Mock() + self.cancel = MagicMock() self.cancel.is_cancelled = None self.timeout = 1 - self.logger = Mock() - self.vm = Mock() - self.vm.guest = Mock() + self.logger = MagicMock() + self.vm = MagicMock() + self.vm.guest = MagicMock() self.vm.guest.toolsStatus = "running" def test_get_match_method_none(self): @@ -32,8 +37,8 @@ def test_get_match_method(self): self.assertEqual(method, re.compile("1.*").match) def test_get_ip_toolsNotInstalled(self): - vm = Mock() - vm.guest = Mock() + vm = MagicMock() + vm.guest = MagicMock() vm.guest.toolsStatus = "toolsNotInstalled" self.assertRaises( ValueError, @@ -69,7 +74,7 @@ def test_get_ip_no_timeout_found(self): def test_get_ip_no_timeout_multi_ip_regex_pattern(self): self.vm.guest.ipAddress = "1.1.1.1" - nic = Mock() + nic = MagicMock() nic.network = None nic.ipAddress = ["2.2.2.2"] self.vm.guest.net = [nic] @@ -121,7 +126,7 @@ def test_get_ip_with_timeout_raised(self): def test_get_ip_cancelled(self): TestVMIPManager.counter = 0 - cancel = Mock() + cancel = MagicMock() cancel.is_cancelled = True res = self.ip_manager.get_ip( diff --git a/tests/test_vm/test_vnic_to_network_mapper.py b/tests/test_vm/test_vnic_to_network_mapper.py index d6f9e28..3ab1e76 100644 --- a/tests/test_vm/test_vnic_to_network_mapper.py +++ b/tests/test_vm/test_vnic_to_network_mapper.py @@ -1,6 +1,6 @@ +import sys from unittest import TestCase -from mock import Mock from pyVmomi import vim from cloudshell.cp.vcenter.network.dvswitch.name_generator import ( @@ -9,16 +9,21 @@ from cloudshell.cp.vcenter.vm.dvswitch_connector import ConnectRequest from cloudshell.cp.vcenter.vm.vnic_to_network_mapper import VnicToNetworkMapper +if sys.version_info >= (3, 0): + from unittest.mock import MagicMock +else: + from mock import MagicMock + class TestVnicToNetworkMapper(TestCase): def test_(self): vnics = { - "net 1": Mock(spec=vim.vm.device.VirtualEthernetCard), - "net 2": Mock(spec=vim.vm.device.VirtualEthernetCard), + "net 1": MagicMock(spec=vim.vm.device.VirtualEthernetCard), + "net 2": MagicMock(spec=vim.vm.device.VirtualEthernetCard), } - network2 = Mock(spec=vim.Network) + network2 = MagicMock(spec=vim.Network) network2.name = "aa" - network1 = Mock(spec=vim.Network) + network1 = MagicMock(spec=vim.Network) network1.name = "bb" request1 = ConnectRequest("net 2", "aa") request2 = ConnectRequest(None, "ab") diff --git a/tests/tests_pycommon/test_resourceModelParser.py b/tests/tests_pycommon/test_resourceModelParser.py index 032e95e..a1ba198 100644 --- a/tests/tests_pycommon/test_resourceModelParser.py +++ b/tests/tests_pycommon/test_resourceModelParser.py @@ -1,13 +1,6 @@ from unittest import TestCase -from cloudshell.api.cloudshell_api import ResourceAttribute, ResourceInfo -from cloudshell.helpers.scripts.cloudshell_scripts_helpers import ResourceContextDetails -from mock import create_autospec - from cloudshell.cp.vcenter.common.model_factory import ResourceModelParser -from cloudshell.cp.vcenter.models.GenericDeployedAppResourceModel import ( - GenericDeployedAppResourceModel, -) from cloudshell.cp.vcenter.models.VLANAutoResourceModel import VLANAutoResourceModel diff --git a/tox.ini b/tox.ini index 851dbf5..e4cd12f 100644 --- a/tox.ini +++ b/tox.ini @@ -19,7 +19,7 @@ deps = master: -r test_requirements.txt dev: -r dev_requirements.txt commands = - nosetests --with-coverage --cover-package={[DEFAULT]package-name} tests + pytest --cov=cloudshell.cp.vcenter tests [testenv:pre-commit] basepython = python3 @@ -31,14 +31,11 @@ commands = pre-commit run --all-files --show-diff-on-failure skip_install = true commands = python setup.py -q sdist --format zip - python setup.py -q bdist_wheel + python setup.py -q bdist_wheel --universal [isort] -line_length = 88 -forced_separate = %(package-name)s,tests -multi_line_output = 3 -include_trailing_comma = True -combine_as_imports = 1 +profile=black +forced_separate = cloudshell.cp.vcenter,tests [flake8] max-line-length = 88 From ee762e21124819b47543c479e420da098c232cdc Mon Sep 17 00:00:00 2001 From: Costya Date: Wed, 26 May 2021 17:08:51 +0300 Subject: [PATCH 7/9] fixed multiple minor issues: 1. Issues with Saving Sandbox 2. Issues with Restoring Sandbox 3. Fix for the folder remove during tear down. --- .../savers/linked_clone_artifact_saver.py | 21 ++++++++++++------- .../vcenter/common/vcenter/event_manager.py | 4 ++++ .../vcenter/common/vcenter/folder_manager.py | 16 +++++++------- 3 files changed, 26 insertions(+), 15 deletions(-) diff --git a/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py b/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py index 35cebc9..88fce03 100644 --- a/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py +++ b/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py @@ -24,13 +24,13 @@ "VMware vCenter Cloud Provider 2G.vCenter VM From Linked Clone 2G" ) ATTRIBUTES_TO_IGNORE = [ - Attribute("Customization Spec", ""), - Attribute("Private IP", ""), - Attribute("CPU", ""), - Attribute("RAM", ""), - Attribute("Hostname", ""), - Attribute("HDD", ""), -] + Attribute("Customization Spec", ""), + Attribute("Private IP", ""), + Attribute("CPU", ""), + Attribute("RAM", ""), + Attribute("Hostname", ""), + Attribute("HDD", ""), + ] class LinkedCloneArtifactHandler(object): @@ -102,7 +102,12 @@ def save(self, save_action, cancellation_context): thread_id, data_holder.template_resource_model.vcenter_vm ) ) - + data_holder.template_resource_model.cpu = "" + data_holder.template_resource_model.ram = "" + data_holder.template_resource_model.hdd = "" + data_holder.template_resource_model.customization_spec = "" + data_holder.template_resource_model.private_ip = "" + data_holder.template_resource_model.hostname = "" result = self.deployer.deploy_clone_from_vm( self.si, self.logger, diff --git a/cloudshell/cp/vcenter/common/vcenter/event_manager.py b/cloudshell/cp/vcenter/common/vcenter/event_manager.py index 8e819d7..c93ee75 100644 --- a/cloudshell/cp/vcenter/common/vcenter/event_manager.py +++ b/cloudshell/cp/vcenter/common/vcenter/event_manager.py @@ -9,6 +9,8 @@ class VMOSCustomization: START_EVENT = "CustomizationStartedEvent" SUCCESS_END_EVENT = "CustomizationSucceeded" FAILED_END_EVENT = "CustomizationFailed" + FAILED_NETWORKING_END_EVENT = "CustomizationNetworkSetupFailed" + FAILED_UNKNOWN_END_EVENT = "CustomizationUnkownFailure" START_EVENT_TIMEOUT = 5 * 60 END_EVENT_TIMEOUT = 20 * 60 START_EVENT_WAIT_TIME = 10 @@ -152,6 +154,8 @@ def wait_for_vm_os_customization_end_event( event_type_id_list=[ self.VMOSCustomization.SUCCESS_END_EVENT, self.VMOSCustomization.FAILED_END_EVENT, + self.VMOSCustomization.FAILED_UNKNOWN_END_EVENT, + self.VMOSCustomization.FAILED_NETWORKING_END_EVENT ], timeout=timeout, wait_time=wait_time, diff --git a/cloudshell/cp/vcenter/common/vcenter/folder_manager.py b/cloudshell/cp/vcenter/common/vcenter/folder_manager.py index d79d036..70206ba 100644 --- a/cloudshell/cp/vcenter/common/vcenter/folder_manager.py +++ b/cloudshell/cp/vcenter/common/vcenter/folder_manager.py @@ -27,13 +27,15 @@ def delete_folder_if_empty(self, si, folder_full_path, logger): self.locks[folder_full_path] = Lock() with self.locks[folder_full_path]: - if not folder.childEntity: - result = self.delete_folder(folder, logger) - logger.info(f"Remove result for folder '{folder_full_path}':\n{result}") - else: - logger.info( - f"Skip folder '{folder_full_path}' deletion. It contains objects: {folder.childEntity}" - ) + folder = self.pv_service.get_folder(si, folder_full_path) + if folder: + if not folder.childEntity: + result = self.delete_folder(folder, logger) + logger.info(f"Remove result for folder '{folder_full_path}':\n{result}") + else: + logger.info( + f"Skip folder '{folder_full_path}' deletion. It contains objects: {folder.childEntity}" + ) def delete_folder_with_vm_power_off(self, si, logger, folder_full_path): logger.info( From 20551a974e755f4629245045380920c70a3a8515 Mon Sep 17 00:00:00 2001 From: Costya Date: Wed, 26 May 2021 17:11:30 +0300 Subject: [PATCH 8/9] fixed black --- .../utilites/savers/linked_clone_artifact_saver.py | 14 +++++++------- .../cp/vcenter/common/vcenter/event_manager.py | 2 +- .../cp/vcenter/common/vcenter/folder_manager.py | 4 +++- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py b/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py index 88fce03..6256c10 100644 --- a/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py +++ b/cloudshell/cp/vcenter/common/utilites/savers/linked_clone_artifact_saver.py @@ -24,13 +24,13 @@ "VMware vCenter Cloud Provider 2G.vCenter VM From Linked Clone 2G" ) ATTRIBUTES_TO_IGNORE = [ - Attribute("Customization Spec", ""), - Attribute("Private IP", ""), - Attribute("CPU", ""), - Attribute("RAM", ""), - Attribute("Hostname", ""), - Attribute("HDD", ""), - ] + Attribute("Customization Spec", ""), + Attribute("Private IP", ""), + Attribute("CPU", ""), + Attribute("RAM", ""), + Attribute("Hostname", ""), + Attribute("HDD", ""), +] class LinkedCloneArtifactHandler(object): diff --git a/cloudshell/cp/vcenter/common/vcenter/event_manager.py b/cloudshell/cp/vcenter/common/vcenter/event_manager.py index c93ee75..e132ee4 100644 --- a/cloudshell/cp/vcenter/common/vcenter/event_manager.py +++ b/cloudshell/cp/vcenter/common/vcenter/event_manager.py @@ -155,7 +155,7 @@ def wait_for_vm_os_customization_end_event( self.VMOSCustomization.SUCCESS_END_EVENT, self.VMOSCustomization.FAILED_END_EVENT, self.VMOSCustomization.FAILED_UNKNOWN_END_EVENT, - self.VMOSCustomization.FAILED_NETWORKING_END_EVENT + self.VMOSCustomization.FAILED_NETWORKING_END_EVENT, ], timeout=timeout, wait_time=wait_time, diff --git a/cloudshell/cp/vcenter/common/vcenter/folder_manager.py b/cloudshell/cp/vcenter/common/vcenter/folder_manager.py index 70206ba..8a3e74d 100644 --- a/cloudshell/cp/vcenter/common/vcenter/folder_manager.py +++ b/cloudshell/cp/vcenter/common/vcenter/folder_manager.py @@ -31,7 +31,9 @@ def delete_folder_if_empty(self, si, folder_full_path, logger): if folder: if not folder.childEntity: result = self.delete_folder(folder, logger) - logger.info(f"Remove result for folder '{folder_full_path}':\n{result}") + logger.info( + f"Remove result for folder '{folder_full_path}':\n{result}" + ) else: logger.info( f"Skip folder '{folder_full_path}' deletion. It contains objects: {folder.childEntity}" From fe0bc67536bb94dd06fc575593dc1569463df481 Mon Sep 17 00:00:00 2001 From: Alexey Bogoslovskyi Date: Wed, 26 May 2021 17:51:23 +0300 Subject: [PATCH 9/9] pre-commit and tox configuration --- .pre-commit-config.yaml | 4 ++-- cloudshell/cp/vcenter/commands/command_orchestrator.py | 3 ++- cloudshell/cp/vcenter/commands/deploy_vm.py | 5 ++--- .../cp/vcenter/common/vcenter/model_auto_discovery.py | 3 ++- cloudshell/cp/vcenter/common/wrappers/command_wrapper.py | 3 ++- cloudshell/cp/vcenter/vm/vm_details_provider.py | 3 ++- test_requirements.txt | 3 ++- tests/test_commands/test_command_orchestrator.py | 7 ++++--- tests/test_commands/test_vm_details.py | 3 ++- tests/test_common/test_utilities/test_command_wrapper.py | 4 ++-- tests/test_common/test_vcenter/test_vmomi_service.py | 4 ++-- tests/test_network/test_dvswitch/test_connector.py | 4 ++-- tox.ini | 2 -- 13 files changed, 26 insertions(+), 22 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4350209..2daa4ee 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,6 @@ repos: - - repo: https://github.com/pre-commit/mirrors-isort - rev: v4.3.21 + - repo: https://github.com/timothycrosley/isort + rev: 5.6.4 hooks: - id: isort language_version: python3.7 diff --git a/cloudshell/cp/vcenter/commands/command_orchestrator.py b/cloudshell/cp/vcenter/commands/command_orchestrator.py index 9200344..ca60df7 100644 --- a/cloudshell/cp/vcenter/commands/command_orchestrator.py +++ b/cloudshell/cp/vcenter/commands/command_orchestrator.py @@ -2,9 +2,10 @@ from datetime import datetime import jsonpickle -from cloudshell.cp.core.models import DeployApp, DeployAppResult, SaveApp, SaveAppResult from pyVim.connect import Disconnect, SmartConnect +from cloudshell.cp.core.models import DeployApp, DeployAppResult, SaveApp, SaveAppResult + from cloudshell.cp.vcenter import constants from cloudshell.cp.vcenter.commands.cluster_usage import GetClusterUsageCommand from cloudshell.cp.vcenter.commands.connect_dvswitch import VirtualSwitchConnectCommand diff --git a/cloudshell/cp/vcenter/commands/deploy_vm.py b/cloudshell/cp/vcenter/commands/deploy_vm.py index 4bd1277..9e83e5b 100644 --- a/cloudshell/cp/vcenter/commands/deploy_vm.py +++ b/cloudshell/cp/vcenter/commands/deploy_vm.py @@ -1,9 +1,8 @@ -from cloudshell.cp.vcenter.models.DeployFromImageDetails import DeployFromImageDetails - -from os.path import normpath +from os.path import normpath from cloudshell.cp.vcenter.common.vcenter.vm_location import VMLocation from cloudshell.cp.vcenter.constants import DEPLOYED_APPS_FOLDER +from cloudshell.cp.vcenter.models.DeployFromImageDetails import DeployFromImageDetails from cloudshell.cp.vcenter.models.DeployFromTemplateDetails import ( DeployFromTemplateDetails, ) diff --git a/cloudshell/cp/vcenter/common/vcenter/model_auto_discovery.py b/cloudshell/cp/vcenter/common/vcenter/model_auto_discovery.py index bc148a6..4b3fbec 100644 --- a/cloudshell/cp/vcenter/common/vcenter/model_auto_discovery.py +++ b/cloudshell/cp/vcenter/common/vcenter/model_auto_discovery.py @@ -1,9 +1,10 @@ import collections -from cloudshell.shell.core.session.cloudshell_session import CloudShellSessionContext from pyVim.connect import Disconnect, SmartConnect from pyVmomi import vim +from cloudshell.shell.core.session.cloudshell_session import CloudShellSessionContext + from cloudshell.cp.vcenter.common.model_factory import ResourceModelParser from cloudshell.cp.vcenter.common.utilites.common_utils import ( back_slash_to_front_converter, diff --git a/cloudshell/cp/vcenter/common/wrappers/command_wrapper.py b/cloudshell/cp/vcenter/common/wrappers/command_wrapper.py index 321b8cc..9ebe0aa 100644 --- a/cloudshell/cp/vcenter/common/wrappers/command_wrapper.py +++ b/cloudshell/cp/vcenter/common/wrappers/command_wrapper.py @@ -1,10 +1,11 @@ import inspect from threading import Lock -from cloudshell.shell.core.session.cloudshell_session import CloudShellSessionContext from pyVmomi import vim from retrying import retry +from cloudshell.shell.core.session.cloudshell_session import CloudShellSessionContext + from cloudshell.cp.vcenter.common.cloud_shell.conn_details_retriever import ( ResourceConnectionDetailsRetriever, ) diff --git a/cloudshell/cp/vcenter/vm/vm_details_provider.py b/cloudshell/cp/vcenter/vm/vm_details_provider.py index 8db5ad9..e2fc1d9 100644 --- a/cloudshell/cp/vcenter/vm/vm_details_provider.py +++ b/cloudshell/cp/vcenter/vm/vm_details_provider.py @@ -1,12 +1,13 @@ import ipaddress import re +from pyVmomi import vim + from cloudshell.cp.core.models import ( VmDetailsData, VmDetailsNetworkInterface, VmDetailsProperty, ) -from pyVmomi import vim from cloudshell.cp.vcenter.common.vcenter.vmomi_service import pyVmomiService from cloudshell.cp.vcenter.network.vnic.vnic_service import VNicService diff --git a/test_requirements.txt b/test_requirements.txt index a5f34ff..8218dfa 100644 --- a/test_requirements.txt +++ b/test_requirements.txt @@ -1,3 +1,4 @@ mock; python_version <= '2.7' pytest -pytest-cov \ No newline at end of file +pytest-cov +freezegun \ No newline at end of file diff --git a/tests/test_commands/test_command_orchestrator.py b/tests/test_commands/test_command_orchestrator.py index 74b452f..c9e0f98 100644 --- a/tests/test_commands/test_command_orchestrator.py +++ b/tests/test_commands/test_command_orchestrator.py @@ -3,6 +3,8 @@ from unittest import TestCase import jsonpickle +from freezegun import freeze_time + from cloudshell.api.cloudshell_api import ResourceInfo from cloudshell.cp.core.models import ( AppResourceInfo, @@ -16,14 +18,13 @@ ResourceContextDetails, ResourceRemoteCommandContext, ) -from freezegun import freeze_time from cloudshell.cp.vcenter.commands.command_orchestrator import CommandOrchestrator if sys.version_info >= (3, 0): - from unittest.mock import MagicMock, patch, create_autospec + from unittest.mock import MagicMock, create_autospec, patch else: - from mock import MagicMock, patch, create_autospec + from mock import MagicMock, create_autospec, patch RESTORE_SNAPSHOT = "cloudshell.cp.vcenter.commands.command_orchestrator.CommandOrchestrator.restore_snapshot" diff --git a/tests/test_commands/test_vm_details.py b/tests/test_commands/test_vm_details.py index 0035b2a..84eff7b 100644 --- a/tests/test_commands/test_vm_details.py +++ b/tests/test_commands/test_vm_details.py @@ -1,12 +1,13 @@ import sys from unittest import TestCase +from pyVmomi import vim + from cloudshell.cp.core.models import ( VmDetailsData, VmDetailsNetworkInterface, VmDetailsProperty, ) -from pyVmomi import vim from cloudshell.cp.vcenter.commands.vm_details import VmDetailsCommand from cloudshell.cp.vcenter.vm.ip_manager import VMIPManager diff --git a/tests/test_common/test_utilities/test_command_wrapper.py b/tests/test_common/test_utilities/test_command_wrapper.py index da5108f..68b60fb 100644 --- a/tests/test_common/test_utilities/test_command_wrapper.py +++ b/tests/test_common/test_utilities/test_command_wrapper.py @@ -11,9 +11,9 @@ from cloudshell.cp.vcenter.common.wrappers.command_wrapper import CommandWrapper if sys.version_info >= (3, 0): - from unittest.mock import MagicMock, patch, create_autospec + from unittest.mock import MagicMock, create_autospec, patch else: - from mock import MagicMock, patch, create_autospec + from mock import MagicMock, create_autospec, patch class TestCommandWrapper(TestCase): diff --git a/tests/test_common/test_vcenter/test_vmomi_service.py b/tests/test_common/test_vcenter/test_vmomi_service.py index 485cc6d..4aa8f96 100644 --- a/tests/test_common/test_vcenter/test_vmomi_service.py +++ b/tests/test_common/test_vcenter/test_vmomi_service.py @@ -1,5 +1,5 @@ -import unittest -import sys +import sys +import unittest from datetime import datetime from pyVim.connect import Disconnect, SmartConnect diff --git a/tests/test_network/test_dvswitch/test_connector.py b/tests/test_network/test_dvswitch/test_connector.py index 63d9d3c..fde6f0f 100644 --- a/tests/test_network/test_dvswitch/test_connector.py +++ b/tests/test_network/test_dvswitch/test_connector.py @@ -9,9 +9,9 @@ from cloudshell.cp.vcenter.vm.vnic_to_network_mapper import VnicToNetworkMapper if sys.version_info >= (3, 0): - from unittest.mock import MagicMock, patch, create_autospec + from unittest.mock import MagicMock, create_autospec, patch else: - from mock import MagicMock, patch, create_autospec + from mock import MagicMock, create_autospec, patch class TestVirtualSwitchToMachineConnector(TestCase): diff --git a/tox.ini b/tox.ini index e4cd12f..1452490 100644 --- a/tox.ini +++ b/tox.ini @@ -2,8 +2,6 @@ # in multiple virtualenvs. This configuration file will run the # test suite on all supported python versions. To use it, "pip install tox" # and then run "tox" from this directory. -[DEFAULT] -package-name = cloudshell.cp.vcenter [tox] envlist =