Improve netapp_e_hostgroup and add unit tests. (#57094)

* Improve netapp_e_hostgroup and add unit and integration tests.

netapp_e_hostgroup was refactored for maintainability and improved
documentation clarity.

* Remove ignore sanity check E338 for netapp_e_hostgroup module

* Add __future__ import (absolute_import, division, print_function) to test_netapp_e_hostgroup unit test.
pull/60103/head
Nathan Swartz 5 years ago committed by Jake Jackson
parent 4df97c20b6
commit 41235ac05a

@ -8,64 +8,48 @@ from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
ANSIBLE_METADATA = {"metadata_version": "1.1",
"status": ["preview"],
"supported_by": "community"}
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: netapp_e_hostgroup
version_added: "2.2"
short_description: NetApp E-Series manage array host groups
author: Kevin Hulquest (@hulquest)
description:
- Create, update or destroy host groups on a NetApp E-Series storage array.
author:
- Kevin Hulquest (@hulquest)
- Nathan Swartz (@ndswartz)
description: Create, update or destroy host groups on a NetApp E-Series storage array.
extends_documentation_fragment:
- netapp.eseries
options:
api_username:
required: true
description:
- The username to authenticate with the SANtricity WebServices Proxy or embedded REST API.
api_password:
required: true
description:
- The password to authenticate with the SANtricity WebServices Proxy or embedded REST API.
api_url:
required: true
description:
- The url to the SANtricity WebServices Proxy or embedded REST API.
validate_certs:
required: false
default: true
description:
- Should https certificates be validated?
ssid:
required: true
description:
- The ID of the array to manage (as configured on the web services proxy).
state:
required: true
description:
- Whether the specified host group should exist or not.
choices: ['present', 'absent']
name:
required: false
description:
- The name of the host group to manage. Either this or C(id_num) must be supplied.
new_name:
required: false
description:
- specify this when you need to update the name of a host group
id:
required: false
description:
- The id number of the host group to manage. Either this or C(name) must be supplied.
hosts:
required: false
description:
- a list of host names/labels to add to the group
'''
EXAMPLES = '''
state:
required: true
description:
- Whether the specified host group should exist or not.
choices: ["present", "absent"]
name:
required: false
description:
- Name of the host group to manage
- This option is mutually exclusive with I(id).
new_name:
required: false
description:
- Specify this when you need to update the name of a host group
id:
required: false
description:
- Host reference identifier for the host group to manage.
- This option is mutually exclusive with I(name).
hosts:
required: false
description:
- List of host names/labels to add to the group
"""
EXAMPLES = """
- name: Configure Hostgroup
netapp_e_hostgroup:
ssid: "{{ ssid }}"
@ -74,8 +58,8 @@ EXAMPLES = '''
api_password: "{{ netapp_api_password }}"
validate_certs: "{{ netapp_api_validate_certs }}"
state: present
'''
RETURN = '''
"""
RETURN = """
clusterRef:
description: The unique identification value for this object. Other objects may use this reference value to refer to the cluster.
returned: always except when state is absent
@ -118,278 +102,201 @@ protectionInformationCapableAccessMethod:
returned: always except when state is absent
type: bool
sample: true
'''
"""
HEADERS = {
"Content-Type": "application/json",
"Accept": "application/json"
}
import json
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six.moves.urllib.error import HTTPError
from ansible.module_utils.netapp import NetAppESeriesModule
from ansible.module_utils._text import to_native
from ansible.module_utils.urls import open_url
def request(url, data=None, headers=None, method='GET', use_proxy=True,
force=False, last_mod_time=None, timeout=10, validate_certs=True,
url_username=None, url_password=None, http_agent=None, force_basic_auth=True, ignore_errors=False):
try:
r = open_url(url=url, data=data, headers=headers, method=method, use_proxy=use_proxy,
force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs,
url_username=url_username, url_password=url_password, http_agent=http_agent,
force_basic_auth=force_basic_auth)
except HTTPError as e:
r = e.fp
try:
raw_data = r.read()
if raw_data:
data = json.loads(raw_data)
else:
raw_data = None
except Exception:
if ignore_errors:
pass
else:
raise Exception(raw_data)
resp_code = r.getcode()
if resp_code >= 400 and not ignore_errors:
raise Exception(resp_code, data)
else:
return resp_code, data
def group_exists(module, id_type, ident, ssid, api_url, user, pwd):
rc, data = get_hostgroups(module, ssid, api_url, user, pwd)
for group in data:
if group[id_type] == ident:
return True, data
else:
continue
return False, data
def get_hostgroups(module, ssid, api_url, user, pwd):
groups = "storage-systems/%s/host-groups" % ssid
url = api_url + groups
try:
rc, data = request(url, headers=HEADERS, url_username=user, url_password=pwd)
return rc, data
except HTTPError as e:
module.fail_json(msg="Failed to get host groups. Id [%s]. Error [%s]." % (ssid, to_native(e)))
def get_hostref(module, ssid, name, api_url, user, pwd):
all_hosts = 'storage-systems/%s/hosts' % ssid
url = api_url + all_hosts
try:
rc, data = request(url, method='GET', headers=HEADERS, url_username=user, url_password=pwd)
except Exception as e:
module.fail_json(msg="Failed to get hosts. Id [%s]. Error [%s]." % (ssid, to_native(e)))
for host in data:
if host['name'] == name:
return host['hostRef']
else:
continue
module.fail_json(msg="No host with the name %s could be found" % name)
def create_hostgroup(module, ssid, name, api_url, user, pwd, hosts=None):
groups = "storage-systems/%s/host-groups" % ssid
url = api_url + groups
hostrefs = []
if hosts:
for host in hosts:
href = get_hostref(module, ssid, host, api_url, user, pwd)
hostrefs.append(href)
post_data = json.dumps(dict(name=name, hosts=hostrefs))
try:
rc, data = request(url, method='POST', data=post_data, headers=HEADERS, url_username=user, url_password=pwd)
except Exception as e:
module.fail_json(msg="Failed to create host group. Id [%s]. Error [%s]." % (ssid, to_native(e)))
return rc, data
def update_hostgroup(module, ssid, name, api_url, user, pwd, hosts=None, new_name=None):
gid = get_hostgroup_id(module, ssid, name, api_url, user, pwd)
groups = "storage-systems/%s/host-groups/%s" % (ssid, gid)
url = api_url + groups
hostrefs = []
if hosts:
for host in hosts:
href = get_hostref(module, ssid, host, api_url, user, pwd)
hostrefs.append(href)
if new_name:
post_data = json.dumps(dict(name=new_name, hosts=hostrefs))
else:
post_data = json.dumps(dict(hosts=hostrefs))
try:
rc, data = request(url, method='POST', data=post_data, headers=HEADERS, url_username=user, url_password=pwd)
except Exception as e:
module.fail_json(msg="Failed to update host group. Group [%s]. Id [%s]. Error [%s]." % (gid, ssid,
to_native(e)))
return rc, data
def delete_hostgroup(module, ssid, group_id, api_url, user, pwd):
groups = "storage-systems/%s/host-groups/%s" % (ssid, group_id)
url = api_url + groups
# TODO: Loop through hosts, do mapping to href, make new list to pass to data
try:
rc, data = request(url, method='DELETE', headers=HEADERS, url_username=user, url_password=pwd)
except Exception as e:
module.fail_json(msg="Failed to delete host group. Group [%s]. Id [%s]. Error [%s]." % (group_id, ssid, to_native(e)))
return rc, data
def get_hostgroup_id(module, ssid, name, api_url, user, pwd):
all_groups = 'storage-systems/%s/host-groups' % ssid
url = api_url + all_groups
rc, data = request(url, method='GET', headers=HEADERS, url_username=user, url_password=pwd)
for hg in data:
if hg['name'] == name:
return hg['id']
else:
continue
module.fail_json(msg="A hostgroup with the name %s could not be found" % name)
def get_hosts_in_group(module, ssid, group_name, api_url, user, pwd):
all_groups = 'storage-systems/%s/host-groups' % ssid
g_url = api_url + all_groups
try:
g_rc, g_data = request(g_url, method='GET', headers=HEADERS, url_username=user, url_password=pwd)
except Exception as e:
module.fail_json(
msg="Failed in first step getting hosts from group. Group: [%s]. Id [%s]. Error [%s]." % (group_name,
ssid,
to_native(e)))
all_hosts = 'storage-systems/%s/hosts' % ssid
h_url = api_url + all_hosts
try:
h_rc, h_data = request(h_url, method='GET', headers=HEADERS, url_username=user, url_password=pwd)
except Exception as e:
module.fail_json(
msg="Failed in second step getting hosts from group. Group: [%s]. Id [%s]. Error [%s]." % (
group_name,
ssid,
to_native(e)))
hosts_in_group = []
for hg in g_data:
if hg['name'] == group_name:
clusterRef = hg['clusterRef']
for host in h_data:
if host['clusterRef'] == clusterRef:
hosts_in_group.append(host['name'])
return hosts_in_group
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(required=False),
new_name=dict(required=False),
ssid=dict(required=True),
id=dict(required=False),
state=dict(required=True, choices=['present', 'absent']),
hosts=dict(required=False, type='list'),
api_url=dict(required=True),
api_username=dict(required=True),
validate_certs=dict(required=False, default=True),
api_password=dict(required=True, no_log=True)
),
supports_check_mode=False,
mutually_exclusive=[['name', 'id']],
required_one_of=[['name', 'id']]
)
name = module.params['name']
new_name = module.params['new_name']
ssid = module.params['ssid']
id_num = module.params['id']
state = module.params['state']
hosts = module.params['hosts']
user = module.params['api_username']
pwd = module.params['api_password']
api_url = module.params['api_url']
if not api_url.endswith('/'):
api_url += '/'
if name:
id_type = 'name'
id_key = name
elif id_num:
id_type = 'id'
id_key = id_num
exists, group_data = group_exists(module, id_type, id_key, ssid, api_url, user, pwd)
if state == 'present':
if not exists:
class NetAppESeriesHostGroup(NetAppESeriesModule):
EXPANSION_TIMEOUT_SEC = 10
DEFAULT_DISK_POOL_MINIMUM_DISK_COUNT = 11
def __init__(self):
version = "02.00.0000.0000"
ansible_options = dict(
state=dict(required=True, choices=["present", "absent"], type="str"),
name=dict(required=False, type="str"),
new_name=dict(required=False, type="str"),
id=dict(required=False, type="str"),
hosts=dict(required=False, type="list"))
mutually_exclusive = [["name", "id"]]
super(NetAppESeriesHostGroup, self).__init__(ansible_options=ansible_options,
web_services_version=version,
supports_check_mode=True,
mutually_exclusive=mutually_exclusive)
args = self.module.params
self.state = args["state"]
self.name = args["name"]
self.new_name = args["new_name"]
self.id = args["id"]
self.hosts_list = args["hosts"]
self.current_host_group = None
@property
def hosts(self):
"""Retrieve a list of host reference identifiers should be associated with the host group."""
host_list = []
existing_hosts = []
if self.hosts_list:
try:
rc, existing_hosts = self.request("storage-systems/%s/hosts" % self.ssid)
except Exception as error:
self.module.fail_json(msg="Failed to retrieve hosts information. Array id [%s]. Error[%s]."
% (self.ssid, to_native(error)))
for host in self.hosts_list:
for existing_host in existing_hosts:
if host in existing_host["id"] or host in existing_host["name"]:
host_list.append(existing_host["id"])
break
else:
self.module.fail_json(msg="Expected host does not exist. Array id [%s]. Host [%s]."
% (self.ssid, host))
return host_list
@property
def host_groups(self):
"""Retrieve a list of existing host groups."""
host_groups = []
hosts = []
try:
rc, host_groups = self.request("storage-systems/%s/host-groups" % self.ssid)
rc, hosts = self.request("storage-systems/%s/hosts" % self.ssid)
except Exception as error:
self.module.fail_json(msg="Failed to retrieve host group information. Array id [%s]. Error[%s]."
% (self.ssid, to_native(error)))
host_groups = [{"id": group["clusterRef"], "name": group["name"]} for group in host_groups]
for group in host_groups:
hosts_ids = []
for host in hosts:
if group["id"] == host["clusterRef"]:
hosts_ids.append(host["hostRef"])
group.update({"hosts": hosts_ids})
return host_groups
@property
def current_hosts_in_host_group(self):
"""Retrieve the current hosts associated with the current hostgroup."""
current_hosts = []
for group in self.host_groups:
if (self.name and group["name"] == self.name) or (self.id and group["id"] == self.id):
current_hosts = group["hosts"]
return current_hosts
def unassign_hosts(self, host_list=None):
"""Unassign hosts from host group."""
if host_list is None:
host_list = self.current_host_group["hosts"]
for host_id in host_list:
try:
rc, data = create_hostgroup(module, ssid, name, api_url, user, pwd, hosts)
except Exception as e:
module.fail_json(msg="Failed to create a host group. Id [%s]. Error [%s]." % (ssid, to_native(e)))
hosts = get_hosts_in_group(module, ssid, name, api_url, user, pwd)
module.exit_json(changed=True, hosts=hosts, **data)
else:
current_hosts = get_hosts_in_group(module, ssid, name, api_url, user, pwd)
if not current_hosts:
current_hosts = []
if not hosts:
hosts = []
if set(current_hosts) != set(hosts):
try:
rc, data = update_hostgroup(module, ssid, name, api_url, user, pwd, hosts, new_name)
except Exception as e:
module.fail_json(
msg="Failed to update host group. Group: [%s]. Id [%s]. Error [%s]." % (name, ssid, to_native(e)))
module.exit_json(changed=True, hosts=hosts, **data)
rc, resp = self.request("storage-systems/%s/hosts/%s/move" % (self.ssid, host_id),
method="POST", data={"group": "0000000000000000000000000000000000000000"})
except Exception as error:
self.module.fail_json(msg="Failed to unassign hosts from host group. Array id [%s]. Host id [%s]."
" Error[%s]." % (self.ssid, host_id, to_native(error)))
def delete_host_group(self, unassign_hosts=True):
"""Delete host group"""
if unassign_hosts:
self.unassign_hosts()
try:
rc, resp = self.request("storage-systems/%s/host-groups/%s" % (self.ssid, self.current_host_group["id"]),
method="DELETE")
except Exception as error:
self.module.fail_json(msg="Failed to delete host group. Array id [%s]. Error[%s]."
% (self.ssid, to_native(error)))
def create_host_group(self):
"""Create host group."""
data = {"name": self.name, "hosts": self.hosts}
response = None
try:
rc, response = self.request("storage-systems/%s/host-groups" % self.ssid, method="POST", data=data)
except Exception as error:
self.module.fail_json(msg="Failed to create host group. Array id [%s]. Error[%s]."
% (self.ssid, to_native(error)))
return response
def update_host_group(self):
"""Update host group."""
data = {"name": self.new_name if self.new_name else self.name,
"hosts": self.hosts}
# unassign hosts that should not be part of the hostgroup
desired_host_ids = self.hosts
for host in self.current_hosts_in_host_group:
if host not in desired_host_ids:
self.unassign_hosts([host])
update_response = None
try:
rc, update_response = self.request("storage-systems/%s/host-groups/%s"
% (self.ssid, self.current_host_group["id"]), method="POST", data=data)
except Exception as error:
self.module.fail_json(msg="Failed to create host group. Array id [%s]. Error[%s]."
% (self.ssid, to_native(error)))
return update_response
def apply(self):
"""Apply desired host group state to the storage array."""
changes_required = False
# Search for existing host group match
for group in self.host_groups:
if (self.id and group["id"] == self.id) or (self.name and group["name"] == self.name):
self.current_host_group = group
# Determine whether changes are required
if self.state == "present":
if self.current_host_group:
if (self.new_name and self.new_name != self.name) or self.hosts != self.current_host_group["hosts"]:
changes_required = True
else:
for group in group_data:
if group['name'] == name:
module.exit_json(changed=False, hosts=current_hosts, **group)
if not self.name:
self.module.fail_json(msg="The option name must be supplied when creating a new host group."
" Array id [%s]." % self.ssid)
changes_required = True
elif self.current_host_group:
changes_required = True
# Apply any necessary changes
msg = ""
if changes_required and not self.module.check_mode:
msg = "No changes required."
if self.state == "present":
if self.current_host_group:
if ((self.new_name and self.new_name != self.name) or
(self.hosts != self.current_host_group["hosts"])):
msg = self.update_host_group()
else:
msg = self.create_host_group()
elif self.current_host_group:
self.delete_host_group()
msg = "Host group deleted. Array Id [%s]. Host Name [%s]. Host Id [%s]."\
% (self.ssid, self.current_host_group["name"], self.current_host_group["id"])
self.module.exit_json(msg=msg, changed=changes_required)
elif state == 'absent':
if exists:
hg_id = get_hostgroup_id(module, ssid, name, api_url, user, pwd)
try:
rc, data = delete_hostgroup(module, ssid, hg_id, api_url, user, pwd)
except Exception as e:
module.fail_json(
msg="Failed to delete host group. Group: [%s]. Id [%s]. Error [%s]." % (name, ssid, to_native(e)))
module.exit_json(changed=True, msg="Host Group deleted")
else:
module.exit_json(changed=False, msg="Host Group is already absent")
def main():
hostgroup = NetAppESeriesHostGroup()
hostgroup.apply()
if __name__ == '__main__':
if __name__ == "__main__":
main()

@ -6402,7 +6402,6 @@ lib/ansible/modules/storage/netapp/netapp_e_flashcache.py validate-modules:E338
lib/ansible/modules/storage/netapp/netapp_e_global.py validate-modules:E337
lib/ansible/modules/storage/netapp/netapp_e_host.py validate-modules:E337
lib/ansible/modules/storage/netapp/netapp_e_hostgroup.py validate-modules:E337
lib/ansible/modules/storage/netapp/netapp_e_hostgroup.py validate-modules:E338
lib/ansible/modules/storage/netapp/netapp_e_iscsi_interface.py validate-modules:E337
lib/ansible/modules/storage/netapp/netapp_e_iscsi_target.py validate-modules:E337
lib/ansible/modules/storage/netapp/netapp_e_ldap.py validate-modules:E337

@ -0,0 +1,163 @@
# (c) 2018, NetApp Inc.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.modules.storage.netapp.netapp_e_hostgroup import NetAppESeriesHostGroup
from units.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase, set_module_args
try:
from unittest import mock
except ImportError:
import mock
class HostTest(ModuleTestCase):
REQUIRED_PARAMS = {"api_username": "rw",
"api_password": "password",
"api_url": "http://localhost",
"ssid": "1"}
REQ_FUNC = "ansible.modules.storage.netapp.netapp_e_hostgroup.NetAppESeriesHostGroup.request"
HOSTS_GET_RESPONSE = [
{"hostRef": "84000000600A098000A4B28D0030102E5C3DFC0F",
"clusterRef": "85000000600A098000A4B28D0036102C5C3DFC08", "id": "84000000600A098000A4B28D0030102E5C3DFC0F",
"name": "host1"},
{"hostRef": "84000000600A098000A4B28D003010315C3DFC11",
"clusterRef": "85000000600A098000A4B9D100360F765C3DFC1C", "id": "84000000600A098000A4B28D003010315C3DFC11",
"name": "host2"},
{"hostRef": "84000000600A098000A4B28D003010345C3DFC14",
"clusterRef": "85000000600A098000A4B9D100360F765C3DFC1C", "id": "84000000600A098000A4B28D003010345C3DFC14",
"name": "host3"}]
HOSTGROUPS_GET_RESPONSE = [
{"clusterRef": "85000000600A098000A4B28D0036102C5C3DFC08", "id": "85000000600A098000A4B28D0036102C5C3DFC08",
"name": "group1"},
{"clusterRef": "85000000600A098000A4B9D100360F765C3DFC1C", "id": "85000000600A098000A4B9D100360F765C3DFC1C",
"name": "group2"},
{"clusterRef": "85000000600A098000A4B9D100360F775C3DFC1E", "id": "85000000600A098000A4B9D100360F775C3DFC1E",
"name": "group3"}]
def _set_args(self, args):
self.module_args = self.REQUIRED_PARAMS.copy()
self.module_args.update(args)
set_module_args(self.module_args)
def test_hosts_fail(self):
"""Ensure that the host property method fails when self.request throws an exception."""
self._set_args({"state": "present", "name": "hostgroup1", "hosts": ["host1", "host2"]})
hostgroup_object = NetAppESeriesHostGroup()
with self.assertRaises(AnsibleFailJson):
with mock.patch(self.REQ_FUNC, return_value=Exception()):
hosts = hostgroup_object.hosts
with mock.patch(self.REQ_FUNC, return_value=(200, [])):
with self.assertRaisesRegexp(AnsibleFailJson, "Expected host does not exist"):
hosts = hostgroup_object.hosts
def test_hosts_pass(self):
"""Evaluate hosts property method for valid returned data structure."""
expected_host_list = ['84000000600A098000A4B28D003010315C3DFC11', '84000000600A098000A4B28D0030102E5C3DFC0F']
for hostgroup_hosts in [["host1", "host2"], ["84000000600A098000A4B28D0030102E5C3DFC0F",
"84000000600A098000A4B28D003010315C3DFC11"]]:
self._set_args({"state": "present", "name": "hostgroup1", "hosts": hostgroup_hosts})
hostgroup_object = NetAppESeriesHostGroup()
with mock.patch(self.REQ_FUNC, return_value=(200, self.HOSTS_GET_RESPONSE)):
for item in hostgroup_object.hosts:
self.assertTrue(item in expected_host_list)
# Create hostgroup with no hosts
self._set_args({"state": "present", "name": "hostgroup1"})
hostgroup_object = NetAppESeriesHostGroup()
with mock.patch(self.REQ_FUNC, return_value=(200, [])):
self.assertEqual(hostgroup_object.hosts, [])
def test_host_groups_fail(self):
"""Ensure that the host_groups property method fails when self.request throws an exception."""
self._set_args({"state": "present", "name": "hostgroup1", "hosts": ["host1", "host2"]})
hostgroup_object = NetAppESeriesHostGroup()
with self.assertRaises(AnsibleFailJson):
with mock.patch(self.REQ_FUNC, return_value=Exception()):
host_groups = hostgroup_object.host_groups
def test_host_groups_pass(self):
"""Evaluate host_groups property method for valid return data structure."""
expected_groups = [
{'hosts': ['84000000600A098000A4B28D0030102E5C3DFC0F'], 'id': '85000000600A098000A4B28D0036102C5C3DFC08',
'name': 'group1'},
{'hosts': ['84000000600A098000A4B28D003010315C3DFC11', '84000000600A098000A4B28D003010345C3DFC14'],
'id': '85000000600A098000A4B9D100360F765C3DFC1C', 'name': 'group2'},
{'hosts': [], 'id': '85000000600A098000A4B9D100360F775C3DFC1E', 'name': 'group3'}]
self._set_args({"state": "present", "name": "hostgroup1", "hosts": ["host1", "host2"]})
hostgroup_object = NetAppESeriesHostGroup()
with mock.patch(self.REQ_FUNC,
side_effect=[(200, self.HOSTGROUPS_GET_RESPONSE), (200, self.HOSTS_GET_RESPONSE)]):
self.assertEqual(hostgroup_object.host_groups, expected_groups)
@mock.patch.object(NetAppESeriesHostGroup, "host_groups")
@mock.patch.object(NetAppESeriesHostGroup, "hosts")
@mock.patch.object(NetAppESeriesHostGroup, "create_host_group")
@mock.patch.object(NetAppESeriesHostGroup, "update_host_group")
@mock.patch.object(NetAppESeriesHostGroup, "delete_host_group")
def test_apply_pass(self, fake_delete_host_group, fake_update_host_group, fake_create_host_group, fake_hosts,
fake_host_groups):
"""Apply desired host group state to the storage array."""
hosts_response = ['84000000600A098000A4B28D003010315C3DFC11', '84000000600A098000A4B28D0030102E5C3DFC0F']
host_groups_response = [
{'hosts': ['84000000600A098000A4B28D0030102E5C3DFC0F'], 'id': '85000000600A098000A4B28D0036102C5C3DFC08',
'name': 'group1'},
{'hosts': ['84000000600A098000A4B28D003010315C3DFC11', '84000000600A098000A4B28D003010345C3DFC14'],
'id': '85000000600A098000A4B9D100360F765C3DFC1C', 'name': 'group2'},
{'hosts': [], 'id': '85000000600A098000A4B9D100360F775C3DFC1E', 'name': 'group3'}]
fake_host_groups.return_value = host_groups_response
fake_hosts.return_value = hosts_response
fake_create_host_group.return_value = lambda x: "Host group created!"
fake_update_host_group.return_value = lambda x: "Host group updated!"
fake_delete_host_group.return_value = lambda x: "Host group deleted!"
# Test create new host group
self._set_args({"state": "present", "name": "hostgroup1", "hosts": ["host1", "host2"]})
hostgroup_object = NetAppESeriesHostGroup()
with self.assertRaises(AnsibleExitJson):
hostgroup_object.apply()
# Test make no changes to existing host group
self._set_args({"state": "present", "name": "group1", "hosts": ["host1"]})
hostgroup_object = NetAppESeriesHostGroup()
with self.assertRaises(AnsibleExitJson):
hostgroup_object.apply()
# Test add host to existing host group
self._set_args({"state": "present", "name": "group1", "hosts": ["host1", "host2"]})
hostgroup_object = NetAppESeriesHostGroup()
with self.assertRaises(AnsibleExitJson):
hostgroup_object.apply()
# Test delete existing host group
self._set_args({"state": "absent", "name": "group1"})
hostgroup_object = NetAppESeriesHostGroup()
with self.assertRaises(AnsibleExitJson):
hostgroup_object.apply()
@mock.patch.object(NetAppESeriesHostGroup, "host_groups")
@mock.patch.object(NetAppESeriesHostGroup, "hosts")
def test_apply_fail(self, fake_hosts, fake_host_groups):
"""Apply desired host group state to the storage array."""
hosts_response = ['84000000600A098000A4B28D003010315C3DFC11', '84000000600A098000A4B28D0030102E5C3DFC0F']
host_groups_response = [
{'hosts': ['84000000600A098000A4B28D0030102E5C3DFC0F'], 'id': '85000000600A098000A4B28D0036102C5C3DFC08',
'name': 'group1'},
{'hosts': ['84000000600A098000A4B28D003010315C3DFC11', '84000000600A098000A4B28D003010345C3DFC14'],
'id': '85000000600A098000A4B9D100360F765C3DFC1C', 'name': 'group2'},
{'hosts': [], 'id': '85000000600A098000A4B9D100360F775C3DFC1E', 'name': 'group3'}]
fake_host_groups.return_value = host_groups_response
fake_hosts.return_value = hosts_response
self._set_args(
{"state": "present", "id": "84000000600A098000A4B28D0030102E5C3DFC0F", "hosts": ["host1", "host2"]})
hostgroup_object = NetAppESeriesHostGroup()
with self.assertRaisesRegexp(AnsibleFailJson,
"The option name must be supplied when creating a new host group."):
hostgroup_object.apply()
Loading…
Cancel
Save