summaryrefslogtreecommitdiff
path: root/cloudinit/cmd/tests/test_query.py
blob: 241f54133fcccc1b5c9d0f299fdc95ccb3433219 (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
# This file is part of cloud-init. See LICENSE file for license information.

from six import StringIO
from textwrap import dedent
import os

from collections import namedtuple
from cloudinit.cmd import query
from cloudinit.helpers import Paths
from cloudinit.sources import (
    REDACT_SENSITIVE_VALUE, INSTANCE_JSON_FILE, INSTANCE_JSON_SENSITIVE_FILE)
from cloudinit.tests.helpers import CiTestCase, mock
from cloudinit.util import ensure_dir, write_file


class TestQuery(CiTestCase):

    with_logs = True

    args = namedtuple(
        'queryargs',
        ('debug dump_all format instance_data list_keys user_data vendor_data'
         ' varname'))

    def setUp(self):
        super(TestQuery, self).setUp()
        self.tmp = self.tmp_dir()
        self.instance_data = self.tmp_path('instance-data', dir=self.tmp)

    def test_handle_args_error_on_missing_param(self):
        """Error when missing required parameters and print usage."""
        args = self.args(
            debug=False, dump_all=False, format=None, instance_data=None,
            list_keys=False, user_data=None, vendor_data=None, varname=None)
        with mock.patch('sys.stderr', new_callable=StringIO) as m_stderr:
            with mock.patch('sys.stdout', new_callable=StringIO) as m_stdout:
                self.assertEqual(1, query.handle_args('anyname', args))
        expected_error = (
            'ERROR: Expected one of the options: --all, --format, --list-keys'
            ' or varname\n')
        self.assertIn(expected_error, self.logs.getvalue())
        self.assertIn('usage: query', m_stdout.getvalue())
        self.assertIn(expected_error, m_stderr.getvalue())

    def test_handle_args_error_on_missing_instance_data(self):
        """When instance_data file path does not exist, log an error."""
        absent_fn = self.tmp_path('absent', dir=self.tmp)
        args = self.args(
            debug=False, dump_all=True, format=None, instance_data=absent_fn,
            list_keys=False, user_data='ud', vendor_data='vd', varname=None)
        with mock.patch('sys.stderr', new_callable=StringIO) as m_stderr:
            self.assertEqual(1, query.handle_args('anyname', args))
        self.assertIn(
            'ERROR: Missing instance-data.json file: %s' % absent_fn,
            self.logs.getvalue())
        self.assertIn(
            'ERROR: Missing instance-data.json file: %s' % absent_fn,
            m_stderr.getvalue())

    def test_handle_args_defaults_instance_data(self):
        """When no instance_data argument, default to configured run_dir."""
        args = self.args(
            debug=False, dump_all=True, format=None, instance_data=None,
            list_keys=False, user_data=None, vendor_data=None, varname=None)
        run_dir = self.tmp_path('run_dir', dir=self.tmp)
        ensure_dir(run_dir)
        paths = Paths({'run_dir': run_dir})
        self.add_patch('cloudinit.cmd.query.read_cfg_paths', 'm_paths')
        self.m_paths.return_value = paths
        with mock.patch('sys.stderr', new_callable=StringIO) as m_stderr:
            self.assertEqual(1, query.handle_args('anyname', args))
        json_file = os.path.join(run_dir, INSTANCE_JSON_FILE)
        self.assertIn(
            'ERROR: Missing instance-data.json file: %s' % json_file,
            self.logs.getvalue())
        self.assertIn(
            'ERROR: Missing instance-data.json file: %s' % json_file,
            m_stderr.getvalue())

    def test_handle_args_root_fallsback_to_instance_data(self):
        """When no instance_data argument, root falls back to redacted json."""
        args = self.args(
            debug=False, dump_all=True, format=None, instance_data=None,
            list_keys=False, user_data=None, vendor_data=None, varname=None)
        run_dir = self.tmp_path('run_dir', dir=self.tmp)
        ensure_dir(run_dir)
        paths = Paths({'run_dir': run_dir})
        self.add_patch('cloudinit.cmd.query.read_cfg_paths', 'm_paths')
        self.m_paths.return_value = paths
        with mock.patch('sys.stderr', new_callable=StringIO) as m_stderr:
            with mock.patch('os.getuid') as m_getuid:
                m_getuid.return_value = 0
                self.assertEqual(1, query.handle_args('anyname', args))
        json_file = os.path.join(run_dir, INSTANCE_JSON_FILE)
        sensitive_file = os.path.join(run_dir, INSTANCE_JSON_SENSITIVE_FILE)
        self.assertIn(
            'WARNING: Missing root-readable %s. Using redacted %s instead.' % (
                sensitive_file, json_file),
            m_stderr.getvalue())

    def test_handle_args_root_uses_instance_sensitive_data(self):
        """When no instance_data argument, root uses semsitive json."""
        user_data = self.tmp_path('user-data', dir=self.tmp)
        vendor_data = self.tmp_path('vendor-data', dir=self.tmp)
        write_file(user_data, 'ud')
        write_file(vendor_data, 'vd')
        run_dir = self.tmp_path('run_dir', dir=self.tmp)
        sensitive_file = os.path.join(run_dir, INSTANCE_JSON_SENSITIVE_FILE)
        write_file(sensitive_file, '{"my-var": "it worked"}')
        ensure_dir(run_dir)
        paths = Paths({'run_dir': run_dir})
        self.add_patch('cloudinit.cmd.query.read_cfg_paths', 'm_paths')
        self.m_paths.return_value = paths
        args = self.args(
            debug=False, dump_all=True, format=None, instance_data=None,
            list_keys=False, user_data=vendor_data, vendor_data=vendor_data,
            varname=None)
        with mock.patch('sys.stdout', new_callable=StringIO) as m_stdout:
            with mock.patch('os.getuid') as m_getuid:
                m_getuid.return_value = 0
                self.assertEqual(0, query.handle_args('anyname', args))
        self.assertEqual(
            '{\n "my_var": "it worked",\n "userdata": "vd",\n '
            '"vendordata": "vd"\n}\n', m_stdout.getvalue())

    def test_handle_args_dumps_all_instance_data(self):
        """When --all is specified query will dump all instance data vars."""
        write_file(self.instance_data, '{"my-var": "it worked"}')
        args = self.args(
            debug=False, dump_all=True, format=None,
            instance_data=self.instance_data, list_keys=False,
            user_data='ud', vendor_data='vd', varname=None)
        with mock.patch('sys.stdout', new_callable=StringIO) as m_stdout:
            self.assertEqual(0, query.handle_args('anyname', args))
        self.assertEqual(
            '{\n "my_var": "it worked",\n "userdata": "<%s> file:ud",\n'
            ' "vendordata": "<%s> file:vd"\n}\n' % (
                REDACT_SENSITIVE_VALUE, REDACT_SENSITIVE_VALUE),
            m_stdout.getvalue())

    def test_handle_args_returns_top_level_varname(self):
        """When the argument varname is passed, report its value."""
        write_file(self.instance_data, '{"my-var": "it worked"}')
        args = self.args(
            debug=False, dump_all=True, format=None,
            instance_data=self.instance_data, list_keys=False,
            user_data='ud', vendor_data='vd', varname='my_var')
        with mock.patch('sys.stdout', new_callable=StringIO) as m_stdout:
            self.assertEqual(0, query.handle_args('anyname', args))
        self.assertEqual('it worked\n', m_stdout.getvalue())

    def test_handle_args_returns_nested_varname(self):
        """If user_data file is a jinja template render instance-data vars."""
        write_file(self.instance_data,
                   '{"v1": {"key-2": "value-2"}, "my-var": "it worked"}')
        args = self.args(
            debug=False, dump_all=False, format=None,
            instance_data=self.instance_data, user_data='ud', vendor_data='vd',
            list_keys=False, varname='v1.key_2')
        with mock.patch('sys.stdout', new_callable=StringIO) as m_stdout:
            self.assertEqual(0, query.handle_args('anyname', args))
        self.assertEqual('value-2\n', m_stdout.getvalue())

    def test_handle_args_returns_standardized_vars_to_top_level_aliases(self):
        """Any standardized vars under v# are promoted as top-level aliases."""
        write_file(
            self.instance_data,
            '{"v1": {"v1_1": "val1.1"}, "v2": {"v2_2": "val2.2"},'
            ' "top": "gun"}')
        expected = dedent("""\
            {
             "top": "gun",
             "userdata": "<redacted for non-root user> file:ud",
             "v1": {
              "v1_1": "val1.1"
             },
             "v1_1": "val1.1",
             "v2": {
              "v2_2": "val2.2"
             },
             "v2_2": "val2.2",
             "vendordata": "<redacted for non-root user> file:vd"
            }
        """)
        args = self.args(
            debug=False, dump_all=True, format=None,
            instance_data=self.instance_data, user_data='ud', vendor_data='vd',
            list_keys=False, varname=None)
        with mock.patch('sys.stdout', new_callable=StringIO) as m_stdout:
            self.assertEqual(0, query.handle_args('anyname', args))
        self.assertEqual(expected, m_stdout.getvalue())

    def test_handle_args_list_keys_sorts_top_level_keys_when_no_varname(self):
        """Sort all top-level keys when only --list-keys provided."""
        write_file(
            self.instance_data,
            '{"v1": {"v1_1": "val1.1"}, "v2": {"v2_2": "val2.2"},'
            ' "top": "gun"}')
        expected = 'top\nuserdata\nv1\nv1_1\nv2\nv2_2\nvendordata\n'
        args = self.args(
            debug=False, dump_all=False, format=None,
            instance_data=self.instance_data, list_keys=True, user_data='ud',
            vendor_data='vd', varname=None)
        with mock.patch('sys.stdout', new_callable=StringIO) as m_stdout:
            self.assertEqual(0, query.handle_args('anyname', args))
        self.assertEqual(expected, m_stdout.getvalue())

    def test_handle_args_list_keys_sorts_nested_keys_when_varname(self):
        """Sort all nested keys of varname object when --list-keys provided."""
        write_file(
            self.instance_data,
            '{"v1": {"v1_1": "val1.1", "v1_2": "val1.2"}, "v2":' +
            ' {"v2_2": "val2.2"}, "top": "gun"}')
        expected = 'v1_1\nv1_2\n'
        args = self.args(
            debug=False, dump_all=False, format=None,
            instance_data=self.instance_data, list_keys=True,
            user_data='ud', vendor_data='vd', varname='v1')
        with mock.patch('sys.stdout', new_callable=StringIO) as m_stdout:
            self.assertEqual(0, query.handle_args('anyname', args))
        self.assertEqual(expected, m_stdout.getvalue())

    def test_handle_args_list_keys_errors_when_varname_is_not_a_dict(self):
        """Raise an error when --list-keys and varname specify a non-list."""
        write_file(
            self.instance_data,
            '{"v1": {"v1_1": "val1.1", "v1_2": "val1.2"}, "v2": ' +
            '{"v2_2": "val2.2"}, "top": "gun"}')
        expected_error = "ERROR: --list-keys provided but 'top' is not a dict"
        args = self.args(
            debug=False, dump_all=False, format=None,
            instance_data=self.instance_data, list_keys=True, user_data='ud',
            vendor_data='vd',  varname='top')
        with mock.patch('sys.stderr', new_callable=StringIO) as m_stderr:
            with mock.patch('sys.stdout', new_callable=StringIO) as m_stdout:
                self.assertEqual(1, query.handle_args('anyname', args))
        self.assertEqual('', m_stdout.getvalue())
        self.assertIn(expected_error, m_stderr.getvalue())

# vi: ts=4 expandtab