summaryrefslogtreecommitdiff
path: root/tests/unittests/distros/test_generic.py
blob: 93c5395c52e3a22ae67f0627123881031e3afaed (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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# This file is part of cloud-init. See LICENSE file for license information.

import os
import shutil
import tempfile
from unittest import mock

import pytest

from cloudinit import distros, util
from tests.unittests import helpers

unknown_arch_info = {
    "arches": ["default"],
    "failsafe": {
        "primary": "http://fs-primary-default",
        "security": "http://fs-security-default",
    },
}

package_mirrors = [
    {
        "arches": ["i386", "amd64"],
        "failsafe": {
            "primary": "http://fs-primary-intel",
            "security": "http://fs-security-intel",
        },
        "search": {
            "primary": [
                "http://%(ec2_region)s.ec2/",
                "http://%(availability_zone)s.clouds/",
            ],
            "security": [
                "http://security-mirror1-intel",
                "http://security-mirror2-intel",
            ],
        },
    },
    {
        "arches": ["armhf", "armel"],
        "failsafe": {
            "primary": "http://fs-primary-arm",
            "security": "http://fs-security-arm",
        },
    },
    unknown_arch_info,
]

gpmi = distros._get_package_mirror_info
gapmi = distros._get_arch_package_mirror_info


class TestGenericDistro(helpers.FilesystemMockingTestCase):
    def setUp(self):
        super(TestGenericDistro, self).setUp()
        # Make a temp directoy for tests to use.
        self.tmp = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, self.tmp)

    def _write_load_sudoers(self, _user, rules):
        cls = distros.fetch("ubuntu")
        d = cls("ubuntu", {}, None)
        os.makedirs(os.path.join(self.tmp, "etc"))
        os.makedirs(os.path.join(self.tmp, "etc", "sudoers.d"))
        self.patchOS(self.tmp)
        self.patchUtils(self.tmp)
        d.write_sudo_rules("harlowja", rules)
        contents = util.load_file(d.ci_sudoers_fn)
        return contents

    def _count_in(self, lines_look_for, text_content):
        found_amount = 0
        for e in lines_look_for:
            for line in text_content.splitlines():
                line = line.strip()
                if line == e:
                    found_amount += 1
        return found_amount

    def test_sudoers_ensure_rules(self):
        rules = "ALL=(ALL:ALL) ALL"
        contents = self._write_load_sudoers("harlowja", rules)
        expected = ["harlowja ALL=(ALL:ALL) ALL"]
        self.assertEqual(len(expected), self._count_in(expected, contents))
        not_expected = [
            "harlowja A",
            "harlowja L",
            "harlowja L",
        ]
        self.assertEqual(0, self._count_in(not_expected, contents))

    def test_sudoers_ensure_rules_list(self):
        rules = [
            "ALL=(ALL:ALL) ALL",
            "B-ALL=(ALL:ALL) ALL",
            "C-ALL=(ALL:ALL) ALL",
        ]
        contents = self._write_load_sudoers("harlowja", rules)
        expected = [
            "harlowja ALL=(ALL:ALL) ALL",
            "harlowja B-ALL=(ALL:ALL) ALL",
            "harlowja C-ALL=(ALL:ALL) ALL",
        ]
        self.assertEqual(len(expected), self._count_in(expected, contents))
        not_expected = [
            "harlowja A",
            "harlowja L",
            "harlowja L",
        ]
        self.assertEqual(0, self._count_in(not_expected, contents))

    def test_sudoers_ensure_new(self):
        cls = distros.fetch("ubuntu")
        d = cls("ubuntu", {}, None)
        self.patchOS(self.tmp)
        self.patchUtils(self.tmp)
        d.ensure_sudo_dir("/b")
        contents = util.load_file("/etc/sudoers")
        self.assertIn("includedir /b", contents)
        self.assertTrue(os.path.isdir("/b"))

    def test_sudoers_ensure_append(self):
        cls = distros.fetch("ubuntu")
        d = cls("ubuntu", {}, None)
        self.patchOS(self.tmp)
        self.patchUtils(self.tmp)
        util.write_file("/etc/sudoers", "josh, josh\n")
        d.ensure_sudo_dir("/b")
        contents = util.load_file("/etc/sudoers")
        self.assertIn("includedir /b", contents)
        self.assertTrue(os.path.isdir("/b"))
        self.assertIn("josh", contents)
        self.assertEqual(2, contents.count("josh"))

    def test_sudoers_ensure_only_one_includedir(self):
        cls = distros.fetch("ubuntu")
        d = cls("ubuntu", {}, None)
        self.patchOS(self.tmp)
        self.patchUtils(self.tmp)
        for char in ["#", "@"]:
            util.write_file("/etc/sudoers", "{}includedir /b".format(char))
            d.ensure_sudo_dir("/b")
            contents = util.load_file("/etc/sudoers")
            self.assertIn("includedir /b", contents)
            self.assertTrue(os.path.isdir("/b"))
            self.assertEqual(1, contents.count("includedir /b"))

    def test_arch_package_mirror_info_unknown(self):
        """for an unknown arch, we should get back that with arch 'default'."""
        arch_mirrors = gapmi(package_mirrors, arch="unknown")
        self.assertEqual(unknown_arch_info, arch_mirrors)

    def test_arch_package_mirror_info_known(self):
        arch_mirrors = gapmi(package_mirrors, arch="amd64")
        self.assertEqual(package_mirrors[0], arch_mirrors)

    def test_systemd_in_use(self):
        cls = distros.fetch("ubuntu")
        d = cls("ubuntu", {}, None)
        self.patchOS(self.tmp)
        self.patchUtils(self.tmp)
        os.makedirs("/run/systemd/system")
        self.assertTrue(d.uses_systemd())

    def test_systemd_not_in_use(self):
        cls = distros.fetch("ubuntu")
        d = cls("ubuntu", {}, None)
        self.patchOS(self.tmp)
        self.patchUtils(self.tmp)
        self.assertFalse(d.uses_systemd())

    def test_systemd_symlink(self):
        cls = distros.fetch("ubuntu")
        d = cls("ubuntu", {}, None)
        self.patchOS(self.tmp)
        self.patchUtils(self.tmp)
        os.makedirs("/run/systemd")
        os.symlink("/", "/run/systemd/system")
        self.assertFalse(d.uses_systemd())

    @mock.patch("cloudinit.distros.debian.read_system_locale")
    def test_get_locale_ubuntu(self, m_locale):
        """Test ubuntu distro returns locale set to C.UTF-8"""
        m_locale.return_value = "C.UTF-8"
        cls = distros.fetch("ubuntu")
        d = cls("ubuntu", {}, None)
        locale = d.get_locale()
        self.assertEqual("C.UTF-8", locale)

    def test_get_locale_rhel(self):
        """Test rhel distro returns NotImplementedError exception"""
        cls = distros.fetch("rhel")
        d = cls("rhel", {}, None)
        with self.assertRaises(NotImplementedError):
            d.get_locale()

    def test_expire_passwd_uses_chpasswd(self):
        """Test ubuntu.expire_passwd uses the passwd command."""
        for d_name in ("ubuntu", "rhel"):
            cls = distros.fetch(d_name)
            d = cls(d_name, {}, None)
            with mock.patch("cloudinit.subp.subp") as m_subp:
                d.expire_passwd("myuser")
            m_subp.assert_called_once_with(["passwd", "--expire", "myuser"])

    def test_expire_passwd_freebsd_uses_pw_command(self):
        """Test FreeBSD.expire_passwd uses the pw command."""
        cls = distros.fetch("freebsd")
        d = cls("freebsd", {}, None)
        with mock.patch("cloudinit.subp.subp") as m_subp:
            d.expire_passwd("myuser")
        m_subp.assert_called_once_with(
            ["pw", "usermod", "myuser", "-p", "01-Jan-1970"]
        )


class TestGetPackageMirrors:
    def return_first(self, mlist):
        if not mlist:
            return None
        return mlist[0]

    def return_second(self, mlist):
        if not mlist:
            return None

        return mlist[1] if len(mlist) > 1 else None

    def return_none(self, _mlist):
        return None

    def return_last(self, mlist):
        if not mlist:
            return None
        return mlist[-1]

    @pytest.mark.parametrize(
        "allow_ec2_mirror, platform_type, mirrors",
        [
            (
                True,
                "ec2",
                [
                    {
                        "primary": "http://us-east-1.ec2/",
                        "security": "http://security-mirror1-intel",
                    },
                    {
                        "primary": "http://us-east-1a.clouds/",
                        "security": "http://security-mirror2-intel",
                    },
                ],
            ),
            (
                True,
                "other",
                [
                    {
                        "primary": "http://us-east-1.ec2/",
                        "security": "http://security-mirror1-intel",
                    },
                    {
                        "primary": "http://us-east-1a.clouds/",
                        "security": "http://security-mirror2-intel",
                    },
                ],
            ),
            (
                False,
                "ec2",
                [
                    {
                        "primary": "http://us-east-1.ec2/",
                        "security": "http://security-mirror1-intel",
                    },
                    {
                        "primary": "http://us-east-1a.clouds/",
                        "security": "http://security-mirror2-intel",
                    },
                ],
            ),
            (
                False,
                "other",
                [
                    {
                        "primary": "http://us-east-1a.clouds/",
                        "security": "http://security-mirror1-intel",
                    },
                    {
                        "primary": "http://fs-primary-intel",
                        "security": "http://security-mirror2-intel",
                    },
                ],
            ),
        ],
    )
    def test_get_package_mirror_info_az_ec2(
        self, allow_ec2_mirror, platform_type, mirrors
    ):
        flag_path = (
            "cloudinit.distros.ALLOW_EC2_MIRRORS_ON_NON_AWS_INSTANCE_TYPES"
        )
        with mock.patch(flag_path, allow_ec2_mirror):
            arch_mirrors = gapmi(package_mirrors, arch="amd64")
            data_source_mock = mock.Mock(
                availability_zone="us-east-1a", platform_type=platform_type
            )

            results = gpmi(
                arch_mirrors,
                data_source=data_source_mock,
                mirror_filter=self.return_first,
            )
            assert results == mirrors[0]

            results = gpmi(
                arch_mirrors,
                data_source=data_source_mock,
                mirror_filter=self.return_second,
            )
            assert results == mirrors[1]

            results = gpmi(
                arch_mirrors,
                data_source=data_source_mock,
                mirror_filter=self.return_none,
            )
            assert results == package_mirrors[0]["failsafe"]

    def test_get_package_mirror_info_az_non_ec2(self):
        arch_mirrors = gapmi(package_mirrors, arch="amd64")
        data_source_mock = mock.Mock(availability_zone="nova.cloudvendor")

        results = gpmi(
            arch_mirrors,
            data_source=data_source_mock,
            mirror_filter=self.return_first,
        )
        assert results == {
            "primary": "http://nova.cloudvendor.clouds/",
            "security": "http://security-mirror1-intel",
        }

        results = gpmi(
            arch_mirrors,
            data_source=data_source_mock,
            mirror_filter=self.return_last,
        )
        assert results == {
            "primary": "http://nova.cloudvendor.clouds/",
            "security": "http://security-mirror2-intel",
        }

    def test_get_package_mirror_info_none(self):
        arch_mirrors = gapmi(package_mirrors, arch="amd64")
        data_source_mock = mock.Mock(availability_zone=None)

        # because both search entries here replacement based on
        # availability-zone, the filter will be called with an empty list and
        # failsafe should be taken.
        results = gpmi(
            arch_mirrors,
            data_source=data_source_mock,
            mirror_filter=self.return_first,
        )
        assert results == {
            "primary": "http://fs-primary-intel",
            "security": "http://security-mirror1-intel",
        }

        results = gpmi(
            arch_mirrors,
            data_source=data_source_mock,
            mirror_filter=self.return_last,
        )
        assert results == {
            "primary": "http://fs-primary-intel",
            "security": "http://security-mirror2-intel",
        }


# vi: ts=4 expandtab