File: test_apply_config.py

package info (click to toggle)
python-os-apply-config 14.0.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 292 kB
  • sloc: python: 1,129; makefile: 25; sh: 2
file content (429 lines) | stat: -rw-r--r-- 17,303 bytes parent folder | download
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import atexit
import json
import os
import tempfile
from unittest import mock

import fixtures
import testtools

from os_apply_config import apply_config
from os_apply_config import config_exception as exc
from os_apply_config import oac_file

# example template tree
TEMPLATES = os.path.join(os.path.dirname(__file__), 'templates')

# config for example tree
CONFIG = {
    "x": "foo",
    "y": False,
    "z": None,
    "btrue": True,
    "bfalse": False,
    "database": {
        "url": "sqlite:///blah"
    },
    "l": [1, 2],
}

# config for example tree - with subhash
CONFIG_SUBHASH = {
    "OpenStack::Config": {
        "x": "foo",
        "database": {
            "url": "sqlite:///blah"
        }
    }
}

# expected output for example tree
OUTPUT = {
    "/etc/glance/script.conf": oac_file.OacFile(
        "foo\n"),
    "/etc/keystone/keystone.conf": oac_file.OacFile(
        "[foo]\ndatabase = sqlite:///blah\n"),
    "/etc/control/empty": oac_file.OacFile(
        "foo\n"),
    "/etc/control/allow_empty": oac_file.OacFile(
        "").set('allow_empty', False),
    "/etc/control/mode": oac_file.OacFile(
        "lorem modus\n").set('mode', 0o755),
}
TEMPLATE_PATHS = OUTPUT.keys()

# expected output for chown tests
# separated out to avoid needing to mock os.chown for most tests
CHOWN_TEMPLATES = os.path.join(os.path.dirname(__file__), 'chown_templates')
CHOWN_OUTPUT = {
    "owner.uid": oac_file.OacFile("lorem uido\n").set('owner', 0),
    "owner.name": oac_file.OacFile("namo uido\n").set('owner', 0),
    "group.gid": oac_file.OacFile("lorem gido\n").set('group', 0),
    "group.name": oac_file.OacFile("namo gido\n").set('group', 0),
}


def template(relpath):
    return os.path.join(TEMPLATES, relpath[1:])


class TestRunOSConfigApplier(testtools.TestCase):
    """Tests the commandline options."""

    def setUp(self):
        super().setUp()
        self.useFixture(fixtures.NestedTempfile())
        self.stdout = self.useFixture(fixtures.StringStream('stdout')).stream
        self.useFixture(fixtures.MonkeyPatch('sys.stdout', self.stdout))
        stderr = self.useFixture(fixtures.StringStream('stderr')).stream
        self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
        self.logger = self.useFixture(
            fixtures.FakeLogger(name="os-apply-config"))
        fd, self.path = tempfile.mkstemp()
        with os.fdopen(fd, 'w') as t:
            t.write(json.dumps(CONFIG))
            t.flush()

    def test_print_key(self):
        self.assertEqual(0, apply_config.main(
            ['os-apply-config.py', '--metadata', self.path, '--key',
             'database.url', '--type', 'raw']))
        self.stdout.seek(0)
        self.assertEqual(CONFIG['database']['url'],
                         self.stdout.read().strip())
        self.assertEqual('', self.logger.output)

    def test_print_key_json_dict(self):
        self.assertEqual(0, apply_config.main(
            ['os-apply-config.py', '--metadata', self.path, '--key',
             'database', '--type', 'raw']))
        self.stdout.seek(0)
        self.assertEqual(CONFIG['database'],
                         json.loads(self.stdout.read().strip()))
        self.assertEqual('', self.logger.output)

    def test_print_key_json_list(self):
        self.assertEqual(0, apply_config.main(
            ['os-apply-config.py', '--metadata', self.path, '--key',
             'l', '--type', 'raw']))
        self.stdout.seek(0)
        self.assertEqual(CONFIG['l'],
                         json.loads(self.stdout.read().strip()))
        self.assertEqual('', self.logger.output)

    def test_print_non_string_key(self):
        self.assertEqual(0, apply_config.main(
            ['os-apply-config.py', '--metadata', self.path, '--key',
             'y', '--type', 'raw']))
        self.stdout.seek(0)
        self.assertEqual("false",
                         self.stdout.read().strip())
        self.assertEqual('', self.logger.output)

    def test_print_null_key(self):
        self.assertEqual(0, apply_config.main(
            ['os-apply-config.py', '--metadata', self.path, '--key',
             'z', '--type', 'raw', '--key-default', '']))
        self.stdout.seek(0)
        self.assertEqual('', self.stdout.read().strip())
        self.assertEqual('', self.logger.output)

    def test_print_key_missing(self):
        self.assertEqual(1, apply_config.main(
            ['os-apply-config.py', '--metadata', self.path, '--key',
             'does.not.exist']))
        self.assertIn('does not exist', self.logger.output)

    def test_print_key_missing_default(self):
        self.assertEqual(0, apply_config.main(
            ['os-apply-config.py', '--metadata', self.path, '--key',
             'does.not.exist', '--key-default', '']))
        self.stdout.seek(0)
        self.assertEqual('', self.stdout.read().strip())
        self.assertEqual('', self.logger.output)

    def test_print_key_wrong_type(self):
        self.assertEqual(1, apply_config.main(
            ['os-apply-config.py', '--metadata', self.path, '--key',
             'x', '--type', 'int']))
        self.assertIn('cannot interpret value', self.logger.output)

    def test_print_key_from_list(self):
        self.assertEqual(0, apply_config.main(
            ['os-apply-config.py', '--metadata', self.path, '--key',
             'l.0', '--type', 'int']))
        self.stdout.seek(0)
        self.assertEqual(str(CONFIG['l'][0]),
                         self.stdout.read().strip())
        self.assertEqual('', self.logger.output)

    def test_print_key_from_list_missing(self):
        self.assertEqual(1, apply_config.main(
            ['os-apply-config.py', '--metadata', self.path, '--key',
             'l.2', '--type', 'int']))
        self.assertIn('does not exist', self.logger.output)

    def test_print_key_from_list_missing_default(self):
        self.assertEqual(0, apply_config.main(
            ['os-apply-config.py', '--metadata', self.path, '--key',
             'l.2', '--type', 'int', '--key-default', '']))
        self.stdout.seek(0)
        self.assertEqual('', self.stdout.read().strip())
        self.assertEqual('', self.logger.output)

    def test_print_templates(self):
        apply_config.main(['os-apply-config', '--print-templates'])
        self.stdout.seek(0)
        self.assertEqual(
            self.stdout.read().strip(), apply_config.TEMPLATES_DIR)
        self.assertEqual('', self.logger.output)

    def test_boolean_key(self):
        rcode = apply_config.main(['os-apply-config', '--metadata',
                                   self.path, '--boolean-key', 'btrue'])
        self.assertEqual(0, rcode)
        rcode = apply_config.main(['os-apply-config', '--metadata',
                                   self.path, '--boolean-key', 'bfalse'])
        self.assertEqual(1, rcode)
        rcode = apply_config.main(['os-apply-config', '--metadata',
                                   self.path, '--boolean-key', 'x'])
        self.assertEqual(-1, rcode)

    def test_boolean_key_and_key(self):
        rcode = apply_config.main(['os-apply-config', '--metadata',
                                   self.path, '--boolean-key', 'btrue',
                                   '--key', 'x'])
        self.assertEqual(0, rcode)
        self.stdout.seek(0)
        self.assertEqual(self.stdout.read().strip(), 'foo')
        self.assertIn('--boolean-key ignored', self.logger.output)

    def test_os_config_files(self):
        with tempfile.NamedTemporaryFile() as fake_os_config_files:
            with tempfile.NamedTemporaryFile() as fake_config:
                fake_config.write(json.dumps(CONFIG).encode('utf-8'))
                fake_config.flush()
                fake_os_config_files.write(
                    json.dumps([fake_config.name]).encode('utf-8'))
                fake_os_config_files.flush()
                apply_config.main(['os-apply-config',
                                   '--key', 'database.url',
                                   '--type', 'raw',
                                   '--os-config-files',
                                   fake_os_config_files.name])
                self.stdout.seek(0)
                self.assertEqual(
                    CONFIG['database']['url'], self.stdout.read().strip())


class OSConfigApplierTestCase(testtools.TestCase):

    def setUp(self):
        super().setUp()
        self.logger = self.useFixture(fixtures.FakeLogger('os-apply-config'))
        self.useFixture(fixtures.NestedTempfile())

    def write_config(self, config):
        fd, path = tempfile.mkstemp()
        with os.fdopen(fd, 'w') as t:
            t.write(json.dumps(config))
            t.flush()
        return path

    def check_output_file(self, tmpdir, path, obj):
        full_path = os.path.join(tmpdir, path[1:])
        if obj.allow_empty:
            assert os.path.exists(full_path), "%s doesn't exist" % path
            self.assertEqual(obj.body, open(full_path).read())
        else:
            assert not os.path.exists(full_path), "%s exists" % path

    def test_install_config(self):
        path = self.write_config(CONFIG)
        tmpdir = tempfile.mkdtemp()
        apply_config.install_config([path], TEMPLATES, tmpdir, False)
        for path, obj in OUTPUT.items():
            self.check_output_file(tmpdir, path, obj)

    def test_install_config_subhash(self):
        tpath = self.write_config(CONFIG_SUBHASH)
        tmpdir = tempfile.mkdtemp()
        apply_config.install_config(
            [tpath], TEMPLATES, tmpdir, False, 'OpenStack::Config')
        for path, obj in OUTPUT.items():
            self.check_output_file(tmpdir, path, obj)

    def test_delete_if_not_allowed_empty(self):
        path = self.write_config(CONFIG)
        tmpdir = tempfile.mkdtemp()
        template = "/etc/control/allow_empty"
        target_file = os.path.join(tmpdir, template[1:])
        # Touch the file
        os.makedirs(os.path.dirname(target_file))
        open(target_file, 'a').close()
        apply_config.install_config([path], TEMPLATES, tmpdir, False)
        # File should be gone
        self.assertFalse(os.path.exists(target_file))

    def test_respect_file_permissions(self):
        path = self.write_config(CONFIG)
        tmpdir = tempfile.mkdtemp()
        template = "/etc/keystone/keystone.conf"
        target_file = os.path.join(tmpdir, template[1:])
        os.makedirs(os.path.dirname(target_file))
        # File doesn't exist, use the default mode (644)
        apply_config.install_config([path], TEMPLATES, tmpdir, False)
        self.assertEqual(0o100644, os.stat(target_file).st_mode)
        self.assertEqual(OUTPUT[template].body, open(target_file).read())
        # Set a different mode:
        os.chmod(target_file, 0o600)
        apply_config.install_config([path], TEMPLATES, tmpdir, False)
        # The permissions should be preserved
        self.assertEqual(0o100600, os.stat(target_file).st_mode)
        self.assertEqual(OUTPUT[template].body, open(target_file).read())

    def test_build_tree(self):
        tree = apply_config.build_tree(
            apply_config.template_paths(TEMPLATES), CONFIG)
        self.assertEqual(OUTPUT, tree)

    def test_render_template(self):
        # execute executable files, moustache non-executables
        self.assertEqual("abc\n", apply_config.render_template(template(
            "/etc/glance/script.conf"), {"x": "abc"}))
        self.assertRaises(
            exc.ConfigException,
            apply_config.render_template,
            template("/etc/glance/script.conf"), {})

    def test_render_template_bad_template(self):
        tdir = self.useFixture(fixtures.TempDir())
        bt_path = os.path.join(tdir.path, 'bad_template')
        with open(bt_path, 'w') as bt:
            bt.write("{{#foo}}bar={{bar}}{{/bar}}")
        e = self.assertRaises(exc.ConfigException,
                              apply_config.render_template,
                              bt_path, {'foo': [{'bar':
                                                 'abc'}]})
        self.assertIn('could not render moustache template', str(e))
        self.assertIn('Section end tag mismatch', self.logger.output)

    def test_render_moustache(self):
        self.assertEqual(
            "ab123cd",
            apply_config.render_moustache("ab{{x.a}}cd", {"x": {"a": "123"}}))

    def test_render_moustache_bad_key(self):
        self.assertEqual('', apply_config.render_moustache("{{badkey}}", {}))

    def test_render_moustache_none(self):
        self.assertEqual('foo: ',
                         apply_config.render_moustache("foo: {{foo}}",
                                                       {'foo': None}))

    def test_render_executable(self):
        params = {"x": "foo"}
        self.assertEqual("foo\n", apply_config.render_executable(
            template("/etc/glance/script.conf"), params))

    def test_render_executable_failure(self):
        self.assertRaises(
            exc.ConfigException,
            apply_config.render_executable,
            template("/etc/glance/script.conf"), {})

    def test_template_paths(self):
        expected = list(map(lambda p: (template(p), p), TEMPLATE_PATHS))
        actual = apply_config.template_paths(TEMPLATES)
        expected.sort(key=lambda tup: tup[1])
        actual.sort(key=lambda tup: tup[1])
        self.assertEqual(expected, actual)

    def test_strip_hash(self):
        h = {'a': {'b': {'x': 'y'}}, "c": [1, 2, 3]}
        self.assertEqual({'x': 'y'}, apply_config.strip_hash(h, 'a.b'))
        self.assertRaises(exc.ConfigException,
                          apply_config.strip_hash, h, 'a.nonexistent')
        self.assertRaises(exc.ConfigException,
                          apply_config.strip_hash, h, 'a.c')

    def test_load_list_from_json(self):
        def mkstemp():
            fd, path = tempfile.mkstemp()
            atexit.register(
                lambda: os.path.exists(path) and os.remove(path))
            return (fd, path)

        def write_contents(fd, contents):
            with os.fdopen(fd, 'w') as t:
                t.write(contents)
                t.flush()

        fd, path = mkstemp()
        load_list = apply_config.load_list_from_json
        self.assertRaises(ValueError, load_list, path)
        write_contents(fd, json.dumps(["/tmp/config.json"]))
        json_obj = load_list(path)
        self.assertEqual(["/tmp/config.json"], json_obj)
        os.remove(path)
        self.assertEqual([], load_list(path))

        fd, path = mkstemp()
        write_contents(fd, json.dumps({}))
        self.assertRaises(ValueError, load_list, path)

    def test_default_templates_dir_current(self):
        default = '/usr/libexec/os-apply-config/templates'
        with mock.patch('os.path.isdir', lambda x: x == default):
            self.assertEqual(default, apply_config.templates_dir())

    def test_default_templates_dir_deprecated(self):
        default = '/opt/stack/os-apply-config/templates'
        with mock.patch('os.path.isdir', lambda x: x == default):
            self.assertEqual(default, apply_config.templates_dir())

    def test_default_templates_dir_old_deprecated(self):
        default = '/opt/stack/os-config-applier/templates'
        with mock.patch('os.path.isdir', lambda x: x == default):
            self.assertEqual(default, apply_config.templates_dir())

    def test_default_templates_dir_both(self):
        default = '/usr/libexec/os-apply-config/templates'
        deprecated = '/opt/stack/os-apply-config/templates'
        with mock.patch('os.path.isdir', lambda x: (x == default or
                                                    x == deprecated)):
            self.assertEqual(default, apply_config.templates_dir())

    def test_control_mode(self):
        path = self.write_config(CONFIG)
        tmpdir = tempfile.mkdtemp()
        template = "/etc/control/mode"
        target_file = os.path.join(tmpdir, template[1:])
        apply_config.install_config([path], TEMPLATES, tmpdir, False)
        self.assertEqual(0o100755, os.stat(target_file).st_mode)

    @mock.patch('os.chown')
    def test_control_chown(self, chown_mock):
        path = self.write_config(CONFIG)
        tmpdir = tempfile.mkdtemp()
        apply_config.install_config([path], CHOWN_TEMPLATES, tmpdir, False)
        chown_mock.assert_has_calls([mock.call(mock.ANY, 0, -1),   # uid
                                     mock.call(mock.ANY, 0, -1),   # username
                                     mock.call(mock.ANY, -1, 0),   # gid
                                     mock.call(mock.ANY, -1, 0)],  # groupname
                                    any_order=True)