mirror of
https://github.com/ansible-collections/community.general.git
synced 2024-09-14 20:13:21 +02:00
Refactor nxos_interface and add unit test (#24008)
* [WIP] Refactor nxos_interface Signed-off-by: Trishna Guha <trishnaguha17@gmail.com> * Modification in refactor Unittest for nxos_interface
This commit is contained in:
parent
689b93bf14
commit
2741907cba
2 changed files with 154 additions and 143 deletions
|
@ -16,9 +16,11 @@
|
||||||
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
||||||
#
|
#
|
||||||
|
|
||||||
ANSIBLE_METADATA = {'metadata_version': '1.0',
|
ANSIBLE_METADATA = {
|
||||||
|
'metadata_version': '1.0',
|
||||||
'status': ['preview'],
|
'status': ['preview'],
|
||||||
'supported_by': 'community'}
|
'supported_by': 'community'
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
DOCUMENTATION = '''
|
DOCUMENTATION = '''
|
||||||
|
@ -135,35 +137,11 @@ EXAMPLES = '''
|
||||||
'''
|
'''
|
||||||
|
|
||||||
RETURN = '''
|
RETURN = '''
|
||||||
proposed:
|
commands:
|
||||||
description: k/v pairs of parameters passed into module
|
|
||||||
returned: always
|
|
||||||
type: dict
|
|
||||||
sample: {"admin_state": "down"}
|
|
||||||
existing:
|
|
||||||
description: k/v pairs of existing switchport
|
|
||||||
returned: always
|
|
||||||
type: dict
|
|
||||||
sample: {"admin_state": "up", "description": "None",
|
|
||||||
"interface": "port-channel101", "mode": "layer2",
|
|
||||||
"type": "portchannel", "ip_forward": "enable"}
|
|
||||||
end_state:
|
|
||||||
description: k/v pairs of switchport after module execution
|
|
||||||
returned: always
|
|
||||||
type: dict
|
|
||||||
sample: {"admin_state": "down", "description": "None",
|
|
||||||
"interface": "port-channel101", "mode": "layer2",
|
|
||||||
"type": "portchannel", "ip_forward": "enable"}
|
|
||||||
updates:
|
|
||||||
description: command list sent to the device
|
description: command list sent to the device
|
||||||
returned: always
|
returned: always
|
||||||
type: list
|
type: list
|
||||||
sample: ["interface port-channel101", "shutdown"]
|
sample: ["interface port-channel101", "shutdown"]
|
||||||
changed:
|
|
||||||
description: check to see if a change was made on the device
|
|
||||||
returned: always
|
|
||||||
type: boolean
|
|
||||||
sample: true
|
|
||||||
'''
|
'''
|
||||||
|
|
||||||
from ansible.module_utils.nxos import get_config, load_config, run_commands
|
from ansible.module_utils.nxos import get_config, load_config, run_commands
|
||||||
|
@ -183,11 +161,10 @@ def is_default_interface(interface, module):
|
||||||
False: if it does not have a default config
|
False: if it does not have a default config
|
||||||
DNE (str): if the interface does not exist - loopbacks, SVIs, etc.
|
DNE (str): if the interface does not exist - loopbacks, SVIs, etc.
|
||||||
"""
|
"""
|
||||||
command = 'show run interface ' + interface
|
command = 'show run interface {0}'.format(interface)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
body = execute_show_command(command, module,
|
body = execute_show_command(command, module)[0]
|
||||||
command_type='cli_show_ascii')[0]
|
|
||||||
except IndexError:
|
except IndexError:
|
||||||
body = ''
|
body = ''
|
||||||
|
|
||||||
|
@ -242,10 +219,10 @@ def get_manual_interface_attributes(interface, module):
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if get_interface_type(interface) == 'svi':
|
if get_interface_type(interface) == 'svi':
|
||||||
command = 'show interface ' + interface
|
command = 'show interface {0}'.format(interface)
|
||||||
try:
|
try:
|
||||||
body = execute_modified_show_for_cli_text(command, module)[0]
|
body = execute_show_command(command, module)[0]
|
||||||
except (IndexError, ShellError):
|
except IndexError:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
command_list = body.split('\n')
|
command_list = body.split('\n')
|
||||||
|
@ -299,7 +276,7 @@ def get_interface(intf, module):
|
||||||
key_map = {}
|
key_map = {}
|
||||||
interface = {}
|
interface = {}
|
||||||
|
|
||||||
command = 'show interface ' + intf
|
command = 'show interface {0}'.format(intf)
|
||||||
try:
|
try:
|
||||||
body = execute_show_command(command, module)[0]
|
body = execute_show_command(command, module)[0]
|
||||||
except IndexError:
|
except IndexError:
|
||||||
|
@ -328,9 +305,8 @@ def get_interface(intf, module):
|
||||||
'nxapibug'))
|
'nxapibug'))
|
||||||
interface['description'] = str(attributes.get('description',
|
interface['description'] = str(attributes.get('description',
|
||||||
'nxapi_bug'))
|
'nxapi_bug'))
|
||||||
command = 'show run interface ' + intf
|
command = 'show run interface {0}'.format(intf)
|
||||||
body = execute_show_command(command, module,
|
body = execute_show_command(command, module)[0]
|
||||||
command_type='cli_show_ascii')[0]
|
|
||||||
if 'ip forward' in body:
|
if 'ip forward' in body:
|
||||||
interface['ip_forward'] = 'enable'
|
interface['ip_forward'] = 'enable'
|
||||||
else:
|
else:
|
||||||
|
@ -521,12 +497,13 @@ def get_interface_config_commands(interface, intf, existing):
|
||||||
commands.append('no fabric forwarding mode anycast-gateway')
|
commands.append('no fabric forwarding mode anycast-gateway')
|
||||||
|
|
||||||
if commands:
|
if commands:
|
||||||
commands.insert(0, 'interface ' + intf)
|
commands.insert(0, 'interface {0}'.format(intf))
|
||||||
|
|
||||||
return commands
|
return commands
|
||||||
|
|
||||||
|
|
||||||
def get_admin_state(interface, intf, admin_state):
|
def get_admin_state(interface, intf, admin_state):
|
||||||
|
command = ''
|
||||||
if admin_state == 'up':
|
if admin_state == 'up':
|
||||||
command = 'no shutdown'
|
command = 'no shutdown'
|
||||||
elif admin_state == 'down':
|
elif admin_state == 'down':
|
||||||
|
@ -568,24 +545,11 @@ def smart_existing(module, intf_type, normalized_interface):
|
||||||
return existing, is_default
|
return existing, is_default
|
||||||
|
|
||||||
|
|
||||||
def execute_show_command(command, module, command_type='cli_show'):
|
def execute_show_command(command, module):
|
||||||
if module.params['transport'] == 'cli':
|
if module.params['transport'] == 'cli':
|
||||||
command += ' | json'
|
command += ' | json'
|
||||||
cmds = [command]
|
cmds = [command]
|
||||||
body = run_commands(module, cmds)
|
body = run_commands(module, cmds)
|
||||||
elif module.params['transport'] == 'nxapi':
|
|
||||||
cmds = [{'command': command, 'output': 'json'}]
|
|
||||||
body = run_commands(module, cmds)
|
|
||||||
return body
|
|
||||||
|
|
||||||
|
|
||||||
def execute_modified_show_for_cli_text(command, module):
|
|
||||||
cmds = [command]
|
|
||||||
if module.params['transport'] == 'cli':
|
|
||||||
body = run_commands(module, cmds)
|
|
||||||
else:
|
|
||||||
body = run_commands(module, cmds)
|
|
||||||
body = response
|
|
||||||
return body
|
return body
|
||||||
|
|
||||||
|
|
||||||
|
@ -616,12 +580,10 @@ def main():
|
||||||
admin_state=dict(default='up', choices=['up', 'down'], required=False),
|
admin_state=dict(default='up', choices=['up', 'down'], required=False),
|
||||||
description=dict(required=False, default=None),
|
description=dict(required=False, default=None),
|
||||||
mode=dict(choices=['layer2', 'layer3'], required=False),
|
mode=dict(choices=['layer2', 'layer3'], required=False),
|
||||||
interface_type=dict(required=False,
|
interface_type=dict(required=False, choices=['loopback', 'portchannel', 'svi', 'nve']),
|
||||||
choices=['loopback', 'portchannel', 'svi', 'nve']),
|
|
||||||
ip_forward=dict(required=False, choices=['enable', 'disable']),
|
ip_forward=dict(required=False, choices=['enable', 'disable']),
|
||||||
fabric_forwarding_anycast_gateway=dict(required=False, type='bool'),
|
fabric_forwarding_anycast_gateway=dict(required=False, type='bool'),
|
||||||
state=dict(choices=['absent', 'present', 'default'],
|
state=dict(choices=['absent', 'present', 'default'], default='present', required=False),
|
||||||
default='present', required=False),
|
|
||||||
include_defaults=dict(default=True),
|
include_defaults=dict(default=True),
|
||||||
config=dict(),
|
config=dict(),
|
||||||
save=dict(type='bool', default=False)
|
save=dict(type='bool', default=False)
|
||||||
|
@ -636,6 +598,8 @@ def main():
|
||||||
warnings = list()
|
warnings = list()
|
||||||
check_args(module, warnings)
|
check_args(module, warnings)
|
||||||
|
|
||||||
|
results = dict(changed=False, warnings=warnings)
|
||||||
|
|
||||||
interface = module.params['interface']
|
interface = module.params['interface']
|
||||||
interface_type = module.params['interface_type']
|
interface_type = module.params['interface_type']
|
||||||
admin_state = module.params['admin_state']
|
admin_state = module.params['admin_state']
|
||||||
|
@ -658,8 +622,7 @@ def main():
|
||||||
module.fail_json(msg='description and mode params are not '
|
module.fail_json(msg='description and mode params are not '
|
||||||
'supported in this module. Use '
|
'supported in this module. Use '
|
||||||
'nxos_vxlan_vtep instead.')
|
'nxos_vxlan_vtep instead.')
|
||||||
if ((ip_forward or fabric_forwarding_anycast_gateway) and
|
if (ip_forward or fabric_forwarding_anycast_gateway) and intf_type != 'svi':
|
||||||
intf_type != 'svi'):
|
|
||||||
module.fail_json(msg='The ip_forward and '
|
module.fail_json(msg='The ip_forward and '
|
||||||
'fabric_forwarding_anycast_gateway features '
|
'fabric_forwarding_anycast_gateway features '
|
||||||
' are only available for SVIs.')
|
' are only available for SVIs.')
|
||||||
|
@ -668,8 +631,7 @@ def main():
|
||||||
fabric_forwarding_anycast_gateway=fabric_forwarding_anycast_gateway)
|
fabric_forwarding_anycast_gateway=fabric_forwarding_anycast_gateway)
|
||||||
|
|
||||||
if intf_type == 'unknown':
|
if intf_type == 'unknown':
|
||||||
module.fail_json(
|
module.fail_json(msg='unknown interface type found-1',
|
||||||
msg='unknown interface type found-1',
|
|
||||||
interface=interface)
|
interface=interface)
|
||||||
|
|
||||||
existing, is_default = smart_existing(module, intf_type, normalized_interface)
|
existing, is_default = smart_existing(module, intf_type, normalized_interface)
|
||||||
|
@ -678,7 +640,6 @@ def main():
|
||||||
intf_type = normalized_interface = interface_type
|
intf_type = normalized_interface = interface_type
|
||||||
proposed = dict(interface_type=interface_type)
|
proposed = dict(interface_type=interface_type)
|
||||||
|
|
||||||
changed = False
|
|
||||||
commands = []
|
commands = []
|
||||||
if interface:
|
if interface:
|
||||||
delta = dict()
|
delta = dict()
|
||||||
|
@ -694,29 +655,22 @@ def main():
|
||||||
commands.append(cmds)
|
commands.append(cmds)
|
||||||
elif state == 'present':
|
elif state == 'present':
|
||||||
if not existing:
|
if not existing:
|
||||||
cmds = get_interface_config_commands(proposed,
|
cmds = get_interface_config_commands(proposed, normalized_interface, existing)
|
||||||
normalized_interface,
|
|
||||||
existing)
|
|
||||||
commands.append(cmds)
|
commands.append(cmds)
|
||||||
else:
|
else:
|
||||||
delta = dict(set(proposed.items()).difference(
|
delta = dict(set(proposed.items()).difference(existing.items()))
|
||||||
existing.items()))
|
|
||||||
if delta:
|
if delta:
|
||||||
cmds = get_interface_config_commands(delta,
|
cmds = get_interface_config_commands(delta, normalized_interface, existing)
|
||||||
normalized_interface,
|
|
||||||
existing)
|
|
||||||
commands.append(cmds)
|
commands.append(cmds)
|
||||||
elif state == 'default':
|
elif state == 'default':
|
||||||
if is_default is False:
|
if is_default is False:
|
||||||
cmds = ['default interface {0}'.format(normalized_interface)]
|
cmds = ['default interface {0}'.format(normalized_interface)]
|
||||||
commands.append(cmds)
|
commands.append(cmds)
|
||||||
elif is_default == 'DNE':
|
elif is_default == 'DNE':
|
||||||
module.exit_json(msg='interface you are trying to default does'
|
module.exit_json(msg='interface you are trying to default does not exist')
|
||||||
' not exist')
|
|
||||||
elif interface_type:
|
elif interface_type:
|
||||||
if state == 'present':
|
if state == 'present':
|
||||||
module.fail_json(msg='The interface_type param can be used '
|
module.fail_json(msg='The interface_type param can be used only with state absent.')
|
||||||
'only with state absent.')
|
|
||||||
|
|
||||||
existing = get_interfaces_dict(module)[interface_type]
|
existing = get_interfaces_dict(module)[interface_type]
|
||||||
cmds = get_interface_type_removed_cmds(existing)
|
cmds = get_interface_type_removed_cmds(existing)
|
||||||
|
@ -730,7 +684,7 @@ def main():
|
||||||
module.exit_json(changed=True, commands=cmds)
|
module.exit_json(changed=True, commands=cmds)
|
||||||
else:
|
else:
|
||||||
load_config(module, cmds)
|
load_config(module, cmds)
|
||||||
changed = True
|
results['changed'] = True
|
||||||
if module.params['interface']:
|
if module.params['interface']:
|
||||||
if delta.get('mode'): # or delta.get('admin_state'):
|
if delta.get('mode'): # or delta.get('admin_state'):
|
||||||
# if the mode changes from L2 to L3, the admin state
|
# if the mode changes from L2 to L3, the admin state
|
||||||
|
@ -748,17 +702,10 @@ def main():
|
||||||
end_state = get_interfaces_dict(module)[interface_type]
|
end_state = get_interfaces_dict(module)[interface_type]
|
||||||
cmds = [cmd for cmd in cmds if cmd != 'configure']
|
cmds = [cmd for cmd in cmds if cmd != 'configure']
|
||||||
|
|
||||||
results = {}
|
results['commands'] = cmds
|
||||||
results['proposed'] = proposed
|
|
||||||
results['existing'] = existing
|
|
||||||
results['end_state'] = end_state
|
|
||||||
results['updates'] = cmds
|
|
||||||
results['changed'] = changed
|
|
||||||
results['warnings'] = warnings
|
|
||||||
|
|
||||||
module.exit_json(**results)
|
module.exit_json(**results)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
main()
|
main()
|
||||||
|
|
||||||
|
|
64
test/units/modules/network/nxos/test_nxos_interface.py
Normal file
64
test/units/modules/network/nxos/test_nxos_interface.py
Normal file
|
@ -0,0 +1,64 @@
|
||||||
|
# (c) 2016 Red Hat Inc.
|
||||||
|
#
|
||||||
|
# This file is part of Ansible
|
||||||
|
#
|
||||||
|
# Ansible is free software: you can redistribute it and/or modify
|
||||||
|
# it under the terms of the GNU General Public License as published by
|
||||||
|
# the Free Software Foundation, either version 3 of the License, or
|
||||||
|
# (at your option) any later version.
|
||||||
|
#
|
||||||
|
# Ansible is distributed in the hope that it will be useful,
|
||||||
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
# GNU General Public License for more details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU General Public License
|
||||||
|
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
# Make coding more python3-ish
|
||||||
|
from __future__ import (absolute_import, division, print_function)
|
||||||
|
__metaclass__ = type
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
from ansible.compat.tests.mock import patch
|
||||||
|
from ansible.modules.network.nxos import nxos_interface
|
||||||
|
from .nxos_module import TestNxosModule, load_fixture, set_module_args
|
||||||
|
|
||||||
|
|
||||||
|
class TestNxosInterfaceModule(TestNxosModule):
|
||||||
|
|
||||||
|
module = nxos_interface
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.mock_run_commands = patch('ansible.modules.network.nxos.nxos_interface.run_commands')
|
||||||
|
self.run_commands = self.mock_run_commands.start()
|
||||||
|
|
||||||
|
self.mock_load_config = patch('ansible.modules.network.nxos.nxos_interface.load_config')
|
||||||
|
self.load_config = self.mock_load_config.start()
|
||||||
|
|
||||||
|
self.mock_get_config = patch('ansible.modules.network.nxos.nxos_interface.get_config')
|
||||||
|
self.get_config = self.mock_get_config.start()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.mock_run_commands.stop()
|
||||||
|
self.mock_load_config.stop()
|
||||||
|
self.mock_get_config.stop()
|
||||||
|
|
||||||
|
def load_fixtures(self, commands=None):
|
||||||
|
self.load_config.return_value = None
|
||||||
|
|
||||||
|
def test_nxos_interface_up(self):
|
||||||
|
set_module_args(dict(interface='loopback0'))
|
||||||
|
result = self.execute_module(changed=True)
|
||||||
|
self.assertEqual(result['commands'], ['interface loopback0', 'no shutdown'])
|
||||||
|
|
||||||
|
def test_nxos_interface_down(self):
|
||||||
|
set_module_args(dict(interface='loopback0', admin_state='down'))
|
||||||
|
result = self.execute_module(changed=True)
|
||||||
|
self.assertEqual(result['commands'], ['interface loopback0', 'shutdown'])
|
||||||
|
|
||||||
|
def test_nxos_interface_delete(self):
|
||||||
|
set_module_args(dict(interface='loopback0', state='absent'))
|
||||||
|
result = self.execute_module(changed=False)
|
||||||
|
self.assertEqual(result['commands'], [])
|
Loading…
Add table
Reference in a new issue