Move modules and module_utils unit tests to correct place (#81)

* Move modules and module_utils unit tests to correct place.

* Update ignore.txt

* Fix imports.

* Fix typos.

* Fix more typos.
This commit is contained in:
Felix Fontein 2020-03-31 10:42:38 +02:00 committed by GitHub
commit be191cce6c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
1170 changed files with 732 additions and 751 deletions

View file

View file

@ -0,0 +1,137 @@
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import sys
import pytest
import ansible_collections.community.general.tests.unit.compat.unittest as unittest
from ansible_collections.community.general.tests.unit.compat.mock import MagicMock
from ansible_collections.community.general.tests.unit.compat.unittest import TestCase
from ansible_collections.community.general.tests.unit.plugins.modules.utils import set_module_args
# Exoscale's cs doesn't support Python 2.6
pytestmark = []
if sys.version_info[:2] != (2, 6):
from ansible_collections.community.general.plugins.modules.cloud.cloudstack.cs_traffic_type import AnsibleCloudStackTrafficType, setup_module_object
from ansible_collections.community.general.plugins.module_utils.cloudstack import HAS_LIB_CS
if not HAS_LIB_CS:
pytestmark.append(pytest.mark.skip('The cloudstack library, "cs", is needed to test cs_traffic_type'))
else:
pytestmark.append(pytest.mark.skip('Exoscale\'s cs doesn\'t support Python 2.6'))
EXISTING_TRAFFIC_TYPES_RESPONSE = {
"count": 3,
"traffictype": [
{
"id": "9801cf73-5a73-4883-97e4-fa20c129226f",
"kvmnetworklabel": "cloudbr0",
"physicalnetworkid": "659c1840-9374-440d-a412-55ca360c9d3c",
"traffictype": "Management"
},
{
"id": "28ed70b7-9a1f-41bf-94c3-53a9f22da8b6",
"kvmnetworklabel": "cloudbr0",
"physicalnetworkid": "659c1840-9374-440d-a412-55ca360c9d3c",
"traffictype": "Guest"
},
{
"id": "9c05c802-84c0-4eda-8f0a-f681364ffb46",
"kvmnetworklabel": "cloudbr0",
"physicalnetworkid": "659c1840-9374-440d-a412-55ca360c9d3c",
"traffictype": "Storage"
}
]
}
VALID_LIST_NETWORKS_RESPONSE = {
"count": 1,
"physicalnetwork": [
{
"broadcastdomainrange": "ZONE",
"id": "659c1840-9374-440d-a412-55ca360c9d3c",
"name": "eth1",
"state": "Enabled",
"vlan": "3900-4000",
"zoneid": "49acf813-a8dd-4da0-aa53-1d826d6003e7"
}
]
}
VALID_LIST_ZONES_RESPONSE = {
"count": 1,
"zone": [
{
"allocationstate": "Enabled",
"dhcpprovider": "VirtualRouter",
"dns1": "8.8.8.8",
"dns2": "8.8.4.4",
"guestcidraddress": "10.10.0.0/16",
"id": "49acf813-a8dd-4da0-aa53-1d826d6003e7",
"internaldns1": "192.168.56.1",
"localstorageenabled": True,
"name": "DevCloud-01",
"networktype": "Advanced",
"securitygroupsenabled": False,
"tags": [],
"zonetoken": "df20d65a-c6c8-3880-9064-4f77de2291ef"
}
]
}
base_module_args = {
"api_key": "api_key",
"api_secret": "very_secret_content",
"api_url": "http://localhost:8888/api/client",
"kvm_networklabel": "cloudbr0",
"physical_network": "eth1",
"poll_async": True,
"state": "present",
"traffic_type": "Guest",
"zone": "DevCloud-01"
}
class TestAnsibleCloudstackTraffiType(TestCase):
def test_module_is_created_sensibly(self):
set_module_args(base_module_args)
module = setup_module_object()
assert module.params['traffic_type'] == 'Guest'
def test_update_called_when_traffic_type_exists(self):
set_module_args(base_module_args)
module = setup_module_object()
actt = AnsibleCloudStackTrafficType(module)
actt.get_traffic_type = MagicMock(return_value=EXISTING_TRAFFIC_TYPES_RESPONSE['traffictype'][0])
actt.update_traffic_type = MagicMock()
actt.present_traffic_type()
self.assertTrue(actt.update_traffic_type.called)
def test_update_not_called_when_traffic_type_doesnt_exist(self):
set_module_args(base_module_args)
module = setup_module_object()
actt = AnsibleCloudStackTrafficType(module)
actt.get_traffic_type = MagicMock(return_value=None)
actt.update_traffic_type = MagicMock()
actt.add_traffic_type = MagicMock()
actt.present_traffic_type()
self.assertFalse(actt.update_traffic_type.called)
self.assertTrue(actt.add_traffic_type.called)
def test_traffic_type_returned_if_exists(self):
set_module_args(base_module_args)
module = setup_module_object()
actt = AnsibleCloudStackTrafficType(module)
actt.get_physical_network = MagicMock(return_value=VALID_LIST_NETWORKS_RESPONSE['physicalnetwork'][0])
actt.get_traffic_types = MagicMock(return_value=EXISTING_TRAFFIC_TYPES_RESPONSE)
tt = actt.present_traffic_type()
self.assertTrue(tt.get('kvmnetworklabel') == base_module_args['kvm_networklabel'])
self.assertTrue(tt.get('traffictype') == base_module_args['traffic_type'])
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,22 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import unittest
from ansible_collections.community.general.plugins.modules.cloud.docker.docker_container import TaskParameters
class TestTaskParameters(unittest.TestCase):
"""Unit tests for TaskParameters."""
def test_parse_exposed_ports_tcp_udp(self):
"""
Ensure _parse_exposed_ports does not cancel ports with the same
number but different protocol.
"""
task_params = TaskParameters.__new__(TaskParameters)
task_params.exposed_ports = None
result = task_params._parse_exposed_ports([80, '443', '443/udp'])
self.assertTrue((80, 'tcp') in result)
self.assertTrue((443, 'tcp') in result)
self.assertTrue((443, 'udp') in result)

View file

@ -0,0 +1,31 @@
"""Unit tests for docker_network."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from ansible_collections.community.general.plugins.modules.cloud.docker.docker_network import validate_cidr
@pytest.mark.parametrize("cidr,expected", [
('192.168.0.1/16', 'ipv4'),
('192.168.0.1/24', 'ipv4'),
('192.168.0.1/32', 'ipv4'),
('fdd1:ac8c:0557:7ce2::/64', 'ipv6'),
('fdd1:ac8c:0557:7ce2::/128', 'ipv6'),
])
def test_validate_cidr_positives(cidr, expected):
assert validate_cidr(cidr) == expected
@pytest.mark.parametrize("cidr", [
'192.168.0.1',
'192.168.0.1/34',
'192.168.0.1/asd',
'fdd1:ac8c:0557:7ce2::',
])
def test_validate_cidr_negatives(cidr):
with pytest.raises(ValueError) as e:
validate_cidr(cidr)
assert '"{0}" is not a valid CIDR'.format(cidr) == str(e.value)

View file

@ -0,0 +1,510 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
class APIErrorMock(Exception):
def __init__(self, message, response=None, explanation=None):
self.message = message
self.response = response
self.explanation = explanation
@pytest.fixture(autouse=True)
def docker_module_mock(mocker):
docker_module_mock = mocker.MagicMock()
docker_utils_module_mock = mocker.MagicMock()
docker_errors_module_mock = mocker.MagicMock()
docker_errors_module_mock.APIError = APIErrorMock
mock_modules = {
'docker': docker_module_mock,
'docker.utils': docker_utils_module_mock,
'docker.errors': docker_errors_module_mock,
}
return mocker.patch.dict('sys.modules', **mock_modules)
@pytest.fixture(autouse=True)
def docker_swarm_service():
from ansible_collections.community.general.plugins.modules.cloud.docker import docker_swarm_service
return docker_swarm_service
def test_retry_on_out_of_sequence_error(mocker, docker_swarm_service):
run_mock = mocker.MagicMock(
side_effect=APIErrorMock(
message='',
response=None,
explanation='rpc error: code = Unknown desc = update out of sequence',
)
)
manager = docker_swarm_service.DockerServiceManager(client=None)
manager.run = run_mock
with pytest.raises(APIErrorMock):
manager.run_safe()
assert run_mock.call_count == 3
def test_no_retry_on_general_api_error(mocker, docker_swarm_service):
run_mock = mocker.MagicMock(
side_effect=APIErrorMock(message='', response=None, explanation='some error')
)
manager = docker_swarm_service.DockerServiceManager(client=None)
manager.run = run_mock
with pytest.raises(APIErrorMock):
manager.run_safe()
assert run_mock.call_count == 1
def test_get_docker_environment(mocker, docker_swarm_service):
env_file_result = {'TEST1': 'A', 'TEST2': 'B', 'TEST3': 'C'}
env_dict = {'TEST3': 'CC', 'TEST4': 'D'}
env_string = "TEST3=CC,TEST4=D"
env_list = ['TEST3=CC', 'TEST4=D']
expected_result = sorted(['TEST1=A', 'TEST2=B', 'TEST3=CC', 'TEST4=D'])
mocker.patch.object(
docker_swarm_service, 'parse_env_file', return_value=env_file_result
)
mocker.patch.object(
docker_swarm_service,
'format_environment',
side_effect=lambda d: ['{0}={1}'.format(key, value) for key, value in d.items()],
)
# Test with env dict and file
result = docker_swarm_service.get_docker_environment(
env_dict, env_files=['dummypath']
)
assert result == expected_result
# Test with env list and file
result = docker_swarm_service.get_docker_environment(
env_list,
env_files=['dummypath']
)
assert result == expected_result
# Test with env string and file
result = docker_swarm_service.get_docker_environment(
env_string, env_files=['dummypath']
)
assert result == expected_result
assert result == expected_result
# Test with empty env
result = docker_swarm_service.get_docker_environment(
[], env_files=None
)
assert result == []
# Test with empty env_files
result = docker_swarm_service.get_docker_environment(
None, env_files=[]
)
assert result == []
def test_get_nanoseconds_from_raw_option(docker_swarm_service):
value = docker_swarm_service.get_nanoseconds_from_raw_option('test', None)
assert value is None
value = docker_swarm_service.get_nanoseconds_from_raw_option('test', '1m30s535ms')
assert value == 90535000000
value = docker_swarm_service.get_nanoseconds_from_raw_option('test', 10000000000)
assert value == 10000000000
with pytest.raises(ValueError):
docker_swarm_service.get_nanoseconds_from_raw_option('test', [])
def test_has_dict_changed(docker_swarm_service):
assert not docker_swarm_service.has_dict_changed(
{"a": 1},
{"a": 1},
)
assert not docker_swarm_service.has_dict_changed(
{"a": 1},
{"a": 1, "b": 2}
)
assert docker_swarm_service.has_dict_changed(
{"a": 1},
{"a": 2, "b": 2}
)
assert docker_swarm_service.has_dict_changed(
{"a": 1, "b": 1},
{"a": 1}
)
assert not docker_swarm_service.has_dict_changed(
None,
{"a": 2, "b": 2}
)
assert docker_swarm_service.has_dict_changed(
{},
{"a": 2, "b": 2}
)
assert docker_swarm_service.has_dict_changed(
{"a": 1},
{}
)
assert docker_swarm_service.has_dict_changed(
{"a": 1},
None
)
assert not docker_swarm_service.has_dict_changed(
{},
{}
)
assert not docker_swarm_service.has_dict_changed(
None,
None
)
assert not docker_swarm_service.has_dict_changed(
{},
None
)
assert not docker_swarm_service.has_dict_changed(
None,
{}
)
def test_has_list_changed(docker_swarm_service):
# List comparisons without dictionaries
# I could improve the indenting, but pycodestyle wants this instead
assert not docker_swarm_service.has_list_changed(None, None)
assert not docker_swarm_service.has_list_changed(None, [])
assert not docker_swarm_service.has_list_changed(None, [1, 2])
assert not docker_swarm_service.has_list_changed([], None)
assert not docker_swarm_service.has_list_changed([], [])
assert docker_swarm_service.has_list_changed([], [1, 2])
assert docker_swarm_service.has_list_changed([1, 2], None)
assert docker_swarm_service.has_list_changed([1, 2], [])
assert docker_swarm_service.has_list_changed([1, 2, 3], [1, 2])
assert docker_swarm_service.has_list_changed([1, 2], [1, 2, 3])
# Check list sorting
assert not docker_swarm_service.has_list_changed([1, 2], [2, 1])
assert docker_swarm_service.has_list_changed(
[1, 2],
[2, 1],
sort_lists=False
)
# Check type matching
assert docker_swarm_service.has_list_changed([None, 1], [2, 1])
assert docker_swarm_service.has_list_changed([2, 1], [None, 1])
assert docker_swarm_service.has_list_changed(
"command --with args",
['command', '--with', 'args']
)
assert docker_swarm_service.has_list_changed(
['sleep', '3400'],
[u'sleep', u'3600'],
sort_lists=False
)
# List comparisons with dictionaries
assert not docker_swarm_service.has_list_changed(
[{'a': 1}],
[{'a': 1}],
sort_key='a'
)
assert not docker_swarm_service.has_list_changed(
[{'a': 1}, {'a': 2}],
[{'a': 1}, {'a': 2}],
sort_key='a'
)
with pytest.raises(Exception):
docker_swarm_service.has_list_changed(
[{'a': 1}, {'a': 2}],
[{'a': 1}, {'a': 2}]
)
# List sort checking with sort key
assert not docker_swarm_service.has_list_changed(
[{'a': 1}, {'a': 2}],
[{'a': 2}, {'a': 1}],
sort_key='a'
)
assert docker_swarm_service.has_list_changed(
[{'a': 1}, {'a': 2}],
[{'a': 2}, {'a': 1}],
sort_lists=False
)
assert docker_swarm_service.has_list_changed(
[{'a': 1}, {'a': 2}, {'a': 3}],
[{'a': 2}, {'a': 1}],
sort_key='a'
)
assert docker_swarm_service.has_list_changed(
[{'a': 1}, {'a': 2}],
[{'a': 1}, {'a': 2}, {'a': 3}],
sort_lists=False
)
# Additional dictionary elements
assert not docker_swarm_service.has_list_changed(
[
{"src": 1, "dst": 2},
{"src": 1, "dst": 2, "protocol": "udp"},
],
[
{"src": 1, "dst": 2, "protocol": "tcp"},
{"src": 1, "dst": 2, "protocol": "udp"},
],
sort_key='dst'
)
assert not docker_swarm_service.has_list_changed(
[
{"src": 1, "dst": 2, "protocol": "udp"},
{"src": 1, "dst": 3, "protocol": "tcp"},
],
[
{"src": 1, "dst": 2, "protocol": "udp"},
{"src": 1, "dst": 3, "protocol": "tcp"},
],
sort_key='dst'
)
assert docker_swarm_service.has_list_changed(
[
{"src": 1, "dst": 2, "protocol": "udp"},
{"src": 1, "dst": 2},
{"src": 3, "dst": 4},
],
[
{"src": 1, "dst": 3, "protocol": "udp"},
{"src": 1, "dst": 2, "protocol": "tcp"},
{"src": 3, "dst": 4, "protocol": "tcp"},
],
sort_key='dst'
)
assert docker_swarm_service.has_list_changed(
[
{"src": 1, "dst": 3, "protocol": "tcp"},
{"src": 1, "dst": 2, "protocol": "udp"},
],
[
{"src": 1, "dst": 2, "protocol": "tcp"},
{"src": 1, "dst": 2, "protocol": "udp"},
],
sort_key='dst'
)
assert docker_swarm_service.has_list_changed(
[
{"src": 1, "dst": 2, "protocol": "udp"},
{"src": 1, "dst": 2, "protocol": "tcp", "extra": {"test": "foo"}},
],
[
{"src": 1, "dst": 2, "protocol": "udp"},
{"src": 1, "dst": 2, "protocol": "tcp"},
],
sort_key='dst'
)
assert not docker_swarm_service.has_list_changed(
[{'id': '123', 'aliases': []}],
[{'id': '123'}],
sort_key='id'
)
def test_have_networks_changed(docker_swarm_service):
assert not docker_swarm_service.have_networks_changed(
None,
None
)
assert not docker_swarm_service.have_networks_changed(
[],
None
)
assert not docker_swarm_service.have_networks_changed(
[{'id': 1}],
[{'id': 1}]
)
assert docker_swarm_service.have_networks_changed(
[{'id': 1}],
[{'id': 1}, {'id': 2}]
)
assert not docker_swarm_service.have_networks_changed(
[{'id': 1}, {'id': 2}],
[{'id': 1}, {'id': 2}]
)
assert not docker_swarm_service.have_networks_changed(
[{'id': 1}, {'id': 2}],
[{'id': 2}, {'id': 1}]
)
assert not docker_swarm_service.have_networks_changed(
[
{'id': 1},
{'id': 2, 'aliases': []}
],
[
{'id': 1},
{'id': 2}
]
)
assert docker_swarm_service.have_networks_changed(
[
{'id': 1},
{'id': 2, 'aliases': ['alias1']}
],
[
{'id': 1},
{'id': 2}
]
)
assert docker_swarm_service.have_networks_changed(
[
{'id': 1},
{'id': 2, 'aliases': ['alias1', 'alias2']}
],
[
{'id': 1},
{'id': 2, 'aliases': ['alias1']}
]
)
assert not docker_swarm_service.have_networks_changed(
[
{'id': 1},
{'id': 2, 'aliases': ['alias1', 'alias2']}
],
[
{'id': 1},
{'id': 2, 'aliases': ['alias1', 'alias2']}
]
)
assert not docker_swarm_service.have_networks_changed(
[
{'id': 1},
{'id': 2, 'aliases': ['alias1', 'alias2']}
],
[
{'id': 1},
{'id': 2, 'aliases': ['alias2', 'alias1']}
]
)
assert not docker_swarm_service.have_networks_changed(
[
{'id': 1, 'options': {}},
{'id': 2, 'aliases': ['alias1', 'alias2']}],
[
{'id': 1},
{'id': 2, 'aliases': ['alias2', 'alias1']}
]
)
assert not docker_swarm_service.have_networks_changed(
[
{'id': 1, 'options': {'option1': 'value1'}},
{'id': 2, 'aliases': ['alias1', 'alias2']}],
[
{'id': 1, 'options': {'option1': 'value1'}},
{'id': 2, 'aliases': ['alias2', 'alias1']}
]
)
assert docker_swarm_service.have_networks_changed(
[
{'id': 1, 'options': {'option1': 'value1'}},
{'id': 2, 'aliases': ['alias1', 'alias2']}],
[
{'id': 1, 'options': {'option1': 'value2'}},
{'id': 2, 'aliases': ['alias2', 'alias1']}
]
)
def test_get_docker_networks(docker_swarm_service):
network_names = [
'network_1',
'network_2',
'network_3',
'network_4',
]
networks = [
network_names[0],
{'name': network_names[1]},
{'name': network_names[2], 'aliases': ['networkalias1']},
{'name': network_names[3], 'aliases': ['networkalias2'], 'options': {'foo': 'bar'}},
]
network_ids = {
network_names[0]: '1',
network_names[1]: '2',
network_names[2]: '3',
network_names[3]: '4',
}
parsed_networks = docker_swarm_service.get_docker_networks(
networks,
network_ids
)
assert len(parsed_networks) == 4
for i, network in enumerate(parsed_networks):
assert 'name' not in network
assert 'id' in network
expected_name = network_names[i]
assert network['id'] == network_ids[expected_name]
if i == 2:
assert network['aliases'] == ['networkalias1']
if i == 3:
assert network['aliases'] == ['networkalias2']
if i == 3:
assert 'foo' in network['options']
# Test missing name
with pytest.raises(TypeError):
docker_swarm_service.get_docker_networks([{'invalid': 'err'}], {'err': 1})
# test for invalid aliases type
with pytest.raises(TypeError):
docker_swarm_service.get_docker_networks(
[{'name': 'test', 'aliases': 1}],
{'test': 1}
)
# Test invalid aliases elements
with pytest.raises(TypeError):
docker_swarm_service.get_docker_networks(
[{'name': 'test', 'aliases': [1]}],
{'test': 1}
)
# Test for invalid options type
with pytest.raises(TypeError):
docker_swarm_service.get_docker_networks(
[{'name': 'test', 'options': 1}],
{'test': 1}
)
# Test for invalid networks type
with pytest.raises(TypeError):
docker_swarm_service.get_docker_networks(
1,
{'test': 1}
)
# Test for non existing networks
with pytest.raises(ValueError):
docker_swarm_service.get_docker_networks(
[{'name': 'idontexist'}],
{'test': 1}
)
# Test empty values
assert docker_swarm_service.get_docker_networks([], {}) == []
assert docker_swarm_service.get_docker_networks(None, {}) is None
# Test invalid options
with pytest.raises(TypeError):
docker_swarm_service.get_docker_networks(
[{'name': 'test', 'nonexisting_option': 'foo'}],
{'test': '1'}
)

View file

@ -0,0 +1,36 @@
# Copyright (c) 2018 Ansible Project
# 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
import json
import pytest
from ansible_collections.community.general.plugins.modules.cloud.docker import docker_volume
from ansible_collections.community.general.plugins.module_utils.docker import common
pytestmark = pytest.mark.usefixtures('patch_ansible_module')
TESTCASE_DOCKER_VOLUME = [
{
'name': 'daemon_config',
'state': 'present'
}
]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_DOCKER_VOLUME, indirect=['patch_ansible_module'])
def test_create_volume_on_invalid_docker_version(mocker, capfd):
mocker.patch.object(common, 'HAS_DOCKER_PY', True)
mocker.patch.object(common, 'docker_version', '1.8.0')
with pytest.raises(SystemExit):
docker_volume.main()
out, dummy = capfd.readouterr()
results = json.loads(out)
assert results['failed']
assert 'Error: Docker SDK for Python version is 1.8.0 ' in results['msg']
assert 'Minimum version required is 1.10.0.' in results['msg']

View file

@ -0,0 +1,61 @@
import unittest
from ansible_collections.community.general.plugins.modules.cloud.google.gce_tag import _get_changed_items, _intersect_items, _union_items
class TestGCETag(unittest.TestCase):
"""Unit tests for gce_tag module."""
def test_union_items(self):
"""
Combine items in both lists
removing duplicates.
"""
listA = [1, 2, 3, 4, 5, 8, 9]
listB = [1, 2, 3, 4, 5, 6, 7]
want = [1, 2, 3, 4, 5, 6, 7, 8, 9]
got = _union_items(listA, listB)
self.assertEqual(want, got)
def test_intersect_items(self):
"""
All unique items from either list.
"""
listA = [1, 2, 3, 4, 5, 8, 9]
listB = [1, 2, 3, 4, 5, 6, 7]
want = [1, 2, 3, 4, 5]
got = _intersect_items(listA, listB)
self.assertEqual(want, got)
# tags removed
new_tags = ['one', 'two']
existing_tags = ['two']
want = ['two'] # only remove the tag that was present
got = _intersect_items(existing_tags, new_tags)
self.assertEqual(want, got)
def test_get_changed_items(self):
"""
All the items from left list that don't match
any item from the right list.
"""
listA = [1, 2, 3, 4, 5, 8, 9]
listB = [1, 2, 3, 4, 5, 6, 7]
want = [8, 9]
got = _get_changed_items(listA, listB)
self.assertEqual(want, got)
# simulate new tags added
tags_to_add = ['one', 'two']
existing_tags = ['two']
want = ['one']
got = _get_changed_items(tags_to_add, existing_tags)
self.assertEqual(want, got)
# simulate removing tags
# specifying one tag on right that doesn't exist
tags_to_remove = ['one', 'two']
existing_tags = ['two', 'three']
want = ['three']
got = _get_changed_items(existing_tags, tags_to_remove)
self.assertEqual(want, got)

View file

@ -0,0 +1,30 @@
import unittest
from ansible_collections.community.general.plugins.modules.cloud.google.gcp_forwarding_rule import _build_global_forwarding_rule_dict
class TestGCPFowardingRule(unittest.TestCase):
"""Unit tests for gcp_fowarding_rule module."""
params_dict = {
'forwarding_rule_name': 'foo_fowarding_rule_name',
'address': 'foo_external_address',
'target': 'foo_targetproxy',
'region': 'global',
'port_range': 80,
'protocol': 'TCP',
'state': 'present',
}
def test__build_global_forwarding_rule_dict(self):
expected = {
'name': 'foo_fowarding_rule_name',
'IPAddress': 'https://www.googleapis.com/compute/v1/projects/my-project/global/addresses/foo_external_address',
'target': 'https://www.googleapis.com/compute/v1/projects/my-project/global/targetHttpProxies/foo_targetproxy',
'region': 'global',
'portRange': 80,
'IPProtocol': 'TCP',
}
actual = _build_global_forwarding_rule_dict(
self.params_dict, 'my-project')
self.assertEqual(expected, actual)

View file

@ -0,0 +1,164 @@
import unittest
from ansible_collections.community.general.plugins.modules.cloud.google.gcp_url_map import _build_path_matchers, _build_url_map_dict
class TestGCPUrlMap(unittest.TestCase):
"""Unit tests for gcp_url_map module."""
params_dict = {
'url_map_name': 'foo_url_map_name',
'description': 'foo_url_map description',
'host_rules': [
{
'description': 'host rules description',
'hosts': [
'www.example.com',
'www2.example.com'
],
'path_matcher': 'host_rules_path_matcher'
}
],
'path_matchers': [
{
'name': 'path_matcher_one',
'description': 'path matcher one',
'defaultService': 'bes-pathmatcher-one-default',
'pathRules': [
{
'service': 'my-one-bes',
'paths': [
'/',
'/aboutus'
]
}
]
},
{
'name': 'path_matcher_two',
'description': 'path matcher two',
'defaultService': 'bes-pathmatcher-two-default',
'pathRules': [
{
'service': 'my-two-bes',
'paths': [
'/webapp',
'/graphs'
]
}
]
}
]
}
def test__build_path_matchers(self):
input_list = [
{
'defaultService': 'bes-pathmatcher-one-default',
'description': 'path matcher one',
'name': 'path_matcher_one',
'pathRules': [
{
'paths': [
'/',
'/aboutus'
],
'service': 'my-one-bes'
}
]
},
{
'defaultService': 'bes-pathmatcher-two-default',
'description': 'path matcher two',
'name': 'path_matcher_two',
'pathRules': [
{
'paths': [
'/webapp',
'/graphs'
],
'service': 'my-two-bes'
}
]
}
]
expected = [
{
'defaultService': 'https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/bes-pathmatcher-one-default',
'description': 'path matcher one',
'name': 'path_matcher_one',
'pathRules': [
{
'paths': [
'/',
'/aboutus'
],
'service': 'https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/my-one-bes'
}
]
},
{
'defaultService': 'https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/bes-pathmatcher-two-default',
'description': 'path matcher two',
'name': 'path_matcher_two',
'pathRules': [
{
'paths': [
'/webapp',
'/graphs'
],
'service': 'https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/my-two-bes'
}
]
}
]
actual = _build_path_matchers(input_list, 'my-project')
self.assertEqual(expected, actual)
def test__build_url_map_dict(self):
expected = {
'description': 'foo_url_map description',
'hostRules': [
{
'description': 'host rules description',
'hosts': [
'www.example.com',
'www2.example.com'
],
'pathMatcher': 'host_rules_path_matcher'
}
],
'name': 'foo_url_map_name',
'pathMatchers': [
{
'defaultService': 'https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/bes-pathmatcher-one-default',
'description': 'path matcher one',
'name': 'path_matcher_one',
'pathRules': [
{
'paths': [
'/',
'/aboutus'
],
'service': 'https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/my-one-bes'
}
]
},
{
'defaultService': 'https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/bes-pathmatcher-two-default',
'description': 'path matcher two',
'name': 'path_matcher_two',
'pathRules': [
{
'paths': [
'/webapp',
'/graphs'
],
'service': 'https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/my-two-bes'
}
]
}
]
}
actual = _build_url_map_dict(self.params_dict, 'my-project')
self.assertEqual(expected, actual)

View file

@ -0,0 +1,73 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from ansible_collections.community.general.tests.unit.compat.mock import MagicMock
from ansible_collections.community.kubernetes.plugins.module_utils.common import K8sAnsibleMixin
from ansible_collections.community.kubernetes.plugins.module_utils.raw import KubernetesRawModule
from ansible_collections.community.general.plugins.module_utils.kubevirt import KubeVirtRawModule
import openshift.dynamic
RESOURCE_DEFAULT_ARGS = {'api_version': 'v1alpha3', 'group': 'kubevirt.io',
'prefix': 'apis', 'namespaced': True}
class AnsibleExitJson(Exception):
"""Exception class to be raised by module.exit_json and caught
by the test case"""
def __init__(self, **kwargs):
for k in kwargs:
setattr(self, k, kwargs[k])
def __getitem__(self, attr):
return getattr(self, attr)
class AnsibleFailJson(Exception):
"""Exception class to be raised by module.fail_json and caught
by the test case"""
def __init__(self, **kwargs):
for k in kwargs:
setattr(self, k, kwargs[k])
def __getitem__(self, attr):
return getattr(self, attr)
def exit_json(*args, **kwargs):
kwargs['success'] = True
if 'changed' not in kwargs:
kwargs['changed'] = False
raise AnsibleExitJson(**kwargs)
def fail_json(*args, **kwargs):
kwargs['success'] = False
raise AnsibleFailJson(**kwargs)
@pytest.fixture()
def base_fixture(monkeypatch):
monkeypatch.setattr(
KubernetesRawModule, "exit_json", exit_json)
monkeypatch.setattr(
KubernetesRawModule, "fail_json", fail_json)
# Create mock methods in Resource directly, otherwise dyn client
# tries binding those to corresponding methods in DynamicClient
# (with partial()), which is more problematic to intercept
openshift.dynamic.Resource.get = MagicMock()
openshift.dynamic.Resource.create = MagicMock()
openshift.dynamic.Resource.delete = MagicMock()
openshift.dynamic.Resource.patch = MagicMock()
openshift.dynamic.Resource.search = MagicMock()
openshift.dynamic.Resource.watch = MagicMock()
# Globally mock some methods, since all tests will use this
KubernetesRawModule.patch_resource = MagicMock()
KubernetesRawModule.patch_resource.return_value = ({}, None)
K8sAnsibleMixin.get_api_client = MagicMock()
K8sAnsibleMixin.get_api_client.return_value = None
K8sAnsibleMixin.find_resource = MagicMock()
KubeVirtRawModule.find_supported_resource = MagicMock()

View file

@ -0,0 +1,75 @@
import pytest
openshiftdynamic = pytest.importorskip("openshift.dynamic")
from ansible_collections.community.general.tests.unit.plugins.modules.utils import set_module_args
from .kubevirt_fixtures import base_fixture, RESOURCE_DEFAULT_ARGS, AnsibleExitJson
from ansible_collections.community.kubernetes.plugins.module_utils.raw import KubernetesRawModule
from ansible_collections.community.general.plugins.modules.cloud.kubevirt import kubevirt_rs as mymodule
KIND = 'VirtualMachineInstanceReplicaSet'
@pytest.mark.usefixtures("base_fixture")
@pytest.mark.parametrize("_replicas, _changed", ((1, True),
(3, True),
(2, False),
(5, True),))
def test_scale_rs_nowait(_replicas, _changed):
_name = 'test-rs'
# Desired state:
args = dict(name=_name, namespace='vms', replicas=_replicas, wait=False)
set_module_args(args)
# Mock pre-change state:
resource_args = dict(kind=KIND, **RESOURCE_DEFAULT_ARGS)
mymodule.KubeVirtVMIRS.find_supported_resource.return_value = openshiftdynamic.Resource(**resource_args)
res_inst = openshiftdynamic.ResourceInstance('', dict(kind=KIND, metadata={'name': _name}, spec={'replicas': 2}))
openshiftdynamic.Resource.get.return_value = res_inst
openshiftdynamic.Resource.search.return_value = [res_inst]
# Final state, after patching the object
KubernetesRawModule.patch_resource.return_value = dict(kind=KIND, metadata={'name': _name},
spec={'replicas': _replicas}), None
# Run code:
with pytest.raises(AnsibleExitJson) as result:
mymodule.KubeVirtVMIRS().execute_module()
# Verify result:
assert result.value['changed'] == _changed
@pytest.mark.usefixtures("base_fixture")
@pytest.mark.parametrize("_replicas, _success", ((1, False),
(2, False),
(5, True),))
def test_scale_rs_wait(_replicas, _success):
_name = 'test-rs'
# Desired state:
args = dict(name=_name, namespace='vms', replicas=5, wait=True)
set_module_args(args)
# Mock pre-change state:
resource_args = dict(kind=KIND, **RESOURCE_DEFAULT_ARGS)
mymodule.KubeVirtVMIRS.find_supported_resource.return_value = openshiftdynamic.Resource(**resource_args)
res_inst = openshiftdynamic.ResourceInstance('', dict(kind=KIND, metadata={'name': _name}, spec={'replicas': 2}))
openshiftdynamic.Resource.get.return_value = res_inst
openshiftdynamic.Resource.search.return_value = [res_inst]
# ~Final state, after patching the object (`replicas` match desired state)
KubernetesRawModule.patch_resource.return_value = dict(kind=KIND, name=_name, metadata={'name': _name},
spec={'replicas': 5}), None
# Final final state, as returned by resource.watch()
final_obj = dict(metadata=dict(name=_name), status=dict(readyReplicas=_replicas), **resource_args)
event = openshiftdynamic.ResourceInstance(None, final_obj)
openshiftdynamic.Resource.watch.return_value = [dict(object=event)]
# Run code:
with pytest.raises(Exception) as result:
mymodule.KubeVirtVMIRS().execute_module()
# Verify result:
assert result.value['success'] == _success

View file

@ -0,0 +1,110 @@
import pytest
openshiftdynamic = pytest.importorskip("openshift.dynamic")
from ansible_collections.community.general.tests.unit.plugins.modules.utils import set_module_args
from .kubevirt_fixtures import base_fixture, RESOURCE_DEFAULT_ARGS, AnsibleExitJson
from ansible_collections.community.general.plugins.module_utils.kubevirt import KubeVirtRawModule
from ansible_collections.community.general.plugins.modules.cloud.kubevirt import kubevirt_vm as mymodule
KIND = 'VirtulMachine'
@pytest.mark.usefixtures("base_fixture")
def test_create_vm_with_multus_nowait():
# Desired state:
args = dict(
state='present', name='testvm',
namespace='vms',
interfaces=[
{'bridge': {}, 'name': 'default', 'network': {'pod': {}}},
{'bridge': {}, 'name': 'mynet', 'network': {'multus': {'networkName': 'mynet'}}},
],
wait=False,
)
set_module_args(args)
# State as "returned" by the "k8s cluster":
resource_args = dict(kind=KIND, **RESOURCE_DEFAULT_ARGS)
KubeVirtRawModule.find_supported_resource.return_value = openshiftdynamic.Resource(**resource_args)
openshiftdynamic.Resource.get.return_value = None # Object doesn't exist in the cluster
# Run code:
with pytest.raises(AnsibleExitJson) as result:
mymodule.KubeVirtVM().execute_module()
# Verify result:
assert result.value['changed']
assert result.value['method'] == 'create'
@pytest.mark.usefixtures("base_fixture")
@pytest.mark.parametrize("_wait", (False, True))
def test_vm_is_absent(_wait):
# Desired state:
args = dict(
state='absent', name='testvmi',
namespace='vms',
wait=_wait,
)
set_module_args(args)
# State as "returned" by the "k8s cluster":
resource_args = dict(kind=KIND, **RESOURCE_DEFAULT_ARGS)
KubeVirtRawModule.find_supported_resource.return_value = openshiftdynamic.Resource(**resource_args)
openshiftdynamic.Resource.get.return_value = None # Object doesn't exist in the cluster
# Run code:
with pytest.raises(AnsibleExitJson) as result:
mymodule.KubeVirtVM().execute_module()
# Verify result:
assert not result.value['kubevirt_vm']
assert result.value['method'] == 'delete'
# Note: nothing actually gets deleted, as we mock that there's not object in the cluster present,
# so if the method changes to something other than 'delete' at some point, that's fine
@pytest.mark.usefixtures("base_fixture")
def test_vmpreset_create():
KIND = 'VirtulMachineInstancePreset'
# Desired state:
args = dict(state='present', name='testvmipreset', namespace='vms', memory='1024Mi', wait=False)
set_module_args(args)
# State as "returned" by the "k8s cluster":
resource_args = dict(kind=KIND, **RESOURCE_DEFAULT_ARGS)
KubeVirtRawModule.find_supported_resource.return_value = openshiftdynamic.Resource(**resource_args)
openshiftdynamic.Resource.get.return_value = None # Object doesn't exist in the cluster
# Run code:
with pytest.raises(AnsibleExitJson) as result:
mymodule.KubeVirtVM().execute_module()
# Verify result:
assert result.value['changed']
assert result.value['method'] == 'create'
@pytest.mark.usefixtures("base_fixture")
def test_vmpreset_is_absent():
KIND = 'VirtulMachineInstancePreset'
# Desired state:
args = dict(state='absent', name='testvmipreset', namespace='vms')
set_module_args(args)
# State as "returned" by the "k8s cluster":
resource_args = dict(kind=KIND, **RESOURCE_DEFAULT_ARGS)
KubeVirtRawModule.find_supported_resource.return_value = openshiftdynamic.Resource(**resource_args)
openshiftdynamic.Resource.get.return_value = None # Object doesn't exist in the cluster
# Run code:
with pytest.raises(AnsibleExitJson) as result:
mymodule.KubeVirtVM().execute_module()
# Verify result:
assert not result.value['kubevirt_vm']
assert result.value['method'] == 'delete'
# Note: nothing actually gets deleted, as we mock that there's not object in the cluster present,
# so if the method changes to something other than 'delete' at some point, that's fine

View file

@ -0,0 +1,80 @@
import pytest
@pytest.fixture
def api_key(monkeypatch):
monkeypatch.setenv('LINODE_API_KEY', 'foobar')
@pytest.fixture
def auth(monkeypatch):
def patched_test_echo(dummy):
return []
monkeypatch.setattr('linode.api.Api.test_echo', patched_test_echo)
@pytest.fixture
def access_token(monkeypatch):
monkeypatch.setenv('LINODE_ACCESS_TOKEN', 'barfoo')
@pytest.fixture
def no_access_token_in_env(monkeypatch):
try:
monkeypatch.delenv('LINODE_ACCESS_TOKEN')
except KeyError:
pass
@pytest.fixture
def default_args():
return {'state': 'present', 'label': 'foo'}
@pytest.fixture
def mock_linode():
class Linode():
def delete(self, *args, **kwargs):
pass
@property
def _raw_json(self):
return {
"alerts": {
"cpu": 90,
"io": 10000,
"network_in": 10,
"network_out": 10,
"transfer_quota": 80
},
"backups": {
"enabled": False,
"schedule": {
"day": None,
"window": None,
}
},
"created": "2018-09-26T08:12:33",
"group": "Foobar Group",
"hypervisor": "kvm",
"id": 10480444,
"image": "linode/centos7",
"ipv4": [
"130.132.285.233"
],
"ipv6": "2a82:7e00::h03c:46ff:fe04:5cd2/64",
"label": "lin-foo",
"region": "eu-west",
"specs": {
"disk": 25600,
"memory": 1024,
"transfer": 1000,
"vcpus": 1
},
"status": "running",
"tags": [],
"type": "g6-nanode-1",
"updated": "2018-09-26T10:10:14",
"watchdog_enabled": True
}
return Linode()

View file

@ -0,0 +1,15 @@
from __future__ import (absolute_import, division, print_function)
import pytest
from ansible_collections.community.general.plugins.modules.cloud.linode import linode
from ansible_collections.community.general.tests.unit.plugins.modules.utils import set_module_args
if not linode.HAS_LINODE:
pytestmark = pytest.mark.skip('test_linode.py requires the `linode-python` module')
def test_name_is_a_required_parameter(api_key, auth):
with pytest.raises(SystemExit):
set_module_args({})
linode.main()

View file

@ -0,0 +1,323 @@
from __future__ import (absolute_import, division, print_function)
import json
import os
import sys
import pytest
linode_apiv4 = pytest.importorskip('linode_api4')
mandatory_py_version = pytest.mark.skipif(
sys.version_info < (2, 7),
reason='The linode_api4 dependency requires python2.7 or higher'
)
from linode_api4.errors import ApiError as LinodeApiError
from linode_api4 import LinodeClient
from ansible_collections.community.general.plugins.modules.cloud.linode import linode_v4
from ansible_collections.community.general.plugins.module_utils.linode import get_user_agent
from ansible_collections.community.general.tests.unit.plugins.modules.utils import set_module_args
from ansible_collections.community.general.tests.unit.compat import mock
def test_mandatory_state_is_validated(capfd):
with pytest.raises(SystemExit):
set_module_args({'label': 'foo'})
linode_v4.initialise_module()
out, err = capfd.readouterr()
results = json.loads(out)
assert all(txt in results['msg'] for txt in ('state', 'required'))
assert results['failed'] is True
def test_mandatory_label_is_validated(capfd):
with pytest.raises(SystemExit):
set_module_args({'state': 'present'})
linode_v4.initialise_module()
out, err = capfd.readouterr()
results = json.loads(out)
assert all(txt in results['msg'] for txt in ('label', 'required'))
assert results['failed'] is True
def test_mandatory_access_token_is_validated(default_args,
no_access_token_in_env,
capfd):
with pytest.raises(SystemExit):
set_module_args(default_args)
linode_v4.initialise_module()
out, err = capfd.readouterr()
results = json.loads(out)
assert results['failed'] is True
assert all(txt in results['msg'] for txt in (
'missing',
'required',
'access_token',
))
def test_mandatory_access_token_passed_in_env(default_args,
access_token):
set_module_args(default_args)
try:
module = linode_v4.initialise_module()
except SystemExit:
pytest.fail("'access_token' is passed in environment")
now_set_token = module.params['access_token']
assert now_set_token == os.environ['LINODE_ACCESS_TOKEN']
def test_mandatory_access_token_passed_in_as_parameter(default_args,
no_access_token_in_env):
default_args.update({'access_token': 'foo'})
set_module_args(default_args)
try:
module = linode_v4.initialise_module()
except SystemExit:
pytest.fail("'access_token' is passed in as parameter")
assert module.params['access_token'] == 'foo'
def test_instance_by_label_cannot_authenticate(capfd, access_token,
default_args):
set_module_args(default_args)
module = linode_v4.initialise_module()
client = LinodeClient(module.params['access_token'])
target = 'linode_api4.linode_client.LinodeGroup.instances'
with mock.patch(target, side_effect=LinodeApiError('foo')):
with pytest.raises(SystemExit):
linode_v4.maybe_instance_from_label(module, client)
out, err = capfd.readouterr()
results = json.loads(out)
assert results['failed'] is True
assert 'Unable to query the Linode API' in results['msg']
def test_no_instances_found_with_label_gives_none(default_args,
access_token):
set_module_args(default_args)
module = linode_v4.initialise_module()
client = LinodeClient(module.params['access_token'])
target = 'linode_api4.linode_client.LinodeGroup.instances'
with mock.patch(target, return_value=[]):
result = linode_v4.maybe_instance_from_label(module, client)
assert result is None
def test_optional_region_is_validated(default_args, capfd, access_token):
default_args.update({'type': 'foo', 'image': 'bar'})
set_module_args(default_args)
with pytest.raises(SystemExit):
linode_v4.initialise_module()
out, err = capfd.readouterr()
results = json.loads(out)
assert results['failed'] is True
assert all(txt in results['msg'] for txt in (
'required',
'together',
'region'
))
def test_optional_type_is_validated(default_args, capfd, access_token):
default_args.update({'region': 'foo', 'image': 'bar'})
set_module_args(default_args)
with pytest.raises(SystemExit):
linode_v4.initialise_module()
out, err = capfd.readouterr()
results = json.loads(out)
assert results['failed'] is True
assert all(txt in results['msg'] for txt in (
'required',
'together',
'type'
))
def test_optional_image_is_validated(default_args, capfd, access_token):
default_args.update({'type': 'foo', 'region': 'bar'})
set_module_args(default_args)
with pytest.raises(SystemExit):
linode_v4.initialise_module()
out, err = capfd.readouterr()
results = json.loads(out)
assert results['failed'] is True
assert all(txt in results['msg'] for txt in (
'required',
'together',
'image'
))
def test_instance_already_created(default_args,
mock_linode,
capfd,
access_token):
default_args.update({
'type': 'foo',
'region': 'bar',
'image': 'baz'
})
set_module_args(default_args)
target = 'linode_api4.linode_client.LinodeGroup.instances'
with mock.patch(target, return_value=[mock_linode]):
with pytest.raises(SystemExit) as sys_exit_exc:
linode_v4.main()
assert sys_exit_exc.value.code == 0
out, err = capfd.readouterr()
results = json.loads(out)
assert results['changed'] is False
assert 'root_password' not in results['instance']
assert (
results['instance']['label'] ==
mock_linode._raw_json['label']
)
def test_instance_to_be_created_without_root_pass(default_args,
mock_linode,
capfd,
access_token):
default_args.update({
'type': 'foo',
'region': 'bar',
'image': 'baz'
})
set_module_args(default_args)
target = 'linode_api4.linode_client.LinodeGroup.instances'
with mock.patch(target, return_value=[]):
with pytest.raises(SystemExit) as sys_exit_exc:
target = 'linode_api4.linode_client.LinodeGroup.instance_create'
with mock.patch(target, return_value=(mock_linode, 'passw0rd')):
linode_v4.main()
assert sys_exit_exc.value.code == 0
out, err = capfd.readouterr()
results = json.loads(out)
assert results['changed'] is True
assert (
results['instance']['label'] ==
mock_linode._raw_json['label']
)
assert results['instance']['root_pass'] == 'passw0rd'
def test_instance_to_be_created_with_root_pass(default_args,
mock_linode,
capfd,
access_token):
default_args.update({
'type': 'foo',
'region': 'bar',
'image': 'baz',
'root_pass': 'passw0rd',
})
set_module_args(default_args)
target = 'linode_api4.linode_client.LinodeGroup.instances'
with mock.patch(target, return_value=[]):
with pytest.raises(SystemExit) as sys_exit_exc:
target = 'linode_api4.linode_client.LinodeGroup.instance_create'
with mock.patch(target, return_value=mock_linode):
linode_v4.main()
assert sys_exit_exc.value.code == 0
out, err = capfd.readouterr()
results = json.loads(out)
assert results['changed'] is True
assert (
results['instance']['label'] ==
mock_linode._raw_json['label']
)
assert 'root_pass' not in results['instance']
def test_instance_to_be_deleted(default_args,
mock_linode,
capfd,
access_token):
default_args.update({'state': 'absent'})
set_module_args(default_args)
target = 'linode_api4.linode_client.LinodeGroup.instances'
with mock.patch(target, return_value=[mock_linode]):
with pytest.raises(SystemExit) as sys_exit_exc:
linode_v4.main()
assert sys_exit_exc.value.code == 0
out, err = capfd.readouterr()
results = json.loads(out)
assert results['changed'] is True
assert (
results['instance']['label'] ==
mock_linode._raw_json['label']
)
def test_instance_already_deleted_no_change(default_args,
mock_linode,
capfd,
access_token):
default_args.update({'state': 'absent'})
set_module_args(default_args)
target = 'linode_api4.linode_client.LinodeGroup.instances'
with mock.patch(target, return_value=[]):
with pytest.raises(SystemExit) as sys_exit_exc:
linode_v4.main()
assert sys_exit_exc.value.code == 0
out, err = capfd.readouterr()
results = json.loads(out)
assert results['changed'] is False
assert results['instance'] == {}
def test_user_agent_created_properly():
try:
from ansible.module_utils.ansible_release import (
__version__ as ansible_version
)
except ImportError:
ansible_version = 'unknown'
expected_user_agent = 'Ansible-linode_v4_module/%s' % ansible_version
assert expected_user_agent == get_user_agent('linode_v4_module')

View file

@ -0,0 +1,20 @@
# Copyright: (c) 2019, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
import json
import pytest
from ansible_collections.community.general.plugins.modules.cloud.misc import terraform
from ansible_collections.community.general.tests.unit.plugins.modules.utils import set_module_args
def test_terraform_without_argument(capfd):
set_module_args({})
with pytest.raises(SystemExit) as results:
terraform.main()
out, err = capfd.readouterr()
assert not err
assert json.loads(out)['failed']
assert 'project_path' in json.loads(out)['msg']

View file

@ -0,0 +1,30 @@
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2019, Bojan Vitnik <bvitnik@mainstream.rs>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class AnsibleModuleException(Exception):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
class ExitJsonException(AnsibleModuleException):
pass
class FailJsonException(AnsibleModuleException):
pass
class FakeAnsibleModule:
def __init__(self, params=None, check_mode=False):
self.params = params
self.check_mode = check_mode
def exit_json(self, *args, **kwargs):
raise ExitJsonException(*args, **kwargs)
def fail_json(self, *args, **kwargs):
raise FailJsonException(*args, **kwargs)

View file

@ -0,0 +1,66 @@
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2019, Bojan Vitnik <bvitnik@mainstream.rs>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
FAKE_API_VERSION = "1.1"
class Failure(Exception):
def __init__(self, details):
self.details = details
def __str__(self):
return str(self.details)
class Session(object):
def __init__(self, uri, transport=None, encoding=None, verbose=0,
allow_none=1, ignore_ssl=False):
self.transport = transport
self._session = None
self.last_login_method = None
self.last_login_params = None
self.API_version = FAKE_API_VERSION
def _get_api_version(self):
return FAKE_API_VERSION
def _login(self, method, params):
self._session = "OpaqueRef:fake-xenapi-session-ref"
self.last_login_method = method
self.last_login_params = params
self.API_version = self._get_api_version()
def _logout(self):
self._session = None
self.last_login_method = None
self.last_login_params = None
self.API_version = FAKE_API_VERSION
def xenapi_request(self, methodname, params):
if methodname.startswith('login'):
self._login(methodname, params)
return None
elif methodname == 'logout' or methodname == 'session.logout':
self._logout()
return None
else:
# Should be patched with mocker.patch().
return None
def __getattr__(self, name):
if name == 'handle':
return self._session
elif name == 'xenapi':
# Should be patched with mocker.patch().
return None
elif name.startswith('login') or name.startswith('slave_local'):
return lambda *params: self._login(name, params)
elif name == 'logout':
return self._logout
def xapi_local():
return Session("http://_var_lib_xcp_xapi/")

View file

@ -0,0 +1,11 @@
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2019, Bojan Vitnik <bvitnik@mainstream.rs>
# 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
def fake_xenapi_ref(xenapi_class):
return "OpaqueRef:fake-xenapi-%s-ref" % xenapi_class

View file

@ -0,0 +1,75 @@
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2019, Bojan Vitnik <bvitnik@mainstream.rs>
# 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
import sys
import importlib
import pytest
from .FakeAnsibleModule import FakeAnsibleModule
@pytest.fixture
def fake_ansible_module(request):
"""Returns fake AnsibleModule with fake module params."""
if hasattr(request, 'param'):
return FakeAnsibleModule(request.param)
else:
params = {
"hostname": "somehost",
"username": "someuser",
"password": "somepwd",
"validate_certs": True,
}
return FakeAnsibleModule(params)
@pytest.fixture(autouse=True)
def XenAPI():
"""Imports and returns fake XenAPI module."""
# Import of fake XenAPI module is wrapped by fixture so that it does not
# affect other unit tests which could potentialy also use XenAPI module.
# First we use importlib.import_module() to import the module and assign
# it to a local symbol.
fake_xenapi = importlib.import_module('ansible_collections.community.general.tests.unit.plugins.modules.cloud.xenserver.FakeXenAPI')
# Now we populate Python module cache with imported fake module using the
# original module name (XenAPI). That way, any 'import XenAPI' statement
# will just load already imported fake module from the cache.
sys.modules['XenAPI'] = fake_xenapi
return fake_xenapi
@pytest.fixture
def xenserver_guest_info(XenAPI):
"""Imports and returns xenserver_guest_info module."""
# Since we are wrapping fake XenAPI module inside a fixture, all modules
# that depend on it have to be imported inside a test function. To make
# this easier to handle and remove some code repetition, we wrap the import
# of xenserver_guest_info module with a fixture.
from ansible_collections.community.general.plugins.modules.cloud.xenserver import xenserver_guest_info
return xenserver_guest_info
@pytest.fixture
def xenserver_guest_powerstate(XenAPI):
"""Imports and returns xenserver_guest_powerstate module."""
# Since we are wrapping fake XenAPI module inside a fixture, all modules
# that depend on it have to be imported inside a test function. To make
# this easier to handle and remove some code repetition, we wrap the import
# of xenserver_guest_powerstate module with a fixture.
from ansible_collections.community.general.plugins.modules.cloud.xenserver import xenserver_guest_powerstate
return xenserver_guest_powerstate

View file

@ -0,0 +1,77 @@
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2019, Bojan Vitnik <bvitnik@mainstream.rs>
# 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
import json
import pytest
from .common import fake_xenapi_ref
pytestmark = pytest.mark.usefixtures('patch_ansible_module')
testcase_module_params = {
"params": [
{
"hostname": "somehost",
"username": "someuser",
"password": "somepwd",
"name": "somevmname",
},
{
"hostname": "somehost",
"username": "someuser",
"password": "somepwd",
"uuid": "somevmuuid",
},
{
"hostname": "somehost",
"username": "someuser",
"password": "somepwd",
"name": "somevmname",
"uuid": "somevmuuid",
},
],
"ids": [
"name",
"uuid",
"name+uuid",
],
}
@pytest.mark.parametrize('patch_ansible_module', testcase_module_params['params'], ids=testcase_module_params['ids'], indirect=True)
def test_xenserver_guest_info(mocker, capfd, XenAPI, xenserver_guest_info):
"""
Tests regular module invocation including parsing and propagation of
module params and module output.
"""
fake_vm_facts = {"fake-vm-fact": True}
mocker.patch('ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_info.get_object_ref', return_value=None)
mocker.patch('ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_info.gather_vm_params', return_value=None)
mocker.patch('ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_info.gather_vm_facts', return_value=fake_vm_facts)
mocked_xenapi = mocker.patch.object(XenAPI.Session, 'xenapi', create=True)
mocked_returns = {
"pool.get_all.return_value": [fake_xenapi_ref('pool')],
"pool.get_default_SR.return_value": fake_xenapi_ref('SR'),
}
mocked_xenapi.configure_mock(**mocked_returns)
mocker.patch('ansible_collections.community.general.plugins.module_utils.xenserver.get_xenserver_version', return_value=[7, 2, 0])
with pytest.raises(SystemExit):
xenserver_guest_info.main()
out, err = capfd.readouterr()
result = json.loads(out)
assert result['instance'] == fake_vm_facts

View file

@ -0,0 +1,298 @@
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2019, Bojan Vitnik <bvitnik@mainstream.rs>
# 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
import json
import pytest
from .common import fake_xenapi_ref
testcase_set_powerstate = {
"params": [
(False, "someoldstate"),
(True, "somenewstate"),
],
"ids": [
"state-same",
"state-changed",
],
}
testcase_module_params_state_present = {
"params": [
{
"hostname": "somehost",
"username": "someuser",
"password": "somepwd",
"name": "somevmname",
},
{
"hostname": "somehost",
"username": "someuser",
"password": "somepwd",
"name": "somevmname",
"state": "present",
},
],
"ids": [
"present-implicit",
"present-explicit",
],
}
testcase_module_params_state_other = {
"params": [
{
"hostname": "somehost",
"username": "someuser",
"password": "somepwd",
"name": "somevmname",
"state": "powered-on",
},
{
"hostname": "somehost",
"username": "someuser",
"password": "somepwd",
"name": "somevmname",
"state": "powered-off",
},
{
"hostname": "somehost",
"username": "someuser",
"password": "somepwd",
"name": "somevmname",
"state": "restarted",
},
{
"hostname": "somehost",
"username": "someuser",
"password": "somepwd",
"name": "somevmname",
"state": "shutdown-guest",
},
{
"hostname": "somehost",
"username": "someuser",
"password": "somepwd",
"name": "somevmname",
"state": "reboot-guest",
},
{
"hostname": "somehost",
"username": "someuser",
"password": "somepwd",
"name": "somevmname",
"state": "suspended",
},
],
"ids": [
"powered-on",
"powered-off",
"restarted",
"shutdown-guest",
"reboot-guest",
"suspended",
],
}
testcase_module_params_wait = {
"params": [
{
"hostname": "somehost",
"username": "someuser",
"password": "somepwd",
"name": "somevmname",
"state": "present",
"wait_for_ip_address": "yes",
},
{
"hostname": "somehost",
"username": "someuser",
"password": "somepwd",
"name": "somevmname",
"state": "powered-on",
"wait_for_ip_address": "yes",
},
],
"ids": [
"wait-present",
"wait-other",
],
}
@pytest.mark.parametrize('power_state', testcase_set_powerstate['params'], ids=testcase_set_powerstate['ids'])
def test_xenserver_guest_powerstate_set_power_state(mocker, fake_ansible_module, XenAPI, xenserver_guest_powerstate, power_state):
"""Tests power state change handling."""
mocker.patch('ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.get_object_ref',
return_value=fake_xenapi_ref('VM'))
mocker.patch('ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.gather_vm_params',
return_value={"power_state": "Someoldstate"})
mocked_set_vm_power_state = mocker.patch(
'ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.set_vm_power_state',
return_value=power_state)
mocked_xenapi = mocker.patch.object(XenAPI.Session, 'xenapi', create=True)
mocked_returns = {
"pool.get_all.return_value": [fake_xenapi_ref('pool')],
"pool.get_default_SR.return_value": fake_xenapi_ref('SR'),
}
mocked_xenapi.configure_mock(**mocked_returns)
mocker.patch('ansible_collections.community.general.plugins.module_utils.xenserver.get_xenserver_version', return_value=[7, 2, 0])
fake_ansible_module.params.update({
"name": "somename",
"uuid": "someuuid",
"state_change_timeout": 1,
})
vm = xenserver_guest_powerstate.XenServerVM(fake_ansible_module)
state_changed = vm.set_power_state(None)
mocked_set_vm_power_state.assert_called_once_with(fake_ansible_module, fake_xenapi_ref('VM'), None, 1)
assert state_changed == power_state[0]
assert vm.vm_params['power_state'] == power_state[1].capitalize()
@pytest.mark.parametrize('patch_ansible_module',
testcase_module_params_state_present['params'],
ids=testcase_module_params_state_present['ids'],
indirect=True)
def test_xenserver_guest_powerstate_present(mocker, patch_ansible_module, capfd, XenAPI, xenserver_guest_powerstate):
"""
Tests regular module invocation including parsing and propagation of
module params and module output when state is set to present.
"""
fake_vm_facts = {"fake-vm-fact": True}
mocker.patch('ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.get_object_ref',
return_value=fake_xenapi_ref('VM'))
mocker.patch('ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.gather_vm_params', return_value={})
mocker.patch('ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.gather_vm_facts',
return_value=fake_vm_facts)
mocked_set_vm_power_state = mocker.patch(
'ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.set_vm_power_state',
return_value=(True, "somenewstate"))
mocked_wait_for_vm_ip_address = mocker.patch(
'ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.wait_for_vm_ip_address',
return_value={})
mocked_xenapi = mocker.patch.object(XenAPI.Session, 'xenapi', create=True)
mocked_returns = {
"pool.get_all.return_value": [fake_xenapi_ref('pool')],
"pool.get_default_SR.return_value": fake_xenapi_ref('SR'),
}
mocked_xenapi.configure_mock(**mocked_returns)
mocker.patch('ansible_collections.community.general.plugins.module_utils.xenserver.get_xenserver_version', return_value=[7, 2, 0])
with pytest.raises(SystemExit):
xenserver_guest_powerstate.main()
out, err = capfd.readouterr()
result = json.loads(out)
mocked_set_vm_power_state.assert_not_called()
mocked_wait_for_vm_ip_address.assert_not_called()
assert result['changed'] is False
assert result['instance'] == fake_vm_facts
@pytest.mark.parametrize('patch_ansible_module',
testcase_module_params_state_other['params'],
ids=testcase_module_params_state_other['ids'],
indirect=True)
def test_xenserver_guest_powerstate_other(mocker, patch_ansible_module, capfd, XenAPI, xenserver_guest_powerstate):
"""
Tests regular module invocation including parsing and propagation of
module params and module output when state is set to other value than
present.
"""
fake_vm_facts = {"fake-vm-fact": True}
mocker.patch('ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.get_object_ref',
return_value=fake_xenapi_ref('VM'))
mocker.patch('ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.gather_vm_params', return_value={})
mocker.patch('ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.gather_vm_facts', return_value=fake_vm_facts)
mocked_set_vm_power_state = mocker.patch(
'ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.set_vm_power_state',
return_value=(True, "somenewstate"))
mocked_wait_for_vm_ip_address = mocker.patch(
'ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.wait_for_vm_ip_address',
return_value={})
mocked_xenapi = mocker.patch.object(XenAPI.Session, 'xenapi', create=True)
mocked_returns = {
"pool.get_all.return_value": [fake_xenapi_ref('pool')],
"pool.get_default_SR.return_value": fake_xenapi_ref('SR'),
}
mocked_xenapi.configure_mock(**mocked_returns)
mocker.patch('ansible_collections.community.general.plugins.module_utils.xenserver.get_xenserver_version', return_value=[7, 2, 0])
with pytest.raises(SystemExit):
xenserver_guest_powerstate.main()
out, err = capfd.readouterr()
result = json.loads(out)
mocked_set_vm_power_state.assert_called_once()
mocked_wait_for_vm_ip_address.assert_not_called()
assert result['changed'] is True
assert result['instance'] == fake_vm_facts
@pytest.mark.parametrize('patch_ansible_module',
testcase_module_params_wait['params'],
ids=testcase_module_params_wait['ids'],
indirect=True)
def test_xenserver_guest_powerstate_wait(mocker, patch_ansible_module, capfd, XenAPI, xenserver_guest_powerstate):
"""
Tests regular module invocation including parsing and propagation of
module params and module output when wait_for_ip_address option is used.
"""
fake_vm_facts = {"fake-vm-fact": True}
mocker.patch('ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.get_object_ref',
return_value=fake_xenapi_ref('VM'))
mocker.patch('ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.gather_vm_params', return_value={})
mocker.patch('ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.gather_vm_facts', return_value=fake_vm_facts)
mocked_set_vm_power_state = mocker.patch(
'ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.set_vm_power_state',
return_value=(True, "somenewstate"))
mocked_wait_for_vm_ip_address = mocker.patch(
'ansible_collections.community.general.plugins.modules.cloud.xenserver.xenserver_guest_powerstate.wait_for_vm_ip_address',
return_value={})
mocked_xenapi = mocker.patch.object(XenAPI.Session, 'xenapi', create=True)
mocked_returns = {
"pool.get_all.return_value": [fake_xenapi_ref('pool')],
"pool.get_default_SR.return_value": fake_xenapi_ref('SR'),
}
mocked_xenapi.configure_mock(**mocked_returns)
mocker.patch('ansible_collections.community.general.plugins.module_utils.xenserver.get_xenserver_version', return_value=[7, 2, 0])
with pytest.raises(SystemExit):
xenserver_guest_powerstate.main()
out, err = capfd.readouterr()
result = json.loads(out)
mocked_wait_for_vm_ip_address.assert_called_once()
assert result['instance'] == fake_vm_facts

View file

@ -0,0 +1,28 @@
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
import json
import pytest
from ansible.module_utils.six import string_types
from ansible.module_utils._text import to_bytes
from ansible.module_utils.common._collections_compat import MutableMapping
@pytest.fixture
def patch_ansible_module(request, mocker):
if isinstance(request.param, string_types):
args = request.param
elif isinstance(request.param, MutableMapping):
if 'ANSIBLE_MODULE_ARGS' not in request.param:
request.param = {'ANSIBLE_MODULE_ARGS': request.param}
if '_ansible_remote_tmp' not in request.param['ANSIBLE_MODULE_ARGS']:
request.param['ANSIBLE_MODULE_ARGS']['_ansible_remote_tmp'] = '/tmp'
if '_ansible_keep_remote_files' not in request.param['ANSIBLE_MODULE_ARGS']:
request.param['ANSIBLE_MODULE_ARGS']['_ansible_keep_remote_files'] = False
args = json.dumps(request.param)
else:
raise Exception('Malformed data to the patch_ansible_module pytest fixture')
mocker.patch('ansible.module_utils.basic._ANSIBLE_ARGS', to_bytes(args))

View file

@ -0,0 +1,147 @@
# -*- coding: utf-8 -*-
import io
import json
import re
import uuid
from urllib3.response import HTTPResponse
from ansible_collections.community.general.tests.unit.compat.mock import patch
from ansible.module_utils._text import to_bytes
from ansible_collections.community.general.plugins.modules.monitoring import circonus_annotation
from ansible_collections.community.general.tests.unit.plugins.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase, set_module_args
class TestCirconusAnnotation(ModuleTestCase):
def setUp(self):
super(TestCirconusAnnotation, self).setUp()
self.module = circonus_annotation
def tearDown(self):
super(TestCirconusAnnotation, self).tearDown()
def test_without_required_parameters(self):
"""Failure must occurs when all parameters are missing"""
with self.assertRaises(AnsibleFailJson):
set_module_args({})
self.module.main()
def test_add_annotation(self):
"""Check that result is changed"""
set_module_args({
'category': 'test category',
'description': 'test description',
'title': 'test title',
'api_key': str(uuid.uuid4()),
})
cid = '/annotation/100000'
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
data = {
'_cid': cid,
'_created': 1502146995,
'_last_modified': 1502146995,
'_last_modified_by': '/user/1000',
'category': 'test category',
'description': 'test description',
'rel_metrics': [],
'start': 1502145480,
'stop': None,
'title': 'test title',
}
raw = to_bytes(json.dumps(data))
resp = HTTPResponse(body=io.BytesIO(raw), preload_content=False)
resp.status = 200
resp.reason = 'OK'
resp.headers = {'X-Circonus-API-Version': '2.00'}
return self.build_response(request, resp)
with patch('requests.adapters.HTTPAdapter.send', autospec=True, side_effect=send) as send:
with self.assertRaises(AnsibleExitJson) as result:
self.module.main()
self.assertTrue(result.exception.args[0]['changed'])
self.assertEqual(result.exception.args[0]['annotation']['_cid'], cid)
self.assertEqual(send.call_count, 1)
def test_add_annotation_unicode(self):
"""Check that result is changed.
Note: it seems there is a bug which prevent to create an annotation
with a non-ASCII category if this category already exists, in such
case an Internal Server Error (500) occurs."""
set_module_args({
'category': 'new catégorÿ',
'description': 'test description',
'title': 'test title',
'api_key': str(uuid.uuid4()),
})
cid = '/annotation/100000'
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
data = {
'_cid': '/annotation/100000',
'_created': 1502236928,
'_last_modified': 1502236928,
'_last_modified_by': '/user/1000',
# use res['annotation']['category'].encode('latin1').decode('utf8')
'category': u'new cat\xc3\xa9gor\xc3\xbf',
'description': 'test description',
'rel_metrics': [],
'start': 1502236927,
'stop': 1502236927,
'title': 'test title',
}
raw = to_bytes(json.dumps(data), encoding='latin1')
resp = HTTPResponse(body=io.BytesIO(raw), preload_content=False)
resp.status = 200
resp.reason = 'OK'
resp.headers = {'X-Circonus-API-Version': '2.00'}
return self.build_response(request, resp)
with patch('requests.adapters.HTTPAdapter.send', autospec=True, side_effect=send) as send:
with self.assertRaises(AnsibleExitJson) as result:
self.module.main()
self.assertTrue(result.exception.args[0]['changed'])
self.assertEqual(result.exception.args[0]['annotation']['_cid'], cid)
self.assertEqual(send.call_count, 1)
def test_auth_failure(self):
"""Check that an error is raised when authentication failed"""
set_module_args({
'category': 'test category',
'description': 'test description',
'title': 'test title',
'api_key': str(uuid.uuid4()),
})
cid = '/annotation/100000'
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
data = {
'_cid': cid,
'_created': 1502146995,
'_last_modified': 1502146995,
'_last_modified_by': '/user/1000',
'category': 'test category',
'description': 'test description',
'rel_metrics': [],
'start': 1502145480,
'stop': None,
'title': 'test title',
}
raw = to_bytes(json.dumps(data))
resp = HTTPResponse(body=io.BytesIO(raw), preload_content=False)
resp.status = 403
resp.reason = 'Forbidden'
resp.headers = {'X-Circonus-API-Version': '2.00'}
return self.build_response(request, resp)
with patch('requests.adapters.HTTPAdapter.send', autospec=True, side_effect=send) as send:
with self.assertRaises(AnsibleFailJson) as result:
self.module.main()
self.assertTrue(result.exception.args[0]['failed'])
self.assertTrue(re.match(r'\b403\b', result.exception.args[0]['reason']))
self.assertEqual(send.call_count, 1)

View file

@ -0,0 +1,96 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2018, Ansible Project
# Copyright (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from ansible_collections.community.general.plugins.modules.monitoring import icinga2_feature
from ansible_collections.community.general.tests.unit.plugins.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase, set_module_args
from ansible_collections.community.general.tests.unit.compat.mock import patch
from ansible.module_utils import basic
def get_bin_path(*args, **kwargs):
"""Function to return path of icinga2 binary."""
return "/bin/icinga2"
class TestIcinga2Feature(ModuleTestCase):
"""Main class for testing icinga2_feature module."""
def setUp(self):
"""Setup."""
super(TestIcinga2Feature, self).setUp()
self.module = icinga2_feature
self.mock_get_bin_path = patch.object(basic.AnsibleModule, 'get_bin_path', get_bin_path)
self.mock_get_bin_path.start()
self.addCleanup(self.mock_get_bin_path.stop) # ensure that the patching is 'undone'
def tearDown(self):
"""Teardown."""
super(TestIcinga2Feature, self).tearDown()
def test_without_required_parameters(self):
"""Failure must occurs when all parameters are missing."""
with self.assertRaises(AnsibleFailJson):
set_module_args({})
self.module.main()
def test_enable_feature(self):
"""Check that result is changed."""
set_module_args({
'name': 'api',
})
with patch.object(basic.AnsibleModule, 'run_command') as run_command:
run_command.return_value = 0, '', '' # successful execution, no output
with self.assertRaises(AnsibleExitJson) as result:
icinga2_feature.main()
self.assertTrue(result.exception.args[0]['changed'])
self.assertEqual(run_command.call_count, 2)
self.assertEqual(run_command.call_args[0][0][-1], 'api')
def test_enable_feature_with_check_mode(self):
"""Check that result is changed in check mode."""
set_module_args({
'name': 'api',
'_ansible_check_mode': True,
})
with patch.object(basic.AnsibleModule, 'run_command') as run_command:
run_command.return_value = 0, '', '' # successful execution, no output
with self.assertRaises(AnsibleExitJson) as result:
icinga2_feature.main()
self.assertTrue(result.exception.args[0]['changed'])
self.assertEqual(run_command.call_count, 1)
def test_disable_feature(self):
"""Check that result is changed."""
set_module_args({
'name': 'api',
'state': 'absent'
})
with patch.object(basic.AnsibleModule, 'run_command') as run_command:
run_command.return_value = 0, '', '' # successful execution, no output
with self.assertRaises(AnsibleExitJson) as result:
icinga2_feature.main()
self.assertTrue(result.exception.args[0]['changed'])
self.assertEqual(run_command.call_count, 2)
self.assertEqual(run_command.call_args[0][0][-1], 'api')
def test_disable_feature_with_check_mode(self):
"""Check that result is changed in check mode."""
set_module_args({
'name': 'api',
'state': 'absent',
'_ansible_check_mode': True,
})
with patch.object(basic.AnsibleModule, 'run_command') as run_command:
run_command.return_value = 0, '', '' # successful execution, no output
with self.assertRaises(AnsibleExitJson) as result:
icinga2_feature.main()
self.assertTrue(result.exception.args[0]['changed'])
self.assertEqual(run_command.call_count, 1)

View file

@ -0,0 +1,123 @@
from ansible_collections.community.general.tests.unit.compat import unittest
from ansible_collections.community.general.plugins.modules.monitoring import pagerduty
import json
class PagerDutyTest(unittest.TestCase):
def setUp(self):
self.pd = pagerduty.PagerDutyRequest(module=pagerduty, name='name', user='user', token='token')
def _assert_ongoing_maintenance_windows(self, module, url, headers):
self.assertEqual('https://api.pagerduty.com/maintenance_windows?filter=ongoing', url)
return object(), {'status': 200}
def _assert_ongoing_window_with_v1_compatible_header(self, module, url, headers, data=None, method=None):
self.assertDictContainsSubset(
{'Accept': 'application/vnd.pagerduty+json;version=2'},
headers,
'Accept:application/vnd.pagerduty+json;version=2 HTTP header not found'
)
return object(), {'status': 200}
def _assert_create_a_maintenance_window_url(self, module, url, headers, data=None, method=None):
self.assertEqual('https://api.pagerduty.com/maintenance_windows', url)
return object(), {'status': 201}
def _assert_create_a_maintenance_window_http_method(self, module, url, headers, data=None, method=None):
self.assertEqual('POST', method)
return object(), {'status': 201}
def _assert_create_a_maintenance_window_from_header(self, module, url, headers, data=None, method=None):
self.assertDictContainsSubset(
{'From': 'requester_id'},
headers,
'From:requester_id HTTP header not found'
)
return object(), {'status': 201}
def _assert_create_window_with_v1_compatible_header(self, module, url, headers, data=None, method=None):
self.assertDictContainsSubset(
{'Accept': 'application/vnd.pagerduty+json;version=2'},
headers,
'Accept:application/vnd.pagerduty+json;version=2 HTTP header not found'
)
return object(), {'status': 201}
def _assert_create_window_payload(self, module, url, headers, data=None, method=None):
payload = json.loads(data)
window_data = payload['maintenance_window']
self.assertTrue('start_time' in window_data, '"start_time" is requiered attribute')
self.assertTrue('end_time' in window_data, '"end_time" is requiered attribute')
self.assertTrue('services' in window_data, '"services" is requiered attribute')
return object(), {'status': 201}
def _assert_create_window_single_service(self, module, url, headers, data=None, method=None):
payload = json.loads(data)
window_data = payload['maintenance_window']
services = window_data['services']
self.assertEqual(
[{'id': 'service_id', 'type': 'service_reference'}],
services
)
return object(), {'status': 201}
def _assert_create_window_multiple_service(self, module, url, headers, data=None, method=None):
payload = json.loads(data)
window_data = payload['maintenance_window']
services = window_data['services']
print(services)
self.assertEqual(
[
{'id': 'service_id_1', 'type': 'service_reference'},
{'id': 'service_id_2', 'type': 'service_reference'},
{'id': 'service_id_3', 'type': 'service_reference'},
],
services
)
return object(), {'status': 201}
def _assert_absent_maintenance_window_url(self, module, url, headers, method=None):
self.assertEqual('https://api.pagerduty.com/maintenance_windows/window_id', url)
return object(), {'status': 204}
def _assert_absent_window_with_v1_compatible_header(self, module, url, headers, method=None):
self.assertDictContainsSubset(
{'Accept': 'application/vnd.pagerduty+json;version=2'},
headers,
'Accept:application/vnd.pagerduty+json;version=2 HTTP header not found'
)
return object(), {'status': 204}
def test_ongoing_maintenance_windos_url(self):
self.pd.ongoing(http_call=self._assert_ongoing_maintenance_windows)
def test_ongoing_maintenance_windos_compatibility_header(self):
self.pd.ongoing(http_call=self._assert_ongoing_window_with_v1_compatible_header)
def test_create_maintenance_window_url(self):
self.pd.create('requester_id', 'service', 1, 0, 'desc', http_call=self._assert_create_a_maintenance_window_url)
def test_create_maintenance_window_http_method(self):
self.pd.create('requester_id', 'service', 1, 0, 'desc', http_call=self._assert_create_a_maintenance_window_http_method)
def test_create_maintenance_from_header(self):
self.pd.create('requester_id', 'service', 1, 0, 'desc', http_call=self._assert_create_a_maintenance_window_from_header)
def test_create_maintenance_compatibility_header(self):
self.pd.create('requester_id', 'service', 1, 0, 'desc', http_call=self._assert_create_window_with_v1_compatible_header)
def test_create_maintenance_request_payload(self):
self.pd.create('requester_id', 'service', 1, 0, 'desc', http_call=self._assert_create_window_payload)
def test_create_maintenance_for_single_service(self):
self.pd.create('requester_id', 'service_id', 1, 0, 'desc', http_call=self._assert_create_window_single_service)
def test_create_maintenance_for_multiple_services(self):
self.pd.create('requester_id', ['service_id_1', 'service_id_2', 'service_id_3'], 1, 0, 'desc', http_call=self._assert_create_window_multiple_service)
def test_absent_maintenance_window_url(self):
self.pd.absent('window_id', http_call=self._assert_absent_maintenance_window_url)
def test_absent_maintenance_compatibility_header(self):
self.pd.absent('window_id', http_call=self._assert_absent_window_with_v1_compatible_header)

View file

@ -0,0 +1,39 @@
from ansible_collections.community.general.tests.unit.compat import unittest
from ansible_collections.community.general.plugins.modules.monitoring import pagerduty_alert
class PagerDutyAlertsTest(unittest.TestCase):
def _assert_incident_api(self, module, url, method, headers):
self.assertTrue('https://api.pagerduty.com/incidents' in url, 'url must contain REST API v2 network path')
self.assertTrue('service_ids%5B%5D=service_id' in url, 'url must contain service id to filter incidents')
self.assertTrue('sort_by=incident_number%3Adesc' in url, 'url should contain sorting parameter')
self.assertTrue('time_zone=UTC' in url, 'url should contain time zone parameter')
return Response(), {'status': 200}
def _assert_compatibility_header(self, module, url, method, headers):
self.assertDictContainsSubset(
{'Accept': 'application/vnd.pagerduty+json;version=2'},
headers,
'Accept:application/vnd.pagerduty+json;version=2 HTTP header not found'
)
return Response(), {'status': 200}
def _assert_incident_key(self, module, url, method, headers):
self.assertTrue('incident_key=incident_key_value' in url, 'url must contain incident key')
return Response(), {'status': 200}
def test_incident_url(self):
pagerduty_alert.check(None, 'name', 'state', 'service_id', 'integration_key', 'api_key', http_call=self._assert_incident_api)
def test_compatibility_header(self):
pagerduty_alert.check(None, 'name', 'state', 'service_id', 'integration_key', 'api_key', http_call=self._assert_compatibility_header)
def test_incident_key_in_url_when_it_is_given(self):
pagerduty_alert.check(
None, 'name', 'state', 'service_id', 'integration_key', 'api_key', incident_key='incident_key_value', http_call=self._assert_incident_key
)
class Response(object):
def read(self):
return '{"incidents":[{"id": "incident_id", "status": "triggered"}]}'

View file

@ -0,0 +1,159 @@
# 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
from ansible_collections.community.general.plugins.modules.net_tools.nios import nios_a_record
from ansible_collections.community.general.plugins.module_utils.net_tools.nios import api
from ansible_collections.community.general.tests.unit.compat.mock import patch, MagicMock, Mock
from .test_nios_module import TestNiosModule, load_fixture
class TestNiosARecordModule(TestNiosModule):
module = nios_a_record
def setUp(self):
super(TestNiosARecordModule, self).setUp()
self.module = MagicMock(name='ansible_collections.community.general.plugins.modules.net_tools.nios.nios_a_record.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_a_record.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_a_record.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosARecordModule, self).tearDown()
self.mock_wapi.stop()
self.mock_wapi_run.stop()
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def test_nios_a_record_create(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'a.ansible.com',
'ipv4': '192.168.10.1', 'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"name": {"ib_req": True},
"ipv4": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi.__dict__)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'name': self.module._check_type_dict().__getitem__(),
'ipv4': '192.168.10.1'})
def test_nios_a_record_update_comment(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'a.ansible.com', 'ipv4': '192.168.10.1',
'comment': 'updated comment', 'extattrs': None}
test_object = [
{
"comment": "test comment",
"_ref": "arecord/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"name": "a.ansible.com",
"ipv4": "192.168.10.1",
"extattrs": {}
}
]
test_spec = {
"name": {"ib_req": True},
"ipv4": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
def test_nios_a_record_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'name': 'a.ansible.com', 'ipv4': '192.168.10.1',
'comment': None, 'extattrs': None}
ref = "arecord/ZG5zLm5ldHdvcmtfdmlldyQw:default/false"
test_object = [{
"comment": "test comment",
"_ref": ref,
"name": "a.ansible.com",
"ipv4": "192.168.10.1",
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"name": {"ib_req": True},
"ipv4": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)
def test_nios_a_record_update_record_name(self):
self.module.params = {'provider': None, 'state': 'present', 'name': {'new_name': 'a_new.ansible.com', 'old_name': 'a.ansible.com'},
'comment': 'comment', 'extattrs': None}
test_object = [
{
"comment": "test comment",
"_ref": "arecord/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"name": "a_new.ansible.com",
"old_name": "a.ansible.com",
"extattrs": {}
}
]
test_spec = {
"name": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.update_object.called_once_with(test_object)

View file

@ -0,0 +1,159 @@
# 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
from ansible_collections.community.general.plugins.modules.net_tools.nios import nios_aaaa_record
from ansible_collections.community.general.plugins.module_utils.net_tools.nios import api
from ansible_collections.community.general.tests.unit.compat.mock import patch, MagicMock, Mock
from .test_nios_module import TestNiosModule, load_fixture
class TestNiosAAAARecordModule(TestNiosModule):
module = nios_aaaa_record
def setUp(self):
super(TestNiosAAAARecordModule, self).setUp()
self.module = MagicMock(name='ansible_collections.community.general.plugins.modules.net_tools.nios.nios_aaaa_record.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_aaaa_record.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_aaaa_record.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosAAAARecordModule, self).tearDown()
self.mock_wapi.stop()
self.mock_wapi_run.stop()
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def test_nios_aaaa_record_create(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'aaaa.ansible.com',
'ipv6': '2001:0db8:85a3:0000:0000:8a2e:0370:7334', 'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"name": {"ib_req": True},
"ipv6": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi.__dict__)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'name': self.module._check_type_dict().__getitem__(),
'ipv6': '2001:0db8:85a3:0000:0000:8a2e:0370:7334'})
def test_nios_aaaa_record_update_comment(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'aaaa.ansible.com',
'ipv6': '2001:0db8:85a3:0000:0000:8a2e:0370:7334', 'comment': 'updated comment', 'extattrs': None}
test_object = [
{
"comment": "test comment",
"_ref": "aaaarecord/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"name": "aaaa.ansible.com",
"ipv6": "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
"extattrs": {}
}
]
test_spec = {
"name": {"ib_req": True},
"ipv6": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
def test_nios_aaaa_record_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'name': 'aaaa.ansible.com',
'ipv6': '2001:0db8:85a3:0000:0000:8a2e:0370:7334', 'comment': None, 'extattrs': None}
ref = "aaaarecord/ZG5zLm5ldHdvcmtfdmlldyQw:default/false"
test_object = [{
"comment": "test comment",
"_ref": ref,
"name": "aaaa.ansible.com",
"ipv6": "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"name": {"ib_req": True},
"ipv6": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)
def test_nios_aaaa_record_update_record_name(self):
self.module.params = {'provider': None, 'state': 'present', 'name': {'new_name': 'aaaa_new.ansible.com', 'old_name': 'aaaa.ansible.com'},
'comment': 'comment', 'extattrs': None}
test_object = [
{
"comment": "test comment",
"_ref": "aaaarecord/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"name": "aaaa_new.ansible.com",
"old_name": "aaaa.ansible.com",
"extattrs": {}
}
]
test_spec = {
"name": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.update_object.called_once_with(test_object)

View file

@ -0,0 +1,133 @@
# 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
from ansible_collections.community.general.plugins.modules.net_tools.nios import nios_cname_record
from ansible_collections.community.general.plugins.module_utils.net_tools.nios import api
from ansible_collections.community.general.tests.unit.compat.mock import patch, MagicMock, Mock
from .test_nios_module import TestNiosModule, load_fixture
class TestNiosCNameRecordModule(TestNiosModule):
module = nios_cname_record
def setUp(self):
super(TestNiosCNameRecordModule, self).setUp()
self.module = MagicMock(name='ansible_collections.community.general.plugins.modules.net_tools.nios.nios_cname_record.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_cname_record.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_cname_record.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosCNameRecordModule, self).tearDown()
self.mock_wapi.stop()
self.mock_wapi_run.stop()
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def test_nios_a_record_create(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'cname.ansible.com',
'canonical': 'realhost.ansible.com', 'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"name": {"ib_req": True},
"canonical": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi.__dict__)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'name': self.module._check_type_dict().__getitem__(),
'canonical': 'realhost.ansible.com'})
def test_nios_a_record_update_comment(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'cname.ansible.com',
'canonical': 'realhost.ansible.com', 'comment': 'updated comment', 'extattrs': None}
test_object = [
{
"comment": "test comment",
"_ref": "cnamerecord/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"name": "cname.ansible.com",
"canonical": "realhost.ansible.com",
"extattrs": {}
}
]
test_spec = {
"name": {"ib_req": True},
"canonical": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
def test_nios_a_record_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'name': 'cname.ansible.com',
'canonical': 'realhost.ansible.com', 'comment': None, 'extattrs': None}
ref = "cnamerecord/ZG5zLm5ldHdvcmtfdmlldyQw:default/false"
test_object = [{
"comment": "test comment",
"_ref": ref,
"name": "cname.ansible.com",
"canonical": "realhost.ansible.com",
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"name": {"ib_req": True},
"canonical": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)

View file

@ -0,0 +1,127 @@
# 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
from ansible_collections.community.general.plugins.modules.net_tools.nios import nios_dns_view
from ansible_collections.community.general.plugins.module_utils.net_tools.nios import api
from ansible_collections.community.general.tests.unit.compat.mock import patch, MagicMock, Mock
from .test_nios_module import TestNiosModule, load_fixture
class TestNiosDnsViewModule(TestNiosModule):
module = nios_dns_view
def setUp(self):
super(TestNiosDnsViewModule, self).setUp()
self.module = MagicMock(name='ansible_collections.community.general.plugins.modules.net_tools.nios.nios_dns_view.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_dns_view.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_dns_view.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosDnsViewModule, self).tearDown()
self.mock_wapi.stop()
self.mock_wapi_run.stop()
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def test_nios_dns_view_create(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'ansible-dns',
'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"name": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'name': self.module._check_type_dict().__getitem__()})
def test_nios_dns_view_update_comment(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'ansible-dns',
'comment': 'updated comment', 'extattrs': None}
test_object = [
{
"comment": "test comment",
"_ref": "dnsview/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"name": "ansible-dns",
"extattrs": {}
}
]
test_spec = {
"name": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
def test_nios_dns_view_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'name': 'ansible-dns',
'comment': None, 'extattrs': None}
ref = "dnsview/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/false"
test_object = [{
"comment": "test comment",
"_ref": ref,
"name": "ansible-dns",
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"name": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)

View file

@ -0,0 +1,201 @@
# 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
from ansible_collections.community.general.plugins.module_utils.net_tools.nios import api
from ansible_collections.community.general.plugins.modules.net_tools.nios import nios_fixed_address
from ansible_collections.community.general.tests.unit.compat.mock import patch, MagicMock, Mock
from .test_nios_module import TestNiosModule, load_fixture
class TestNiosFixedAddressModule(TestNiosModule):
module = nios_fixed_address
def setUp(self):
super(TestNiosFixedAddressModule, self).setUp()
self.module = MagicMock(name='ansible_collections.community.general.plugins.modules.net_tools.nios.nios_fixed_address.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_fixed_address.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_fixed_address.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosFixedAddressModule, self).tearDown()
self.mock_wapi.stop()
self.mock_wapi_run.stop()
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def test_nios_fixed_address_ipv4_create(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'test_fa', 'ipaddr': '192.168.10.1', 'mac': '08:6d:41:e8:fd:e8',
'network': '192.168.10.0/24', 'network_view': 'default', 'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"name": {},
"ipaddr": {"ib_req": True},
"mac": {"ib_req": True},
"network": {"ib_req": True},
"network_view": {},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'name': 'test_fa', 'ipaddr': '192.168.10.1', 'mac': '08:6d:41:e8:fd:e8',
'network': '192.168.10.0/24', 'network_view': 'default'})
def test_nios_fixed_address_ipv4_dhcp_update(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'test_fa', 'ipaddr': '192.168.10.1', 'mac': '08:6d:41:e8:fd:e8',
'network': '192.168.10.0/24', 'network_view': 'default', 'comment': 'updated comment', 'extattrs': None}
test_object = [
{
"comment": "test comment",
"name": "test_fa",
"_ref": "network/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"ipaddr": "192.168.10.1",
"mac": "08:6d:41:e8:fd:e8",
"network": "192.168.10.0/24",
"network_view": "default",
"extattrs": {'options': {'name': 'test', 'value': 'ansible.com'}}
}
]
test_spec = {
"name": {},
"ipaddr": {"ib_req": True},
"mac": {"ib_req": True},
"network": {"ib_req": True},
"network_view": {},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
def test_nios_fixed_address_ipv4_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'name': 'test_fa', 'ipaddr': '192.168.10.1', 'mac': '08:6d:41:e8:fd:e8',
'network': '192.168.10.0/24', 'network_view': 'default', 'comment': None, 'extattrs': None}
ref = "fixedaddress/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/false"
test_object = [{
"comment": "test comment",
"name": "test_fa",
"_ref": ref,
"ipaddr": "192.168.10.1",
"mac": "08:6d:41:e8:fd:e8",
"network": "192.168.10.0/24",
"network_view": "default",
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"name": {},
"ipaddr": {"ib_req": True},
"mac": {"ib_req": True},
"network": {"ib_req": True},
"network_view": {},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)
def test_nios_fixed_address_ipv6_create(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'test_fa', 'ipaddr': 'fe80::1/10', 'mac': '08:6d:41:e8:fd:e8',
'network': 'fe80::/64', 'network_view': 'default', 'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"name": {},
"ipaddr": {"ib_req": True},
"mac": {"ib_req": True},
"network": {"ib_req": True},
"network_view": {},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'name': 'test_fa', 'ipaddr': 'fe80::1/10', 'mac': '08:6d:41:e8:fd:e8',
'network': 'fe80::/64', 'network_view': 'default'})
def test_nios_fixed_address_ipv6_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'name': 'test_fa', 'ipaddr': 'fe80::1/10', 'mac': '08:6d:41:e8:fd:e8',
'network': 'fe80::/64', 'network_view': 'default', 'comment': None, 'extattrs': None}
ref = "ipv6fixedaddress/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/false"
test_object = [{
"comment": "test comment",
"name": "test_fa",
"_ref": ref,
"ipaddr": "fe80::1/10",
"mac": "08:6d:41:e8:fd:e8",
"network": "fe80::/64",
"network_view": "default",
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"name": {},
"ipaddr": {"ib_req": True},
"mac": {"ib_req": True},
"network": {"ib_req": True},
"network_view": {},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)

View file

@ -0,0 +1,152 @@
# 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
from ansible_collections.community.general.plugins.modules.net_tools.nios import nios_host_record
from ansible_collections.community.general.plugins.module_utils.net_tools.nios import api
from ansible_collections.community.general.tests.unit.compat.mock import patch, MagicMock, Mock
from .test_nios_module import TestNiosModule, load_fixture
class TestNiosHostRecordModule(TestNiosModule):
module = nios_host_record
def setUp(self):
super(TestNiosHostRecordModule, self).setUp()
self.module = MagicMock(name='ansible_collections.community.general.plugins.modules.net_tools.nios.nios_host_record.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_host_record.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_host_record.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosHostRecordModule, self).tearDown()
self.mock_wapi.stop()
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def test_nios_host_record_create(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'ansible',
'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"name": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'name': self.module._check_type_dict().__getitem__()})
def test_nios_host_record_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'name': 'ansible',
'comment': None, 'extattrs': None}
ref = "record:host/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/false"
test_object = [{
"comment": "test comment",
"_ref": ref,
"name": "ansible",
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"name": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)
def test_nios_host_record_update_comment(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'default',
'comment': 'updated comment', 'extattrs': None}
test_object = [
{
"comment": "test comment",
"_ref": "record:host/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"name": "default",
"extattrs": {}
}
]
test_spec = {
"name": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.update_object.called_once_with(test_object)
def test_nios_host_record_update_record_name(self):
self.module.params = {'provider': None, 'state': 'present', 'name': {'new_name': 'default', 'old_name': 'old_default'},
'comment': 'comment', 'extattrs': None}
test_object = [
{
"comment": "test comment",
"_ref": "record:host/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"name": "default",
"old_name": "old_default",
"extattrs": {}
}
]
test_spec = {
"name": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.update_object.called_once_with(test_object)

View file

@ -0,0 +1,162 @@
# 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
from ansible_collections.community.general.plugins.module_utils.net_tools.nios import api
from ansible_collections.community.general.plugins.modules.net_tools.nios import nios_member
from ansible_collections.community.general.tests.unit.compat.mock import patch, MagicMock, Mock
from .test_nios_module import TestNiosModule, load_fixture
class TestNiosMemberModule(TestNiosModule):
module = nios_member
def setUp(self):
super(TestNiosMemberModule, self).setUp()
self.module = MagicMock(name='ansible_collections.community.general.plugins.modules.net_tools.nios.nios_member.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_member.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_member.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosMemberModule, self).tearDown()
self.mock_wapi.stop()
self.mock_wapi_run.stop()
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def test_nios_member_create(self):
self.module.params = {'provider': None, 'state': 'present', 'host_name': 'test_member',
'vip_setting': {'address': '192.168.1.110', 'subnet_mask': '255.255.255.0', 'gateway': '192.168.1.1'},
'config_addr_type': 'IPV4', 'platform': 'VNIOS', 'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"host_name": {"ib_req": True},
"vip_setting": {},
"config_addr_type": {},
"platform": {},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'host_name': 'test_member',
'vip_setting': {'address': '192.168.1.110', 'subnet_mask': '255.255.255.0',
'gateway': '192.168.1.1'},
'config_addr_type': 'IPV4', 'platform': 'VNIOS'})
def test_nios_member_update(self):
self.module.params = {'provider': None, 'state': 'present', 'host_name': 'test_member',
'vip_setting': {'address': '192.168.1.110', 'subnet_mask': '255.255.255.0', 'gateway': '192.168.1.1'},
'config_addr_type': 'IPV4', 'platform': 'VNIOS', 'comment': 'updated comment', 'extattrs': None}
test_object = [
{
"comment": "Created with Ansible",
"_ref": "member/b25lLnZpcnR1YWxfbm9kZSQ3:member01.ansible-dev.com",
"config_addr_type": "IPV4",
"host_name": "member01.ansible-dev.com",
"platform": "VNIOS",
"service_type_configuration": "ALL_V4",
"vip_setting":
{
"address": "192.168.1.100",
"dscp": 0,
"gateway": "192.168.1.1",
"primary": True,
"subnet_mask": "255.255.255.0",
"use_dscp": False
}
}
]
test_spec = {
"host_name": {"ib_req": True},
"vip_setting": {},
"config_addr_type": {},
"platform": {},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
def test_nios_member_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'host_name': 'test_member',
'vip_setting': {'address': '192.168.1.110', 'subnet_mask': '255.255.255.0', 'gateway': '192.168.1.1'},
'config_addr_type': 'IPV4', 'platform': 'VNIOS', 'comment': 'updated comment', 'extattrs': None}
ref = "member/b25lLnZpcnR1YWxfbm9kZSQ3:member01.ansible-dev.com"
test_object = [
{
"comment": "Created with Ansible",
"_ref": "member/b25lLnZpcnR1YWxfbm9kZSQ3:member01.ansible-dev.com",
"config_addr_type": "IPV4",
"host_name": "member01.ansible-dev.com",
"platform": "VNIOS",
"service_type_configuration": "ALL_V4",
"vip_setting":
{
"address": "192.168.1.100",
"dscp": 0,
"gateway": "192.168.1.1",
"primary": True,
"subnet_mask": "255.255.255.0",
"use_dscp": False
}
}
]
test_spec = {
"host_name": {"ib_req": True},
"vip_setting": {},
"config_addr_type": {},
"platform": {},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)

View file

@ -0,0 +1,88 @@
# (c) 2018 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 os
import json
from ansible_collections.community.general.tests.unit.plugins.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {}
def load_fixture(name):
path = os.path.join(fixture_path, name)
if path in fixture_data:
return fixture_data[path]
with open(path) as f:
data = f.read()
try:
data = json.loads(data)
except Exception:
pass
fixture_data[path] = data
return data
class TestNiosModule(ModuleTestCase):
def execute_module(self, failed=False, changed=False, commands=None, sort=True, defaults=False):
self.load_fixtures(commands)
if failed:
result = self.failed()
self.assertTrue(result['failed'], result)
else:
result = self.changed(changed)
self.assertEqual(result['changed'], changed, result)
if commands is not None:
if sort:
self.assertEqual(sorted(commands), sorted(result['commands']), result['commands'])
else:
self.assertEqual(commands, result['commands'], result['commands'])
return result
def failed(self):
with self.assertRaises(AnsibleFailJson) as exc:
self.module.main()
result = exc.exception.args[0]
self.assertTrue(result['failed'], result)
return result
def changed(self, changed=False):
with self.assertRaises(AnsibleExitJson) as exc:
self.module.main()
result = exc.exception.args[0]
self.assertEqual(result['changed'], changed, result)
return result
def load_fixtures(self, commands=None):
pass

View file

@ -0,0 +1,137 @@
# 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
from ansible_collections.community.general.plugins.modules.net_tools.nios import nios_mx_record
from ansible_collections.community.general.plugins.module_utils.net_tools.nios import api
from ansible_collections.community.general.tests.unit.compat.mock import patch, MagicMock, Mock
from .test_nios_module import TestNiosModule, load_fixture
class TestNiosMXRecordModule(TestNiosModule):
module = nios_mx_record
def setUp(self):
super(TestNiosMXRecordModule, self).setUp()
self.module = MagicMock(name='ansible_collections.community.general.plugins.modules.net_tools.nios.nios_mx_record.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_mx_record.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_mx_record.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosMXRecordModule, self).tearDown()
self.mock_wapi.stop()
self.mock_wapi_run.stop()
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def test_nios_mx_record_create(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'ansible.com',
'mx': 'mailhost.ansible.com', 'preference': 0, 'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"name": {"ib_req": True},
"mx": {"ib_req": True},
"preference": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'name': self.module._check_type_dict().__getitem__(),
'mx': 'mailhost.ansible.com', 'preference': 0})
def test_nios_mx_record_update_comment(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'ansible.com', 'mx': 'mailhost.ansible.com',
'preference': 0, 'comment': 'updated comment', 'extattrs': None}
test_object = [
{
"comment": "test comment",
"_ref": "mxrecord/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"name": "ansible.com",
"mx": "mailhost.ansible.com",
"preference": 0,
"extattrs": {}
}
]
test_spec = {
"name": {"ib_req": True},
"mx": {"ib_req": True},
"preference": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
def test_nios_mx_record_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'name': 'ansible.com', 'mx': 'mailhost.ansible.com',
'preference': 0, 'comment': None, 'extattrs': None}
ref = "mxrecord/ZG5zLm5ldHdvcmtfdmlldyQw:default/false"
test_object = [{
"comment": "test comment",
"_ref": ref,
"name": "ansible.com",
"mx": "mailhost.ansible.com",
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"name": {"ib_req": True},
"mx": {"ib_req": True},
"preference": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)

View file

@ -0,0 +1,147 @@
# 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
from ansible_collections.community.general.plugins.modules.net_tools.nios import nios_naptr_record
from ansible_collections.community.general.plugins.module_utils.net_tools.nios import api
from ansible_collections.community.general.tests.unit.compat.mock import patch, MagicMock, Mock
from .test_nios_module import TestNiosModule, load_fixture
class TestNiosNAPTRRecordModule(TestNiosModule):
module = nios_naptr_record
def setUp(self):
super(TestNiosNAPTRRecordModule, self).setUp()
self.module = MagicMock(name='ansible_collections.community.general.plugins.modules.net_tools.nios.nios_naptr_record.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_naptr_record.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_naptr_record.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosNAPTRRecordModule, self).tearDown()
self.mock_wapi.stop()
self.mock_wapi_run.stop()
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def test_nios_naptr_record_create(self):
self.module.params = {'provider': None, 'state': 'present', 'name': '*.subscriber-100.ansiblezone.com',
'order': '1000', 'preference': '10', 'replacement': 'replacement1.network.ansiblezone.com',
'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"name": {"ib_req": True},
"order": {"ib_req": True},
"preference": {"ib_req": True},
"replacement": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi.__dict__)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'name': self.module._check_type_dict().__getitem__(),
'order': '1000', 'preference': '10',
'replacement': 'replacement1.network.ansiblezone.com'})
def test_nios_naptr_record_update_comment(self):
self.module.params = {'provider': None, 'state': 'present', 'name': '*.subscriber-100.ansiblezone.com',
'order': '1000', 'preference': '10', 'replacement': 'replacement1.network.ansiblezone.com',
'comment': 'updated comment', 'extattrs': None}
test_object = [
{
"comment": "test comment",
"_ref": "naptrrecord/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"name": "*.subscriber-100.ansiblezone.com",
"order": "1000",
"preference": "10",
"replacement": "replacement1.network.ansiblezone.com",
"extattrs": {}
}
]
test_spec = {
"name": {"ib_req": True},
"order": {"ib_req": True},
"preference": {"ib_req": True},
"replacement": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
def test_nios_naptr_record_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'name': '*.subscriber-100.ansiblezone.com',
'order': '1000', 'preference': '10', 'replacement': 'replacement1.network.ansiblezone.com',
'comment': None, 'extattrs': None}
ref = "naptrrecord/ZG5zLm5ldHdvcmtfdmlldyQw:default/false"
test_object = [{
"comment": "test comment",
"_ref": ref,
"name": "*.subscriber-100.ansiblezone.com",
"order": "1000",
"preference": "10",
"replacement": "replacement1.network.ansiblezone.com",
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"name": {"ib_req": True},
"order": {"ib_req": True},
"preference": {"ib_req": True},
"replacement": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)

View file

@ -0,0 +1,248 @@
# 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
from ansible_collections.community.general.plugins.module_utils.net_tools.nios import api
from ansible_collections.community.general.plugins.modules.net_tools.nios import nios_network
from ansible_collections.community.general.tests.unit.compat.mock import patch, MagicMock, Mock
from .test_nios_module import TestNiosModule, load_fixture
class TestNiosNetworkModule(TestNiosModule):
module = nios_network
def setUp(self):
super(TestNiosNetworkModule, self).setUp()
self.module = MagicMock(name='ansible_collections.community.general.plugins.modules.net_tools.nios.nios_network.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_network.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_network.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosNetworkModule, self).tearDown()
self.mock_wapi.stop()
self.mock_wapi_run.stop()
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def test_nios_network_ipv4_create(self):
self.module.params = {'provider': None, 'state': 'present', 'network': '192.168.10.0/24',
'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"network": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'network': '192.168.10.0/24'})
def test_nios_network_ipv4_dhcp_update(self):
self.module.params = {'provider': None, 'state': 'present', 'network': '192.168.10.0/24',
'comment': 'updated comment', 'extattrs': None}
test_object = [
{
"comment": "test comment",
"_ref": "network/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"network": "192.168.10.0/24",
"extattrs": {'options': {'name': 'test', 'value': 'ansible.com'}}
}
]
test_spec = {
"network": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
def test_nios_network_ipv6_dhcp_update(self):
self.module.params = {'provider': None, 'state': 'present', 'ipv6network': 'fe80::/64',
'comment': 'updated comment', 'extattrs': None}
test_object = [
{
"comment": "test comment",
"_ref": "ipv6network/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"ipv6network": "fe80::/64",
"extattrs": {'options': {'name': 'test', 'value': 'ansible.com'}}
}
]
test_spec = {
"ipv6network": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
def test_nios_network_ipv4_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'network': '192.168.10.0/24',
'comment': None, 'extattrs': None}
ref = "network/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/false"
test_object = [{
"comment": "test comment",
"_ref": ref,
"network": "192.168.10.0/24",
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"network": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)
def test_nios_network_ipv6_create(self):
self.module.params = {'provider': None, 'state': 'present', 'ipv6network': 'fe80::/64',
'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"ipv6network": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'ipv6network': 'fe80::/64'})
def test_nios_network_ipv6_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'ipv6network': 'fe80::/64',
'comment': None, 'extattrs': None}
ref = "ipv6network/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/false"
test_object = [{
"comment": "test comment",
"_ref": ref,
"ipv6network": "fe80::/64",
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"ipv6network": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)
def test_nios_networkcontainer_ipv4_create(self):
self.module.params = {'provider': None, 'state': 'present', 'networkcontainer': '192.168.10.0/24',
'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"networkcontainer": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'networkcontainer': '192.168.10.0/24'})
def test_nios_networkcontainer_ipv4_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'networkcontainer': '192.168.10.0/24',
'comment': None, 'extattrs': None}
ref = "networkcontainer/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/false"
test_object = [{
"comment": "test comment",
"_ref": ref,
"networkcontainer": "192.168.10.0/24"
}]
test_spec = {
"networkcontainer": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)
def test_nios_networkcontainer_ipv6_create(self):
self.module.params = {'provider': None, 'state': 'present', 'ipv6networkcontainer': 'fe80::/64',
'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"ipv6networkcontainer": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'ipv6networkcontainer': 'fe80::/64'})

View file

@ -0,0 +1,156 @@
# 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
from ansible_collections.community.general.plugins.modules.net_tools.nios import nios_network_view
from ansible_collections.community.general.plugins.module_utils.net_tools.nios import api
from ansible_collections.community.general.tests.unit.compat.mock import patch, MagicMock, Mock
from .test_nios_module import TestNiosModule, load_fixture
class TestNiosNetworkViewModule(TestNiosModule):
module = nios_network_view
def setUp(self):
super(TestNiosNetworkViewModule, self).setUp()
self.module = MagicMock(name='ansible_collections.community.general.plugins.modules.net_tools.nios.nios_network_view.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_network_view.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_network_view.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosNetworkViewModule, self).tearDown()
self.mock_wapi.stop()
self.mock_wapi_run.stop()
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def test_nios_network_view_create(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'ansible',
'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"name": {"ib_req": True},
"comment": {},
"extattrs": {},
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'name': self.module._check_type_dict().__getitem__()})
def test_nios_network_view_update_comment(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'default',
'comment': 'updated comment', 'extattrs': None, 'network_view': 'default'}
test_object = [
{
"comment": "test comment",
"_ref": "networkview/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"name": "default",
"extattrs": {},
"network_view": "default"
}
]
test_spec = {
"name": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.update_object.called_once_with(test_object)
def test_nios_network_view_update_name(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'default', 'old_name': 'old_default',
'comment': 'updated comment', 'extattrs': None, 'network_view': 'default'}
test_object = [
{
"comment": "test comment",
"_ref": "networkview/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"name": "default",
"old_name": "old_default",
"extattrs": {},
"network_view": "default"
}
]
test_spec = {
"name": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.update_object.called_once_with(test_object)
def test_nios_network_view_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'name': 'ansible',
'comment': None, 'extattrs': None}
ref = "networkview/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/false"
test_object = [{
"comment": "test comment",
"_ref": ref,
"name": "ansible",
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"name": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)

View file

@ -0,0 +1,125 @@
# 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
from ansible_collections.community.general.plugins.modules.net_tools.nios import nios_nsgroup
from ansible_collections.community.general.plugins.module_utils.net_tools.nios import api
from ansible_collections.community.general.tests.unit.compat.mock import patch, MagicMock, Mock
from .test_nios_module import TestNiosModule, load_fixture
class TestNiosNSGroupModule(TestNiosModule):
module = nios_nsgroup
def setUp(self):
super(TestNiosNSGroupModule, self).setUp()
self.module = MagicMock(name='ansible_collections.community.general.plugins.modules.net_tools.nios.nios_nsgroup.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_nsgroup.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_nsgroup.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosNSGroupModule, self).tearDown()
self.mock_wapi.stop()
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def test_nios_nsgroup_create(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'my-simple-group',
'comment': None, 'grid_primary': None}
test_object = None
test_spec = {
"name": {"ib_req": True},
"comment": {},
"grid_primary": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'name': self.module._check_type_dict().__getitem__()})
def test_nios_nsgroup_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'name': 'my-simple-group',
'comment': None, 'grid_primary': None}
ref = "nsgroup/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/false"
test_object = [{
"comment": "test comment",
"_ref": ref,
"name": "my-simple-group",
"grid_primary": {'name': 'infoblox-test.example.com'}
}]
test_spec = {
"name": {"ib_req": True},
"comment": {},
"grid_primary": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)
def test_nios_nsgroup_update_comment(self):
self.module.params = {'provider': None, 'state': 'present', 'name': 'default',
'comment': 'updated comment', 'grid_primary': None}
test_object = [
{
"comment": "test comment",
"_ref": "nsgroup/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"name": "default",
"grid_primary": {}
}
]
test_spec = {
"name": {"ib_req": True},
"comment": {},
"grid_primary": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.update_object.called_once_with(test_object)

View file

@ -0,0 +1,184 @@
# 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
from ansible_collections.community.general.plugins.modules.net_tools.nios import nios_ptr_record
from ansible_collections.community.general.plugins.module_utils.net_tools.nios import api
from ansible_collections.community.general.tests.unit.compat.mock import patch, MagicMock, Mock
from .test_nios_module import TestNiosModule, load_fixture
class TestNiosPTRRecordModule(TestNiosModule):
module = nios_ptr_record
def setUp(self):
super(TestNiosPTRRecordModule, self).setUp()
self.module = MagicMock(name='ansible_collections.community.general.plugins.modules.net_tools.nios.nios_ptr_record.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_ptr_record.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_ptr_record.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosPTRRecordModule, self).tearDown()
self.mock_wapi.stop()
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def test_nios_ptr_record_create(self):
self.module.params = {'provider': None, 'state': 'present', 'ptrdname': 'ansible.test.com',
'ipv4addr': '10.36.241.14', 'comment': None, 'extattrs': None, 'view': 'default'}
test_object = None
test_spec = {
"ipv4addr": {"ib_req": True},
"ptrdname": {"ib_req": True},
"comment": {},
"extattrs": {},
"view": {"ib_req": True}
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'ipv4addr': '10.36.241.14', 'ptrdname': 'ansible.test.com', 'view': 'default'})
def test_nios_ptr_record_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'ptrdname': 'ansible.test.com',
'ipv4addr': '10.36.241.14', 'comment': None, 'extattrs': None, 'view': 'default'}
ref = "record:ptr/ZG5zLm5ldHdvcmtfdmlldyQw:14.241.36.10.in-addr.arpa/default"
test_object = [{
"comment": "test comment",
"_ref": ref,
"ptrdname": "ansible.test.com",
"ipv4addr": "10.36.241.14",
"view": "default",
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"ipv4addr": {"ib_req": True},
"ptrdname": {"ib_req": True},
"comment": {},
"extattrs": {},
"view": {"ib_req": True}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)
def test_nios_ptr_record_update_comment(self):
self.module.params = {'provider': None, 'state': 'present', 'ptrdname': 'ansible.test.com',
'ipv4addr': '10.36.241.14', 'comment': 'updated comment', 'extattrs': None, 'view': 'default'}
test_object = [
{
"comment": "test comment",
"_ref": "record:ptr/ZG5zLm5ldHdvcmtfdmlldyQw:14.241.36.10.in-addr.arpa/default",
"ptrdname": "ansible.test.com",
"ipv4addr": "10.36.241.14",
"extattrs": {},
"view": "default"
}
]
test_spec = {
"ipv4addr": {"ib_req": True},
"ptrdname": {"ib_req": True},
"comment": {},
"extattrs": {},
"view": {"ib_req": True}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.update_object.called_once_with(test_object)
def test_nios_ptr_record_update_record_ptrdname(self):
self.module.params = {'provider': None, 'state': 'present', 'ptrdname': 'ansible.test.org',
'ipv4addr': '10.36.241.14', 'comment': 'comment', 'extattrs': None, 'view': 'default'}
test_object = [
{
"comment": "test comment",
"_ref": "record:ptr/ZG5zLm5ldHdvcmtfdmlldyQw:14.241.36.10.in-addr.arpa/default",
"ptrdname": "ansible.test.com",
"ipv4addr": "10.36.241.14",
"extattrs": {},
"view": "default"
}
]
test_spec = {
"ipv4addr": {"ib_req": True},
"ptrdname": {"ib_req": True},
"comment": {},
"extattrs": {},
"view": {"ib_req": True}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.update_object.called_once_with(test_object)
def test_nios_ptr6_record_create(self):
self.module.params = {'provider': None, 'state': 'present', 'ptrdname': 'ansible6.test.com',
'ipv6addr': '2002:8ac3:802d:1242:20d:60ff:fe38:6d16', 'comment': None, 'extattrs': None, 'view': 'default'}
test_object = None
test_spec = {"ipv6addr": {"ib_req": True},
"ptrdname": {"ib_req": True},
"comment": {},
"extattrs": {},
"view": {"ib_req": True}}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'ipv6addr': '2002:8ac3:802d:1242:20d:60ff:fe38:6d16',
'ptrdname': 'ansible6.test.com', 'view': 'default'})

View file

@ -0,0 +1,153 @@
# 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
from ansible_collections.community.general.plugins.modules.net_tools.nios import nios_srv_record
from ansible_collections.community.general.plugins.module_utils.net_tools.nios import api
from ansible_collections.community.general.tests.unit.compat.mock import patch, MagicMock, Mock
from .test_nios_module import TestNiosModule, load_fixture
class TestNiosSRVRecordModule(TestNiosModule):
module = nios_srv_record
def setUp(self):
super(TestNiosSRVRecordModule, self).setUp()
self.module = MagicMock(name='ansible_collections.community.general.plugins.modules.net_tools.nios.nios_srv_record.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_srv_record.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_srv_record.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosSRVRecordModule, self).tearDown()
self.mock_wapi.stop()
self.mock_wapi_run.stop()
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def test_nios_srv_record_create(self):
self.module.params = {'provider': None, 'state': 'present', 'name': '_sip._tcp.service.ansible.com',
'port': 5080, 'target': 'service1.ansible.com', 'priority': 10, 'weight': 10,
'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"name": {"ib_req": True},
"port": {"ib_req": True},
"target": {"ib_req": True},
"priority": {"ib_req": True},
"weight": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'name': self.module._check_type_dict().__getitem__(),
'port': 5080, 'target': 'service1.ansible.com', 'priority': 10, 'weight': 10})
def test_nios_srv_record_update_comment(self):
self.module.params = {'provider': None, 'state': 'present', 'name': '_sip._tcp.service.ansible.com',
'port': 5080, 'target': 'service1.ansible.com', 'priority': 10, 'weight': 10,
'comment': None, 'extattrs': None}
test_object = [
{
"comment": "test comment",
"_ref": "srvrecord/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"name": "_sip._tcp.service.ansible.com",
'port': 5080,
"target": "mailhost.ansible.com",
"priority": 10,
'weight': 10,
"extattrs": {}
}
]
test_spec = {
"name": {"ib_req": True},
"port": {"ib_req": True},
"target": {"ib_req": True},
"priority": {"ib_req": True},
"weight": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
def test_nios_srv_record_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'name': '_sip._tcp.service.ansible.com',
'port': 5080, 'target': 'service1.ansible.com', 'priority': 10, 'weight': 10,
'comment': None, 'extattrs': None}
ref = "srvrecord/ZG5zLm5ldHdvcmtfdmlldyQw:default/false"
test_object = [
{
"comment": "test comment",
"_ref": ref,
"name": "_sip._tcp.service.ansible.com",
"port": 5080,
"target": "mailhost.ansible.com",
"priority": 10,
"weight": 10,
"extattrs": {'Site': {'value': 'test'}}
}
]
test_spec = {
"name": {"ib_req": True},
"port": {"ib_req": True},
"target": {"ib_req": True},
"priority": {"ib_req": True},
"weight": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)

View file

@ -0,0 +1,287 @@
# 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
from ansible_collections.community.general.plugins.modules.net_tools.nios import nios_zone
from ansible_collections.community.general.plugins.module_utils.net_tools.nios import api
from ansible_collections.community.general.tests.unit.compat.mock import patch, MagicMock, Mock
from .test_nios_module import TestNiosModule, load_fixture
class TestNiosZoneModule(TestNiosModule):
module = nios_zone
def setUp(self):
super(TestNiosZoneModule, self).setUp()
self.module = MagicMock(name='ansible_collections.community.general.plugins.modules.net_tools.nios.nios_zone.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_zone.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_zone.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosZoneModule, self).tearDown()
self.mock_wapi.stop()
self.mock_wapi_run.stop()
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def test_nios_zone_create(self):
self.module.params = {'provider': None, 'state': 'present', 'fqdn': 'ansible.com',
'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"fqdn": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'fqdn': 'ansible.com'})
def test_nios_zone_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'fqdn': 'ansible.com',
'comment': None, 'extattrs': None}
ref = "zone/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/false"
test_object = [{
"comment": "test comment",
"_ref": ref,
"fqdn": "ansible.com",
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"fqdn": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)
def test_nios_zone_update_comment(self):
self.module.params = {'provider': None, 'state': 'present', 'fqdn': 'ansible.com',
'comment': 'updated comment', 'extattrs': None}
test_object = [
{
"comment": "test comment",
"_ref": "zone/ZG5zLm5ldHdvcmtfdmlldyQw:default/true",
"fqdn": "ansible.com",
"extattrs": {'Site': {'value': 'test'}}
}
]
test_spec = {
"fqdn": {"ib_req": True},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
def test_nios_zone_create_using_grid_primary_secondaries(self):
self.module.params = {'provider': None, 'state': 'present', 'fqdn': 'ansible.com',
'grid_primary': [{"name": "gridprimary.grid.com"}],
'grid_secondaries': [{"name": "gridsecondary1.grid.com"},
{"name": "gridsecondary2.grid.com"}],
'restart_if_needed': True,
'comment': None, 'extattrs': None}
test_object = None
grid_spec = dict(
name=dict(required=True),
)
test_spec = {
"fqdn": {"ib_req": True},
"grid_primary": {},
"grid_secondaries": {},
"restart_if_needed": {},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'fqdn': 'ansible.com',
"grid_primary": [{"name": "gridprimary.grid.com"}],
"grid_secondaries": [{"name": "gridsecondary1.grid.com"},
{"name": "gridsecondary2.grid.com"}],
"restart_if_needed": True
})
def test_nios_zone_remove_using_grid_primary_secondaries(self):
self.module.params = {'provider': None, 'state': 'absent', 'fqdn': 'ansible.com',
'grid_primary': [{"name": "gridprimary.grid.com"}],
'grid_secondaries': [{"name": "gridsecondary1.grid.com"},
{"name": "gridsecondary2.grid.com"}],
'restart_if_needed': True,
'comment': None, 'extattrs': None}
ref = "zone/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/false"
test_object = [{
"comment": "test comment",
"_ref": ref,
"fqdn": "ansible.com",
"grid_primary": [{"name": "gridprimary.grid.com"}],
"grid_secondaries": [{"name": "gridsecondary1.grid.com"}, {"name": "gridsecondary2.grid.com"}],
"restart_if_needed": True,
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"fqdn": {"ib_req": True},
"grid_primary": {},
"grid_secondaries": {},
"restart_if_needed": {},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)
def test_nios_zone_create_using_name_server_group(self):
self.module.params = {'provider': None, 'state': 'present', 'fqdn': 'ansible.com',
'ns_group': 'examplensg', 'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"fqdn": {"ib_req": True},
"ns_group": {},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'fqdn': 'ansible.com',
'ns_group': 'examplensg'})
def test_nios_zone_remove_using_name_server_group(self):
self.module.params = {'provider': None, 'state': 'absent', 'fqdn': 'ansible.com',
'ns_group': 'examplensg', 'comment': None, 'extattrs': None}
ref = "zone/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/false"
test_object = [{
"comment": "test comment",
"_ref": ref,
"fqdn": "ansible.com",
"ns_group": "examplensg",
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"fqdn": {"ib_req": True},
"ns_group": {},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)
def test_nios_zone_create_using_zone_format(self):
self.module.params = {'provider': None, 'state': 'present', 'fqdn': '10.10.10.in-addr.arpa',
'zone_format': 'IPV4', 'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"fqdn": {"ib_req": True},
"zone_format": {},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
print("WAPI: ", wapi)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'fqdn': '10.10.10.in-addr.arpa',
'zone_format': 'IPV4'})
def test_nios_zone_remove_using_using_zone_format(self):
self.module.params = {'provider': None, 'state': 'absent', 'fqdn': 'ansible.com',
'zone_format': 'IPV4', 'comment': None, 'extattrs': None}
ref = "zone/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/false"
test_object = [{
"comment": "test comment",
"_ref": ref,
"fqdn": "ansible.com",
"zone_format": "IPV4",
"extattrs": {'Site': {'value': 'test'}}
}]
test_spec = {
"fqdn": {"ib_req": True},
"zone_format": {},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,239 @@
# (c) 2019 Felix Fontein <felix@fontein.de>
# 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
import pytest
from ansible_collections.community.general.plugins.module_utils.hetzner import BASE_URL
from ansible_collections.community.general.plugins.modules.net_tools import hetzner_firewall_info
from .test_hetzner_firewall import FetchUrlCall, run_module_success, run_module_failed
# Tests for state (absent and present)
def test_absent(mocker):
result = run_module_success(mocker, hetzner_firewall_info, {
'hetzner_user': '',
'hetzner_password': '',
'server_ip': '1.2.3.4',
}, [
FetchUrlCall('GET', 200)
.result_json({
'firewall': {
'server_ip': '1.2.3.4',
'server_number': 1,
'status': 'disabled',
'whitelist_hos': False,
'port': 'main',
'rules': {
'input': [],
},
},
})
.expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)),
])
assert result['changed'] is False
assert result['firewall']['status'] == 'disabled'
assert result['firewall']['server_ip'] == '1.2.3.4'
assert result['firewall']['server_number'] == 1
def test_present(mocker):
result = run_module_success(mocker, hetzner_firewall_info, {
'hetzner_user': '',
'hetzner_password': '',
'server_ip': '1.2.3.4',
}, [
FetchUrlCall('GET', 200)
.result_json({
'firewall': {
'server_ip': '1.2.3.4',
'server_number': 1,
'status': 'active',
'whitelist_hos': False,
'port': 'main',
'rules': {
'input': [],
},
},
})
.expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)),
])
assert result['changed'] is False
assert result['firewall']['status'] == 'active'
assert result['firewall']['server_ip'] == '1.2.3.4'
assert result['firewall']['server_number'] == 1
assert len(result['firewall']['rules']['input']) == 0
def test_present_w_rules(mocker):
result = run_module_success(mocker, hetzner_firewall_info, {
'hetzner_user': '',
'hetzner_password': '',
'server_ip': '1.2.3.4',
}, [
FetchUrlCall('GET', 200)
.result_json({
'firewall': {
'server_ip': '1.2.3.4',
'server_number': 1,
'status': 'active',
'whitelist_hos': False,
'port': 'main',
'rules': {
'input': [
{
'name': 'Accept HTTPS traffic',
'ip_version': 'ipv4',
'dst_ip': None,
'dst_port': '443',
'src_ip': None,
'src_port': None,
'protocol': 'tcp',
'tcp_flags': None,
'action': 'accept',
},
{
'name': None,
'ip_version': 'ipv4',
'dst_ip': None,
'dst_port': None,
'src_ip': None,
'src_port': None,
'protocol': None,
'tcp_flags': None,
'action': 'discard',
}
],
},
},
})
.expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)),
])
assert result['changed'] is False
assert result['firewall']['status'] == 'active'
assert result['firewall']['server_ip'] == '1.2.3.4'
assert result['firewall']['server_number'] == 1
assert len(result['firewall']['rules']['input']) == 2
assert result['firewall']['rules']['input'][0]['name'] == 'Accept HTTPS traffic'
assert result['firewall']['rules']['input'][0]['dst_port'] == '443'
assert result['firewall']['rules']['input'][0]['action'] == 'accept'
assert result['firewall']['rules']['input'][1]['dst_port'] is None
assert result['firewall']['rules']['input'][1]['action'] == 'discard'
# Tests for wait_for_configured in getting status
def test_wait_get(mocker):
result = run_module_success(mocker, hetzner_firewall_info, {
'hetzner_user': '',
'hetzner_password': '',
'server_ip': '1.2.3.4',
'wait_for_configured': True,
}, [
FetchUrlCall('GET', 200)
.result_json({
'firewall': {
'server_ip': '1.2.3.4',
'server_number': 1,
'status': 'in process',
'whitelist_hos': False,
'port': 'main',
'rules': {
'input': [],
},
},
})
.expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)),
FetchUrlCall('GET', 200)
.result_json({
'firewall': {
'server_ip': '1.2.3.4',
'server_number': 1,
'status': 'active',
'whitelist_hos': False,
'port': 'main',
'rules': {
'input': [],
},
},
})
.expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)),
])
assert result['changed'] is False
assert result['firewall']['status'] == 'active'
assert result['firewall']['server_ip'] == '1.2.3.4'
assert result['firewall']['server_number'] == 1
def test_wait_get_timeout(mocker):
result = run_module_failed(mocker, hetzner_firewall_info, {
'hetzner_user': '',
'hetzner_password': '',
'server_ip': '1.2.3.4',
'wait_for_configured': True,
'timeout': 0,
}, [
FetchUrlCall('GET', 200)
.result_json({
'firewall': {
'server_ip': '1.2.3.4',
'server_number': 1,
'status': 'in process',
'whitelist_hos': False,
'port': 'main',
'rules': {
'input': [],
},
},
})
.expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)),
FetchUrlCall('GET', 200)
.result_json({
'firewall': {
'server_ip': '1.2.3.4',
'server_number': 1,
'status': 'in process',
'whitelist_hos': False,
'port': 'main',
'rules': {
'input': [],
},
},
})
.expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)),
])
assert result['msg'] == 'Timeout while waiting for firewall to be configured.'
def test_nowait_get(mocker):
result = run_module_success(mocker, hetzner_firewall_info, {
'hetzner_user': '',
'hetzner_password': '',
'server_ip': '1.2.3.4',
'wait_for_configured': False,
}, [
FetchUrlCall('GET', 200)
.result_json({
'firewall': {
'server_ip': '1.2.3.4',
'server_number': 1,
'status': 'in process',
'whitelist_hos': False,
'port': 'main',
'rules': {
'input': [],
},
},
})
.expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)),
])
assert result['changed'] is False
assert result['firewall']['status'] == 'in process'
assert result['firewall']['server_ip'] == '1.2.3.4'
assert result['firewall']['server_number'] == 1

View file

@ -0,0 +1,656 @@
# Copyright: (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
import json
import pytest
from ansible_collections.community.general.plugins.modules.net_tools import nmcli
pytestmark = pytest.mark.usefixtures('patch_ansible_module')
TESTCASE_CONNECTION = [
{
'type': 'ethernet',
'conn_name': 'non_existent_nw_device',
'state': 'absent',
'_ansible_check_mode': True,
},
{
'type': 'generic',
'conn_name': 'non_existent_nw_device',
'state': 'absent',
'_ansible_check_mode': True,
},
{
'type': 'team',
'conn_name': 'non_existent_nw_device',
'state': 'absent',
'_ansible_check_mode': True,
},
{
'type': 'bond',
'conn_name': 'non_existent_nw_device',
'state': 'absent',
'_ansible_check_mode': True,
},
{
'type': 'bond-slave',
'conn_name': 'non_existent_nw_device',
'state': 'absent',
'_ansible_check_mode': True,
},
{
'type': 'bridge',
'conn_name': 'non_existent_nw_device',
'state': 'absent',
'_ansible_check_mode': True,
},
{
'type': 'vlan',
'conn_name': 'non_existent_nw_device',
'state': 'absent',
'_ansible_check_mode': True,
},
{
'type': 'vxlan',
'conn_name': 'non_existent_nw_device',
'state': 'absent',
'_ansible_check_mode': True,
},
{
'type': 'ipip',
'conn_name': 'non_existent_nw_device',
'state': 'absent',
'_ansible_check_mode': True,
},
{
'type': 'sit',
'conn_name': 'non_existent_nw_device',
'state': 'absent',
'_ansible_check_mode': True,
},
]
TESTCASE_GENERIC = [
{
'type': 'generic',
'conn_name': 'non_existent_nw_device',
'ifname': 'generic_non_existant',
'ip4': '10.10.10.10',
'gw4': '10.10.10.1',
'state': 'present',
'_ansible_check_mode': False,
},
]
TESTCASE_GENERIC_DNS4_SEARCH = [
{
'type': 'generic',
'conn_name': 'non_existent_nw_device',
'ifname': 'generic_non_existant',
'ip4': '10.10.10.10',
'gw4': '10.10.10.1',
'state': 'present',
'dns4_search': 'search.redhat.com',
'dns6_search': 'search6.redhat.com',
'_ansible_check_mode': False,
}
]
TESTCASE_BOND = [
{
'type': 'bond',
'conn_name': 'non_existent_nw_device',
'ifname': 'bond_non_existant',
'mode': 'active-backup',
'ip4': '10.10.10.10',
'gw4': '10.10.10.1',
'state': 'present',
'primary': 'non_existent_primary',
'_ansible_check_mode': False,
}
]
TESTCASE_BRIDGE = [
{
'type': 'bridge',
'conn_name': 'non_existent_nw_device',
'ifname': 'br0_non_existant',
'ip4': '10.10.10.10',
'gw4': '10.10.10.1',
'maxage': 100,
'stp': True,
'state': 'present',
'_ansible_check_mode': False,
}
]
TESTCASE_BRIDGE_SLAVE = [
{
'type': 'bridge-slave',
'conn_name': 'non_existent_nw_device',
'ifname': 'br0_non_existant',
'path_cost': 100,
'state': 'present',
'_ansible_check_mode': False,
}
]
TESTCASE_VLAN = [
{
'type': 'vlan',
'conn_name': 'non_existent_nw_device',
'ifname': 'vlan_not_exists',
'ip4': '10.10.10.10',
'gw4': '10.10.10.1',
'vlanid': 10,
'state': 'present',
'_ansible_check_mode': False,
}
]
TESTCASE_VXLAN = [
{
'type': 'vxlan',
'conn_name': 'non_existent_nw_device',
'ifname': 'vxlan-existent_nw_device',
'vxlan_id': 11,
'vxlan_local': '192.168.225.5',
'vxlan_remote': '192.168.225.6',
'state': 'present',
'_ansible_check_mode': False,
}
]
TESTCASE_IPIP = [
{
'type': 'ipip',
'conn_name': 'non_existent_nw_device',
'ifname': 'ipip-existent_nw_device',
'ip_tunnel_dev': 'non_existent_ipip_device',
'ip_tunnel_local': '192.168.225.5',
'ip_tunnel_remote': '192.168.225.6',
'state': 'present',
'_ansible_check_mode': False,
}
]
TESTCASE_SIT = [
{
'type': 'sit',
'conn_name': 'non_existent_nw_device',
'ifname': 'sit-existent_nw_device',
'ip_tunnel_dev': 'non_existent_sit_device',
'ip_tunnel_local': '192.168.225.5',
'ip_tunnel_remote': '192.168.225.6',
'state': 'present',
'_ansible_check_mode': False,
}
]
TESTCASE_ETHERNET_DHCP = [
{
'type': 'ethernet',
'conn_name': 'non_existent_nw_device',
'ifname': 'ethernet_non_existant',
'ip4': '10.10.10.10',
'gw4': '10.10.10.1',
'state': 'present',
'_ansible_check_mode': False,
'dhcp_client_id': '00:11:22:AA:BB:CC:DD',
}
]
def mocker_set(mocker, connection_exists=False):
"""
Common mocker object
"""
mocker.patch('ansible_collections.community.general.plugins.modules.net_tools.nmcli.HAVE_DBUS', True)
mocker.patch('ansible_collections.community.general.plugins.modules.net_tools.nmcli.HAVE_NM_CLIENT', True)
get_bin_path = mocker.patch('ansible.module_utils.basic.AnsibleModule.get_bin_path')
get_bin_path.return_value = '/usr/bin/nmcli'
connection = mocker.patch.object(nmcli.Nmcli, 'connection_exists')
connection.return_value = connection_exists
return connection
@pytest.fixture
def mocked_generic_connection_create(mocker):
mocker_set(mocker)
command_result = mocker.patch.object(nmcli.Nmcli, 'execute_command')
command_result.return_value = {"rc": 100, "out": "aaa", "err": "none"}
return command_result
@pytest.fixture
def mocked_generic_connection_modify(mocker):
mocker_set(mocker, connection_exists=True)
command_result = mocker.patch.object(nmcli.Nmcli, 'execute_command')
command_result.return_value = {"rc": 100, "out": "aaa", "err": "none"}
return command_result
@pytest.fixture
def mocked_connection_exists(mocker):
connection = mocker_set(mocker, connection_exists=True)
return connection
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_BOND, indirect=['patch_ansible_module'])
def test_bond_connection_create(mocked_generic_connection_create):
"""
Test : Bond connection created
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert args[0][0] == '/usr/bin/nmcli'
assert args[0][1] == 'con'
assert args[0][2] == 'add'
assert args[0][3] == 'type'
assert args[0][4] == 'bond'
assert args[0][5] == 'con-name'
assert args[0][6] == 'non_existent_nw_device'
assert args[0][7] == 'ifname'
assert args[0][8] == 'bond_non_existant'
for param in ['gw4', 'primary', 'autoconnect', 'mode', 'active-backup', 'ip4']:
assert param in args[0]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_GENERIC, indirect=['patch_ansible_module'])
def test_generic_connection_create(mocked_generic_connection_create):
"""
Test : Generic connection created
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert args[0][0] == '/usr/bin/nmcli'
assert args[0][1] == 'con'
assert args[0][2] == 'add'
assert args[0][3] == 'type'
assert args[0][4] == 'generic'
assert args[0][5] == 'con-name'
assert args[0][6] == 'non_existent_nw_device'
for param in ['autoconnect', 'gw4', 'ip4']:
assert param in args[0]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_GENERIC, indirect=['patch_ansible_module'])
def test_generic_connection_modify(mocked_generic_connection_modify):
"""
Test : Generic connection modify
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert args[0][0] == '/usr/bin/nmcli'
assert args[0][1] == 'con'
assert args[0][2] == 'mod'
assert args[0][3] == 'non_existent_nw_device'
for param in ['ipv4.gateway', 'ipv4.address']:
assert param in args[0]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_GENERIC_DNS4_SEARCH, indirect=['patch_ansible_module'])
def test_generic_connection_create_dns_search(mocked_generic_connection_create):
"""
Test : Generic connection created with dns search
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert 'ipv4.dns-search' in args[0]
assert 'ipv6.dns-search' in args[0]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_GENERIC_DNS4_SEARCH, indirect=['patch_ansible_module'])
def test_generic_connection_modify_dns_search(mocked_generic_connection_create):
"""
Test : Generic connection modified with dns search
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert 'ipv4.dns-search' in args[0]
assert 'ipv6.dns-search' in args[0]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_CONNECTION, indirect=['patch_ansible_module'])
def test_dns4_none(mocked_connection_exists, capfd):
"""
Test if DNS4 param is None
"""
with pytest.raises(SystemExit):
nmcli.main()
out, err = capfd.readouterr()
results = json.loads(out)
assert results['changed']
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_BRIDGE, indirect=['patch_ansible_module'])
def test_create_bridge(mocked_generic_connection_create):
"""
Test if Bridge created
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert args[0][0] == '/usr/bin/nmcli'
assert args[0][1] == 'con'
assert args[0][2] == 'add'
assert args[0][3] == 'type'
assert args[0][4] == 'bridge'
assert args[0][5] == 'con-name'
assert args[0][6] == 'non_existent_nw_device'
for param in ['ip4', '10.10.10.10', 'gw4', '10.10.10.1', 'bridge.max-age', 100, 'bridge.stp', 'yes']:
assert param in args[0]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_BRIDGE, indirect=['patch_ansible_module'])
def test_mod_bridge(mocked_generic_connection_modify):
"""
Test if Bridge modified
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert args[0][0] == '/usr/bin/nmcli'
assert args[0][1] == 'con'
assert args[0][2] == 'mod'
assert args[0][3] == 'non_existent_nw_device'
for param in ['ipv4.address', '10.10.10.10', 'ipv4.gateway', '10.10.10.1', 'bridge.max-age', 100, 'bridge.stp', 'yes']:
assert param in args[0]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_BRIDGE_SLAVE, indirect=['patch_ansible_module'])
def test_create_bridge_slave(mocked_generic_connection_create):
"""
Test if Bridge_slave created
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert args[0][0] == '/usr/bin/nmcli'
assert args[0][1] == 'con'
assert args[0][2] == 'add'
assert args[0][3] == 'type'
assert args[0][4] == 'bridge-slave'
assert args[0][5] == 'con-name'
assert args[0][6] == 'non_existent_nw_device'
for param in ['bridge-port.path-cost', 100]:
assert param in args[0]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_BRIDGE_SLAVE, indirect=['patch_ansible_module'])
def test_mod_bridge_slave(mocked_generic_connection_modify):
"""
Test if Bridge_slave modified
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert args[0][0] == '/usr/bin/nmcli'
assert args[0][1] == 'con'
assert args[0][2] == 'mod'
assert args[0][3] == 'non_existent_nw_device'
for param in ['bridge-port.path-cost', 100]:
assert param in args[0]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_VLAN, indirect=['patch_ansible_module'])
def test_create_vlan_con(mocked_generic_connection_create):
"""
Test if VLAN created
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert args[0][0] == '/usr/bin/nmcli'
assert args[0][1] == 'con'
assert args[0][2] == 'add'
assert args[0][3] == 'type'
assert args[0][4] == 'vlan'
assert args[0][5] == 'con-name'
assert args[0][6] == 'non_existent_nw_device'
for param in ['ip4', '10.10.10.10', 'gw4', '10.10.10.1', 'id', '10']:
assert param in args[0]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_VLAN, indirect=['patch_ansible_module'])
def test_mod_vlan_conn(mocked_generic_connection_modify):
"""
Test if VLAN modified
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert args[0][0] == '/usr/bin/nmcli'
assert args[0][1] == 'con'
assert args[0][2] == 'mod'
assert args[0][3] == 'non_existent_nw_device'
for param in ['ipv4.address', '10.10.10.10', 'ipv4.gateway', '10.10.10.1', 'vlan.id', '10']:
assert param in args[0]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_VXLAN, indirect=['patch_ansible_module'])
def test_create_vxlan(mocked_generic_connection_create):
"""
Test if vxlan created
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert args[0][0] == '/usr/bin/nmcli'
assert args[0][1] == 'con'
assert args[0][2] == 'add'
assert args[0][3] == 'type'
assert args[0][4] == 'vxlan'
assert args[0][5] == 'con-name'
assert args[0][6] == 'non_existent_nw_device'
assert args[0][7] == 'ifname'
for param in ['vxlan.local', '192.168.225.5', 'vxlan.remote', '192.168.225.6', 'vxlan.id', 11]:
assert param in args[0]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_VXLAN, indirect=['patch_ansible_module'])
def test_vxlan_mod(mocked_generic_connection_modify):
"""
Test if vxlan modified
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert args[0][0] == '/usr/bin/nmcli'
assert args[0][1] == 'con'
assert args[0][2] == 'mod'
assert args[0][3] == 'non_existent_nw_device'
for param in ['vxlan.local', '192.168.225.5', 'vxlan.remote', '192.168.225.6', 'vxlan.id', 11]:
assert param in args[0]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_IPIP, indirect=['patch_ansible_module'])
def test_create_ipip(mocked_generic_connection_create):
"""
Test if ipip created
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert args[0][0] == '/usr/bin/nmcli'
assert args[0][1] == 'con'
assert args[0][2] == 'add'
assert args[0][3] == 'type'
assert args[0][4] == 'ip-tunnel'
assert args[0][5] == 'mode'
assert args[0][6] == 'ipip'
assert args[0][7] == 'con-name'
assert args[0][8] == 'non_existent_nw_device'
assert args[0][9] == 'ifname'
assert args[0][10] == 'ipip-existent_nw_device'
assert args[0][11] == 'dev'
assert args[0][12] == 'non_existent_ipip_device'
for param in ['ip-tunnel.local', '192.168.225.5', 'ip-tunnel.remote', '192.168.225.6']:
assert param in args[0]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_IPIP, indirect=['patch_ansible_module'])
def test_ipip_mod(mocked_generic_connection_modify):
"""
Test if ipip modified
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert args[0][0] == '/usr/bin/nmcli'
assert args[0][1] == 'con'
assert args[0][2] == 'mod'
assert args[0][3] == 'non_existent_nw_device'
for param in ['ip-tunnel.local', '192.168.225.5', 'ip-tunnel.remote', '192.168.225.6']:
assert param in args[0]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_SIT, indirect=['patch_ansible_module'])
def test_create_sit(mocked_generic_connection_create):
"""
Test if sit created
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert args[0][0] == '/usr/bin/nmcli'
assert args[0][1] == 'con'
assert args[0][2] == 'add'
assert args[0][3] == 'type'
assert args[0][4] == 'ip-tunnel'
assert args[0][5] == 'mode'
assert args[0][6] == 'sit'
assert args[0][7] == 'con-name'
assert args[0][8] == 'non_existent_nw_device'
assert args[0][9] == 'ifname'
assert args[0][10] == 'sit-existent_nw_device'
assert args[0][11] == 'dev'
assert args[0][12] == 'non_existent_sit_device'
for param in ['ip-tunnel.local', '192.168.225.5', 'ip-tunnel.remote', '192.168.225.6']:
assert param in args[0]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_SIT, indirect=['patch_ansible_module'])
def test_sit_mod(mocked_generic_connection_modify):
"""
Test if sit modified
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert args[0][0] == '/usr/bin/nmcli'
assert args[0][1] == 'con'
assert args[0][2] == 'mod'
assert args[0][3] == 'non_existent_nw_device'
for param in ['ip-tunnel.local', '192.168.225.5', 'ip-tunnel.remote', '192.168.225.6']:
assert param in args[0]
@pytest.mark.parametrize('patch_ansible_module', TESTCASE_ETHERNET_DHCP, indirect=['patch_ansible_module'])
def test_eth_dhcp_client_id_con_create(mocked_generic_connection_create):
"""
Test : Ethernet connection created with DHCP_CLIENT_ID
"""
with pytest.raises(SystemExit):
nmcli.main()
assert nmcli.Nmcli.execute_command.call_count == 1
arg_list = nmcli.Nmcli.execute_command.call_args_list
args, kwargs = arg_list[0]
assert 'ipv4.dhcp-client-id' in args[0]

View file

@ -0,0 +1,87 @@
# (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 os
import json
from ansible_collections.community.general.tests.unit.plugins.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {}
def load_fixture(name):
path = os.path.join(fixture_path, name)
if path in fixture_data:
return fixture_data[path]
with open(path) as f:
data = f.read()
try:
data = json.loads(data)
except Exception:
pass
fixture_data[path] = data
return data
class TestCiscoWlcModule(ModuleTestCase):
def execute_module(self, failed=False, changed=False, commands=None, sort=True, defaults=False):
self.load_fixtures(commands)
if failed:
result = self.failed()
self.assertTrue(result['failed'], result)
else:
result = self.changed(changed)
self.assertEqual(result['changed'], changed, result)
if commands is not None:
if sort:
self.assertEqual(sorted(commands), sorted(result['commands']), result['commands'])
else:
self.assertEqual(commands, result['commands'], result['commands'])
return result
def failed(self):
with self.assertRaises(AnsibleFailJson) as exc:
self.module.main()
result = exc.exception.args[0]
self.assertTrue(result['failed'], result)
return result
def changed(self, changed=False):
with self.assertRaises(AnsibleExitJson) as exc:
self.module.main()
result = exc.exception.args[0]
self.assertEqual(result['changed'], changed, result)
return result
def load_fixtures(self, commands=None):
pass

View file

@ -0,0 +1,9 @@
sysname router
interface create mtc-1 1
interface address dynamic-interface mtc-1 10.33.20.4 255.255.255.0 10.33.20.1
interface vlan mtc-1 1
interface create mtc-2 2
interface address dynamic-interface mtc-2 10.33.26.4 255.255.255.0 10.33.26.1
interface vlan mtc-2 2

View file

@ -0,0 +1,9 @@
sysname foo
interface create mtc-1 1
interface address dynamic-interface mtc-1 10.33.20.4 255.255.255.0 10.33.20.2
interface vlan mtc-1 1
interface create mtc-2 2
interface address dynamic-interface mtc-2 10.33.26.4 255.255.255.0 10.33.26.1
interface vlan mtc-2 2

View file

@ -0,0 +1,43 @@
Manufacturer's Name.............................. Cisco Systems Inc.
Product Name..................................... Cisco Controller
Product Version.................................. 8.2.110.0
RTOS Version..................................... 8.2.110.0
Bootloader Version............................... 8.0.100.0
Emergency Image Version.......................... 8.0.100.0
Build Type....................................... DATA + WPS
System Name...................................... SOMEHOST
System Location.................................. USA
System Contact................................... SN:E228240;ASSET:LSMTCc1
System ObjectID.................................. 1.3.6.1.4.1.9.1.1615
Redundancy Mode.................................. Disabled
IP Address....................................... 10.10.10.10
IPv6 Address..................................... ::
System Up Time................................... 328 days 7 hrs 54 mins 49 secs
System Timezone Location......................... (GMT) London, Lisbon, Dublin, Edinburgh
System Stats Realtime Interval................... 5
System Stats Normal Interval..................... 180
Configured Country............................... US - United States
Operating Environment............................ Commercial (10 to 35 C)
Internal Temp Alarm Limits....................... 10 to 38 C
Internal Temperature............................. +18 C
Fan Status....................................... OK
RAID Volume Status
Drive 0.......................................... Good
Drive 1.......................................... Good
State of 802.11b Network......................... Enabled
State of 802.11a Network......................... Enabled
Number of WLANs.................................. 1
Number of Active Clients......................... 0
Burned-in MAC Address............................ AA:AA:AA:AA:AA:AA
Power Supply 1................................... Present, OK
Power Supply 2................................... Present, OK
Maximum number of APs supported.................. 6000
System Nas-Id....................................
WLC MIC Certificate Types........................ SHA1/SHA2
Licensing Type................................... RTU

View file

@ -0,0 +1,122 @@
# (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_collections.community.general.tests.unit.compat.mock import patch
from ansible_collections.community.general.plugins.modules.network.aireos import aireos_command
from ansible_collections.community.general.tests.unit.plugins.modules.utils import set_module_args
from .aireos_module import TestCiscoWlcModule, load_fixture
from ansible.module_utils import six
class TestCiscoWlcCommandModule(TestCiscoWlcModule):
module = aireos_command
def setUp(self):
super(TestCiscoWlcCommandModule, self).setUp()
self.mock_run_commands = patch('ansible_collections.community.general.plugins.modules.network.aireos.aireos_command.run_commands')
self.run_commands = self.mock_run_commands.start()
def tearDown(self):
super(TestCiscoWlcCommandModule, self).tearDown()
self.mock_run_commands.stop()
def load_fixtures(self, commands=None):
def load_from_file(*args, **kwargs):
module, commands = args
output = list()
for item in commands:
try:
obj = json.loads(item['command'])
command = obj['command']
except ValueError:
command = item['command']
filename = str(command).replace(' ', '_')
output.append(load_fixture(filename))
return output
self.run_commands.side_effect = load_from_file
def test_aireos_command_simple(self):
set_module_args(dict(commands=['show sysinfo']))
result = self.execute_module()
self.assertEqual(len(result['stdout']), 1)
self.assertTrue(result['stdout'][0].startswith('Manufacturer\'s Name'))
def test_aireos_command_multiple(self):
set_module_args(dict(commands=['show sysinfo', 'show sysinfo']))
result = self.execute_module()
self.assertEqual(len(result['stdout']), 2)
self.assertTrue(result['stdout'][0].startswith('Manufacturer\'s Name'))
def test_aireos_command_wait_for(self):
wait_for = 'result[0] contains "Cisco Systems Inc"'
set_module_args(dict(commands=['show sysinfo'], wait_for=wait_for))
self.execute_module()
def test_aireos_command_wait_for_fails(self):
wait_for = 'result[0] contains "test string"'
set_module_args(dict(commands=['show sysinfo'], wait_for=wait_for))
self.execute_module(failed=True)
self.assertEqual(self.run_commands.call_count, 10)
def test_aireos_command_retries(self):
wait_for = 'result[0] contains "test string"'
set_module_args(dict(commands=['show sysinfo'], wait_for=wait_for, retries=2))
self.execute_module(failed=True)
self.assertEqual(self.run_commands.call_count, 2)
def test_aireos_command_match_any(self):
wait_for = ['result[0] contains "Cisco Systems Inc"',
'result[0] contains "test string"']
set_module_args(dict(commands=['show sysinfo'], wait_for=wait_for, match='any'))
self.execute_module()
def test_aireos_command_match_all(self):
wait_for = ['result[0] contains "Cisco Systems Inc"',
'result[0] contains "Cisco Controller"']
set_module_args(dict(commands=['show sysinfo'], wait_for=wait_for, match='all'))
self.execute_module()
def test_aireos_command_match_all_failure(self):
wait_for = ['result[0] contains "Cisco Systems Inc"',
'result[0] contains "test string"']
commands = ['show sysinfo', 'show sysinfo']
set_module_args(dict(commands=commands, wait_for=wait_for, match='all'))
self.execute_module(failed=True)
def test_aireos_command_to_lines_non_ascii(self):
''' Test data is one variation of the result of a `show run-config commands`
command on Cisco WLC version 8.8.120.0 '''
test_data = '''
wlan flexconnect learn-ipaddr 101 enable
`\xc8\x92\xef\xbf\xbdR\x7f`\xc8\x92\xef\xbf\xbdR\x7f`
wlan wgb broadcast-tagging disable 1
'''.strip()
test_string = six.u(test_data)
test_stdout = [test_string, ]
result = list(aireos_command.to_lines(test_stdout))
print(result[0])
self.assertEqual(len(result[0]), 3)

View file

@ -0,0 +1,131 @@
#
# (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
from ansible_collections.community.general.tests.unit.compat.mock import patch
from ansible_collections.community.general.plugins.modules.network.aireos import aireos_config
from ansible_collections.community.general.tests.unit.plugins.modules.utils import set_module_args
from .aireos_module import TestCiscoWlcModule, load_fixture
class TestCiscoWlcConfigModule(TestCiscoWlcModule):
module = aireos_config
def setUp(self):
super(TestCiscoWlcConfigModule, self).setUp()
self.mock_get_config = patch('ansible_collections.community.general.plugins.modules.network.aireos.aireos_config.get_config')
self.get_config = self.mock_get_config.start()
self.mock_load_config = patch('ansible_collections.community.general.plugins.modules.network.aireos.aireos_config.load_config')
self.load_config = self.mock_load_config.start()
self.mock_run_commands = patch('ansible_collections.community.general.plugins.modules.network.aireos.aireos_config.run_commands')
self.run_commands = self.mock_run_commands.start()
self.mock_save_config = patch('ansible_collections.community.general.plugins.modules.network.aireos.aireos_config.save_config')
self.save_config = self.mock_save_config.start()
def tearDown(self):
super(TestCiscoWlcConfigModule, self).tearDown()
self.mock_get_config.stop()
self.mock_load_config.stop()
self.mock_run_commands.stop()
def load_fixtures(self, commands=None):
config_file = 'aireos_config_config.cfg'
self.get_config.return_value = load_fixture(config_file)
self.load_config.return_value = None
def test_aireos_config_unchanged(self):
src = load_fixture('aireos_config_config.cfg')
set_module_args(dict(src=src))
self.execute_module()
def test_aireos_config_src(self):
src = load_fixture('aireos_config_src.cfg')
set_module_args(dict(src=src))
commands = ['sysname foo', 'interface address dynamic-interface mtc-1 10.33.20.4 255.255.255.0 10.33.20.2']
self.execute_module(changed=True, commands=commands)
def test_aireos_config_backup(self):
set_module_args(dict(backup=True))
result = self.execute_module()
self.assertIn('__backup__', result)
def test_aireos_config_save(self):
set_module_args(dict(save=True))
self.execute_module()
self.assertEqual(self.save_config.call_count, 1)
self.assertEqual(self.get_config.call_count, 0)
self.assertEqual(self.load_config.call_count, 0)
def test_aireos_config_before(self):
set_module_args(dict(lines=['sysname foo'], before=['test1', 'test2']))
commands = ['test1', 'test2', 'sysname foo']
self.execute_module(changed=True, commands=commands, sort=False)
def test_aireos_config_after(self):
set_module_args(dict(lines=['sysname foo'], after=['test1', 'test2']))
commands = ['sysname foo', 'test1', 'test2']
self.execute_module(changed=True, commands=commands, sort=False)
def test_aireos_config_before_after_no_change(self):
set_module_args(dict(lines=['sysname router'],
before=['test1', 'test2'],
after=['test3', 'test4']))
self.execute_module()
def test_aireos_config_config(self):
config = 'sysname localhost'
set_module_args(dict(lines=['sysname router'], config=config))
commands = ['sysname router']
self.execute_module(changed=True, commands=commands)
def test_aireos_config_match_none(self):
lines = ['sysname router', 'interface create mtc-1 1']
set_module_args(dict(lines=lines, match='none'))
self.execute_module(changed=True, commands=lines, sort=False)
def test_nxos_config_save_always(self):
args = dict(save_when='always')
set_module_args(args)
self.execute_module()
self.assertEqual(self.save_config.call_count, 1)
self.assertEqual(self.get_config.call_count, 0)
self.assertEqual(self.load_config.call_count, 0)
def test_nxos_config_save_changed_true(self):
args = dict(save_when='changed', lines=['sysname foo', 'interface create mtc-3 3'])
set_module_args(args)
self.execute_module(changed=True)
self.assertEqual(self.save_config.call_count, 1)
self.assertEqual(self.get_config.call_count, 1)
self.assertEqual(self.load_config.call_count, 1)
def test_nxos_config_save_changed_false(self):
args = dict(save_when='changed')
set_module_args(args)
self.execute_module()
self.assertEqual(self.save_config.call_count, 0)
self.assertEqual(self.get_config.call_count, 0)
self.assertEqual(self.load_config.call_count, 0)

View file

@ -0,0 +1,88 @@
# (c) 2019 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 os
import json
from ansible_collections.community.general.tests.unit.plugins.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {}
def load_fixture(name):
path = os.path.join(fixture_path, name)
if path in fixture_data:
return fixture_data[path]
with open(path) as f:
data = f.read()
try:
data = json.loads(data)
except Exception:
pass
fixture_data[path] = data
return data
class TestApconosModule(ModuleTestCase):
def execute_module(self, failed=False, changed=False, commands=None, sort=True, defaults=False):
self.load_fixtures(commands)
if failed:
result = self.failed()
self.assertTrue(result['failed'], result)
else:
result = self.changed(changed)
self.assertEqual(result['changed'], changed, result)
if commands is not None:
if sort:
self.assertEqual(sorted(commands), sorted(result['commands']), result['commands'])
else:
self.assertEqual(commands, result['commands'], result['commands'])
return result
def failed(self):
with self.assertRaises(AnsibleFailJson) as exc:
self.module.main()
result = exc.exception.args[0]
self.assertTrue(result['failed'], result)
return result
def changed(self, changed=False):
with self.assertRaises(AnsibleExitJson) as exc:
self.module.main()
result = exc.exception.args[0]
self.assertEqual(result['changed'], changed, result)
return result
def load_fixtures(self, commands=None):
pass

View file

@ -0,0 +1,2 @@
APCON
COMPONENT MODEL VERSION

View file

@ -0,0 +1,110 @@
# (c) 2019 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_collections.community.general.tests.unit.compat.mock import patch
from ansible_collections.community.general.plugins.modules.network.apconos import apconos_command
from ansible_collections.community.general.tests.unit.plugins.modules.utils import set_module_args
from .apconos_module import TestApconosModule, load_fixture
class TestApconosCommandModule(TestApconosModule):
module = apconos_command
def setUp(self):
super(TestApconosCommandModule, self).setUp()
self.mock_run_commands = patch('ansible_collections.community.general.plugins.modules.network.apconos.apconos_command.run_commands')
self.run_commands = self.mock_run_commands.start()
def tearDown(self):
super(TestApconosCommandModule, self).tearDown()
self.mock_run_commands.stop()
def load_fixtures(self, commands=None):
def load_from_file(*args, **kwargs):
module, commands = args
output = list()
for item in commands:
filename = str(item).replace(' ', '_')
output.append(load_fixture(filename))
return output
self.run_commands.side_effect = load_from_file
def test_apcon_command_simple(self):
set_module_args(dict(commands=['show version']))
result = self.execute_module()
self.assertEqual(len(result['stdout_lines']), 1)
self.assertEqual(result['stdout_lines'][0][0], 'APCON')
def test_apcon_command_multiple(self):
set_module_args(dict(commands=['show version', 'show version']))
result = self.execute_module()
self.assertEqual(len(result['stdout_lines']), 2)
self.assertEqual(result['stdout_lines'][0][0], 'APCON')
self.assertEqual(result['stdout_lines'][1][0], 'APCON')
def test_apcon_command_wait_for(self):
wait_for = 'result[0] contains "APCON"'
set_module_args(dict(commands=['show version'], wait_for=wait_for))
self.execute_module()
def test_apcon_command_wait_for_fails(self):
wait_for = 'result[0] contains "test string"'
set_module_args(dict(commands=['show version'], wait_for=wait_for))
self.execute_module(failed=True)
self.assertEqual(self.run_commands.call_count, 10)
def test_apcon_command_retries(self):
wait_for = 'result[0] contains "test string"'
set_module_args(dict(commands=['show version'], wait_for=wait_for, retries=2))
self.execute_module(failed=True)
self.assertEqual(self.run_commands.call_count, 2)
def test_apcon_command_match_any(self):
wait_for = ['result[0] contains "test string"',
'result[0] contains "VERSION"']
set_module_args(dict(commands=['show version'], wait_for=wait_for, match='any'))
self.execute_module()
def test_apcon_command_match_all(self):
wait_for = ['result[0] contains "COMPONENT"',
'result[0] contains "MODEL"',
'result[0] contains "VERSION"']
set_module_args(dict(commands=['show version'], wait_for=wait_for, match='all'))
self.execute_module()
def test_apcon_command_match_all_failure(self):
wait_for = ['result[0] contains "APCON OS"',
'result[0] contains "test string"']
commands = ['show version', 'show version']
set_module_args(dict(commands=commands, wait_for=wait_for, match='all'))
self.execute_module(failed=True)
def test_apcon_command_checkmode_not_warning(self):
commands = ['enable ssh']
set_module_args(dict(commands=commands, _ansible_check_mode=False))
result = self.execute_module(changed=True)
self.assertEqual(result['warnings'], [])

View file

@ -0,0 +1,88 @@
# (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 os
import json
from ansible_collections.community.general.tests.unit.plugins.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {}
def load_fixture(name):
path = os.path.join(fixture_path, name)
if path in fixture_data:
return fixture_data[path]
with open(path) as f:
data = f.read()
try:
data = json.loads(data)
except Exception:
pass
fixture_data[path] = data
return data
class TestArubaModule(ModuleTestCase):
def execute_module(self, failed=False, changed=False, commands=None, sort=True, defaults=False):
self.load_fixtures(commands)
if failed:
result = self.failed()
self.assertTrue(result['failed'], result)
else:
result = self.changed(changed)
self.assertEqual(result['changed'], changed, result)
if commands is not None:
if sort:
self.assertEqual(sorted(commands), sorted(result['commands']), result['commands'])
else:
self.assertEqual(commands, result['commands'], result['commands'])
return result
def failed(self):
with self.assertRaises(AnsibleFailJson) as exc:
self.module.main()
result = exc.exception.args[0]
self.assertTrue(result['failed'], result)
return result
def changed(self, changed=False):
with self.assertRaises(AnsibleExitJson) as exc:
self.module.main()
result = exc.exception.args[0]
self.assertEqual(result['changed'], changed, result)
return result
def load_fixtures(self, commands=None):
pass

View file

@ -0,0 +1,17 @@
!
hostname router
!
interface GigabitEthernet0/0
ip address 1.2.3.4 255.255.255.0
description test string
!
interface GigabitEthernet0/1
ip address 6.7.8.9 255.255.255.0
description test string
shutdown
!
wlan ssid-profile "blah"
essid "blah"
!
ip access-list session blah
any any any permit

View file

@ -0,0 +1,13 @@
!
hostname router
!
interface GigabitEthernet0/0
ip address 1.2.3.4 255.255.255.0
description test string
no shutdown
!
interface GigabitEthernet0/1
ip address 6.7.8.9 255.255.255.0
description test string
shutdown
!

View file

@ -0,0 +1,11 @@
!
hostname foo
!
interface GigabitEthernet0/0
no ip address
!
interface GigabitEthernet0/1
ip address 6.7.8.9 255.255.255.0
description test string
shutdown
!

View file

@ -0,0 +1,17 @@
Aruba Operating System Software.
ArubaOS (MODEL: Aruba7220-US), Version 6.4.3.10
Website: http://www.arubanetworks.com
Copyright (c) 2002-2016, Aruba Networks, Inc.
Compiled on 2016-08-31 at 18:31:30 PDT (build 56305) by p4build
ROM: System Bootstrap, Version CPBoot 1.2.1.0 (build 39183)
Built: 2013-07-26 04:57:47
Built by: p4build@re_client_39183
Switch uptime is 15 days 20 hours 51 minutes 51 seconds
Reboot Cause: User reboot (Intent:cause:register 78:86:50:2)
Supervisor Card
Processor (XLP432 Rev B1 (Secure Boot) , 1000 MHz) with 7370M bytes of memory.
32K bytes of non-volatile configuration memory.
7920M bytes of Supervisor Card system flash.

View file

@ -0,0 +1,109 @@
# (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_collections.community.general.tests.unit.compat.mock import patch
from ansible_collections.community.general.plugins.modules.network.aruba import aruba_command
from ansible_collections.community.general.tests.unit.plugins.modules.utils import set_module_args
from .aruba_module import TestArubaModule, load_fixture
class TestArubaCommandModule(TestArubaModule):
module = aruba_command
def setUp(self):
super(TestArubaCommandModule, self).setUp()
self.mock_run_commands = patch('ansible_collections.community.general.plugins.modules.network.aruba.aruba_command.run_commands')
self.run_commands = self.mock_run_commands.start()
def tearDown(self):
super(TestArubaCommandModule, self).tearDown()
self.mock_run_commands.stop()
def load_fixtures(self, commands=None):
def load_from_file(*args, **kwargs):
module, commands = args
output = list()
for item in commands:
try:
obj = json.loads(item['command'])
command = obj['command']
except ValueError:
command = item['command']
filename = str(command).replace(' ', '_')
output.append(load_fixture(filename))
return output
self.run_commands.side_effect = load_from_file
def test_aruba_command_simple(self):
set_module_args(dict(commands=['show version']))
result = self.execute_module()
self.assertEqual(len(result['stdout']), 1)
self.assertTrue(result['stdout'][0].startswith('Aruba Operating System Software'))
def test_aruba_command_multiple(self):
set_module_args(dict(commands=['show version', 'show version']))
result = self.execute_module()
self.assertEqual(len(result['stdout']), 2)
self.assertTrue(result['stdout'][0].startswith('Aruba Operating System Software'))
def test_aruba_command_wait_for(self):
wait_for = 'result[0] contains "Aruba Operating System Software"'
set_module_args(dict(commands=['show version'], wait_for=wait_for))
self.execute_module()
def test_aruba_command_wait_for_fails(self):
wait_for = 'result[0] contains "test string"'
set_module_args(dict(commands=['show version'], wait_for=wait_for))
self.execute_module(failed=True)
self.assertEqual(self.run_commands.call_count, 10)
def test_aruba_command_retries(self):
wait_for = 'result[0] contains "test string"'
set_module_args(dict(commands=['show version'], wait_for=wait_for, retries=2))
self.execute_module(failed=True)
self.assertEqual(self.run_commands.call_count, 2)
def test_aruba_command_match_any(self):
wait_for = ['result[0] contains "Aruba Operating System Software"',
'result[0] contains "test string"']
set_module_args(dict(commands=['show version'], wait_for=wait_for, match='any'))
self.execute_module()
def test_aruba_command_match_all(self):
wait_for = ['result[0] contains "Aruba Operating System Software"',
'result[0] contains "Aruba Networks"']
set_module_args(dict(commands=['show version'], wait_for=wait_for, match='all'))
self.execute_module()
def test_aruba_command_match_all_failure(self):
wait_for = ['result[0] contains "Aruba Operating System Software"',
'result[0] contains "test string"']
commands = ['show version', 'show version']
set_module_args(dict(commands=commands, wait_for=wait_for, match='all'))
self.execute_module(failed=True)

View file

@ -0,0 +1,189 @@
#
# (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
from ansible_collections.community.general.tests.unit.compat.mock import patch
from ansible_collections.community.general.plugins.modules.network.aruba import aruba_config
from ansible_collections.community.general.tests.unit.plugins.modules.utils import set_module_args
from .aruba_module import TestArubaModule, load_fixture
class TestArubaConfigModule(TestArubaModule):
module = aruba_config
def setUp(self):
super(TestArubaConfigModule, self).setUp()
self.mock_get_config = patch('ansible_collections.community.general.plugins.modules.network.aruba.aruba_config.get_config')
self.get_config = self.mock_get_config.start()
self.mock_load_config = patch('ansible_collections.community.general.plugins.modules.network.aruba.aruba_config.load_config')
self.load_config = self.mock_load_config.start()
self.mock_run_commands = patch('ansible_collections.community.general.plugins.modules.network.aruba.aruba_config.run_commands')
self.run_commands = self.mock_run_commands.start()
def tearDown(self):
super(TestArubaConfigModule, self).tearDown()
self.mock_get_config.stop()
self.mock_load_config.stop()
self.mock_run_commands.stop()
def load_fixtures(self, commands=None):
config_file = 'aruba_config_config.cfg'
self.get_config.return_value = load_fixture(config_file)
self.load_config.return_value = None
def test_aruba_config_unchanged(self):
src = load_fixture('aruba_config_config.cfg')
set_module_args(dict(src=src))
self.execute_module()
def test_aruba_config_unchanged_different_spacing(self):
# Tab indented
set_module_args(dict(lines=['description test string'], parents=['interface GigabitEthernet0/0']))
self.execute_module(changed=False)
# 3 spaces indented
set_module_args(dict(lines=['essid "blah"'], parents=['wlan ssid-profile "blah"']))
self.execute_module(changed=False)
def test_aruba_config_src(self):
src = load_fixture('aruba_config_src.cfg')
set_module_args(dict(src=src))
commands = ['hostname foo', 'interface GigabitEthernet0/0',
'no ip address']
self.execute_module(changed=True, commands=commands)
def test_aruba_config_backup(self):
set_module_args(dict(backup=True))
result = self.execute_module()
self.assertIn('__backup__', result)
def test_aruba_config_save_always(self):
self.run_commands.return_value = "Hostname foo"
set_module_args(dict(save_when='always'))
self.execute_module(changed=True)
self.assertEqual(self.run_commands.call_count, 1)
self.assertEqual(self.get_config.call_count, 0)
self.assertEqual(self.load_config.call_count, 0)
args = self.run_commands.call_args[0][1]
self.assertIn('write memory', args)
def test_aruba_config_save_changed_true(self):
src = load_fixture('aruba_config_src.cfg')
set_module_args(dict(src=src, save_when='changed'))
commands = ['hostname foo', 'interface GigabitEthernet0/0',
'no ip address']
self.execute_module(changed=True, commands=commands)
# src = load_fixture('aruba_config_src.cfg')
# set_module_args(dict(save_when='changed'))
# commands = ['hostname changed']
# self.execute_module(changed=False, commands=commands)
self.assertEqual(self.run_commands.call_count, 1)
self.assertEqual(self.get_config.call_count, 1)
self.assertEqual(self.load_config.call_count, 1)
args = self.run_commands.call_args[0][1]
self.assertIn('write memory', args)
def test_aruba_config_save_changed_false(self):
set_module_args(dict(save_when='changed'))
self.execute_module(changed=False)
self.assertEqual(self.run_commands.call_count, 0)
self.assertEqual(self.get_config.call_count, 0)
self.assertEqual(self.load_config.call_count, 0)
def test_aruba_config_lines_wo_parents(self):
set_module_args(dict(lines=['hostname foo']))
commands = ['hostname foo']
self.execute_module(changed=True, commands=commands)
def test_aruba_config_lines_w_parents(self):
set_module_args(dict(lines=['shutdown'], parents=['interface GigabitEthernet0/0']))
commands = ['interface GigabitEthernet0/0', 'shutdown']
self.execute_module(changed=True, commands=commands)
def test_aruba_config_before(self):
set_module_args(dict(lines=['hostname foo'], before=['test1', 'test2']))
commands = ['test1', 'test2', 'hostname foo']
self.execute_module(changed=True, commands=commands, sort=False)
def test_aruba_config_after(self):
set_module_args(dict(lines=['hostname foo'], after=['test1', 'test2']))
commands = ['hostname foo', 'test1', 'test2']
self.execute_module(changed=True, commands=commands, sort=False)
def test_aruba_config_before_after_no_change(self):
set_module_args(dict(lines=['hostname router'],
before=['test1', 'test2'],
after=['test3', 'test4']))
self.execute_module()
def test_aruba_config_config(self):
config = 'hostname localhost'
set_module_args(dict(lines=['hostname router'], config=config))
commands = ['hostname router']
self.execute_module(changed=True, commands=commands)
def test_aruba_config_replace_block(self):
lines = ['description test string', 'test string']
parents = ['interface GigabitEthernet0/0']
set_module_args(dict(lines=lines, replace='block', parents=parents))
commands = parents + lines
self.execute_module(changed=True, commands=commands)
def test_aruba_config_force(self):
lines = ['hostname router']
set_module_args(dict(lines=lines, match='none'))
self.execute_module(changed=True, commands=lines)
def test_aruba_config_match_none(self):
lines = ['ip address 1.2.3.4 255.255.255.0', 'description test string']
parents = ['interface GigabitEthernet0/0']
set_module_args(dict(lines=lines, parents=parents, match='none'))
commands = parents + lines
self.execute_module(changed=True, commands=commands, sort=False)
def test_aruba_config_match_strict(self):
lines = ['ip address 1.2.3.4 255.255.255.0', 'description test string',
'shutdown']
parents = ['interface GigabitEthernet0/0']
set_module_args(dict(lines=lines, parents=parents, match='strict'))
commands = parents + ['shutdown']
self.execute_module(changed=True, commands=commands, sort=False)
def test_aruba_config_match_exact(self):
lines = ['ip address 1.2.3.4 255.255.255.0', 'description test string',
'shutdown']
parents = ['interface GigabitEthernet0/0']
set_module_args(dict(lines=lines, parents=parents, match='exact'))
commands = parents + lines
self.execute_module(changed=True, commands=commands, sort=False)
def test_aruba_encrypt_false(self):
set_module_args(dict(encrypt=False))
self.execute_module()
self.assertEqual(self.run_commands.call_count, 2)
args = self.run_commands.call_args_list
self.assertIn('encrypt disable', args[0][0])
self.assertIn('encrypt enable', args[1][0])

View file

@ -0,0 +1,215 @@
{
"mock_create_res": {
"ansible_facts": {
"avi_api_context": {
"192.0.2.97:admin:None": {
"csrftoken": "qG23CCARDL3rh1KZ66XXPIeUYCUCOZ4q",
"session_id": "h5nynf9u9nompp5byai7vii2v8bbn9kd"
}
}
},
"api_context": null,
"changed": true,
"invocation": {
"module_args": {
"access": [{
"role_ref": "/api/role?name=Tenant-Admin",
"tenant_ref": "/api/tenant/********#********",
"all_tenants": false
}],
"api_context": null,
"api_version": "18.2.5",
"avi_api_update_method": "put",
"avi_credentials": null,
"avi_disable_session_cache_as_fact": false,
"avi_login_info": null,
"controller": "192.0.2.97",
"default_tenant_ref": "/api/tenant?name=********",
"email": "test@abc.com",
"is_active": true,
"is_superuser": true,
"name": "testuser",
"obj_password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"obj_username": "testuser",
"password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"state": "present",
"tenant": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"tenant_uuid": "",
"user_profile_ref": "/api/useraccountprofile?name=Default-User-Account-Profile",
"username": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
}
},
"obj": {
"_last_modified": "1559736767460818",
"access": [{
"all_tenants": false,
"role_ref": "https://192.0.2.97/api/tenant/********/role/role-ff851004-bd75-485b-87ec-2fe1d6a03fb9#Tenant-Admin",
"tenant_ref": "https://192.0.2.97/api/tenant/********#********"
}],
"default_tenant_ref": "https://192.0.2.97/api/tenant/********#********",
"email": "test@abc.com",
"full_name": "testuser",
"is_active": true,
"is_superuser": true,
"local": true,
"name": "testuser",
"obj_password": "<sensitive>",
"obj_username": "testuser",
"password": "<sensitive>",
"uid": 2004,
"url": "https://192.0.2.97/api/user/user-7087578f-4dfe-4e06-a153-495a91824a1d#testuser",
"user_profile_ref": "https://192.0.2.97/api/useraccountprofile/useraccountprofile-78063e7c-b443-48d6-b34c-5253ae1fcd2a#Default-User-Account-Profile",
"username": "testuser",
"uuid": "user-7087578f-4dfe-4e06-a153-495a91824a1d"
},
"old_obj": null
},
"mock_put_res": {
"obj": {
"username": "testuser",
"user_profile_ref": "https://192.0.2.97/api/useraccountprofile/useraccountprofile-546c5e88-6270-4ba1-9cfd-d0c755e68f47#Default-User-Account-Profile",
"name": "testuser",
"url": "https://192.0.2.97/api/user/user-ed10f328-bd92-4db2-bacd-0cf795fcbf8a#testuser",
"is_active": true,
"uuid": "user-ed10f328-bd92-4db2-bacd-0cf795fcbf8a",
"email": "newemail@abc.com",
"access": [{
"tenant_ref": "https://192.0.2.97/api/tenant/tenant-57af0f3f-6f14-4657-8f32-9b289407752b#Test-Admin",
"all_tenants": false,
"role_ref": "https://192.0.2.97/api/tenant/********/role/role-b073ab0d-e1d0-4800-95ef-6ecf2c5ed7d1#Tenant-Admin"
}],
"is_superuser": true,
"obj_username": "testuser",
"full_name": "testuser",
"_last_modified": "1559802772203285",
"password": "<sensitive>",
"local": true,
"obj_password": "<sensitive>",
"default_tenant_ref": "https://192.0.2.97/api/tenant/********#********",
"uid": 2002
},
"changed": true,
"api_context": null,
"invocation": {
"module_args": {
"username": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"user_profile_ref": "/api/useraccountprofile?name=Default-User-Account-Profile",
"api_version": "18.2.5",
"name": "testuser",
"state": "present",
"is_active": true,
"api_context": null,
"avi_disable_session_cache_as_fact": false,
"controller": "192.0.2.97",
"avi_api_patch_op": null,
"access": [{
"tenant_ref": "/api/tenant?name=Test-Admin",
"all_tenants": false,
"role_ref": "/api/role?name=Tenant-Admin"
}],
"is_superuser": true,
"avi_credentials": null,
"email": "newemail@abc.com",
"default_tenant_ref": "/api/tenant?name=********",
"obj_username": "testuser",
"password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"tenant_uuid": "",
"obj_password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"avi_api_update_method": "put",
"tenant": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
}
},
"ansible_facts": {
"avi_api_context": {
"192.0.2.97:admin:None": {
"csrftoken": "Y7CET6zaIC9VZAzBqEW4cWo1N26jPg55",
"session_id": "364n7o0p3o5so63b9rzd47v6ehya6xg7"
}
}
},
"old_obj": {
"username": "testuser",
"user_profile_ref": "https://192.0.2.97/api/useraccountprofile/useraccountprofile-546c5e88-6270-4ba1-9cfd-d0c755e68f47#Default-User-Account-Profile",
"name": "testuser",
"url": "https://192.0.2.97/api/user/user-ed10f328-bd92-4db2-bacd-0cf795fcbf8a#testuser",
"is_active": true,
"uuid": "user-ed10f328-bd92-4db2-bacd-0cf795fcbf8a",
"access": [{
"tenant_ref": "https://192.0.2.97/api/tenant/tenant-57af0f3f-6f14-4657-8f32-9b289407752b#Test-Admin",
"all_tenants": false,
"role_ref": "https://192.0.2.97/api/tenant/********/role/role-b073ab0d-e1d0-4800-95ef-6ecf2c5ed7d1#Tenant-Admin"
}],
"is_superuser": true,
"full_name": "testuser",
"ui_property": "",
"password": "<sensitive>",
"local": true,
"email": "test@abc.com",
"default_tenant_ref": "https://192.0.2.97/api/tenant/********#********",
"uid": 2002
}
},
"mock_del_res": {
"ansible_facts": {
"avi_api_context": {
"192.0.2.97:admin:None": {
"csrftoken": "Vtkx9GeS2lsrld5yX83cmJqbZO3MAimb",
"session_id": "ix3t1dja8yzwb155de59viyn96hibn6b"
}
}
},
"api_context": null,
"changed": true,
"invocation": {
"module_args": {
"access": [{
"role_ref": "/api/role?name=Tenant-Admin",
"tenant_ref": "/api/tenant/********#********"
}],
"api_context": null,
"api_version": "18.2.5",
"avi_api_update_method": "put",
"avi_credentials": null,
"avi_disable_session_cache_as_fact": false,
"avi_login_info": null,
"controller": "192.0.2.97",
"default_tenant_ref": "/api/tenant?name=********",
"email": "test@abc.com",
"is_active": true,
"is_superuser": true,
"name": "testuser",
"obj_password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"obj_username": "testuser",
"password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"state": "absent",
"tenant": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"tenant_uuid": "",
"user_profile_ref": "/api/useraccountprofile?name=Default-User-Account-Profile",
"username": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
}
},
"obj": null,
"old_obj": {
"_last_modified": "1559803346264869",
"access": [{
"all_tenants": false,
"role_ref": "https://192.0.2.97/api/tenant/********/role/role-b073ab0d-e1d0-4800-95ef-6ecf2c5ed7d1#Tenant-Admin",
"tenant_ref": "https://192.0.2.97/api/tenant/tenant-57af0f3f-6f14-4657-8f32-9b289407752b#Test-Admin"
}],
"default_tenant_ref": "https://192.0.2.97/api/tenant/********#********",
"email": "newemail@abc.com",
"full_name": "testuser",
"is_active": true,
"is_superuser": true,
"local": true,
"name": "testuser",
"password": "<sensitive>",
"ui_property": "",
"uid": 2002,
"url": "https://192.0.2.97/api/user/user-ed10f328-bd92-4db2-bacd-0cf795fcbf8a#testuser",
"user_profile_ref": "https://192.0.2.97/api/useraccountprofile/useraccountprofile-546c5e88-6270-4ba1-9cfd-d0c755e68f47#Default-User-Account-Profile",
"username": "testuser",
"uuid": "user-ed10f328-bd92-4db2-bacd-0cf795fcbf8a"
}
}
}

View file

@ -0,0 +1,101 @@
import os
import json
from ansible_collections.community.general.tests.unit.compat import unittest
from ansible_collections.community.general.tests.unit.compat.mock import Mock
from ansible_collections.community.general.tests.unit.plugins.modules.utils import set_module_args
from ansible_collections.community.general.plugins.modules.network.avi import avi_user
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
with open(fixture_path + '/avi_user.json') as json_file:
data = json.load(json_file)
class TestAviUser(unittest.TestCase):
def test_create_user(self):
set_module_args({
"avi_credentials": {
"controller": "192.0.2.13",
"username": "username",
"password": "fakepassword",
"api_version": "18.2.5"
},
"state": "present",
"name": "testuser",
"obj_username": "testuser",
"obj_password": "test123",
"email": "test@abc.com",
"access": [
{
"role_ref": "/api/role?name=Tenant-Admin",
"tenant_ref": "/api/tenant?name=Test-Admin",
"all_tenants": False
}
],
"user_profile_ref": "/api/useraccountprofile?name=Default-User-Account-Profile",
"is_active": True,
"is_superuser": True,
"default_tenant_ref": "/api/tenant?name=admin"
})
avi_user.avi_ansible_api = Mock(return_value=data['mock_create_res'])
response = avi_user.main()
assert response['changed']
def test_put_on_user(self):
set_module_args({
"avi_credentials": {
"controller": "192.0.2.13",
"username": "username",
"password": "fakepassword",
"api_version": "18.2.5"
},
"state": "present",
"avi_api_update_method": "put",
"name": "testuser",
"obj_username": "testuser",
"obj_password": "test123",
"email": "newemail@abc.com",
"access": [{
"role_ref": "/api/role?name=Tenant-Admin",
"tenant_ref": "/api/tenant?name=Test-Admin",
"all_tenants": False
}],
"user_profile_ref": "/api/useraccountprofile?name=Default-User-Account-Profile",
"is_active": True,
"is_superuser": True,
"default_tenant_ref": "/api/tenant?name=admin"
})
avi_user.avi_ansible_api = Mock(return_value=data['mock_put_res'])
response = avi_user.main()
assert response['changed']
assert response['obj']
assert response['old_obj']
def test_delete_user(self):
set_module_args({
"avi_credentials": {
"controller": "192.0.2.13",
"username": "username",
"password": "fakepassword",
"api_version": "18.2.5"
},
"name": "testuser",
"obj_username": "testuser",
"obj_password": "test123",
"email": "test@abc.com",
"access": [{
"role_ref": "/api/role?name=Tenant-Admin",
"tenant_ref": "/api/tenant?name=Test-Admin",
"all_tenants": False
}],
"user_profile_ref": "/api/useraccountprofile?name=Default-User-Account-Profile",
"is_active": True,
"is_superuser": True,
"default_tenant_ref": "/api/tenant?name=admin"
})
avi_user.avi_ansible_api = Mock(return_value=data['mock_del_res'])
response = avi_user.main()
assert response['changed']
assert not response['obj']
assert response['old_obj']

View file

@ -0,0 +1,105 @@
# Copyright (c) 2018 Red Hat
#
# 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/>.
#
from __future__ import absolute_import
import pytest
from ansible_collections.community.general.tests.unit.plugins.modules.utils import set_module_args, exit_json, fail_json, AnsibleFailJson, AnsibleExitJson
from ansible.module_utils import basic
from ansible_collections.community.general.plugins.modules.network.check_point import checkpoint_access_rule
OBJECT = {'layer': 'foo', 'position': 'bar', 'name': 'baz',
'source': [{'name': 'lol'}], 'destination': [{'name': 'Any'}],
'action': {'name': 'drop'}, 'enabled': True}
PAYLOAD = {'layer': 'foo', 'position': 'bar', 'name': 'baz'}
class TestCheckpointAccessRule(object):
module = checkpoint_access_rule
@pytest.fixture(autouse=True)
def module_mock(self, mocker):
return mocker.patch.multiple(basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json)
@pytest.fixture
def connection_mock(self, mocker):
connection_class_mock = mocker.patch('ansible_collections.community.general.plugins.modules.network.check_point.checkpoint_access_rule.Connection')
return connection_class_mock.return_value
@pytest.fixture
def get_access_rule_200(self, mocker):
mock_function = mocker.patch('ansible_collections.community.general.plugins.modules.network.check_point.checkpoint_access_rule.get_access_rule')
mock_function.return_value = (200, OBJECT)
return mock_function.return_value
@pytest.fixture
def get_access_rule_404(self, mocker):
mock_function = mocker.patch('ansible_collections.community.general.plugins.modules.network.check_point.checkpoint_access_rule.get_access_rule')
mock_function.return_value = (404, 'Object not found')
return mock_function.return_value
def test_create(self, get_access_rule_404, connection_mock):
connection_mock.send_request.return_value = (200, OBJECT)
result = self._run_module(PAYLOAD)
assert result['changed']
assert 'checkpoint_access_rules' in result
def test_create_idempotent(self, get_access_rule_200, connection_mock):
connection_mock.send_request.return_value = (200, PAYLOAD)
result = self._run_module(PAYLOAD)
assert not result['changed']
def test_update(self, get_access_rule_200, connection_mock):
payload_for_update = {'enabled': False}
payload_for_update.update(PAYLOAD)
connection_mock.send_request.return_value = (200, payload_for_update)
result = self._run_module(payload_for_update)
assert result['changed']
assert not result['checkpoint_access_rules']['enabled']
def test_delete(self, get_access_rule_200, connection_mock):
connection_mock.send_request.return_value = (200, OBJECT)
payload_for_delete = {'state': 'absent'}
payload_for_delete.update(PAYLOAD)
result = self._run_module(payload_for_delete)
assert result['changed']
def test_delete_idempotent(self, get_access_rule_404, connection_mock):
payload = {'name': 'baz', 'state': 'absent'}
connection_mock.send_request.return_value = (200, OBJECT)
result = self._run_module(payload)
assert not result['changed']
def _run_module(self, module_args):
set_module_args(module_args)
with pytest.raises(AnsibleExitJson) as ex:
self.module.main()
return ex.value.args[0]
def _run_module_with_fail_json(self, module_args):
set_module_args(module_args)
with pytest.raises(AnsibleFailJson) as exc:
self.module.main()
result = exc.value.args[0]
return result

View file

@ -0,0 +1,99 @@
# Copyright (c) 2018 Red Hat
#
# 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/>.
#
from __future__ import absolute_import
import pytest
from ansible_collections.community.general.tests.unit.plugins.modules.utils import set_module_args, exit_json, fail_json, AnsibleFailJson, AnsibleExitJson
from ansible.module_utils import basic
from ansible_collections.community.general.plugins.modules.network.check_point import checkpoint_host
OBJECT = {'name': 'foo', 'ipv4-address': '192.168.0.15'}
CREATE_PAYLOAD = {'name': 'foo', 'ip_address': '192.168.0.15'}
UPDATE_PAYLOAD = {'name': 'foo', 'ip_address': '192.168.0.16'}
DELETE_PAYLOAD = {'name': 'foo', 'state': 'absent'}
class TestCheckpointHost(object):
module = checkpoint_host
@pytest.fixture(autouse=True)
def module_mock(self, mocker):
return mocker.patch.multiple(basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json)
@pytest.fixture
def connection_mock(self, mocker):
connection_class_mock = mocker.patch('ansible_collections.community.general.plugins.modules.network.check_point.checkpoint_host.Connection')
return connection_class_mock.return_value
@pytest.fixture
def get_host_200(self, mocker):
mock_function = mocker.patch('ansible_collections.community.general.plugins.modules.network.check_point.checkpoint_host.get_host')
mock_function.return_value = (200, OBJECT)
return mock_function.return_value
@pytest.fixture
def get_host_404(self, mocker):
mock_function = mocker.patch('ansible_collections.community.general.plugins.modules.network.check_point.checkpoint_host.get_host')
mock_function.return_value = (404, 'Object not found')
return mock_function.return_value
def test_create(self, get_host_404, connection_mock):
connection_mock.send_request.return_value = (200, OBJECT)
result = self._run_module(CREATE_PAYLOAD)
assert result['changed']
assert 'checkpoint_hosts' in result
def test_create_idempotent(self, get_host_200, connection_mock):
connection_mock.send_request.return_value = (200, OBJECT)
result = self._run_module(CREATE_PAYLOAD)
assert not result['changed']
def test_update(self, get_host_200, connection_mock):
connection_mock.send_request.return_value = (200, OBJECT)
result = self._run_module(UPDATE_PAYLOAD)
assert result['changed']
def test_delete(self, get_host_200, connection_mock):
connection_mock.send_request.return_value = (200, OBJECT)
result = self._run_module(DELETE_PAYLOAD)
assert result['changed']
def test_delete_idempotent(self, get_host_404, connection_mock):
connection_mock.send_request.return_value = (200, OBJECT)
result = self._run_module(DELETE_PAYLOAD)
assert not result['changed']
def _run_module(self, module_args):
set_module_args(module_args)
with pytest.raises(AnsibleExitJson) as ex:
self.module.main()
return ex.value.args[0]
def _run_module_with_fail_json(self, module_args):
set_module_args(module_args)
with pytest.raises(AnsibleFailJson) as exc:
self.module.main()
result = exc.value.args[0]
return result

View file

@ -0,0 +1,67 @@
# Copyright (c) 2018 Red Hat
#
# 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/>.
#
from __future__ import absolute_import
import pytest
from ansible_collections.community.general.tests.unit.plugins.modules.utils import set_module_args, exit_json, fail_json, AnsibleFailJson, AnsibleExitJson
from ansible.module_utils import basic
from ansible_collections.community.general.plugins.modules.network.check_point import checkpoint_session
OBJECT = {'uid': '1234'}
PAYLOAD = {}
class TestCheckpointAccessRule(object):
module = checkpoint_session
@pytest.fixture(autouse=True)
def module_mock(self, mocker):
return mocker.patch.multiple(basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json)
@pytest.fixture
def connection_mock(self, mocker):
connection_class_mock = mocker.patch('ansible_collections.community.general.plugins.modules.network.check_point.checkpoint_session.Connection')
return connection_class_mock.return_value
@pytest.fixture
def get_session_200(self, mocker):
mock_function = mocker.patch('ansible_collections.community.general.plugins.modules.network.check_point.checkpoint_session.get_session')
mock_function.return_value = (200, OBJECT)
return mock_function.return_value
def test_publish(self, get_session_200, connection_mock):
connection_mock.send_request.return_value = (200, OBJECT)
result = self._run_module(PAYLOAD)
assert result['changed']
assert 'checkpoint_session' in result
def _run_module(self, module_args):
set_module_args(module_args)
with pytest.raises(AnsibleExitJson) as ex:
self.module.main()
return ex.value.args[0]
def _run_module_with_fail_json(self, module_args):
set_module_args(module_args)
with pytest.raises(AnsibleFailJson) as exc:
self.module.main()
result = exc.value.args[0]
return result

View file

@ -0,0 +1,99 @@
# Copyright (c) 2018 Red Hat
#
# 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/>.
#
from __future__ import absolute_import
import pytest
from ansible_collections.community.general.tests.unit.plugins.modules.utils import set_module_args, exit_json, fail_json, AnsibleFailJson, AnsibleExitJson
from ansible.module_utils import basic
from ansible_collections.community.general.plugins.modules.network.check_point import checkpoint_host
OBJECT = {'name': 'foo', 'ipv4-address': '192.168.0.15'}
CREATE_PAYLOAD = {'name': 'foo', 'ip_address': '192.168.0.15'}
UPDATE_PAYLOAD = {'name': 'foo', 'ip_address': '192.168.0.16'}
DELETE_PAYLOAD = {'name': 'foo', 'state': 'absent'}
class TestCheckpointHost(object):
module = checkpoint_host
@pytest.fixture(autouse=True)
def module_mock(self, mocker):
return mocker.patch.multiple(basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json)
@pytest.fixture
def connection_mock(self, mocker):
connection_class_mock = mocker.patch('ansible_collections.community.general.plugins.modules.network.check_point.checkpoint_host.Connection')
return connection_class_mock.return_value
@pytest.fixture
def get_host_200(self, mocker):
mock_function = mocker.patch('ansible_collections.community.general.plugins.modules.network.check_point.checkpoint_host.get_host')
mock_function.return_value = (200, OBJECT)
return mock_function.return_value
@pytest.fixture
def get_host_404(self, mocker):
mock_function = mocker.patch('ansible_collections.community.general.plugins.modules.network.check_point.checkpoint_host.get_host')
mock_function.return_value = (404, 'Object not found')
return mock_function.return_value
def test_create(self, get_host_404, connection_mock):
connection_mock.send_request.return_value = (200, OBJECT)
result = self._run_module(CREATE_PAYLOAD)
assert result['changed']
assert 'checkpoint_hosts' in result
def test_create_idempotent(self, get_host_200, connection_mock):
connection_mock.send_request.return_value = (200, OBJECT)
result = self._run_module(CREATE_PAYLOAD)
assert not result['changed']
def test_update(self, get_host_200, connection_mock):
connection_mock.send_request.return_value = (200, OBJECT)
result = self._run_module(UPDATE_PAYLOAD)
assert result['changed']
def test_delete(self, get_host_200, connection_mock):
connection_mock.send_request.return_value = (200, OBJECT)
result = self._run_module(DELETE_PAYLOAD)
assert result['changed']
def test_delete_idempotent(self, get_host_404, connection_mock):
connection_mock.send_request.return_value = (200, OBJECT)
result = self._run_module(DELETE_PAYLOAD)
assert not result['changed']
def _run_module(self, module_args):
set_module_args(module_args)
with pytest.raises(AnsibleExitJson) as ex:
self.module.main()
return ex.value.args[0]
def _run_module_with_fail_json(self, module_args):
set_module_args(module_args)
with pytest.raises(AnsibleFailJson) as exc:
self.module.main()
result = exc.value.args[0]
return result

View file

@ -0,0 +1,90 @@
# Copyright (c) 2019 Red Hat
#
# This file is a 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 os
import json
from ansible_collections.community.general.tests.unit.plugins.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {}
def load_fixture(module_name, name, device=''):
path = os.path.join(fixture_path, module_name, device, name)
if not os.path.exists(path):
path = os.path.join(fixture_path, module_name, name)
if path in fixture_data:
return fixture_data[path]
with open(path) as f:
data = f.read()
try:
data = json.loads(data)
except Exception:
pass
fixture_data[path] = data
return data
class TestCloudEngineModule(ModuleTestCase):
def execute_module(self, failed=False, changed=False, commands=None, sort=True, defaults=False):
self.load_fixtures(commands)
if failed:
result = self.failed()
self.assertTrue(result['failed'], result)
else:
result = self.changed(changed)
self.assertEqual(result['changed'], changed, result)
if commands is not None:
if sort:
self.assertEqual(sorted(commands), sorted(result['commands']), result['commands'])
else:
self.assertEqual(commands, result['commands'], result['commands'])
return result
def failed(self):
with self.assertRaises(AnsibleFailJson) as exc:
self.module.main()
result = exc.exception.args[0]
self.assertTrue(result['failed'], result)
return result
def changed(self, changed=False):
with self.assertRaises(AnsibleExitJson) as exc:
self.module.main()
result = exc.exception.args[0]
self.assertEqual(result['changed'], changed, result)
return result
def load_fixtures(self, commands=None):
pass

View file

@ -0,0 +1,11 @@
<data>
<isiscomm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
<isSites>
<isSite>
<instanceId>100</instanceId>
<vpnName>_public_</vpnName>
<description>ISIS</description>
</isSite>
</isSites>
</isiscomm>
</data>

View file

@ -0,0 +1,11 @@
<data>
<isiscomm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
<isSites>
<isSite>
<instanceId></instanceId>
<vpnName></vpnName>
<description></description>
</isSite>
</isSites>
</isiscomm>
</data>

View file

@ -0,0 +1,26 @@
<data>
<isiscomm>
<isSites>
<isSite>
<instanceId>100</instanceId>
<isCircuits>
<isCircuit>
<ifName></ifName>
<circuitLevelType>level_1</circuitLevelType>
<level1DisPriority>10</level1DisPriority>
<level2DisPriority>10</level2DisPriority>
<silentEnable>true</silentEnable>
<silentCost>true</silentCost>
<typeP2pEnable>true</typeP2pEnable>
<snpaCheck>true</snpaCheck>
<p2pNegotiationMode>2_way</p2pNegotiationMode>
<p2pPeerIPIgnore>true</p2pPeerIPIgnore>
<pPPOsicpCheckEnable>true</pPPOsicpCheckEnable>
<level1Cost>10</level1Cost>
<level2Cost>10</level2Cost>
</isCircuit>
</isCircuits>
</isSite>
</isSites>
</isiscomm>
</data>

View file

@ -0,0 +1,26 @@
<data>
<isiscomm>
<isSites>
<isSite>
<instanceId>100</instanceId>
<isCircuits>
<isCircuit>
<ifName></ifName>
<circuitLevelType></circuitLevelType>
<level1DisPriority></level1DisPriority>
<level2DisPriority></level2DisPriority>
<silentEnable></silentEnable>
<silentCost></silentCost>
<typeP2pEnable></typeP2pEnable>
<snpaCheck></snpaCheck>
<p2pNegotiationMode></p2pNegotiationMode>
<p2pPeerIPIgnore></p2pPeerIPIgnore>
<pPPOsicpCheckEnable></pPPOsicpCheckEnable>
<level1Cost></level1Cost>
<level2Cost></level2Cost>
</isCircuit>
</isCircuits>
</isSite>
</isSites>
</isiscomm>
</data>

View file

@ -0,0 +1,104 @@
<data>
<isiscomm>
<isSites>
<isSite>
<instanceId>100</instanceId>
<vpnName>_public_</vpnName>
<description>ISIS</description>
<isLevel>level_1</isLevel>
<costStyle>narrow</costStyle>
<relaxSpfLimit>true</relaxSpfLimit>
<stdLevel1Cost>60</stdLevel1Cost>
<stdLevel2Cost>60</stdLevel2Cost>
<stdbandwidth>100</stdbandwidth>
<stdAutoCostEnable>true</stdAutoCostEnable>
<stdAutoCostEnableCompatible>true</stdAutoCostEnableCompatible>
<isNetEntitys>
<isNetEntity>
<netEntity>netentity</netEntity>
</isNetEntity>
</isNetEntitys>
<isSiteMTs>
<isSiteMT>
<addressFamily>afIpv4</addressFamily>
<mtId>0</mtId>
<bfdMinRx>100</bfdMinRx>
<bfdMinTx>100</bfdMinTx>
<bfdMultNum>10</bfdMultNum>
<maxLoadBalancing>32</maxLoadBalancing>
<isPreferences>
<isPreference>
<preferenceValue>100</preferenceValue>
<routePolicyName>route</routePolicyName>
</isPreference>
</isPreferences>
<isNextHopWeights>
<isNextHopWeight>
<ipAddress>1.1.1.1</ipAddress>
<weight>100</weight>
</isNextHopWeight>
</isNextHopWeights>
<isFilterImports>
<isFilterImport>
<aclNumOrName>3001</aclNumOrName>
<ipPrefix>ip</ipPrefix>
<routePolicyName>route</routePolicyName>
<policyType>level_1</policyType>
</isFilterImport>
</isFilterImports>
<isFilterExports>
<isFilterExport>
<protocol>ospf</protocol>
<processId>100</processId>
<policyType>level_1</policyType>
</isFilterExport>
</isFilterExports>
<isDefaultRoutes>
<isDefaultRoute>
<defaultMode>always</defaultMode>
<routePolicyName>mode</routePolicyName>
<cost>100</cost>
<tag>100</tag>
<levelType>level_1</levelType>
<avoidLearning>true</avoidLearning>
</isDefaultRoute>
</isDefaultRoutes>
<isImportRoutes>
<isImportRoute>
<protocol>import</protocol>
<processId>100</processId>
<costType>level_1</costType>
<cost>100</cost>
<tag>100</tag>
<policyType>level_1</policyType>
<routePolicyName>import</routePolicyName>
<levelType>level_1</levelType>
<inheritCost>100</inheritCost>
<permitIbgp>true</permitIbgp>
</isImportRoute>
</isImportRoutes>
<isLeakRouteLevel1ToLevel2s>
<isLeakRouteLevel1ToLevel2>
<tag>100</tag>
<routePolicyName>route</routePolicyName>
<aclNumOrName>3001</aclNumOrName>
<ipPrefix>ip</ipPrefix>
<leakEnableFlag>true</leakEnableFlag>
<allowFilter>true</allowFilter>
</isLeakRouteLevel1ToLevel2>
</isLeakRouteLevel1ToLevel2s>
<isLeakRouteLevel2ToLevel1s>
<isLeakRouteLevel2ToLevel1>
<tag>100</tag>
<routePolicyName>route</routePolicyName>
<aclNumOrName>3001</aclNumOrName>
<ipPrefix>ip</ipPrefix>
<allowFilter>true</allowFilter>
</isLeakRouteLevel2ToLevel1>
</isLeakRouteLevel2ToLevel1s>
</isSiteMT>
</isSiteMTs>
</isSite>
</isSites>
</isiscomm>
</data>

View file

@ -0,0 +1,10 @@
<data>
<isiscomm>
<isSites>
<isSite>
<instanceId>100</instanceId>
<vpnName>_public_</vpnName>
</isSite>
</isSites>
</isiscomm>
</data>

View file

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="1024">
<data>
<ifmtrunk xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
<TrunkIfs>
<TrunkIf>
<ifName>Eth-Trunk10</ifName>
<lacpTrunk>
<isSupportPrmpt>false</isSupportPrmpt>
<rcvTimeoutType>Fast</rcvTimeoutType>
<fastTimeoutUserDefinedValue>3</fastTimeoutUserDefinedValue>
<selectPortStd>Speed</selectPortStd>
<promptDelay>30</promptDelay>
<maxActiveNum>1</maxActiveNum>
<collectMaxDelay>0</collectMaxDelay>
<mixRateEnable>false</mixRateEnable>
<dampStaFlapEn>false</dampStaFlapEn>
<dampUnexpMacEn>false</dampUnexpMacEn>
<trunkSysMac>11-22-33</trunkSysMac>
<trunkPortIdExt>false</trunkPortIdExt>
</lacpTrunk>
</TrunkIf>
</TrunkIfs>
</ifmtrunk>
</data>
</rpc-reply>

View file

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="1024">
<data>
<ifmtrunk xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
<TrunkIfs>
<TrunkIf>
<ifName>Eth-Trunk10</ifName>
<lacpTrunk>
<isSupportPrmpt>true</isSupportPrmpt>
<rcvTimeoutType>Fast</rcvTimeoutType>
<fastTimeoutUserDefinedValue>10</fastTimeoutUserDefinedValue>
<selectPortStd>Speed</selectPortStd>
<promptDelay>130</promptDelay>
<maxActiveNum>13</maxActiveNum>
<collectMaxDelay>12</collectMaxDelay>
<mixRateEnable>true</mixRateEnable>
<dampStaFlapEn>true</dampStaFlapEn>
<dampUnexpMacEn>true</dampUnexpMacEn>
<trunkSysMac>0000-1111-2222</trunkSysMac>
<trunkPortIdExt>true</trunkPortIdExt>
</lacpTrunk>
</TrunkIf>
</TrunkIfs>
</ifmtrunk>
</data>
</rpc-reply>

View file

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="1024">
<data>
<ifmtrunk xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
<lacpSysInfo>
<priority>32768</priority>
</lacpSysInfo>
</ifmtrunk>
</data>
</rpc-reply>

Some files were not shown because too many files have changed in this diff Show more