Skip to content

Commit eeb6b5b

Browse files
authored
Unit test expansion (#75)
Unit test expansion Reviewed-by: https://github.com/apps/ansible-zuul
1 parent 2c90cd9 commit eeb6b5b

File tree

10 files changed

+867
-360
lines changed

10 files changed

+867
-360
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
bugfixes:
3+
- nthhost filter now returns str instead of IPAddress object
4+
- slaac filter now returns str instead of IPAddress object
5+
removed_features:
6+
- module_utils.network.common.utils.EntityCollection has been removed as identical to ComplexList
7+
- module_utils.network.common.utils.ComplexDict has been removed

plugins/filter/ipaddr.py

Lines changed: 12 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,6 @@ def _first_last(v):
6262

6363
def _6to4_query(v, vtype, value):
6464
if v.version == 4:
65-
6665
if v.size == 1:
6766
ipconv = str(v.ip)
6867
elif v.size > 1:
@@ -77,7 +76,7 @@ def _6to4_query(v, vtype, value):
7776
try:
7877
return "2002:{:02x}{:02x}:{:02x}{:02x}::1/48".format(*numbers)
7978
except Exception:
80-
return False
79+
pass
8180

8281
elif v.version == 6:
8382
if vtype == "address":
@@ -87,8 +86,8 @@ def _6to4_query(v, vtype, value):
8786
if v.ip != v.network:
8887
if ipaddr(str(v.ip), "2002::/16"):
8988
return value
90-
else:
91-
return False
89+
90+
return False
9291

9392

9493
def _ip_query(v):
@@ -100,12 +99,6 @@ def _ip_query(v):
10099
return str(v.ip)
101100

102101

103-
def _gateway_query(v):
104-
if v.size > 1:
105-
if v.ip != v.network:
106-
return str(v.ip) + "/" + str(v.prefixlen)
107-
108-
109102
def _address_prefix_query(v):
110103
if v.size > 1:
111104
if v.ip != v.network:
@@ -180,16 +173,6 @@ def _ip_netmask_query(v):
180173
return str(v.ip) + " " + str(v.netmask)
181174

182175

183-
"""
184-
def _ip_wildcard_query(v):
185-
if v.size == 2:
186-
return str(v.ip) + ' ' + str(v.hostmask)
187-
elif v.size > 1:
188-
if v.ip != v.network:
189-
return str(v.ip) + ' ' + str(v.hostmask)
190-
"""
191-
192-
193176
def _ipv4_query(v, value):
194177
if v.version == 6:
195178
try:
@@ -517,12 +500,12 @@ def ipaddr(value, query="", version=False, alias="ipaddr"):
517500
"cidr": _cidr_query,
518501
"cidr_lookup": _cidr_lookup_query,
519502
"first_usable": _first_usable_query,
520-
"gateway": _gateway_query, # deprecate
521-
"gw": _gateway_query, # deprecate
503+
"gateway": _address_prefix_query, # deprecate
504+
"gw": _address_prefix_query, # deprecate
522505
"host": _host_query,
523506
"host/prefix": _address_prefix_query, # deprecate
524507
"hostmask": _hostmask_query,
525-
"hostnet": _gateway_query, # deprecate
508+
"hostnet": _address_prefix_query, # deprecate
526509
"int": _int_query,
527510
"ip": _ip_query,
528511
"ip/prefix": _ip_prefix_query,
@@ -550,7 +533,7 @@ def ipaddr(value, query="", version=False, alias="ipaddr"):
550533
"public": _public_query,
551534
"range_usable": _range_usable_query,
552535
"revdns": _revdns_query,
553-
"router": _gateway_query, # deprecate
536+
"router": _address_prefix_query, # deprecate
554537
"size": _size_query,
555538
"size_usable": _size_usable_query,
556539
"subnet": _subnet_query,
@@ -880,7 +863,7 @@ def nthhost(value, query=""):
880863
try:
881864
nth = int(query)
882865
if value.size > nth:
883-
return value[nth]
866+
return str(value[nth])
884867

885868
except ValueError:
886869
return False
@@ -961,6 +944,8 @@ def _address_normalizer(value):
961944
vtype = ipaddr(value, "type")
962945
if vtype == "address" or vtype == "network":
963946
v = ipaddr(value, "subnet")
947+
else:
948+
return False
964949
except Exception:
965950
return False
966951

@@ -1086,7 +1071,7 @@ def slaac(value, query=""):
10861071
except Exception:
10871072
return False
10881073

1089-
return eui.ipv6(value.network)
1074+
return str(eui.ipv6(value.network))
10901075

10911076

10921077
# ---- HWaddr / MAC address filters ----
@@ -1113,6 +1098,7 @@ def hwaddr(value, query="", alias="hwaddr"):
11131098
try:
11141099
v = netaddr.EUI(value)
11151100
except Exception:
1101+
v = None
11161102
if query and query != "bool":
11171103
raise errors.AnsibleFilterError(
11181104
alias + ": not a hardware address: %s" % value
@@ -1128,8 +1114,6 @@ def hwaddr(value, query="", alias="hwaddr"):
11281114
alias + ": unknown filter type: %s" % query
11291115
)
11301116

1131-
return False
1132-
11331117

11341118
def macaddr(value, query=""):
11351119
return hwaddr(value, query, alias="macaddr")

plugins/module_utils/network/common/network.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,16 @@
3636
from ansible.module_utils.basic import AnsibleModule
3737
from ansible.module_utils.basic import env_fallback
3838
from ansible.module_utils.connection import Connection, ConnectionError
39+
from ansible.module_utils.six import iteritems
3940
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.netconf import (
4041
NetconfConnection,
4142
)
4243
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.parsing import (
4344
Cli,
4445
)
45-
from ansible.module_utils.six import iteritems
46+
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import (
47+
to_list,
48+
)
4649

4750

4851
NET_TRANSPORT_ARGS = dict(
@@ -81,15 +84,6 @@ def _transitional_argument_spec():
8184
return argument_spec
8285

8386

84-
def to_list(val):
85-
if isinstance(val, (list, tuple)):
86-
return list(val)
87-
elif val is not None:
88-
return [val]
89-
else:
90-
return list()
91-
92-
9387
class ModuleStub(object):
9488
def __init__(self, argument_spec, fail_json):
9589
self.params = dict()

plugins/module_utils/network/common/parsing.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -38,15 +38,9 @@
3838
)
3939
from ansible.module_utils.six import string_types, text_type
4040
from ansible.module_utils.six.moves import zip
41-
42-
43-
def to_list(val):
44-
if isinstance(val, (list, tuple)):
45-
return list(val)
46-
elif val is not None:
47-
return [val]
48-
else:
49-
return list()
41+
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import (
42+
to_list,
43+
)
5044

5145

5246
class FailedConditionsError(Exception):

plugins/module_utils/network/common/utils.py

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -289,38 +289,26 @@ def __call__(self, value, strict=True):
289289
return value
290290

291291

292-
class EntityCollection(Entity):
292+
class ComplexList(Entity):
293293
"""Extends ```Entity``` to handle a list of dicts """
294294

295+
def __init__(self, attrs, module, *args, **kwargs):
296+
super(ComplexList, self).__init__(module, attrs, *args, **kwargs)
297+
295298
def __call__(self, iterable, strict=True):
296299
if iterable is None:
297300
iterable = [
298-
super(EntityCollection, self).__call__(
299-
self._module.params, strict
300-
)
301+
super(ComplexList, self).__call__(self._module.params, strict)
301302
]
302303

303304
if not isinstance(iterable, (list, tuple)):
304305
self._module.fail_json(msg="value must be an iterable")
305306

306307
return [
307-
(super(EntityCollection, self).__call__(i, strict))
308-
for i in iterable
308+
(super(ComplexList, self).__call__(i, strict)) for i in iterable
309309
]
310310

311311

312-
# these two are for backwards compatibility and can be removed once all of the
313-
# modules that use them are updated
314-
class ComplexDict(Entity):
315-
def __init__(self, attrs, module, *args, **kwargs):
316-
super(ComplexDict, self).__init__(module, attrs, *args, **kwargs)
317-
318-
319-
class ComplexList(EntityCollection):
320-
def __init__(self, attrs, module, *args, **kwargs):
321-
super(ComplexList, self).__init__(module, attrs, *args, **kwargs)
322-
323-
324312
def dict_diff(base, comparable):
325313
""" Generate a dict object of differences
326314

plugins/modules/cli_config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ def validate_args(module, device_operations):
229229
supports_feature = device_operations.get("supports_%s" % feature)
230230
if supports_feature is None:
231231
module.fail_json(
232-
"This platform does not specify whether %s is supported or not. "
232+
msg="This platform does not specify whether %s is supported or not. "
233233
"Please report an issue against this platform's cliconf plugin."
234234
% feature
235235
)
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# -*- coding: utf-8 -*-
2+
#
3+
# (c) 2017 Red Hat, Inc.
4+
#
5+
# This file is part of Ansible
6+
#
7+
# Ansible is free software: you can redistribute it and/or modify
8+
# it under the terms of the GNU General Public License as published by
9+
# the Free Software Foundation, either version 3 of the License, or
10+
# (at your option) any later version.
11+
#
12+
# Ansible is distributed in the hope that it will be useful,
13+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15+
# GNU General Public License for more details.
16+
#
17+
# You should have received a copy of the GNU General Public License
18+
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
19+
20+
# Make coding more python3-ish
21+
from __future__ import absolute_import, division, print_function
22+
23+
__metaclass__ = type
24+
25+
import re
26+
27+
import pytest
28+
29+
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import (
30+
config,
31+
)
32+
33+
34+
RUNNING = """interface Ethernet1
35+
speed auto
36+
no switchport
37+
no lldp receive
38+
!
39+
interface Ethernet2
40+
speed auto
41+
no switchport
42+
no lldp transmit
43+
!
44+
interface Management1
45+
ip address dhcp
46+
!"""
47+
48+
49+
def test_config_items():
50+
net_config = config.NetworkConfig(indent=3, contents=RUNNING)
51+
assert len(net_config.items) == 10
52+
53+
net_config = config.NetworkConfig(
54+
indent=3, contents=RUNNING, ignore_lines=[r"\s*no .*"]
55+
)
56+
assert len(net_config.items) == 6
57+
58+
net_config = config.NetworkConfig(
59+
indent=3, contents=RUNNING, ignore_lines=[re.compile(r"\s*no .*")]
60+
)
61+
assert len(net_config.items) == 6
62+
63+
64+
def test_config_get_block():
65+
net_config = config.NetworkConfig(indent=3, contents=RUNNING)
66+
67+
with pytest.raises(
68+
AssertionError, match="path argument must be a list object"
69+
):
70+
net_config.get_block("interface Ethernet2")
71+
72+
with pytest.raises(ValueError, match="path does not exist in config"):
73+
net_config.get_block(["interface Ethernet3"])
74+
75+
block = net_config.get_block(["interface Ethernet2"])
76+
assert len(block) == 4
77+
78+
79+
def test_line_hierarchy():
80+
net_config = config.NetworkConfig(indent=3, contents=RUNNING)
81+
82+
lines = net_config.items
83+
assert lines[0].has_children
84+
assert not lines[0].has_parents
85+
assert not lines[1].has_children
86+
assert lines[1].has_parents

0 commit comments

Comments
 (0)