Debian Codegraph @

glanceclient/tests/unit/test_utils.py

raw symbols SCIP
1 # Copyright 2012 OpenStack Foundation
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 import io
17 import sys
18 from unittest import mock
19
20 from oslo_utils import encodeutils
21 from requests import Response
22 # NOTE(jokke): simplified transition to py3, behaves like py2 xrange
23 import testtools
24
25 from glanceclient.common import utils
26
27
28 REQUEST_ID = 'req-1234'
29
30
31 def create_response_obj_with_req_id(req_id):
32 resp = Response()
33 resp.headers['x-openstack-request-id'] = req_id
34 return resp
35
36
37 class TestUtils(testtools.TestCase):
38
39 def test_make_size_human_readable(self):
40 self.assertEqual("106B", utils.make_size_human_readable(106))
41 self.assertEqual("1000kB", utils.make_size_human_readable(1024000))
42 self.assertEqual("1MB", utils.make_size_human_readable(1048576))
43 self.assertEqual("1.4GB", utils.make_size_human_readable(1476395008))
44 self.assertEqual("9.3MB", utils.make_size_human_readable(9761280))
45 self.assertEqual("0B", utils.make_size_human_readable(None))
46
47 def test_get_new_file_size(self):
48 size = 98304
49 file_obj = io.StringIO('X' * size)
50 try:
51 self.assertEqual(size, utils.get_file_size(file_obj))
52 # Check that get_file_size didn't change original file position.
53 self.assertEqual(0, file_obj.tell())
54 finally:
55 file_obj.close()
56
57 def test_get_consumed_file_size(self):
58 size, consumed = 98304, 304
59 file_obj = io.StringIO('X' * size)
60 file_obj.seek(consumed)
61 try:
62 self.assertEqual(size, utils.get_file_size(file_obj))
63 # Check that get_file_size didn't change original file position.
64 self.assertEqual(consumed, file_obj.tell())
65 finally:
66 file_obj.close()
67
68 def test_prettytable(self):
69 class Struct(object):
70 def __init__(self, **entries):
71 self.__dict__.update(entries)
72
73 # test that the prettytable output is wellformatted (left-aligned)
74 columns = ['ID', 'Name']
75 val = ['Name1', 'another', 'veeeery long']
76 images = [Struct(**{'id': i ** 16, 'name': val[i]})
77 for i in range(len(val))]
78
79 saved_stdout = sys.stdout
80 try:
81 sys.stdout = output_list = io.StringIO()
82 utils.print_list(images, columns)
83
84 sys.stdout = output_dict = io.StringIO()
85 utils.print_dict({'K': 'k', 'Key': 'veeeeeeeeeeeeeeeeeeeeeeee'
86 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'
87 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'
88 'eeeeeeeeeeeery long value'},
89 max_column_width=60)
90
91 finally:
92 sys.stdout = saved_stdout
93
94 self.assertEqual('''\
95 +-------+--------------+
96 | ID | Name |
97 +-------+--------------+
98 | | Name1 |
99 | 1 | another |
100 | 65536 | veeeery long |
101 +-------+--------------+
102 ''',
103 output_list.getvalue())
104
105 self.assertEqual('''\
106 +----------+--------------------------------------------------------------+
107 | Property | Value |
108 +----------+--------------------------------------------------------------+
109 | K | k |
110 | Key | veeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee |
111 | | eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee |
112 | | ery long value |
113 +----------+--------------------------------------------------------------+
114 ''',
115 output_dict.getvalue())
116
117 def test_print_list_with_list_no_unicode(self):
118 class Struct(object):
119 def __init__(self, **entries):
120 self.__dict__.update(entries)
121
122 # test for removing 'u' from lists in print_list output
123 columns = ['ID', 'Tags']
124 images = [Struct(**{'id': 'b8e1c57e-907a-4239-aed8-0df8e54b8d2d',
125 'tags': ['Name1', 'Tag_123', 'veeeery long']})]
126 saved_stdout = sys.stdout
127 try:
128 sys.stdout = output_list = io.StringIO()
129 utils.print_list(images, columns)
130
131 finally:
132 sys.stdout = saved_stdout
133
134 self.assertEqual('''\
135 +--------------------------------------+--------------------------------------+
136 | ID | Tags |
137 +--------------------------------------+--------------------------------------+
138 | b8e1c57e-907a-4239-aed8-0df8e54b8d2d | ['Name1', 'Tag_123', 'veeeery long'] |
139 +--------------------------------------+--------------------------------------+
140 ''',
141 output_list.getvalue())
142
143 def test_print_image_virtual_size_available(self):
144 image = {'id': '42', 'virtual_size': 1337}
145 saved_stdout = sys.stdout
146 try:
147 sys.stdout = output_list = io.StringIO()
148 utils.print_image(image)
149 finally:
150 sys.stdout = saved_stdout
151
152 self.assertEqual('''\
153 +--------------+-------+
154 | Property | Value |
155 +--------------+-------+
156 | id | 42 |
157 | virtual_size | 1337 |
158 +--------------+-------+
159 ''',
160 output_list.getvalue())
161
162 def test_print_image_virtual_size_not_available(self):
163 image = {'id': '42', 'virtual_size': None}
164 saved_stdout = sys.stdout
165 try:
166 sys.stdout = output_list = io.StringIO()
167 utils.print_image(image)
168 finally:
169 sys.stdout = saved_stdout
170
171 self.assertEqual('''\
172 +--------------+---------------+
173 | Property | Value |
174 +--------------+---------------+
175 | id | 42 |
176 | virtual_size | Not available |
177 +--------------+---------------+
178 ''',
179 output_list.getvalue())
180
181 def test_schema_args_with_list_types(self):
182 # NOTE(flaper87): Regression for bug
183 # https://bugs.launchpad.net/python-glanceclient/+bug/1401032
184
185 def schema_getter(_type='string', enum=False):
186 prop = {
187 'type': ['null', _type],
188 'description': 'Test schema',
189 }
190 prop_readonly = {
191 'type': ['null', _type],
192 'readOnly': True,
193 'description': 'Test schema read-only',
194 }
195
196 if enum:
197 prop['enum'] = [None, 'opt-1', 'opt-2']
198 prop_readonly['enum'] = [None, 'opt-ro-1', 'opt-ro-2']
199
200 def actual_getter():
201 return {
202 'additionalProperties': False,
203 'required': ['name'],
204 'name': 'test_schema',
205 'properties': {
206 'test': prop,
207 'readonly-test': prop_readonly,
208 }
209 }
210
211 return actual_getter
212
213 def dummy_func():
214 pass
215
216 decorated = utils.schema_args(schema_getter())(dummy_func)
217 self.assertEqual(len(decorated.__dict__['arguments']), 1)
218 arg, opts = decorated.__dict__['arguments'][0]
219 self.assertIn('--test', arg)
220 self.assertEqual(encodeutils.safe_decode, opts['type'])
221
222 decorated = utils.schema_args(schema_getter('integer'))(dummy_func)
223 arg, opts = decorated.__dict__['arguments'][0]
224 self.assertIn('--test', arg)
225 self.assertEqual(int, opts['type'])
226
227 decorated = utils.schema_args(schema_getter(enum=True))(dummy_func)
228 arg, opts = decorated.__dict__['arguments'][0]
229 self.assertIn('--test', arg)
230 self.assertEqual(encodeutils.safe_decode, opts['type'])
231 self.assertIn('None, opt-1, opt-2', opts['help'])
232
233 # Make sure we use strict checking for boolean values.
234 decorated = utils.schema_args(schema_getter('boolean'))(dummy_func)
235 arg, opts = decorated.__dict__['arguments'][0]
236 type_function = opts['type']
237 self.assertEqual(type_function('False'), False)
238 self.assertEqual(type_function('True'), True)
239 self.assertRaises(ValueError, type_function, 'foo')
240
241 def test_iterable_closes(self):
242 # Regression test for bug 1461678.
243 def _iterate(i):
244 for chunk in i:
245 raise IOError()
246
247 data = io.StringIO('somestring')
248 data.close = mock.Mock()
249 i = utils.IterableWithLength(data, 10)
250 self.assertRaises(IOError, _iterate, i)
251 data.close.assert_called_with()
252
253 def test_safe_header(self):
254 self.assertEqual(('somekey', 'somevalue'),
255 utils.safe_header('somekey', 'somevalue'))
256 self.assertEqual(('somekey', None),
257 utils.safe_header('somekey', None))
258
259 for sensitive_header in utils.SENSITIVE_HEADERS:
260 (name, value) = utils.safe_header(
261 sensitive_header,
262 encodeutils.safe_encode('somestring'))
263 self.assertEqual(sensitive_header, name)
264 self.assertTrue(value.startswith("{SHA1}"))
265
266 (name, value) = utils.safe_header(sensitive_header, None)
267 self.assertEqual(sensitive_header, name)
268 self.assertIsNone(value)
269
270 def test_generator_proxy(self):
271 def _test_decorator():
272 i = 1
273 resp = create_response_obj_with_req_id(REQUEST_ID)
274 while True:
275 yield i, resp
276 i += 1
277
278 gen_obj = _test_decorator()
279 proxy = utils.GeneratorProxy(gen_obj)
280
281 # Proxy object should succeed in behaving as the
282 # wrapped object
283 self.assertIsInstance(proxy, type(gen_obj))
284
285 # Initially request_ids should be empty
286 self.assertEqual([], proxy.request_ids)
287
288 # Only after we have started iterating we should
289 # see non-empty `request_ids` property
290 proxy.next()
291 self.assertEqual([REQUEST_ID], proxy.request_ids)
292
293 # Even after multiple iterations `request_ids` property
294 # should only contain one request id
295 proxy.next()
296 proxy.next()
297 self.assertEqual(1, len(proxy.request_ids))
298
299 def test_request_id_proxy(self):
300 def test_data(val):
301 resp = create_response_obj_with_req_id(REQUEST_ID)
302 return val, resp
303
304 # Object of any type except decorator can be passed to test_data
305 proxy = utils.RequestIdProxy(test_data(11))
306 # Verify that proxy object has a property `request_ids` and it is
307 # a list of one request id
308 self.assertEqual([REQUEST_ID], proxy.request_ids)