Debian Codegraph @

glanceclient/tests/unit/v1/test_shell.py

raw symbols ◀ ▶ SCIP
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 @testtools.skip("Skipped by Debian")
267 def test_image_list_invalid_endpoint(self):
268 self.assertRaises(
269 exc.CommunicationError, self.run_command, 'image-list')
270
271 def test_image_create_invalid_endpoint(self):
272 self.assertRaises(
273 exc.CommunicationError,
274 self.run_command, 'image-create')
275
•276 @testtools.skip("Skipped by Debian")
277 def test_image_delete_invalid_endpoint(self):
278 self.assertRaises(
279 exc.CommunicationError,
280 self.run_command, 'image-delete <fake>')
281
•282 @testtools.skip("Skipped by Debian")
283 def test_image_download_invalid_endpoint(self):
284 self.assertRaises(
285 exc.CommunicationError,
286 self.run_command, 'image-download <fake>')
287
•288 @testtools.skip("Skipped by Debian")
289 def test_members_list_invalid_endpoint(self):
290 self.assertRaises(
291 exc.CommunicationError,
292 self.run_command, 'member-list --image-id fake')
293
•294 @testtools.skip("Skipped by Debian")
295 def test_image_show_invalid_endpoint(self):
296 self.assertRaises(
297 exc.CommunicationError,
298 self.run_command, 'image-show --human-readable <IMAGE_ID>')
299
•300 @testtools.skip("Skipped by Debian")
301 def test_member_create_invalid_endpoint(self):
302 self.assertRaises(
303 exc.CommunicationError,
304 self.run_command,
305 'member-create --can-share <IMAGE_ID> <TENANT_ID>')
306
•307 @testtools.skip("Skipped by Debian")
308 def test_member_delete_invalid_endpoint(self):
309 self.assertRaises(
310 exc.CommunicationError,
311 self.run_command,
312 'member-delete <IMAGE_ID> <TENANT_ID>')
313
314 @mock.patch('sys.stderr')
315 def test_image_create_invalid_size_parameter(self, __):
316 self.assertRaises(
317 SystemExit,
318 self.run_command, 'image-create --size 10gb')
319
320 @mock.patch('sys.stderr')
321 def test_image_create_invalid_ram_parameter(self, __):
322 self.assertRaises(
323 SystemExit,
324 self.run_command, 'image-create --min-ram 10gb')
325
326 @mock.patch('sys.stderr')
327 def test_image_create_invalid_min_disk_parameter(self, __):
328 self.assertRaises(
329 SystemExit,
330 self.run_command, 'image-create --min-disk 10gb')
331
332 @mock.patch('sys.stderr')
333 def test_image_create_missing_disk_format(self, __):
334 # We test for all possible sources
335 for origin in ('--file', '--location', '--copy-from'):
336 e = self.assertRaises(exc.CommandError, self.run_command,
337 '--os-image-api-version 1 image-create ' +
338 origin + ' fake_src --container-format bare')
339 self.assertEqual('error: Must provide --disk-format when using ' +
340 origin + '.', e.message)
341
342 @mock.patch('sys.stderr')
343 def test_image_create_missing_container_format(self, __):
344 # We test for all possible sources
345 for origin in ('--file', '--location', '--copy-from'):
346 e = self.assertRaises(exc.CommandError, self.run_command,
347 '--os-image-api-version 1 image-create ' +
348 origin + ' fake_src --disk-format qcow2')
349 self.assertEqual('error: Must provide --container-format when '
350 'using ' + origin + '.', e.message)
351
352 @mock.patch('sys.stderr')
353 def test_image_create_missing_container_format_stdin_data(self, __):
354 # Fake that get_data_file method returns data
355 self.mock_get_data_file.return_value = io.StringIO()
356 e = self.assertRaises(exc.CommandError, self.run_command,
357 '--os-image-api-version 1 image-create'
358 ' --disk-format qcow2')
359 self.assertEqual('error: Must provide --container-format when '
360 'using stdin.', e.message)
361
362 @mock.patch('sys.stderr')
363 def test_image_create_missing_disk_format_stdin_data(self, __):
364 # Fake that get_data_file method returns data
365 self.mock_get_data_file.return_value = io.StringIO()
366 e = self.assertRaises(exc.CommandError, self.run_command,
367 '--os-image-api-version 1 image-create'
368 ' --container-format bare')
369 self.assertEqual('error: Must provide --disk-format when using stdin.',
370 e.message)
371
372 @mock.patch('sys.stderr')
373 def test_image_update_invalid_size_parameter(self, __):
374 self.assertRaises(
375 SystemExit,
376 self.run_command, 'image-update --size 10gb')
377
378 @mock.patch('sys.stderr')
379 def test_image_update_invalid_min_disk_parameter(self, __):
380 self.assertRaises(
381 SystemExit,
382 self.run_command, 'image-update --min-disk 10gb')
383
384 @mock.patch('sys.stderr')
385 def test_image_update_invalid_ram_parameter(self, __):
386 self.assertRaises(
387 SystemExit,
388 self.run_command, 'image-update --min-ram 10gb')
389
390 @mock.patch('sys.stderr')
391 def test_image_list_invalid_min_size_parameter(self, __):
392 self.assertRaises(
393 SystemExit,
394 self.run_command, 'image-list --size-min 10gb')
395
396 @mock.patch('sys.stderr')
397 def test_image_list_invalid_max_size_parameter(self, __):
398 self.assertRaises(
399 SystemExit,
400 self.run_command, 'image-list --size-max 10gb')
401
402 def test_do_image_list_with_changes_since(self):
403 input = {
404 'name': None,
405 'limit': None,
406 'status': None,
407 'container_format': 'bare',
408 'size_min': None,
409 'size_max': None,
410 'is_public': True,
411 'disk_format': 'raw',
412 'page_size': 20,
413 'visibility': True,
414 'member_status': 'Fake',
415 'owner': 'test',
416 'checksum': 'fake_checksum',
417 'tag': 'fake tag',
418 'properties': [],
419 'sort_key': None,
420 'sort_dir': None,
421 'all_tenants': False,
422 'human_readable': True,
423 'changes_since': '2011-1-1'
424 }
425 args = self._make_args(input)
426 with mock.patch.object(self.gc.images, 'list') as mocked_list:
427 mocked_list.return_value = {}
428
429 v1shell.do_image_list(self.gc, args)
430
431 exp_img_filters = {'container_format': 'bare',
432 'changes-since': '2011-1-1',
433 'disk_format': 'raw',
434 'is_public': True}
435 mocked_list.assert_called_once_with(sort_dir=None,
436 sort_key=None,
437 owner='test',
438 page_size=20,
439 filters=exp_img_filters)
440
441
442 class ShellStdinHandlingTests(testtools.TestCase):
443
444 def _fake_update_func(self, *args, **kwargs):
445 """Replace glanceclient.images.update with a fake.
446
447 To determine the parameters that would be supplied with the update
448 request.
449 """
450
451 # Store passed in args
452 self.collected_args = (args, kwargs)
453
454 # Return the first arg, which is an image,
455 # as do_image_update expects this.
456 return args[0]
457
458 def setUp(self):
459 super(ShellStdinHandlingTests, self).setUp()
460 self.api = utils.FakeAPI(fixtures)
461 self.gc = client.Client("http://fakeaddress.com")
462 self.gc.images = glanceclient.v1.images.ImageManager(self.api)
463
464 # Store real stdin, so it can be restored in tearDown.
465 self.real_sys_stdin_fd = os.dup(0)
466
467 # Replace stdin with a FD that points to /dev/null.
468 dev_null = open('/dev/null')
469 self.dev_null_fd = dev_null.fileno()
470 os.dup2(dev_null.fileno(), 0)
471
472 # Replace the image update function with a fake,
473 # so that we can tell if the data field was set correctly.
474 self.real_update_func = self.gc.images.update
475 self.collected_args = []
476 self.gc.images.update = self._fake_update_func
477
478 def tearDown(self):
479 """Restore stdin and gc.images.update to their pretest states."""
480 super(ShellStdinHandlingTests, self).tearDown()
481
482 def try_close(fd):
483 try:
484 os.close(fd)
485 except OSError:
486 # Already closed
487 pass
488
489 # Restore stdin
490 os.dup2(self.real_sys_stdin_fd, 0)
491
492 # Close duplicate stdin handle
493 try_close(self.real_sys_stdin_fd)
494
495 # Close /dev/null handle
496 try_close(self.dev_null_fd)
497
498 # Restore the real image update function
499 self.gc.images.update = self.real_update_func
500
501 def _do_update(self, image='96d2c7e1-de4e-4612-8aa2-ba26610c804e'):
502 """call v1/shell's do_image_update function."""
503
504 v1shell.do_image_update(
505 self.gc, argparse.Namespace(
506 image=image,
507 name='testimagerename',
508 property={},
509 purge_props=False,
510 human_readable=False,
511 file=None,
512 progress=False
513 )
514 )
515
516 def test_image_delete_deleted(self):
517 self.assertRaises(
518 exc.CommandError,
519 v1shell.do_image_delete,
520 self.gc,
521 argparse.Namespace(
522 images=['70aa106f-3750-4d7c-a5ce-0a535ac08d0a']
523 )
524 )
525
526 def test_image_update_closed_stdin(self):
527 """Test image update with a closed stdin.
528
529 Supply glanceclient with a closed stdin, and perform an image
530 update to an active image. Glanceclient should not attempt to read
531 stdin.
532 """
533
534 # NOTE(hughsaunders) Close stdin, which is repointed to /dev/null by
535 # setUp()
536 os.close(0)
537
538 self._do_update()
539
540 self.assertTrue(
541 'data' not in self.collected_args[1] or
542 self.collected_args[1]['data'] is None
543 )
544
545 def test_image_update_opened_stdin(self):
546 """Test image update with an opened stdin.
547
548 Supply glanceclient with a stdin, and perform an image
549 update to an active image. Glanceclient should not allow it.
550 """
551
552 self.assertRaises(
553 SystemExit,
554 v1shell.do_image_update,
555 self.gc,
556 argparse.Namespace(
557 image='96d2c7e1-de4e-4612-8aa2-ba26610c804e',
558 property={},
559 )
560 )
561
562 def test_image_update_data_is_read_from_file(self):
563 """Ensure that data is read from a file."""
564
565 try:
566
567 # NOTE(hughsaunders) Create a tmpfile, write some data to it and
568 # set it as stdin
569 f = open(tempfile.mktemp(), 'w+')
570 f.write('Some Data')
571 f.flush()
572 f.seek(0)
573 os.dup2(f.fileno(), 0)
574
575 self._do_update('44d2c7e1-de4e-4612-8aa2-ba26610c444f')
576
577 self.assertIn('data', self.collected_args[1])
578 self.assertIsInstance(self.collected_args[1]['data'], io.IOBase)
579 self.assertEqual(b'Some Data',
580 self.collected_args[1]['data'].read())
581
582 finally:
583 try:
584 f.close()
585 os.remove(f.name)
586 except Exception:
587 pass
588
589 def test_image_update_data_is_read_from_pipe(self):
590 """Ensure that data is read from a pipe."""
591
592 try:
593
594 # NOTE(hughsaunders): Setup a pipe, duplicate it to stdin
595 # ensure it is read.
596 process = subprocess.Popen(['/bin/echo', 'Some Data'],
597 stdout=subprocess.PIPE)
598 os.dup2(process.stdout.fileno(), 0)
599
600 self._do_update('44d2c7e1-de4e-4612-8aa2-ba26610c444f')
601
602 self.assertIn('data', self.collected_args[1])
603 self.assertIsInstance(self.collected_args[1]['data'], io.IOBase)
604 self.assertEqual(b'Some Data\n',
605 self.collected_args[1]['data'].read())
606
607 finally:
608 try:
609 process.stdout.close()
610 except OSError:
611 pass