summaryrefslogtreecommitdiff
path: root/tests/unit/modules/test_vyos_static_routes.py
blob: 1a50da9356718db9c19adaaee157d07ad706b2db (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function


__metaclass__ = type

import unittest

from unittest.mock import MagicMock

from ansible_collections.vyos.rest.plugins.modules.vyos_static_routes import (
    _ROUTE_OPTIONS,
    ARGUMENT_SPEC,
    _derive_key_field,
    _device_to_argspec,
    _keyed_list_from_device,
    _keyed_list_to_device,
    _next_hop_entry_from_device,
    _next_hop_entry_to_device,
    _route_entry_from_device,
    _route_entry_to_device,
    _want_to_device,
    build_commands,
    cast_by_spec,
    get_running_config,
)

from .base import load_fixture


_BASE = ["protocols", "static"]


class VyOSModuleTestCase(unittest.TestCase):
    def setUp(self):
        self.mock_vyos = MagicMock()
        self.fixture = load_fixture("static_routes_running.json")
        self.mock_vyos.get_config = MagicMock(return_value=self.fixture)


class TestGetRunningConfig(VyOSModuleTestCase):
    def test_returns_config_directly(self):
        result = get_running_config(self.mock_vyos)
        self.assertIn("route", result)
        self.assertIn("route6", result)

    def test_empty_config(self):
        self.mock_vyos.get_config = MagicMock(return_value=None)
        self.assertEqual(get_running_config(self.mock_vyos), {})


class TestDeriveKeyField(unittest.TestCase):
    def test_derives_dest_key(self):
        route_opts = ARGUMENT_SPEC["config"]["options"]["routes"]["options"]
        self.assertEqual(_derive_key_field(route_opts), "dest")

    def test_derives_forward_router_address_key(self):
        nh_opts = ARGUMENT_SPEC["config"]["options"]["routes"]["options"]["next_hops"]["options"]
        self.assertEqual(_derive_key_field(nh_opts), "forward_router_address")

    def test_raises_if_none_required(self):
        with self.assertRaises(ValueError):
            _derive_key_field({"a": {"type": "str"}})

    def test_raises_if_more_than_one_required(self):
        with self.assertRaises(ValueError):
            _derive_key_field({"a": {"required": True}, "b": {"required": True}})


class TestKeyedListHelper(unittest.TestCase):
    def test_to_device_basic(self):
        result = _keyed_list_to_device(
            [{"dest": "192.0.2.0/24", "blackhole_config": {"distance": 200}}],
            "dest",
        )
        self.assertEqual(result, {"192.0.2.0/24": {"blackhole_config": {"distance": 200}}})

    def test_from_device_basic(self):
        result = _keyed_list_from_device({"192.0.2.0/24": {"a": 1}}, "dest")
        self.assertEqual(result, [{"dest": "192.0.2.0/24", "a": 1}])

    def test_empty(self):
        self.assertEqual(_keyed_list_to_device([], "dest"), {})
        self.assertEqual(_keyed_list_from_device({}, "dest"), [])


class TestBlackholeNoTypeField(unittest.TestCase):
    """Regression test for the confirmed hallucinated field: the
    original module's blackhole_config.type does not correspond to
    anything on the device -- confirmed against vyos-1x, the
    "blackhole" node has only "distance" (and "tag", out of scope).
    The field has been removed entirely."""

    def test_type_not_in_argspec(self):
        bh_opts = ARGUMENT_SPEC["config"]["options"]["routes"]["options"]["blackhole_config"]
        self.assertNotIn("type", bh_opts["options"])
        self.assertEqual(set(bh_opts["options"].keys()), {"distance"})


class TestRouteEntryToDeviceFromDevice(unittest.TestCase):
    def test_blackhole_presence_only(self):
        """An empty blackhole_config (no distance) still creates a
        bare presence node -- achieving the same "just blackhole, no
        distance" result the original's bogus "type" field was used
        for, without needing any sentinel field at all."""
        result = _route_entry_to_device({"blackhole_config": {}})
        self.assertEqual(result, {"blackhole": {}})

    def test_blackhole_with_distance(self):
        result = _route_entry_to_device({"blackhole_config": {"distance": 200}})
        self.assertEqual(result, {"blackhole": {"distance": 200}})

    def test_next_hops_keyed_by_address(self):
        result = _route_entry_to_device(
            {"next_hops": [{"forward_router_address": "10.0.0.1", "admin_distance": 50}]},
        )
        self.assertEqual(result, {"next-hop": {"10.0.0.1": {"distance": 50}}})

    def test_disabled_next_hop(self):
        result = _route_entry_to_device(
            {"next_hops": [{"forward_router_address": "10.0.0.1", "enabled": False}]},
        )
        self.assertEqual(result["next-hop"]["10.0.0.1"], {"disable": {}})

    def test_enabled_true_produces_no_disable_leaf(self):
        result = _route_entry_to_device(
            {"next_hops": [{"forward_router_address": "10.0.0.1", "enabled": True}]},
        )
        self.assertNotIn("disable", result["next-hop"]["10.0.0.1"])

    def test_from_device_blackhole(self):
        """from_device stays purely structural (kebab->snake only);
        int-casting is cast_by_spec's responsibility, applied
        downstream in main() -- confirmed separately below."""
        entry = _route_entry_from_device({"blackhole": {"distance": "200"}})
        self.assertEqual(entry["blackhole_config"]["distance"], "200")

    def test_from_device_next_hop_disabled(self):
        entry = _route_entry_from_device({"next-hop": {"10.0.0.1": {"disable": {}}}})
        self.assertEqual(entry["next_hops"][0]["enabled"], False)

    def test_from_device_next_hop_enabled_omitted(self):
        """Confirmed device behavior: an enabled next-hop has no
        "disable" leaf at all -- "enabled" should not appear in the
        parsed entry either, matching the argspec default."""
        entry = _route_entry_from_device({"next-hop": {"10.0.0.1": {}}})
        self.assertNotIn("enabled", entry["next_hops"][0])

    def test_empty(self):
        self.assertEqual(_route_entry_to_device({}), {})
        self.assertEqual(_route_entry_from_device({}), {})


class TestNextHopEntryToDeviceFromDevice(unittest.TestCase):
    def test_interface(self):
        result = _next_hop_entry_to_device({"interface": "eth0"})
        self.assertEqual(result, {"interface": "eth0"})

    def test_from_device_interface(self):
        entry = _next_hop_entry_from_device({"interface": "eth0"})
        self.assertEqual(entry, {"interface": "eth0"})

    def test_from_device_distance_cast_to_int(self):
        entry = _next_hop_entry_from_device({"distance": "50"})
        self.assertEqual(entry["admin_distance"], 50)
        self.assertIsInstance(entry["admin_distance"], int)


class TestWantToDevice(unittest.TestCase):
    def test_empty(self):
        self.assertEqual(_want_to_device([]), {})
        self.assertEqual(_want_to_device(None), {})

    def test_afi_without_routes_omitted(self):
        self.assertEqual(_want_to_device([{"afi": "ipv4"}]), {})

    def test_keyed_by_route_key(self):
        config = [{"afi": "ipv4", "routes": [{"dest": "192.0.2.0/24"}]}]
        result = _want_to_device(config)
        self.assertIn("192.0.2.0/24", result["route"])

    def test_ipv6_uses_route6_key(self):
        config = [{"afi": "ipv6", "routes": [{"dest": "2001:db8::/32"}]}]
        result = _want_to_device(config)
        self.assertIn("route6", result)


class TestDeviceToArgspecFixture(VyOSModuleTestCase):
    def test_both_afis_parsed(self):
        raw = get_running_config(self.mock_vyos)
        result = _device_to_argspec(raw)
        afis = [e["afi"] for e in result]
        self.assertIn("ipv4", afis)
        self.assertIn("ipv6", afis)

    def test_blackhole_route_parsed_with_casting(self):
        """from_device alone leaves distance as the raw device string;
        cast_by_spec (applied downstream in main(), confirmed here
        directly) is what casts it to int, since cast_by_spec recurses
        into type="dict" suboptions like blackhole_config."""
        raw = get_running_config(self.mock_vyos)
        result = _device_to_argspec(raw)
        ipv4_routes = next(e for e in result if e["afi"] == "ipv4")["routes"]
        bh_route = next(r for r in ipv4_routes if r["dest"] == "203.0.113.0/24")
        self.assertEqual(bh_route["blackhole_config"]["distance"], "200")
        cast_by_spec(bh_route, _ROUTE_OPTIONS)
        self.assertEqual(bh_route["blackhole_config"]["distance"], 200)

    def test_next_hop_route_parsed(self):
        raw = get_running_config(self.mock_vyos)
        result = _device_to_argspec(raw)
        ipv4_routes = next(e for e in result if e["afi"] == "ipv4")["routes"]
        nh_route = next(r for r in ipv4_routes if r["dest"] == "192.0.2.0/24")
        self.assertEqual(nh_route["next_hops"][0]["forward_router_address"], "10.0.0.1")

    def test_empty_config(self):
        self.assertEqual(_device_to_argspec({}), [])
        self.assertEqual(_device_to_argspec(None), [])


class TestBuildCommands(VyOSModuleTestCase):
    def setUp(self):
        super().setUp()
        self.raw = get_running_config(self.mock_vyos)

    def test_merged_idempotent_against_own_fixture(self):
        have = _device_to_argspec(self.raw)
        self.assertEqual(build_commands(have, self.raw, "merged"), [])

    def test_replaced_idempotent_against_own_fixture(self):
        have = _device_to_argspec(self.raw)
        self.assertEqual(build_commands(have, self.raw, "replaced"), [])

    def test_overridden_idempotent_against_own_fixture(self):
        have = _device_to_argspec(self.raw)
        self.assertEqual(build_commands(have, self.raw, "overridden"), [])

    def test_clear_omitted_next_hop_attribute_on_replaced(self):
        """The primary confirmed bug fix from the PR review: the
        original _route_cmds only emitted commands for setting values,
        never for clearing an omitted attribute back to default, and
        "replaced" state's own change-detection missed this entirely
        since it only inspected generated set-commands."""
        raw_have = {"route": {"192.0.2.0/24": {"next-hop": {"10.0.0.1": {"distance": "50"}}}}}
        config = [
            {
                "afi": "ipv4",
                "routes": [
                    {
                        "dest": "192.0.2.0/24",
                        "next_hops": [
                            {"forward_router_address": "10.0.0.1"},
                        ],
                    },
                ],
            },
        ]
        cmds = build_commands(config, raw_have, "replaced")
        expected = ("delete", _BASE + ["route", "192.0.2.0/24", "next-hop", "10.0.0.1", "distance"])
        self.assertIn(expected, cmds)

    def test_replaced_scoped_to_named_route_only(self):
        raw_have = {
            "route": {
                "192.0.2.0/24": {"next-hop": {"10.0.0.1": {}}},
                "203.0.113.0/24": {"blackhole": {"distance": "200"}},
            },
        }
        config = [
            {
                "afi": "ipv4",
                "routes": [
                    {
                        "dest": "192.0.2.0/24",
                        "next_hops": [
                            {"forward_router_address": "10.0.0.1"},
                        ],
                    },
                ],
            },
        ]
        cmds = build_commands(config, raw_have, "replaced")
        self.assertEqual(cmds, [])
        self.assertFalse(any("203.0.113.0/24" in str(c) for c in cmds))

    def test_overridden_deletes_omitted_route(self):
        raw_have = {
            "route": {
                "192.0.2.0/24": {"next-hop": {"10.0.0.1": {}}},
                "203.0.113.0/24": {"blackhole": {"distance": "200"}},
            },
        }
        config = [
            {
                "afi": "ipv4",
                "routes": [
                    {
                        "dest": "192.0.2.0/24",
                        "next_hops": [
                            {"forward_router_address": "10.0.0.1"},
                        ],
                    },
                ],
            },
        ]
        cmds = build_commands(config, raw_have, "overridden")
        self.assertIn(("delete", _BASE + ["route", "203.0.113.0/24"]), cmds)

    def test_deleted_named_route(self):
        cmds = build_commands(
            [{"afi": "ipv4", "routes": [{"dest": "192.0.2.0/24"}]}],
            self.raw,
            "deleted",
        )
        self.assertEqual(cmds, [("delete", _BASE + ["route", "192.0.2.0/24"])])

    def test_deleted_named_afi_no_routes(self):
        cmds = build_commands([{"afi": "ipv4"}], self.raw, "deleted")
        self.assertEqual(cmds, [("delete", _BASE + ["route"])])

    def test_deleted_no_config_removes_all(self):
        cmds = build_commands([], self.raw, "deleted")
        self.assertEqual(cmds, [("delete", _BASE)])

    def test_deleted_named_nonexistent_is_noop(self):
        cmds = build_commands(
            [{"afi": "ipv4", "routes": [{"dest": "198.51.100.0/24"}]}],
            self.raw,
            "deleted",
        )
        self.assertEqual(cmds, [])

    def test_collapsed_bare_route_no_blackhole_or_next_hop(self):
        raw_have = {"route": {"192.0.2.0/24": {}}}
        config = [{"afi": "ipv4", "routes": [{"dest": "192.0.2.0/24"}]}]
        self.assertEqual(build_commands(config, raw_have, "merged"), [])

    def test_merged_new_blackhole_route(self):
        config = [{"afi": "ipv4", "routes": [{"dest": "198.51.100.0/24", "blackhole_config": {}}]}]
        cmds = build_commands(config, {}, "merged")
        self.assertIn(("set", _BASE + ["route", "198.51.100.0/24", "blackhole"]), cmds)

    def test_merged_new_disabled_next_hop(self):
        config = [
            {
                "afi": "ipv4",
                "routes": [
                    {
                        "dest": "198.51.100.0/24",
                        "next_hops": [
                            {"forward_router_address": "10.0.0.9", "enabled": False},
                        ],
                    },
                ],
            },
        ]
        cmds = build_commands(config, {}, "merged")
        self.assertIn(
            ("set", _BASE + ["route", "198.51.100.0/24", "next-hop", "10.0.0.9", "disable"]),
            cmds,
        )


if __name__ == "__main__":
    unittest.main()