summaryrefslogtreecommitdiff
path: root/tests/unittests/cmd/devel/test_net_convert.py
blob: 60acb1a671c877615f21960632d940300f0ed039 (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
# This file is part of cloud-init. See LICENSE file for license information.

import itertools

import pytest

from cloudinit.cmd.devel import net_convert
from cloudinit.distros.debian import NETWORK_FILE_HEADER
from tests.unittests.helpers import mock

M_PATH = "cloudinit.cmd.devel.net_convert."


required_args = [
    "--directory",
    "--network-data",
    "--distro=ubuntu",
    "--kind=eni",
    "--output-kind=eni",
]


SAMPLE_NET_V1 = """\
network:
  version: 1
  config:
  - type: physical
    name: eth0
    subnets:
      - type: dhcp
"""


SAMPLE_NETPLAN_CONTENT = f"""\
{NETWORK_FILE_HEADER}network:
    version: 2
    ethernets:
        eth0:
            dhcp4: true
"""

SAMPLE_ENI_CONTENT = f"""\
{NETWORK_FILE_HEADER}auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp
"""

SAMPLE_NETWORKD_CONTENT = """\
[Match]
Name=eth0

[Network]
DHCP=ipv4

"""

SAMPLE_SYSCONFIG_CONTENT = """\
# Created by cloud-init on instance boot automatically, do not edit.
#
BOOTPROTO=dhcp
DEVICE=eth0
NM_CONTROLLED=no
ONBOOT=yes
TYPE=Ethernet
USERCTL=no
"""

SAMPLE_NETWORK_MANAGER_CONTENT = """\
# Generated by cloud-init. Changes will be lost.

[connection]
id=cloud-init eth0
uuid=1dd9a779-d327-56e1-8454-c65e2556c12c
type=ethernet
interface-name=eth0

[user]
org.freedesktop.NetworkManager.origin=cloud-init

[ethernet]

[ipv4]
method=auto
may-fail=false

"""


class TestNetConvert:

    missing_required_args = itertools.combinations(
        required_args, len(required_args) - 1
    )

    def _replace_path_args(self, cmd, tmpdir):
        """Inject tmpdir replacements for parameterize args."""
        updated_cmd = []
        for arg in cmd:
            if arg == "--network-data":
                net_file = tmpdir.join("net")
                net_file.write("")
                updated_cmd.append(f"--network-data={net_file}")
            elif arg == "--directory":
                updated_cmd.append(f"--directory={tmpdir.strpath}")
            else:
                updated_cmd.append(arg)
        return updated_cmd

    @pytest.mark.parametrize("cmdargs", missing_required_args)
    def test_argparse_error_on_missing_args(self, cmdargs, capsys, tmpdir):
        """Log the appropriate error when required args are missing."""
        params = self._replace_path_args(cmdargs, tmpdir)
        with mock.patch("sys.argv", ["net-convert"] + params):
            with pytest.raises(SystemExit):
                net_convert.get_parser().parse_args()
        _out, err = capsys.readouterr()
        assert "the following arguments are required" in err

    @pytest.mark.parametrize("debug", (False, True))
    @pytest.mark.parametrize(
        "output_kind,outfile_content",
        (
            (
                "netplan",
                {"etc/netplan/50-cloud-init.yaml": SAMPLE_NETPLAN_CONTENT},
            ),
            (
                "eni",
                {
                    "etc/network/interfaces.d/50-cloud-init.cfg": SAMPLE_ENI_CONTENT  # noqa: E501
                },
            ),
            (
                "networkd",
                {
                    "etc/systemd/network/10-cloud-init-eth0.network": SAMPLE_NETWORKD_CONTENT  # noqa: E501
                },
            ),
            (
                "sysconfig",
                {
                    "etc/sysconfig/network-scripts/ifcfg-eth0": SAMPLE_SYSCONFIG_CONTENT  # noqa: E501
                },
            ),
            (
                "network-manager",
                {
                    "etc/NetworkManager/system-connections/cloud-init-eth0.nmconnection": SAMPLE_NETWORK_MANAGER_CONTENT  # noqa: E501
                },
            ),
        ),
    )
    def test_convert_output_kind_artifacts(
        self, output_kind, outfile_content, debug, capsys, tmpdir
    ):
        """Assert proper output-kind artifacts are written."""
        network_data = tmpdir.join("network_data")
        network_data.write(SAMPLE_NET_V1)
        distro = "centos" if output_kind == "sysconfig" else "ubuntu"
        args = [
            f"--directory={tmpdir.strpath}",
            f"--network-data={network_data.strpath}",
            f"--distro={distro}",
            "--kind=yaml",
            f"--output-kind={output_kind}",
        ]
        if debug:
            args.append("--debug")
        params = self._replace_path_args(args, tmpdir)
        with mock.patch("sys.argv", ["net-convert"] + params):
            args = net_convert.get_parser().parse_args()
        with mock.patch("cloudinit.util.chownbyname") as chown:
            net_convert.handle_args("somename", args)
        for path in outfile_content:
            outfile = tmpdir.join(path)
            assert outfile_content[path] == outfile.read()
            if output_kind == "networkd":
                assert [
                    mock.call(
                        outfile.strpath, "systemd-network", "systemd-network"
                    )
                ] == chown.call_args_list


# vi: ts=4 expandtab