Skip to content

Mock the actual behavior of fail_json #173

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 8 additions & 9 deletions plugins/modules/synciqpolicy.py
Original file line number Diff line number Diff line change
Expand Up @@ -550,17 +550,16 @@ def get_synciq_policy_details(self, policy_name, policy_id, job_params=None):
if policy:
return policy[0], False
return None, False

except utils.ApiException as e:
if str(e.status) == "404":
except (utils.ApiException, Exception) as e:
if isinstance(e, utils.ApiException) and str(e.status) == "404":
LOG.info("SyncIQ policy %s is not found", name_or_id)
return self.get_synciq_target_policy(name_or_id, job_params)
except Exception as e:
error_msg = utils.determine_error(error_obj=e)
error_message = 'Get details of SyncIQ policy %s failed with ' \
'error : %s' % (name_or_id, str(error_msg))
LOG.error(error_message)
self.module.fail_json(msg=error_message)
else:
error_msg = utils.determine_error(error_obj=e)
error_message = 'Get details of SyncIQ policy %s failed with ' \
'error : %s' % (name_or_id, str(error_msg))
LOG.error(error_message)
self.module.fail_json(msg=error_message)

def get_synciq_target_policy(self, policy_id, job_params):
""" Returns details of target syncIQ policy"""
Expand Down
21 changes: 0 additions & 21 deletions tests/unit/plugins/module_utils/mock_fail_json.py

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ def get_storage_tiers_response():
tiers_list = MagicMock()
tiers_list.tiers = MagicMock()
tier_one = MagicMock()
tier_one.name = 'test_ansible_neo_tier'
tier_one.name = 'esa_tier'
tier_one.lnns = [1, 2, 3]
tiers_list.tiers = [tier_one]
return tiers_list
Expand Down
17 changes: 13 additions & 4 deletions tests/unit/plugins/module_utils/mock_filesystem_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,10 +265,12 @@ def get_error_responses(response_type):
"404_exception": "status is 404",
"get_filesystem_exception": "Failed to get details of Filesystem",
"update_quota_error_exception": "Modification of Quota on path",
"create_quota_exception": "Creation of Quota ifs/ATest3 failed with error: None",
"create_quota_exception": "Creation of Quota ifs/ATest3 failed with error:",
"delete_filesystem_exception": "Deletion of Filesystem",
"acl_validation_exception": "Invalid path path/path, Path must start with '/'",
"delete_file_system_with_export_exception": "The Filesystem path ifs/ATest3 has NFS exports. Hence, deleting this directory is not safe",
"acl_validation_exception": "Please specify access_rights or inherit_flags to set ACL",
"get_acl_exception": "while retrieving the access control list",
"get_acl_object_exception": "Error SDK Error message while retrieving ACL object instance",
"get_filesystem_snapshots_exception": "Failed to get filesystem snapshots",
"get_zone_path_exception": "Unable to fetch base path of Access Zone",
"get_quota_state_exception": "quota_state is required",
Expand All @@ -278,17 +280,24 @@ def get_error_responses(response_type):
"get_owner_id_exception": "Failed to get the owner id",
"modify_owner_exception": "Failed to modify owner due to error",
"modify_group_exception": "Failed to modify group due to error",
"create_file_system_exception": "Creation of Filesystem ifs/ATest3 failed",
"create_file_system_wo_owner_exception": "owner is required while creating Filesystem",
"create_file_system_wo_owner_name_exception": "Please specify a name for the owner.",
"create_file_system_wo_group_name_exception": "Please specify a name for the group.",
"create_file_system_with_access_control_rights_exception": "Failed to get the wellknown id for wellknown",
"set_acl_exception": "Setting ACL rights of Filesystem",
"modify_acl_exception": "Modification of ACL on path",
"modify_acl_exception": "Setting ACL rights of Filesystem",
"modify_acl_posix_exception": "Modification of ACL",
"check_acl_modified_exception": "determining if ACLs are modified",
"invalid_wellknown_exception": "Provide valid wellknown",
"delete_quota_exception": "Deletion of Quota on path",
"update_quota_exception": "Modification of Quota on path",
"create_quota_error_exception": "Creation of Quota",
"get_quota_update_param_exception": "Creation of Quota update param failed with error",
"update_include_snap_data_exception": "Modifying include_snap_data is not supported",
"create_quota_get_exception": "Creation of Quota",
"set_access_control_rights_exception": "Setting ACL rights of Filesystem"
"set_access_control_rights_exception": "Setting ACL rights of Filesystem",
"is_owner_modified_exception": "Failed to determine if owner is modified",
"is_group_modified_exception": "Failed to determine if group is modified"
}
return err_msg_dict.get(response_type)
16 changes: 16 additions & 0 deletions tests/unit/plugins/module_utils/mock_nfs_alias_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,19 @@ def create_nfs_alias_failed_msg():

def modify_nfs_alias_failed_msg():
return 'failed with error:'


def space_in_nfs_alias_name_msg():
return 'Spaces are not allowed in NFS alias name. Provide a valid nfs_alias_name'


def empty_nfs_alias_name_msg():
return 'Provide a valid NFS alias name'


def get_nfs_alias_failure_msg():
return 'Get details of NFS alias with name:/test_alias_1 failed with error'


def new_alias_name_when_creation_msg():
return 'new_alias_name should not be provided during the creation of an NFS alias'
48 changes: 24 additions & 24 deletions tests/unit/plugins/module_utils/mock_nfs_export_api.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright: (c) 2022-2024, Dell Technologies
# Copyright: (c) 2023-2024, Dell Technologies

# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

Expand Down Expand Up @@ -117,27 +117,27 @@
"snapshot": None,
"zone": SYS_ZONE},
{
"all_dirs": False,
"block_size": 8192,
"case_insensitive": False,
"case_preserving": True,
"clients": [
SAMPLE_IP1
],
"description": "description",
"id": NFS_ID_2,
"name_max_size": 255,
"paths": [PATH_1],
"read_only": False,
"read_only_clients": [],
"read_write_clients": [],
"readdirplus": True,
"root_clients": [],
"security_flavors": [
"krb5"
],
"snapshot": None,
"zone": SYS_ZONE}],
"all_dirs": False,
"block_size": 8192,
"case_insensitive": False,
"case_preserving": True,
"clients": [
SAMPLE_IP1
],
"description": "description",
"id": NFS_ID_2,
"name_max_size": 255,
"paths": [PATH_1],
"read_only": False,
"read_only_clients": [],
"read_write_clients": [],
"readdirplus": True,
"root_clients": [],
"security_flavors": [
"krb5"
],
"snapshot": None,
"zone": SYS_ZONE}],
"total": 2}

NFS_2 = {"exports": [{
Expand Down Expand Up @@ -220,8 +220,8 @@ def get_nfs_failed_msg():
return 'Got error SDK Error message while getting NFS export details for path'


def get_multiple_nfs_failed_msg():
return 'Multiple NFS Exports found'
def get_nfs_non_zone_failed_msg():
return 'Unable to fetch base path of Access Zone'


def create_nfs_failed_msg():
Expand Down
4 changes: 4 additions & 0 deletions tests/unit/plugins/module_utils/mock_node_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,7 @@ def api_exception_msg():

def invalid_node_msg():
return 'Please provide a valid Node Id'


def disallow_delete_node_msg():
return 'Deletion of node is not allowed through Ansible module'
3 changes: 1 addition & 2 deletions tests/unit/plugins/module_utils/mock_s3_bucket_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,7 @@ def get_error_responses(response_type):
return "Failed to get the group id for group wheel in zone " \
"sample-zone and provider local due to error SDK Error message"
elif response_type == "wellknown_exception":
return "Failed to get the wellknown id for wellknown wheel due to" \
" error Wellknown wheel does not exist. Provide valid wellknown"
return "Wellknown wheel does not exist. Provide valid wellknown"
elif response_type == "modify_path":
return "path of the S3 bucket is not modifiable after creation."
elif response_type == "modify_owner":
Expand Down
8 changes: 4 additions & 4 deletions tests/unit/plugins/module_utils/mock_smartquota_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,17 +65,17 @@ def get_group_sid():

@staticmethod
def smartquota_create_quota_response(path):
return "Create quota for" + path + "failed with"
return "Create quota for " + path + " failed with"

@staticmethod
def smartquota_delete_quota_response(path):
return "Delete quota for" + path + "failed with"
return "Delete quota for " + path + " failed with"

@staticmethod
def smartquota_get_sid_exception(name, az, provider):
return "Failed to get " + name + \
"details for AccessZone:" + az + "and Provider:" + provider + \
"with error"
" details for AccessZone:" + az + " and Provider:" + provider + \
" with error"

@staticmethod
def get_smartquota_dependent_response(response_type):
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/plugins/module_utils/mock_smb_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,6 @@ def get_smb_exception_response(response_type):
'modify_path_err': "Modifying path for a SMB Share is not allowed through Ansible Module",
'sid_err': "Failed to get the user details for root in zone None and provider None due to error",
'smb_parm_err': "Failed to get SMB params from details",
'wellknown_err': "Failed to get the wellknown id for wellknown root"
'wellknown_err': "Wellknown root does not exist. Provide valid wellknown"
}
return err_msg_dict.get(response_type)
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,6 @@ def get_error_responses(response_type):
elif response_type == 'invalid_apply_order':
return "apply_order should be greater than 0."
elif response_type == 'new_order_error':
return "Updating user mapping rule failed with error: new_order should be in range of 1 to 1"
return "new_order should be in range of 1 to 1"
elif response_type == 'outbound_apply_order':
return "Fetching user mapping rule failed with error: apply order should be in range of 1 to 1"
return "apply order should be in range of 1 to 1"
21 changes: 0 additions & 21 deletions tests/unit/plugins/module_utils/shared_library/fail_json.py

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -8,46 +8,47 @@
import copy
import pytest
from mock.mock import MagicMock

from ansible_collections.dellemc.powerscale.tests.unit.plugins.module_utils.mock_api_exception \
import MockApiException
from ansible_collections.dellemc.powerscale.tests.unit.plugins.module_utils.shared_library. \
fail_json import FailJsonException, fail_json


class PowerScaleUnitBase:

'''Powerscale Unit Test Base Class'''

@pytest.fixture
@pytest.fixture(autouse=True)
def powerscale_module_mock(self, mocker, module_object):
exception_class_path = 'ansible_collections.dellemc.powerscale.plugins.module_utils.storage.dell.utils.ApiException'
mocker.patch(exception_class_path, new=MockApiException)
powerscale_module_mock = module_object()
powerscale_module_mock.module = MagicMock()
powerscale_module_mock.module.fail_json = fail_json
powerscale_module_mock.module.check_mode = False
return powerscale_module_mock

def capture_fail_json_call(self, error_msg, module_mock, module_handler=None, invoke_perform_module=False):
try:
self.powerscale_module_mock = module_object()
self.powerscale_module_mock.module = MagicMock()
self.powerscale_module_mock.module.fail_json = MagicMock(
side_effect=SystemExit)
self.powerscale_module_mock.module.check_mode = False
return self.powerscale_module_mock

def capture_fail_json_call(self, error_msg, module_handler=None, invoke_perform_module=False):
with pytest.raises(SystemExit):
if not invoke_perform_module:
module_handler().handle(module_mock, module_mock.module.params)
module_handler().handle(self.powerscale_module_mock,
self.powerscale_module_mock.module.params)
else:
module_mock.perform_module_operation()
except FailJsonException as fj_object:
if error_msg not in fj_object.message:
raise AssertionError(fj_object.message)
self.powerscale_module_mock.perform_module_operation()
self.powerscale_module_mock.module.fail_json.assert_called()
call_args = self.powerscale_module_mock.module.fail_json.call_args.kwargs
assert error_msg in call_args['msg']

def capture_fail_json_method(self, error_msg, module_mock, function_name, *args, **kwargs):
try:
with pytest.raises(SystemExit):
func = getattr(module_mock, function_name)
func(*args, **kwargs)
except FailJsonException as fj_object:
if error_msg not in fj_object.message:
raise AssertionError(fj_object.message)
self.powerscale_module_mock.module.fail_json.assert_called()
call_args = self.powerscale_module_mock.module.fail_json.call_args.kwargs
assert error_msg in call_args['msg']

def set_module_params(self, module_mock, get_module_args, params, deep_copy=True):
def set_module_params(self, get_module_args, params, deep_copy=True):
if deep_copy:
get_module_args = copy.deepcopy(get_module_args)
get_module_args.update(params)
module_mock.module.params = get_module_args
self.powerscale_module_mock.module.params = get_module_args
Loading