Debian Codegraph @

glanceclient/tests/unit/v1/test_shell.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # Copyright 2013 OpenStack Foundation
2 # Copyright (C) 2013 Yahoo! Inc.
3 # All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License"); you may
6 # not use this file except in compliance with the License. You may obtain
7 # a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 # License for the specific language governing permissions and limitations
15 # under the License.
16
17 import argparse
18 import io
19 import json
20 import os
21 from unittest import mock
22
23 import subprocess
24 import tempfile
25 import testtools
26
27
28 from glanceclient import exc
29 from glanceclient import shell
30
31 import glanceclient.v1.client as client
32 import glanceclient.v1.images
33 import glanceclient.v1.shell as v1shell
34
35 from glanceclient.tests import utils
36
37 fixtures = {
38 '/v1/images/96d2c7e1-de4e-4612-8aa2-ba26610c804e': {
39 'PUT': (
40 {
41 'Location': 'http://fakeaddress.com:9292/v1/images/'
42 '96d2c7e1-de4e-4612-8aa2-ba26610c804e',
43 'Etag': 'f8a2eeee2dc65b3d9b6e63678955bd83',
44 'X-Openstack-Request-Id':
45 'req-b645039d-e1c7-43e5-b27b-2d18a173c42b',
46 'Date': 'Mon, 29 Apr 2013 10:24:32 GMT'
47 },
48 json.dumps({
49 'image': {
50 'status': 'active', 'name': 'testimagerename',
51 'deleted': False,
52 'container_format': 'ami',
53 'created_at': '2013-04-25T15:47:43',
54 'disk_format': 'ami',
55 'updated_at': '2013-04-29T10:24:32',
56 'id': '96d2c7e1-de4e-4612-8aa2-ba26610c804e',
57 'min_disk': 0,
58 'protected': False,
59 'min_ram': 0,
60 'checksum': 'f8a2eeee2dc65b3d9b6e63678955bd83',
61 'owner': '1310db0cce8f40b0987a5acbe139765a',
62 'is_public': True,
63 'deleted_at': None,
64 'properties': {
65 'kernel_id': '1b108400-65d8-4762-9ea4-1bf6c7be7568',
66 'ramdisk_id': 'b759bee9-0669-4394-a05c-fa2529b1c114'
67 },
68 'size': 25165824
69 }
70 })
71 ),
72 'HEAD': (
73 {
74 'x-image-meta-id': '96d2c7e1-de4e-4612-8aa2-ba26610c804e',
75 'x-image-meta-status': 'active'
76 },
77 None
78 ),
79 'GET': (
80 {
81 'x-image-meta-status': 'active',
82 'x-image-meta-owner': '1310db0cce8f40b0987a5acbe139765a',
83 'x-image-meta-name': 'cirros-0.3.1-x86_64-uec',
84 'x-image-meta-container_format': 'ami',
85 'x-image-meta-created_at': '2013-04-25T15:47:43',
86 'etag': 'f8a2eeee2dc65b3d9b6e63678955bd83',
87 'location': 'http://fakeaddress.com:9292/v1/images/'
88 '96d2c7e1-de4e-4612-8aa2-ba26610c804e',
89 'x-image-meta-min_ram': '0',
90 'x-image-meta-updated_at': '2013-04-25T15:47:43',
91 'x-image-meta-id': '96d2c7e1-de4e-4612-8aa2-ba26610c804e',
92 'x-image-meta-property-ramdisk_id':
93 'b759bee9-0669-4394-a05c-fa2529b1c114',
94 'date': 'Mon, 29 Apr 2013 09:25:17 GMT',
95 'x-image-meta-property-kernel_id':
96 '1b108400-65d8-4762-9ea4-1bf6c7be7568',
97 'x-openstack-request-id':
98 'req-842735bf-77e8-44a7-bfd1-7d95c52cec7f',
99 'x-image-meta-deleted': 'False',
100 'x-image-meta-checksum': 'f8a2eeee2dc65b3d9b6e63678955bd83',
101 'x-image-meta-protected': 'False',
102 'x-image-meta-min_disk': '0',
103 'x-image-meta-size': '25165824',
104 'x-image-meta-is_public': 'True',
105 'content-type': 'text/html; charset=UTF-8',
106 'x-image-meta-disk_format': 'ami',
107 },
108 None
109 )
110 },
111 '/v1/images/44d2c7e1-de4e-4612-8aa2-ba26610c444f': {
112 'PUT': (
113 {
114 'Location': 'http://fakeaddress.com:9292/v1/images/'
115 '44d2c7e1-de4e-4612-8aa2-ba26610c444f',
116 'Etag': 'f8a2eeee2dc65b3d9b6e63678955bd83',
117 'X-Openstack-Request-Id':
118 'req-b645039d-e1c7-43e5-b27b-2d18a173c42b',
119 'Date': 'Mon, 29 Apr 2013 10:24:32 GMT'
120 },
121 json.dumps({
122 'image': {
123 'status': 'queued', 'name': 'testimagerename',
124 'deleted': False,
125 'container_format': 'ami',
126 'created_at': '2013-04-25T15:47:43',
127 'disk_format': 'ami',
128 'updated_at': '2013-04-29T10:24:32',
129 'id': '44d2c7e1-de4e-4612-8aa2-ba26610c444f',
130 'min_disk': 0,
131 'protected': False,
132 'min_ram': 0,
133 'checksum': 'f8a2eeee2dc65b3d9b6e63678955bd83',
134 'owner': '1310db0cce8f40b0987a5acbe139765a',
135 'is_public': True,
136 'deleted_at': None,
137 'properties': {
138 'kernel_id':
139 '1b108400-65d8-4762-9ea4-1bf6c7be7568',
140 'ramdisk_id':
141 'b759bee9-0669-4394-a05c-fa2529b1c114'
142 },
143 'size': 25165824
144 }
145 })
146 ),
147 'HEAD': (
148 {
149 'x-image-meta-id': '44d2c7e1-de4e-4612-8aa2-ba26610c444f',
150 'x-image-meta-status': 'queued'
151 },
152 None
153 ),
154 'GET': (
155 {
156 'x-image-meta-status': 'queued',
157 'x-image-meta-owner': '1310db0cce8f40b0987a5acbe139765a',
158 'x-image-meta-name': 'cirros-0.3.1-x86_64-uec',
159 'x-image-meta-container_format': 'ami',
160 'x-image-meta-created_at': '2013-04-25T15:47:43',
161 'etag': 'f8a2eeee2dc65b3d9b6e63678955bd83',
162 'location': 'http://fakeaddress.com:9292/v1/images/'
163 '44d2c7e1-de4e-4612-8aa2-ba26610c444f',
164 'x-image-meta-min_ram': '0',
165 'x-image-meta-updated_at': '2013-04-25T15:47:43',
166 'x-image-meta-id': '44d2c7e1-de4e-4612-8aa2-ba26610c444f',
167 'x-image-meta-property-ramdisk_id':
168 'b759bee9-0669-4394-a05c-fa2529b1c114',
169 'date': 'Mon, 29 Apr 2013 09:25:17 GMT',
170 'x-image-meta-property-kernel_id':
171 '1b108400-65d8-4762-9ea4-1bf6c7be7568',
172 'x-openstack-request-id':
173 'req-842735bf-77e8-44a7-bfd1-7d95c52cec7f',
174 'x-image-meta-deleted': 'False',
175 'x-image-meta-checksum': 'f8a2eeee2dc65b3d9b6e63678955bd83',
176 'x-image-meta-protected': 'False',
177 'x-image-meta-min_disk': '0',
178 'x-image-meta-size': '25165824',
179 'x-image-meta-is_public': 'True',
180 'content-type': 'text/html; charset=UTF-8',
181 'x-image-meta-disk_format': 'ami',
182 },
183 None
184 )
185 },
186 '/v1/images/detail?limit=20&name=70aa106f-3750-4d7c-a5ce-0a535ac08d0a': {
187 'GET': (
188 {},
189 {'images': [
190 {
191 'id': '70aa106f-3750-4d7c-a5ce-0a535ac08d0a',
192 'name': 'imagedeleted',
193 'deleted': True,
194 'status': 'deleted',
195 },
196 ]},
197 ),
198 },
199 '/v1/images/70aa106f-3750-4d7c-a5ce-0a535ac08d0a': {
200 'HEAD': (
201 {
202 'x-image-meta-id': '70aa106f-3750-4d7c-a5ce-0a535ac08d0a',
203 'x-image-meta-status': 'deleted'
204 },
205 None
206 )
207 }
208 }
209
210
211 class ShellInvalidEndpointandParameterTest(utils.TestCase):
212
213 # Patch os.environ to avoid required auth info.
214 def setUp(self):
215 """Run before each test."""
216 super(ShellInvalidEndpointandParameterTest, self).setUp()
217 self.old_environment = os.environ.copy()
218 os.environ = {
219 'OS_USERNAME': 'username',
220 'OS_PASSWORD': 'password',
221 'OS_TENANT_ID': 'tenant_id',
222 'OS_TOKEN_ID': 'test',
223 'OS_AUTH_URL': 'http://127.0.0.1:5000/v2.0/',
224 'OS_AUTH_TOKEN': 'pass',
225 'OS_IMAGE_API_VERSION': '1',
226 'OS_REGION_NAME': 'test',
227 'OS_IMAGE_URL': 'http://is.invalid'}
228
229 self.shell = shell.OpenStackImagesShell()
230 self.patched = mock.patch('glanceclient.common.utils.get_data_file',
231 autospec=True, return_value=None)
232 self.mock_get_data_file = self.patched.start()
233
234 self.gc = self._mock_glance_client()
235
236 def _make_args(self, args):
237 # NOTE(venkatesh): this conversion from a dict to an object
238 # is required because the test_shell.do_xxx(gc, args) methods
239 # expects the args to be attributes of an object. If passed as
240 # dict directly, it throws an AttributeError.
241 class Args(object):
242 def __init__(self, entries):
243 self.__dict__.update(entries)
244
245 return Args(args)
246
247 def _mock_glance_client(self):
248 my_mocked_gc = mock.Mock()
249 my_mocked_gc.get.return_value = {}
250 return my_mocked_gc
251
252 def tearDown(self):
253 super(ShellInvalidEndpointandParameterTest, self).tearDown()
254 os.environ = self.old_environment
255 self.patched.stop()
256
257 def run_command(self, cmd):
258 self.shell.main(cmd.split())
259
260 def assert_called(self, method, url, body=None, **kwargs):
261 return self.shell.cs.assert_called(method, url, body, **kwargs)
262
263 def assert_called_anytime(self, method, url, body=None):
264 return self.shell.cs.assert_called_anytime(method, url, body)
265
266 def test_image_list_invalid_endpoint(self):
267 self.assertRaises(
268 exc.CommunicationError, self.run_command, 'image-list')
269
270 def test_image_create_invalid_endpoint(self):
271 self.assertRaises(
272 exc.CommunicationError,
273 self.run_command, 'image-create')
274
275 def test_image_delete_invalid_endpoint(self):
276 self.assertRaises(
277 exc.CommunicationError,
278 self.run_command, 'image-delete <fake>')
279
280 def test_image_download_invalid_endpoint(self):
281 self.assertRaises(
282 exc.CommunicationError,
283 self.run_command, 'image-download <fake>')
284
285 def test_members_list_invalid_endpoint(self):
286 self.assertRaises(
287 exc.CommunicationError,
288 self.run_command, 'member-list --image-id fake')
289
290 def test_image_show_invalid_endpoint(self):
291 self.assertRaises(
292 exc.CommunicationError,
293 self.run_command, 'image-show --human-readable <IMAGE_ID>')
294
295 def test_member_create_invalid_endpoint(self):
296 self.assertRaises(
297 exc.CommunicationError,
298 self.run_command,
299 'member-create --can-share <IMAGE_ID> <TENANT_ID>')
300
301 def test_member_delete_invalid_endpoint(self):
302 self.assertRaises(
303 exc.CommunicationError,
304 self.run_command,
305 'member-delete <IMAGE_ID> <TENANT_ID>')
306
307 @mock.patch('sys.stderr')
308 def test_image_create_invalid_size_parameter(self, __):
309 self.assertRaises(
310 SystemExit,
311 self.run_command, 'image-create --size 10gb')
312
313 @mock.patch('sys.stderr')
314 def test_image_create_invalid_ram_parameter(self, __):
315 self.assertRaises(
316 SystemExit,
317 self.run_command, 'image-create --min-ram 10gb')
318
319 @mock.patch('sys.stderr')
320 def test_image_create_invalid_min_disk_parameter(self, __):
321 self.assertRaises(
322 SystemExit,
323 self.run_command, 'image-create --min-disk 10gb')
324
325 @mock.patch('sys.stderr')
326 def test_image_create_missing_disk_format(self, __):
327 # We test for all possible sources
328 for origin in ('--file', '--location', '--copy-from'):
329 e = self.assertRaises(exc.CommandError, self.run_command,
330 '--os-image-api-version 1 image-create ' +
331 origin + ' fake_src --container-format bare')
332 self.assertEqual('error: Must provide --disk-format when using ' +
333 origin + '.', e.message)
334
335 @mock.patch('sys.stderr')
336 def test_image_create_missing_container_format(self, __):
337 # We test for all possible sources
338 for origin in ('--file', '--location', '--copy-from'):
339 e = self.assertRaises(exc.CommandError, self.run_command,
340 '--os-image-api-version 1 image-create ' +
341 origin + ' fake_src --disk-format qcow2')
342 self.assertEqual('error: Must provide --container-format when '
343 'using ' + origin + '.', e.message)
344
345 @mock.patch('sys.stderr')
346 def test_image_create_missing_container_format_stdin_data(self, __):
347 # Fake that get_data_file method returns data
348 self.mock_get_data_file.return_value = io.StringIO()
349 e = self.assertRaises(exc.CommandError, self.run_command,
350 '--os-image-api-version 1 image-create'
351 ' --disk-format qcow2')
352 self.assertEqual('error: Must provide --container-format when '
353 'using stdin.', e.message)
354
355 @mock.patch('sys.stderr')
356 def test_image_create_missing_disk_format_stdin_data(self, __):
357 # Fake that get_data_file method returns data
358 self.mock_get_data_file.return_value = io.StringIO()
359 e = self.assertRaises(exc.CommandError, self.run_command,
360 '--os-image-api-version 1 image-create'
361 ' --container-format bare')
362 self.assertEqual('error: Must provide --disk-format when using stdin.',
363 e.message)
364
365 @mock.patch('sys.stderr')
366 def test_image_update_invalid_size_parameter(self, __):
367 self.assertRaises(
368 SystemExit,
369 self.run_command, 'image-update --size 10gb')
370
371 @mock.patch('sys.stderr')
372 def test_image_update_invalid_min_disk_parameter(self, __):
373 self.assertRaises(
374 SystemExit,
375 self.run_command, 'image-update --min-disk 10gb')
376
377 @mock.patch('sys.stderr')
378 def test_image_update_invalid_ram_parameter(self, __):
379 self.assertRaises(
380 SystemExit,
381 self.run_command, 'image-update --min-ram 10gb')
382
383 @mock.patch('sys.stderr')
384 def test_image_list_invalid_min_size_parameter(self, __):
385 self.assertRaises(
386 SystemExit,
387 self.run_command, 'image-list --size-min 10gb')
388
389 @mock.patch('sys.stderr')
390 def test_image_list_invalid_max_size_parameter(self, __):
391 self.assertRaises(
392 SystemExit,
393 self.run_command, 'image-list --size-max 10gb')
394
395 def test_do_image_list_with_changes_since(self):
396 input = {
397 'name': None,
398 'limit': None,
399 'status': None,
400 'container_format': 'bare',
401 'size_min': None,
402 'size_max': None,
403 'is_public': True,
404 'disk_format': 'raw',
405 'page_size': 20,
406 'visibility': True,
407 'member_status': 'Fake',
408 'owner': 'test',
409 'checksum': 'fake_checksum',
410 'tag': 'fake tag',
411 'properties': [],
412 'sort_key': None,
413 'sort_dir': None,
414 'all_tenants': False,
415 'human_readable': True,
416 'changes_since': '2011-1-1'
417 }
418 args = self._make_args(input)
419 with mock.patch.object(self.gc.images, 'list') as mocked_list:
420 mocked_list.return_value = {}
421
422 v1shell.do_image_list(self.gc, args)
423
424 exp_img_filters = {'container_format': 'bare',
425 'changes-since': '2011-1-1',
426 'disk_format': 'raw',
427 'is_public': True}
428 mocked_list.assert_called_once_with(sort_dir=None,
429 sort_key=None,
430 owner='test',
431 page_size=20,
432 filters=exp_img_filters)
433
434
435 class ShellStdinHandlingTests(testtools.TestCase):
436
437 def _fake_update_func(self, *args, **kwargs):
438 """Replace glanceclient.images.update with a fake.
439
440 To determine the parameters that would be supplied with the update
441 request.
442 """
443
444 # Store passed in args
445 self.collected_args = (args, kwargs)
446
447 # Return the first arg, which is an image,
448 # as do_image_update expects this.
449 return args[0]
450
451 def setUp(self):
452 super(ShellStdinHandlingTests, self).setUp()
453 self.api = utils.FakeAPI(fixtures)
454 self.gc = client.Client("http://fakeaddress.com")
455 self.gc.images = glanceclient.v1.images.ImageManager(self.api)
456
457 # Store real stdin, so it can be restored in tearDown.
458 self.real_sys_stdin_fd = os.dup(0)
459
460 # Replace stdin with a FD that points to /dev/null.
461 dev_null = open('/dev/null')
462 self.dev_null_fd = dev_null.fileno()
463 os.dup2(dev_null.fileno(), 0)
464
465 # Replace the image update function with a fake,
466 # so that we can tell if the data field was set correctly.
467 self.real_update_func = self.gc.images.update
468 self.collected_args = []
469 self.gc.images.update = self._fake_update_func
470
471 def tearDown(self):
472 """Restore stdin and gc.images.update to their pretest states."""
473 super(ShellStdinHandlingTests, self).tearDown()
474
475 def try_close(fd):
476 try:
477 os.close(fd)
478 except OSError:
479 # Already closed
480 pass
481
482 # Restore stdin
483 os.dup2(self.real_sys_stdin_fd, 0)
484
485 # Close duplicate stdin handle
486 try_close(self.real_sys_stdin_fd)
487
488 # Close /dev/null handle
489 try_close(self.dev_null_fd)
490
491 # Restore the real image update function
492 self.gc.images.update = self.real_update_func
493
494 def _do_update(self, image='96d2c7e1-de4e-4612-8aa2-ba26610c804e'):
495 """call v1/shell's do_image_update function."""
496
497 v1shell.do_image_update(
498 self.gc, argparse.Namespace(
499 image=image,
500 name='testimagerename',
501 property={},
502 purge_props=False,
503 human_readable=False,
504 file=None,
505 progress=False
506 )
507 )
508
509 def test_image_delete_deleted(self):
510 self.assertRaises(
511 exc.CommandError,
512 v1shell.do_image_delete,
513 self.gc,
514 argparse.Namespace(
515 images=['70aa106f-3750-4d7c-a5ce-0a535ac08d0a']
516 )
517 )
518
519 def test_image_update_closed_stdin(self):
520 """Test image update with a closed stdin.
521
522 Supply glanceclient with a closed stdin, and perform an image
523 update to an active image. Glanceclient should not attempt to read
524 stdin.
525 """
526
527 # NOTE(hughsaunders) Close stdin, which is repointed to /dev/null by
528 # setUp()
529 os.close(0)
530
531 self._do_update()
532
533 self.assertTrue(
534 'data' not in self.collected_args[1] or
535 self.collected_args[1]['data'] is None
536 )
537
538 def test_image_update_opened_stdin(self):
539 """Test image update with an opened stdin.
540
541 Supply glanceclient with a stdin, and perform an image
542 update to an active image. Glanceclient should not allow it.
543 """
544
545 self.assertRaises(
546 SystemExit,
547 v1shell.do_image_update,
548 self.gc,
549 argparse.Namespace(
550 image='96d2c7e1-de4e-4612-8aa2-ba26610c804e',
551 property={},
552 )
553 )
554
555 def test_image_update_data_is_read_from_file(self):
556 """Ensure that data is read from a file."""
557
558 try:
559
560 # NOTE(hughsaunders) Create a tmpfile, write some data to it and
561 # set it as stdin
562 f = open(tempfile.mktemp(), 'w+')
563 f.write('Some Data')
564 f.flush()
565 f.seek(0)
566 os.dup2(f.fileno(), 0)
567
568 self._do_update('44d2c7e1-de4e-4612-8aa2-ba26610c444f')
569
570 self.assertIn('data', self.collected_args[1])
571 self.assertIsInstance(self.collected_args[1]['data'], io.IOBase)
572 self.assertEqual(b'Some Data',
573 self.collected_args[1]['data'].read())
574
575 finally:
576 try:
577 f.close()
578 os.remove(f.name)
579 except Exception:
580 pass
581
582 def test_image_update_data_is_read_from_pipe(self):
583 """Ensure that data is read from a pipe."""
584
585 try:
586
587 # NOTE(hughsaunders): Setup a pipe, duplicate it to stdin
588 # ensure it is read.
589 process = subprocess.Popen(['/bin/echo', 'Some Data'],
590 stdout=subprocess.PIPE)
591 os.dup2(process.stdout.fileno(), 0)
592
593 self._do_update('44d2c7e1-de4e-4612-8aa2-ba26610c444f')
594
595 self.assertIn('data', self.collected_args[1])
596 self.assertIsInstance(self.collected_args[1]['data'], io.IOBase)
597 self.assertEqual(b'Some Data\n',
598 self.collected_args[1]['data'].read())
599
600 finally:
601 try:
602 process.stdout.close()
603 except OSError:
604 pass