summaryrefslogtreecommitdiff
path: root/cinderclient/tests/unit/test_utils.py
blob: cce4498b4e1c6414cd47ebda58d140ef038e6b07 (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
# 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 collections
import io
import sys
from unittest import mock

import ddt

from cinderclient import api_versions
from cinderclient.apiclient import base as common_base
from cinderclient import base
from cinderclient import exceptions
from cinderclient import shell_utils
from cinderclient.tests.unit import utils as test_utils
from cinderclient import utils

REQUEST_ID = 'req-test-request-id'
UUID = '8e8ec658-c7b0-4243-bdf8-6f7f2952c0d0'


class FakeResource(object):
    NAME_ATTR = 'name'

    def __init__(self, _id, properties, **kwargs):
        self.id = _id
        try:
            self.name = properties['name']
        except KeyError:
            pass

    def append_request_ids(self, resp):
        pass


class FakeManager(base.ManagerWithFind):

    resource_class = FakeResource

    resources = [
        FakeResource('1234', {'name': 'entity_one'}),
        FakeResource(UUID, {'name': 'entity_two'}),
        FakeResource('5678', {'name': '9876'})
    ]

    def get(self, resource_id, **kwargs):
        for resource in self.resources:
            if resource.id == str(resource_id):
                return resource
        raise exceptions.NotFound(resource_id)

    def list(self, search_opts, **kwargs):
        return common_base.ListWithMeta(self.resources, REQUEST_ID)


class FakeManagerWithApi(base.Manager):

    @api_versions.wraps('3.1')
    def return_api_version(self):
        return '3.1'

    @api_versions.wraps('3.2')
    def return_api_version(self):  # noqa: F811
        return '3.2'


class FakeDisplayResource(object):
    NAME_ATTR = 'display_name'

    def __init__(self, _id, properties):
        self.id = _id
        try:
            self.display_name = properties['display_name']
        except KeyError:
            pass

    def append_request_ids(self, resp):
        pass


class FakeDisplayManager(FakeManager):

    resource_class = FakeDisplayResource

    resources = [
        FakeDisplayResource('4242', {'display_name': 'entity_three'}),
    ]


class FindResourceTestCase(test_utils.TestCase):

    def setUp(self):
        super(FindResourceTestCase, self).setUp()
        self.manager = FakeManager(None)

    def test_find_none(self):
        self.manager.find = mock.Mock(side_effect=self.manager.find)
        self.assertRaises(exceptions.CommandError,
                          utils.find_resource,
                          self.manager,
                          'asdf')
        self.assertEqual(2, self.manager.find.call_count)

    def test_find_by_integer_id(self):
        output = utils.find_resource(self.manager, 1234)
        self.assertEqual(self.manager.get('1234'), output)

    def test_find_by_str_id(self):
        output = utils.find_resource(self.manager, '1234')
        self.assertEqual(self.manager.get('1234'), output)

    def test_find_by_uuid(self):
        output = utils.find_resource(self.manager, UUID)
        self.assertEqual(self.manager.get(UUID), output)

    def test_find_by_str_name(self):
        output = utils.find_resource(self.manager, 'entity_one')
        self.assertEqual(self.manager.get('1234'), output)

    def test_find_by_str_displayname(self):
        display_manager = FakeDisplayManager(None)
        output = utils.find_resource(display_manager, 'entity_three')
        self.assertEqual(display_manager.get('4242'), output)

    def test_find_by_group_id(self):
        output = utils.find_resource(self.manager, 1234, is_group=True,
                                     list_volume=True)
        self.assertEqual(self.manager.get('1234', list_volume=True), output)

    def test_find_by_group_name(self):
        display_manager = FakeDisplayManager(None)
        output = utils.find_resource(display_manager, 'entity_three',
                                     is_group=True, list_volume=True)
        self.assertEqual(display_manager.get('4242', list_volume=True),
                         output)


class CaptureStdout(object):
    """Context manager for capturing stdout from statements in its block."""
    def __enter__(self):
        self.real_stdout = sys.stdout
        self.stringio = io.StringIO()
        sys.stdout = self.stringio
        return self

    def __exit__(self, *args):
        sys.stdout = self.real_stdout
        self.stringio.seek(0)
        self.read = self.stringio.read


@ddt.ddt
class BuildQueryParamTestCase(test_utils.TestCase):

    def test_build_param_without_sort_switch(self):
        dict_param = {
            'key1': 'val1',
            'key2': 'val2',
            'key3': 'val3',
        }
        result = utils.build_query_param(dict_param, True)

        self.assertIn('key1=val1', result)
        self.assertIn('key2=val2', result)
        self.assertIn('key3=val3', result)

    def test_build_param_with_sort_switch(self):
        dict_param = {
            'key1': 'val1',
            'key2': 'val2',
            'key3': 'val3',
        }
        result = utils.build_query_param(dict_param, True)

        expected = "?key1=val1&key2=val2&key3=val3"
        self.assertEqual(expected, result)

    @ddt.data({},
              None,
              {'key1': 'val1', 'key2': None, 'key3': False, 'key4': ''})
    def test_build_param_with_nones(self, dict_param):
        result = utils.build_query_param(dict_param)

        expected = ("key1=val1", "key3=False") if dict_param else ()
        for exp in expected:
            self.assertIn(exp, result)
        if not expected:
            self.assertEqual("", result)


@ddt.ddt
class ExtractFilterTestCase(test_utils.TestCase):

    @ddt.data({'content': ['key1=value1'],
               'expected': {'key1': 'value1'}},
              {'content': ['key1={key2:value2}'],
               'expected': {'key1': {'key2': 'value2'}}},
              {'content': ['key1=value1', 'key2={key22:value22}'],
               'expected': {'key1': 'value1', 'key2': {'key22': 'value22'}}})
    @ddt.unpack
    def test_extract_filters(self, content, expected):
        result = shell_utils.extract_filters(content)
        self.assertEqual(expected, result)


class PrintListTestCase(test_utils.TestCase):

    def test_print_list_with_list(self):
        Row = collections.namedtuple('Row', ['a', 'b'])
        to_print = [Row(a=3, b=4), Row(a=1, b=2)]
        with CaptureStdout() as cso:
            utils.print_list(to_print, ['a', 'b'])
        # Output should be sorted by the first key (a)
        self.assertEqual("""\
+---+---+
| a | b |
+---+---+
| 1 | 2 |
| 3 | 4 |
+---+---+
""", cso.read())

    def test_print_list_with_None_data(self):
        Row = collections.namedtuple('Row', ['a', 'b'])
        to_print = [Row(a=3, b=None), Row(a=1, b=2)]
        with CaptureStdout() as cso:
            utils.print_list(to_print, ['a', 'b'])
        # Output should be sorted by the first key (a)
        self.assertEqual("""\
+---+---+
| a | b |
+---+---+
| 1 | 2 |
| 3 | - |
+---+---+
""", cso.read())

    def test_print_list_with_list_sortby(self):
        Row = collections.namedtuple('Row', ['a', 'b'])
        to_print = [Row(a=4, b=3), Row(a=2, b=1)]
        with CaptureStdout() as cso:
            utils.print_list(to_print, ['a', 'b'], sortby_index=1)
        # Output should be sorted by the second key (b)
        self.assertEqual("""\
+---+---+
| a | b |
+---+---+
| 2 | 1 |
| 4 | 3 |
+---+---+
""", cso.read())

    def test_print_list_with_list_no_sort(self):
        Row = collections.namedtuple('Row', ['a', 'b'])
        to_print = [Row(a=3, b=4), Row(a=1, b=2)]
        with CaptureStdout() as cso:
            utils.print_list(to_print, ['a', 'b'], sortby_index=None)
        # Output should be in the order given
        self.assertEqual("""\
+---+---+
| a | b |
+---+---+
| 3 | 4 |
| 1 | 2 |
+---+---+
""", cso.read())

    def test_print_list_with_generator(self):
        Row = collections.namedtuple('Row', ['a', 'b'])

        def gen_rows():
            for row in [Row(a=1, b=2), Row(a=3, b=4)]:
                yield row
        with CaptureStdout() as cso:
            utils.print_list(gen_rows(), ['a', 'b'])
        self.assertEqual("""\
+---+---+
| a | b |
+---+---+
| 1 | 2 |
| 3 | 4 |
+---+---+
""", cso.read())

    def test_print_list_with_return(self):
        Row = collections.namedtuple('Row', ['a', 'b'])
        to_print = [Row(a=3, b='a\r'), Row(a=1, b='c\rd')]
        with CaptureStdout() as cso:
            utils.print_list(to_print, ['a', 'b'])
        # Output should be sorted by the first key (a)
        self.assertEqual("""\
+---+-----+
| a | b   |
+---+-----+
| 1 | c d |
| 3 | a   |
+---+-----+
""", cso.read())


class PrintDictTestCase(test_utils.TestCase):

    def test__pretty_format_dict(self):
        content = {'key1': 'value1', 'key2': 'value2'}
        expected = "key1 : value1\nkey2 : value2"
        result = utils._pretty_format_dict(content)
        self.assertEqual(expected, result)

    def test_print_dict_with_return(self):
        d = {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'test\rcarriage\n\rreturn'}
        with CaptureStdout() as cso:
            utils.print_dict(d)
        self.assertEqual("""\
+----------+---------------+
| Property | Value         |
+----------+---------------+
| a        | A             |
| b        | B             |
| c        | C             |
| d        | test carriage |
|          |  return       |
+----------+---------------+
""", cso.read())

    def test_print_dict_with_dict_inside(self):
        content = {'a': 'A', 'b': 'B', 'f_key':
                   {'key1': 'value1', 'key2': 'value2'}}
        with CaptureStdout() as cso:
            utils.print_dict(content, formatters='f_key')
        self.assertEqual("""\
+----------+---------------+
| Property | Value         |
+----------+---------------+
| a        | A             |
| b        | B             |
| f_key    | key1 : value1 |
|          | key2 : value2 |
+----------+---------------+
""", cso.read())