Debian Codegraph @

glanceclient/tests/unit/v2/test_shell_v2.py

raw symbols SCIP
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 import argparse
17 from copy import deepcopy
18 import io
19 import json
20 import os
21 from unittest import mock
22
23 import sys
24 import tempfile
25 import testtools
26
27 from glanceclient.common import utils
28 from glanceclient import exc
29 from glanceclient import shell
30
31 # NOTE(geguileo): This is very nasty, but I can't find a better way to set
32 # command line arguments in glanceclient.v2.shell.do_image_create that are
33 # set by decorator utils.schema_args while preserving the spirits of the test
34
35 # Backup original decorator
36 original_schema_args = utils.schema_args
37
38
39 # Set our own decorator that calls the original but with simulated schema
40 def schema_args(schema_getter, omit=None):
41 global original_schema_args
42 # We only add the 2 arguments that are required by image-create
43 my_schema_getter = lambda: {
44 'properties': {
45 'container_format': {
46 'enum': [None, 'ami', 'ari', 'aki', 'bare', 'ovf', 'ova',
47 'docker'],
48 'type': 'string',
49 'description': 'Format of the container'},
50 'disk_format': {
51 'enum': [None, 'ami', 'ari', 'aki', 'vhd', 'vhdx', 'vmdk',
52 'raw', 'qcow2', 'vdi', 'iso', 'ploop'],
53 'type': 'string',
54 'description': 'Format of the disk'},
55 'location': {'type': 'string'},
56 'locations': {'type': 'string'},
57 'copy_from': {'type': 'string'}}}
58 return original_schema_args(my_schema_getter, omit)
59
60
61 utils.schema_args = schema_args
62
63 from glanceclient.v2 import shell as test_shell # noqa
64
65 # Return original decorator.
66 utils.schema_args = original_schema_args
67
68
69 class ShellV2Test(testtools.TestCase):
70 def setUp(self):
71 super(ShellV2Test, self).setUp()
72 self._mock_utils()
73 self.gc = self._mock_glance_client()
74 self.shell = shell.OpenStackImagesShell()
75 os.environ = {
76 'OS_USERNAME': 'username',
77 'OS_PASSWORD': 'password',
78 'OS_TENANT_ID': 'tenant_id',
79 'OS_TOKEN_ID': 'test',
80 'OS_AUTH_URL': 'http://127.0.0.1:5000/v2.0/',
81 'OS_AUTH_TOKEN': 'pass',
82 'OS_IMAGE_API_VERSION': '1',
83 'OS_REGION_NAME': 'test',
84 'OS_IMAGE_URL': 'http://is.invalid'}
85 self.shell = shell.OpenStackImagesShell()
86 self.patched = mock.patch('glanceclient.common.utils.get_data_file',
87 autospec=True, return_value=None)
88 self.mock_get_data_file = self.patched.start()
89
90 def tearDown(self):
91 super(ShellV2Test, self).tearDown()
92 self.patched.stop()
93
94 def _make_args(self, args):
95 # NOTE(venkatesh): this conversion from a dict to an object
96 # is required because the test_shell.do_xxx(gc, args) methods
97 # expects the args to be attributes of an object. If passed as
98 # dict directly, it throws an AttributeError.
99 class Args(object):
100 def __init__(self, entries):
101 self.store = None
102 self.__dict__.update(entries)
103
104 return Args(args)
105
106 def _mock_glance_client(self):
107 my_mocked_gc = mock.Mock()
108 my_mocked_gc.schemas.return_value = 'test'
109 my_mocked_gc.get.return_value = {}
110 return my_mocked_gc
111
112 def _mock_utils(self):
113 utils.print_list = mock.Mock()
114 utils.print_dict = mock.Mock()
115 utils.save_image = mock.Mock()
116 utils.print_dict_list = mock.Mock()
117 utils.print_cached_images = mock.Mock()
118
119 def assert_exits_with_msg(self, func, func_args, err_msg=None):
120 with mock.patch.object(utils, 'exit') as mocked_utils_exit:
121 mocked_utils_exit.return_value = '%s' % err_msg
122
123 func(self.gc, func_args)
124 if err_msg:
125 mocked_utils_exit.assert_called_once_with(err_msg)
126 else:
127 mocked_utils_exit.assert_called_once_with()
128
129 def _run_command(self, cmd):
130 self.shell.main(cmd.split())
131
132 stores_info_response = {
133 "stores": [
134 {
135 "default": "true",
136 "id": "ceph1",
137 "description": "RBD backend for glance."
138 },
139 {
140 "id": "file2",
141 "description": "Filesystem backend for glance."
142 },
143 {
144 "id": "file1",
145 "description": "Filesystem backend for gkance."
146 },
147 {
148 "id": "ceph2",
149 "description": "RBD backend for glance."
150 }
151 ]
152 }
153
154 stores_info_detail_response = {
155 "stores": [
156 {
157 "default": "true",
158 "id": "ceph1",
159 "type": "rbd",
160 "description": "RBD backend for glance.",
161 "properties": {
162 "pool": "pool1",
163 "chunk_size": "4"
164 }
165 },
166 {
167 "id": "file2",
168 "type": "file",
169 "description": "Filesystem backend for glance.",
170 "properties": {}
171 },
172 {
173 "id": "file1",
174 "type": "file",
175 "description": "Filesystem backend for gkance.",
176 "properties": {}
177 },
178 {
179 "id": "ceph2",
180 "type": "rbd",
181 "description": "RBD backend for glance.",
182 "properties": {
183 "pool": "pool2",
184 "chunk_size": "4"
185 }
186 }
187 ]
188 }
189
190 def test_do_stores_info(self):
191 args = self._make_args({'detail': False})
192 with mock.patch.object(self.gc.images,
193 'get_stores_info') as mocked_list:
194 mocked_list.return_value = self.stores_info_response
195
196 test_shell.do_stores_info(self.gc, args)
197
198 mocked_list.assert_called_once_with()
199 utils.print_dict.assert_called_once_with(self.stores_info_response)
200
201 @mock.patch('glanceclient.common.utils.exit')
202 @mock.patch('sys.stdin', autospec=True)
203 def test_neg_stores_info(
204 self, mock_stdin, mock_utils_exit):
205 expected_msg = ('Multi Backend support is not enabled')
206 args = self._make_args({'detail': False})
207 mock_utils_exit.side_effect = self._mock_utils_exit
208 with mock.patch.object(self.gc.images,
209 'get_stores_info') as mocked_info:
210 mocked_info.side_effect = exc.HTTPNotFound
211 try:
212 test_shell.do_stores_info(self.gc, args)
213 self.fail("utils.exit should have been called")
214 except SystemExit:
215 pass
216 mock_utils_exit.assert_called_once_with(expected_msg)
217
218 def test_do_stores_info_with_detail(self):
219 args = self._make_args({'detail': True})
220 with mock.patch.object(self.gc.images,
221 'get_stores_info_detail') as mocked_list:
222 mocked_list.return_value = self.stores_info_detail_response
223
224 test_shell.do_stores_info(self.gc, args)
225
226 mocked_list.assert_called_once_with()
227 utils.print_dict.assert_called_once_with(
228 self.stores_info_detail_response)
229
230 @mock.patch('sys.stderr')
231 def test_image_create_missing_disk_format(self, __):
232 e = self.assertRaises(exc.CommandError, self._run_command,
233 '--os-image-api-version 2 image-create ' +
234 '--file fake_src --container-format bare')
235 self.assertEqual('error: Must provide --disk-format when using '
236 '--file.', e.message)
237
238 @mock.patch('sys.stderr')
239 def test_image_create_missing_container_format(self, __):
240 e = self.assertRaises(exc.CommandError, self._run_command,
241 '--os-image-api-version 2 image-create ' +
242 '--file fake_src --disk-format qcow2')
243 self.assertEqual('error: Must provide --container-format when '
244 'using --file.', e.message)
245
246 @mock.patch('sys.stderr')
247 def test_image_create_missing_container_format_stdin_data(self, __):
248 # Fake that get_data_file method returns data
249 self.mock_get_data_file.return_value = io.StringIO()
250 e = self.assertRaises(exc.CommandError, self._run_command,
251 '--os-image-api-version 2 image-create'
252 ' --disk-format qcow2')
253 self.assertEqual('error: Must provide --container-format when '
254 'using stdin.', e.message)
255
256 @mock.patch('sys.stderr')
257 def test_image_create_missing_disk_format_stdin_data(self, __):
258 # Fake that get_data_file method returns data
259 self.mock_get_data_file.return_value = io.StringIO()
260 e = self.assertRaises(exc.CommandError, self._run_command,
261 '--os-image-api-version 2 image-create'
262 ' --container-format bare')
263 self.assertEqual('error: Must provide --disk-format when using stdin.',
264 e.message)
265
266 @mock.patch('sys.stderr')
267 def test_create_via_import_glance_direct_missing_disk_format(self, __):
268 e = self.assertRaises(exc.CommandError, self._run_command,
269 '--os-image-api-version 2 '
270 'image-create-via-import '
271 '--file fake_src --container-format bare')
272 self.assertEqual('error: Must provide --disk-format when using '
273 '--file.', e.message)
274
275 @mock.patch('sys.stderr')
276 def test_create_via_import_glance_direct_missing_container_format(
277 self, __):
278 e = self.assertRaises(exc.CommandError, self._run_command,
279 '--os-image-api-version 2 '
280 'image-create-via-import '
281 '--file fake_src --disk-format qcow2')
282 self.assertEqual('error: Must provide --container-format when '
283 'using --file.', e.message)
284
285 @mock.patch('sys.stderr')
286 def test_create_via_import_web_download_missing_disk_format(self, __):
287 e = self.assertRaises(exc.CommandError, self._run_command,
288 '--os-image-api-version 2 '
289 'image-create-via-import ' +
290 '--import-method web-download ' +
291 '--uri fake_uri --container-format bare')
292 self.assertEqual('error: Must provide --disk-format when using '
293 '--uri.', e.message)
294
295 @mock.patch('sys.stderr')
296 def test_create_via_import_web_download_missing_container_format(
297 self, __):
298 e = self.assertRaises(exc.CommandError, self._run_command,
299 '--os-image-api-version 2 '
300 'image-create-via-import '
301 '--import-method web-download '
302 '--uri fake_uri --disk-format qcow2')
303 self.assertEqual('error: Must provide --container-format when '
304 'using --uri.', e.message)
305
306 def test_do_image_list(self):
307 input = {
308 'limit': None,
309 'page_size': 18,
310 'visibility': True,
311 'member_status': 'Fake',
312 'owner': 'test',
313 'checksum': 'fake_checksum',
314 'tag': 'fake tag',
315 'properties': [],
316 'sort_key': ['name', 'id'],
317 'sort_dir': ['desc', 'asc'],
318 'sort': None,
319 'verbose': False,
320 'include_stores': False,
321 'os_hash_value': None,
322 'os_hidden': False
323 }
324 args = self._make_args(input)
325 with mock.patch.object(self.gc.images, 'list') as mocked_list:
326 mocked_list.return_value = {}
327
328 test_shell.do_image_list(self.gc, args)
329
330 exp_img_filters = {
331 'owner': 'test',
332 'member_status': 'Fake',
333 'visibility': True,
334 'checksum': 'fake_checksum',
335 'tag': 'fake tag',
336 'os_hidden': False
337 }
338 mocked_list.assert_called_once_with(page_size=18,
339 sort_key=['name', 'id'],
340 sort_dir=['desc', 'asc'],
341 filters=exp_img_filters)
342 utils.print_list.assert_called_once_with({}, ['ID', 'Name'])
343
344 def test_do_image_list_verbose(self):
345 input = {
346 'limit': None,
347 'page_size': 18,
348 'visibility': True,
349 'member_status': 'Fake',
350 'owner': 'test',
351 'checksum': 'fake_checksum',
352 'tag': 'fake tag',
353 'properties': [],
354 'sort_key': ['name', 'id'],
355 'sort_dir': ['desc', 'asc'],
356 'sort': None,
357 'verbose': True,
358 'include_stores': False,
359 'os_hash_value': None,
360 'os_hidden': False
361 }
362 args = self._make_args(input)
363 with mock.patch.object(self.gc.images, 'list') as mocked_list:
364 mocked_list.return_value = {}
365
366 test_shell.do_image_list(self.gc, args)
367 utils.print_list.assert_called_once_with(
368 {}, ['ID', 'Name', 'Disk_format', 'Container_format',
369 'Size', 'Status', 'Owner'])
370
371 def test_do_image_list_verbose_cmd(self):
372 self._run_command('--os-image-api-version 2 --verbose image-list')
373 utils.print_list.assert_called_once_with(
374 mock.ANY, ['ID', 'Name', 'Disk_format', 'Container_format',
375 'Size', 'Status', 'Owner'])
376
377 def test_do_image_list_with_include_stores_true(self):
378 input = {
379 'limit': None,
380 'page_size': 18,
381 'visibility': True,
382 'member_status': 'Fake',
383 'owner': 'test',
384 'checksum': 'fake_checksum',
385 'tag': 'fake tag',
386 'properties': [],
387 'sort_key': ['name', 'id'],
388 'sort_dir': ['desc', 'asc'],
389 'sort': None,
390 'verbose': False,
391 'include_stores': True,
392 'os_hash_value': None,
393 'os_hidden': False
394 }
395 args = self._make_args(input)
396 with mock.patch.object(self.gc.images, 'list') as mocked_list:
397 mocked_list.return_value = {}
398
399 test_shell.do_image_list(self.gc, args)
400 utils.print_list.assert_called_once_with(
401 {}, ['ID', 'Name', 'Stores'])
402
403 def test_do_image_list_verbose_with_include_stores_true(self):
404 input = {
405 'limit': None,
406 'page_size': 18,
407 'visibility': True,
408 'member_status': 'Fake',
409 'owner': 'test',
410 'checksum': 'fake_checksum',
411 'tag': 'fake tag',
412 'properties': [],
413 'sort_key': ['name', 'id'],
414 'sort_dir': ['desc', 'asc'],
415 'sort': None,
416 'verbose': True,
417 'include_stores': True,
418 'os_hash_value': None,
419 'os_hidden': False
420 }
421 args = self._make_args(input)
422 with mock.patch.object(self.gc.images, 'list') as mocked_list:
423 mocked_list.return_value = {}
424
425 test_shell.do_image_list(self.gc, args)
426 utils.print_list.assert_called_once_with(
427 {}, ['ID', 'Name', 'Disk_format', 'Container_format',
428 'Size', 'Status', 'Owner', 'Stores'])
429
430 def test_do_image_list_with_hidden_true(self):
431 input = {
432 'limit': None,
433 'page_size': 18,
434 'visibility': True,
435 'member_status': 'Fake',
436 'owner': 'test',
437 'checksum': 'fake_checksum',
438 'tag': 'fake tag',
439 'properties': [],
440 'sort_key': ['name', 'id'],
441 'sort_dir': ['desc', 'asc'],
442 'sort': None,
443 'verbose': False,
444 'include_stores': False,
445 'os_hash_value': None,
446 'os_hidden': True
447 }
448 args = self._make_args(input)
449 with mock.patch.object(self.gc.images, 'list') as mocked_list:
450 mocked_list.return_value = {}
451
452 test_shell.do_image_list(self.gc, args)
453
454 exp_img_filters = {
455 'owner': 'test',
456 'member_status': 'Fake',
457 'visibility': True,
458 'checksum': 'fake_checksum',
459 'tag': 'fake tag',
460 'os_hidden': True
461 }
462 mocked_list.assert_called_once_with(page_size=18,
463 sort_key=['name', 'id'],
464 sort_dir=['desc', 'asc'],
465 filters=exp_img_filters)
466 utils.print_list.assert_called_once_with({}, ['ID', 'Name'])
467
468 def test_do_image_list_with_single_sort_key(self):
469 input = {
470 'limit': None,
471 'page_size': 18,
472 'visibility': True,
473 'member_status': 'Fake',
474 'owner': 'test',
475 'checksum': 'fake_checksum',
476 'tag': 'fake tag',
477 'properties': [],
478 'sort_key': ['name'],
479 'sort_dir': ['desc'],
480 'sort': None,
481 'verbose': False,
482 'include_stores': False,
483 'os_hash_value': None,
484 'os_hidden': False
485 }
486 args = self._make_args(input)
487 with mock.patch.object(self.gc.images, 'list') as mocked_list:
488 mocked_list.return_value = {}
489
490 test_shell.do_image_list(self.gc, args)
491
492 exp_img_filters = {
493 'owner': 'test',
494 'member_status': 'Fake',
495 'visibility': True,
496 'checksum': 'fake_checksum',
497 'tag': 'fake tag',
498 'os_hidden': False
499 }
500 mocked_list.assert_called_once_with(page_size=18,
501 sort_key=['name'],
502 sort_dir=['desc'],
503 filters=exp_img_filters)
504 utils.print_list.assert_called_once_with({}, ['ID', 'Name'])
505
506 def test_do_image_list_new_sorting_syntax(self):
507 input = {
508 'limit': None,
509 'page_size': 18,
510 'visibility': True,
511 'member_status': 'Fake',
512 'owner': 'test',
513 'checksum': 'fake_checksum',
514 'tag': 'fake tag',
515 'properties': [],
516 'sort': 'name:desc,size:asc',
517 'sort_key': [],
518 'sort_dir': [],
519 'verbose': False,
520 'include_stores': False,
521 'os_hash_value': None,
522 'os_hidden': False
523 }
524 args = self._make_args(input)
525 with mock.patch.object(self.gc.images, 'list') as mocked_list:
526 mocked_list.return_value = {}
527
528 test_shell.do_image_list(self.gc, args)
529
530 exp_img_filters = {
531 'owner': 'test',
532 'member_status': 'Fake',
533 'visibility': True,
534 'checksum': 'fake_checksum',
535 'tag': 'fake tag',
536 'os_hidden': False
537 }
538 mocked_list.assert_called_once_with(
539 page_size=18,
540 sort='name:desc,size:asc',
541 filters=exp_img_filters)
542 utils.print_list.assert_called_once_with({}, ['ID', 'Name'])
543
544 def test_do_image_list_with_property_filter(self):
545 input = {
546 'limit': None,
547 'page_size': 1,
548 'visibility': True,
549 'member_status': 'Fake',
550 'owner': 'test',
551 'checksum': 'fake_checksum',
552 'tag': 'fake tag',
553 'properties': ['os_distro=NixOS', 'architecture=x86_64'],
554 'sort_key': ['name'],
555 'sort_dir': ['desc'],
556 'sort': None,
557 'verbose': False,
558 'include_stores': False,
559 'os_hash_value': None,
560 'os_hidden': False
561 }
562 args = self._make_args(input)
563 with mock.patch.object(self.gc.images, 'list') as mocked_list:
564 mocked_list.return_value = {}
565
566 test_shell.do_image_list(self.gc, args)
567
568 exp_img_filters = {
569 'owner': 'test',
570 'member_status': 'Fake',
571 'visibility': True,
572 'checksum': 'fake_checksum',
573 'tag': 'fake tag',
574 'os_distro': 'NixOS',
575 'architecture': 'x86_64',
576 'os_hidden': False
577 }
578
579 mocked_list.assert_called_once_with(page_size=1,
580 sort_key=['name'],
581 sort_dir=['desc'],
582 filters=exp_img_filters)
583 utils.print_list.assert_called_once_with({}, ['ID', 'Name'])
584
585 def test_do_image_show_human_readable(self):
586 args = self._make_args({'id': 'pass', 'page_size': 18,
587 'human_readable': True,
588 'max_column_width': 120})
589 with mock.patch.object(self.gc.images, 'get') as mocked_list:
590 ignore_fields = ['self', 'access', 'file', 'schema']
591 expect_image = dict([(field, field) for field in ignore_fields])
592 expect_image['id'] = 'pass'
593 expect_image['size'] = 1024
594 mocked_list.return_value = expect_image
595
596 test_shell.do_image_show(self.gc, args)
597
598 mocked_list.assert_called_once_with('pass')
599 utils.print_dict.assert_called_once_with({'id': 'pass',
600 'size': '1kB'},
601 max_column_width=120)
602
603 def test_do_image_show(self):
604 args = self._make_args({'id': 'pass', 'page_size': 18,
605 'human_readable': False,
606 'max_column_width': 120})
607 with mock.patch.object(self.gc.images, 'get') as mocked_list:
608 ignore_fields = ['self', 'access', 'file', 'schema']
609 expect_image = dict([(field, field) for field in ignore_fields])
610 expect_image['id'] = 'pass'
611 expect_image['size'] = 1024
612 mocked_list.return_value = expect_image
613
614 test_shell.do_image_show(self.gc, args)
615
616 mocked_list.assert_called_once_with('pass')
617 utils.print_dict.assert_called_once_with({'id': 'pass',
618 'size': 1024},
619 max_column_width=120)
620
621 def _test_do_image_tasks(self, verbose=False, supported=True):
622 args = self._make_args({'id': 'pass', 'verbose': verbose})
623 expected_columns = ["Message", "Status", "Updated at"]
624 expected_output = {
625 "tasks": [
626 {
627 "image_id": "pass",
628 "id": "task_1",
629 "user_id": "user_1",
630 "request_id": "request_id_1",
631 "message": "fake_message",
632 "status": "status",
633 }
634 ]
635 }
636
637 if verbose:
638 columns_to_prepend = ['Image Id', 'Task Id']
639 columns_to_extend = ['User Id', 'Request Id',
640 'Result', 'Owner', 'Input', 'Expires at']
641 expected_columns = (columns_to_prepend + expected_columns +
642 columns_to_extend)
643 expected_output["tasks"][0]["Result"] = "Fake Result"
644 expected_output["tasks"][0]["Owner"] = "Fake Owner"
645 expected_output["tasks"][0]["Input"] = "Fake Input"
646 expected_output["tasks"][0]["Expires at"] = "Fake Expiry"
647
648 with mock.patch.object(self.gc.images,
649 'get_associated_image_tasks') as mocked_tasks:
650 if supported:
651 mocked_tasks.return_value = expected_output
652 else:
653 mocked_tasks.side_effect = exc.HTTPNotImplemented
654 test_shell.do_image_tasks(self.gc, args)
655 mocked_tasks.assert_called_once_with('pass')
656 if supported:
657 utils.print_dict_list.assert_called_once_with(
658 expected_output['tasks'], expected_columns)
659
660 def test_do_image_tasks_without_verbose(self):
661 self._test_do_image_tasks()
662
663 def test_do_image_tasks_with_verbose(self):
664 self._test_do_image_tasks(verbose=True)
665
666 def test_do_image_tasks_unsupported(self):
667 with mock.patch('glanceclient.common.utils.exit') as mock_exit:
668 self._test_do_image_tasks(supported=False)
669 mock_exit.assert_called_once_with(
670 'Server does not support image tasks API (v2.12)')
671
672 def test_usage(self):
673 with mock.patch.object(self.gc.info, 'get_usage') as mock_usage:
674 mock_usage.return_value = {'quota1': {'limit': 10, 'usage': 0},
675 'quota2': {'limit': 20, 'usage': 5}}
676 test_shell.do_usage(self.gc, [])
677 utils.print_dict_list.assert_called_once_with(
678 [{'quota': 'quota1', 'limit': 10, 'usage': 0},
679 {'quota': 'quota2', 'limit': 20, 'usage': 5}],
680 ['Quota', 'Limit', 'Usage'])
681
682 def test_do_image_stage_size_match(self):
683 args = mock.Mock()
684 args.id = 'IMG-01'
685 args.file = 'testfile'
686 args.size = 1024
687 args.progress = False
688
689 with mock.patch('glanceclient.common.utils.get_data_file',
690 return_value='fileobj'), \
691 mock.patch('glanceclient.common.utils.get_file_size',
692 return_value=1024), \
693 mock.patch('glanceclient.v2.shell._validate_backend'), \
694 mock.patch.object(self.gc.images,
695 'stage') as mock_stage:
696 test_shell.do_image_stage(self.gc, args)
697 mock_stage.assert_called_once_with('IMG-01', 'fileobj',
698 1024)
699
700 def test_do_image_stage_size_mismatch(self):
701 args = mock.Mock()
702 args.id = 'IMG-01'
703 args.file = 'testfile'
704 args.size = 1024
705 args.progress = False
706
707 with mock.patch('glanceclient.common.utils.get_data_file',
708 return_value='fileobj'), \
709 mock.patch('glanceclient.common.utils.get_file_size',
710 return_value=2048), \
711 mock.patch('glanceclient.v2.shell._validate_backend'):
712 with self.assertRaisesRegex(ValueError,
713 "Size mismatch: provided size 1024 "
714 "does not match the size of the "
715 "image 2048"):
716 test_shell.do_image_stage(self.gc, args)
717
718 def test_do_image_stage_no_size_in_args(self):
719 args = mock.Mock()
720 args.id = 'IMG-01'
721 args.file = 'testfile'
722 args.size = None
723 args.progress = False
724
725 with mock.patch('glanceclient.common.utils.get_data_file',
726 return_value='fileobj'), \
727 mock.patch('glanceclient.common.utils.get_file_size',
728 return_value=1024), \
729 mock.patch('glanceclient.v2.shell._validate_backend'), \
730 mock.patch.object(self.gc.images,
731 'stage') as mock_upload:
732 test_shell.do_image_stage(self.gc, args)
733 mock_upload.assert_called_once_with('IMG-01', 'fileobj',
734 1024)
735
736 def test_do_image_upload_size_match(self):
737 args = mock.Mock()
738 args.id = 'IMG-01'
739 args.file = 'testfile'
740 args.size = 1024
741 args.store = None
742 args.progress = False
743
744 with mock.patch('glanceclient.common.utils.get_data_file',
745 return_value='fileobj'), \
746 mock.patch('glanceclient.common.utils.get_file_size',
747 return_value=1024), \
748 mock.patch('glanceclient.v2.shell._validate_backend'), \
749 mock.patch.object(self.gc.images,
750 'upload') as mock_upload:
751 test_shell.do_image_upload(self.gc, args)
752 mock_upload.assert_called_once_with('IMG-01', 'fileobj',
753 1024, backend=None)
754
755 def test_do_image_upload_size_mismatch(self):
756 args = mock.Mock()
757 args.id = 'IMG-01'
758 args.file = 'testfile'
759 args.size = 1024
760 args.store = None
761 args.progress = False
762
763 with mock.patch('glanceclient.common.utils.get_data_file',
764 return_value='fileobj'), \
765 mock.patch('glanceclient.common.utils.get_file_size',
766 return_value=2048), \
767 mock.patch('glanceclient.v2.shell._validate_backend'):
768 with self.assertRaisesRegex(ValueError,
769 "Size mismatch: provided size 1024 "
770 "does not match the size of the "
771 "image 2048"):
772 test_shell.do_image_upload(self.gc, args)
773
774 def test_do_image_upload_no_size_in_args(self):
775 args = mock.Mock()
776 args.id = 'IMG-01'
777 args.file = 'testfile'
778 args.size = None
779 args.store = None
780 args.progress = False
781
782 with mock.patch('glanceclient.common.utils.get_data_file',
783 return_value='fileobj'), \
784 mock.patch('glanceclient.common.utils.get_file_size',
785 return_value=1024), \
786 mock.patch('glanceclient.v2.shell._validate_backend'), \
787 mock.patch.object(self.gc.images,
788 'upload') as mock_upload:
789 test_shell.do_image_upload(self.gc, args)
790 mock_upload.assert_called_once_with('IMG-01', 'fileobj',
791 1024, backend=None)
792
793 @mock.patch('sys.stdin', autospec=True)
794 def test_do_image_create_no_user_props(self, mock_stdin):
795 args = self._make_args({'name': 'IMG-01', 'disk_format': 'vhd',
796 'container_format': 'bare',
797 'file': None})
798 with mock.patch.object(self.gc.images, 'create') as mocked_create:
799 ignore_fields = ['self', 'access', 'file', 'schema']
800 expect_image = dict([(field, field) for field in ignore_fields])
801 expect_image['id'] = 'pass'
802 expect_image['name'] = 'IMG-01'
803 expect_image['disk_format'] = 'vhd'
804 expect_image['container_format'] = 'bare'
805 mocked_create.return_value = expect_image
806
807 # Ensure that the test stdin is not considered
808 # to be supplying image data
809 mock_stdin.isatty = lambda: True
810 test_shell.do_image_create(self.gc, args)
811
812 mocked_create.assert_called_once_with(name='IMG-01',
813 disk_format='vhd',
814 container_format='bare')
815 utils.print_dict.assert_called_once_with({
816 'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd',
817 'container_format': 'bare'})
818
819 @mock.patch('sys.stdin', autospec=True)
820 def test_do_image_create_for_none_multi_hash(self, mock_stdin):
821 args = self._make_args({'name': 'IMG-01', 'disk_format': 'vhd',
822 'container_format': 'bare',
823 'file': None})
824 with mock.patch.object(self.gc.images, 'create') as mocked_create:
825 ignore_fields = ['self', 'access', 'file', 'schema']
826 expect_image = dict([(field, field) for field in ignore_fields])
827 expect_image['id'] = 'pass'
828 expect_image['name'] = 'IMG-01'
829 expect_image['disk_format'] = 'vhd'
830 expect_image['container_format'] = 'bare'
831 expect_image['os_hash_algo'] = None
832 expect_image['os_hash_value'] = None
833 mocked_create.return_value = expect_image
834
835 # Ensure that the test stdin is not considered
836 # to be supplying image data
837 mock_stdin.isatty = lambda: True
838 test_shell.do_image_create(self.gc, args)
839
840 mocked_create.assert_called_once_with(name='IMG-01',
841 disk_format='vhd',
842 container_format='bare')
843 utils.print_dict.assert_called_once_with({
844 'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd',
845 'container_format': 'bare', 'os_hash_algo': None,
846 'os_hash_value': None})
847
848 def test_do_image_create_with_multihash(self):
849 self.mock_get_data_file.return_value = io.StringIO()
850 try:
851 with open(tempfile.mktemp(), 'w+') as f:
852 f.write('Some data here')
853 f.flush()
854 f.seek(0)
855 file_name = f.name
856 temp_args = {'name': 'IMG-01',
857 'disk_format': 'vhd',
858 'container_format': 'bare',
859 'file': file_name,
860 'progress': False}
861 args = self._make_args(temp_args)
862 with mock.patch.object(self.gc.images, 'create') as mocked_create:
863 with mock.patch.object(self.gc.images, 'get') as mocked_get:
864
865 ignore_fields = ['self', 'access', 'schema']
866 expect_image = dict([(field, field) for field in
867 ignore_fields])
868 expect_image['id'] = 'pass'
869 expect_image['name'] = 'IMG-01'
870 expect_image['disk_format'] = 'vhd'
871 expect_image['container_format'] = 'bare'
872 expect_image['checksum'] = 'fake-checksum'
873 expect_image['os_hash_algo'] = 'fake-hash_algo'
874 expect_image['os_hash_value'] = 'fake-hash_value'
875 mocked_create.return_value = expect_image
876 mocked_get.return_value = expect_image
877
878 test_shell.do_image_create(self.gc, args)
879
880 temp_args.pop('file', None)
881 mocked_create.assert_called_once_with(**temp_args)
882 mocked_get.assert_called_once_with('pass')
883 utils.print_dict.assert_called_once_with({
884 'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd',
885 'container_format': 'bare',
886 'checksum': 'fake-checksum',
887 'os_hash_algo': 'fake-hash_algo',
888 'os_hash_value': 'fake-hash_value'})
889 finally:
890 try:
891 os.remove(f.name)
892 except Exception:
893 pass
894
895 def _do_image_create(self, temp_args, expect_size=None):
896 self.mock_get_data_file.return_value = io.StringIO()
897 with open(tempfile.mktemp(), 'w+') as f:
898 f.write('Some data here')
899 f.flush()
900 f.seek(0)
901 file_name = f.name
902 self.addCleanup(lambda: os.remove(f.name) if os.path.exists(
903 f.name) else None)
904 temp_args = temp_args.copy()
905 temp_args['file'] = file_name
906 args = self._make_args(temp_args)
907 with mock.patch.object(self.gc.images, 'create') as mocked_create, \
908 mock.patch.object(self.gc.images, 'get') as mocked_get, \
909 mock.patch.object(utils, 'get_file_size') as mock_size:
910 expected_size = len('Some data here')
911 mock_size.return_value = expected_size
912 ignore_fields = ['self', 'access', 'schema']
913 expect_image = dict(
914 [(field, field) for field in ignore_fields])
915 expect_image['id'] = 'pass'
916 expect_image['name'] = 'IMG-01'
917 expect_image['disk_format'] = 'vhd'
918 expect_image['container_format'] = 'bare'
919 expect_image['checksum'] = 'fake-checksum'
920 expect_image['os_hash_algo'] = 'fake-hash_algo'
921 expect_image['os_hash_value'] = 'fake-hash_value'
922 if expect_size is not None:
923 expect_image['size'] = expect_size
924 mocked_create.return_value = expect_image
925 mocked_get.return_value = expect_image
926
927 test_shell.do_image_create(self.gc, args)
928
929 temp_args.pop('file', None)
930 mocked_create.assert_called_once_with(**temp_args)
931 mocked_get.assert_called_once_with('pass')
932 expected_dict = {
933 'id': 'pass', 'name': 'IMG-01',
934 'disk_format': 'vhd',
935 'container_format': 'bare',
936 'checksum': 'fake-checksum',
937 'os_hash_algo': 'fake-hash_algo',
938 'os_hash_value': 'fake-hash_value',
939 }
940 if expect_size is not None:
941 expected_dict['size'] = expect_size
942 utils.print_dict.assert_called_once_with(expected_dict)
943 mock_size.assert_called()
944
945 def test_do_image_create_without_size(self):
946 self._do_image_create(
947 temp_args={'name': 'IMG-01', 'disk_format': 'vhd',
948 'container_format': 'bare', 'progress': False},
949 expect_size=14)
950
951 def test_do_image_create_with_size_exits(self):
952 args = self._make_args({'name': 'test-image', 'size': 1234})
953 expected_msg = ("Setting 'size' during image creation is "
954 "not supported. Please use --size only when "
955 "uploading data.")
956 with mock.patch('glanceclient.common.utils.exit') as mock_exit:
957 mock_exit.side_effect = self._mock_utils_exit
958 try:
959 test_shell.do_image_create(self.gc, args)
960 self.fail("utils.exit should have been called")
961 except SystemExit:
962 pass
963
964 mock_exit.assert_called_once_with(expected_msg)
965
966 @mock.patch('sys.stdin', autospec=True)
967 def test_do_image_create_hidden_image(self, mock_stdin):
968 args = self._make_args({'name': 'IMG-01', 'disk_format': 'vhd',
969 'container_format': 'bare',
970 'file': None,
971 'os_hidden': True})
972 with mock.patch.object(self.gc.images, 'create') as mocked_create:
973 ignore_fields = ['self', 'access', 'file', 'schema']
974 expect_image = dict([(field, field) for field in ignore_fields])
975 expect_image['id'] = 'pass'
976 expect_image['name'] = 'IMG-01'
977 expect_image['disk_format'] = 'vhd'
978 expect_image['container_format'] = 'bare'
979 expect_image['os_hidden'] = True
980 mocked_create.return_value = expect_image
981
982 # Ensure that the test stdin is not considered
983 # to be supplying image data
984 mock_stdin.isatty = lambda: True
985 test_shell.do_image_create(self.gc, args)
986
987 mocked_create.assert_called_once_with(name='IMG-01',
988 disk_format='vhd',
989 container_format='bare',
990 os_hidden=True)
991 utils.print_dict.assert_called_once_with({
992 'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd',
993 'container_format': 'bare', 'os_hidden': True})
994
995 def test_do_image_create_with_file(self):
996 self.mock_get_data_file.return_value = io.StringIO()
997 try:
998 file_name = None
999 with open(tempfile.mktemp(), 'w+') as f:
1000 f.write('Some data here')
1001 f.flush()
1002 f.seek(0)
1003 file_name = f.name
1004 temp_args = {'name': 'IMG-01',
1005 'disk_format': 'vhd',
1006 'container_format': 'bare',
1007 'file': file_name,
1008 'progress': False}
1009 args = self._make_args(temp_args)
1010 with mock.patch.object(self.gc.images, 'create') as mocked_create:
1011 with mock.patch.object(self.gc.images, 'get') as mocked_get:
1012
1013 ignore_fields = ['self', 'access', 'schema']
1014 expect_image = dict([(field, field) for field in
1015 ignore_fields])
1016 expect_image['id'] = 'pass'
1017 expect_image['name'] = 'IMG-01'
1018 expect_image['disk_format'] = 'vhd'
1019 expect_image['container_format'] = 'bare'
1020 mocked_create.return_value = expect_image
1021 mocked_get.return_value = expect_image
1022
1023 test_shell.do_image_create(self.gc, args)
1024
1025 temp_args.pop('file', None)
1026 mocked_create.assert_called_once_with(**temp_args)
1027 mocked_get.assert_called_once_with('pass')
1028 utils.print_dict.assert_called_once_with({
1029 'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd',
1030 'container_format': 'bare'})
1031 finally:
1032 try:
1033 os.remove(f.name)
1034 except Exception:
1035 pass
1036
1037 @mock.patch('sys.stdin', autospec=True)
1038 def test_do_image_create_with_unicode(self, mock_stdin):
1039 name = '\u041f\u0420\u0418\u0412\u0415\u0422\u0418\u041a'
1040
1041 args = self._make_args({'name': name,
1042 'file': None})
1043 with mock.patch.object(self.gc.images, 'create') as mocked_create:
1044 ignore_fields = ['self', 'access', 'file', 'schema']
1045 expect_image = dict((field, field) for field in ignore_fields)
1046 expect_image['id'] = 'pass'
1047 expect_image['name'] = name
1048 mocked_create.return_value = expect_image
1049
1050 mock_stdin.isatty = lambda: True
1051 test_shell.do_image_create(self.gc, args)
1052
1053 mocked_create.assert_called_once_with(name=name)
1054 utils.print_dict.assert_called_once_with({
1055 'id': 'pass', 'name': name})
1056
1057 @mock.patch('sys.stdin', autospec=True)
1058 def test_do_image_create_with_user_props(self, mock_stdin):
1059 args = self._make_args({'name': 'IMG-01',
1060 'property': ['myprop=myval'],
1061 'file': None,
1062 'container_format': 'bare',
1063 'disk_format': 'qcow2'})
1064 with mock.patch.object(self.gc.images, 'create') as mocked_create:
1065 ignore_fields = ['self', 'access', 'file', 'schema']
1066 expect_image = dict([(field, field) for field in ignore_fields])
1067 expect_image['id'] = 'pass'
1068 expect_image['name'] = 'IMG-01'
1069 expect_image['myprop'] = 'myval'
1070 mocked_create.return_value = expect_image
1071
1072 # Ensure that the test stdin is not considered
1073 # to be supplying image data
1074 mock_stdin.isatty = lambda: True
1075 test_shell.do_image_create(self.gc, args)
1076
1077 mocked_create.assert_called_once_with(name='IMG-01',
1078 myprop='myval',
1079 container_format='bare',
1080 disk_format='qcow2')
1081 utils.print_dict.assert_called_once_with({
1082 'id': 'pass', 'name': 'IMG-01', 'myprop': 'myval'})
1083
1084 @mock.patch('glanceclient.common.utils.exit')
1085 @mock.patch('os.access')
1086 @mock.patch('sys.stdin', autospec=True)
1087 def test_neg_do_image_create_no_file_and_stdin_with_store(
1088 self, mock_stdin, mock_access, mock_utils_exit):
1089 expected_msg = ('--store option should only be provided with --file '
1090 'option or stdin.')
1091 mock_utils_exit.side_effect = self._mock_utils_exit
1092 mock_stdin.isatty = lambda: True
1093 mock_access.return_value = False
1094 args = self._make_args({'name': 'IMG-01',
1095 'property': ['myprop=myval'],
1096 'file': None,
1097 'store': 'file1',
1098 'container_format': 'bare',
1099 'disk_format': 'qcow2'})
1100
1101 try:
1102 test_shell.do_image_create(self.gc, args)
1103 self.fail("utils.exit should have been called")
1104 except SystemExit:
1105 pass
1106
1107 mock_utils_exit.assert_called_once_with(expected_msg)
1108
1109 @mock.patch('glanceclient.common.utils.exit')
1110 def test_neg_do_image_create_invalid_store(
1111 self, mock_utils_exit):
1112 expected_msg = ("Store 'dummy' is not valid for this cloud. "
1113 "Valid values can be retrieved with stores-info "
1114 "command.")
1115 mock_utils_exit.side_effect = self._mock_utils_exit
1116 args = self._make_args({'name': 'IMG-01',
1117 'property': ['myprop=myval'],
1118 'file': "somefile.txt",
1119 'store': 'dummy',
1120 'container_format': 'bare',
1121 'disk_format': 'qcow2'})
1122
1123 with mock.patch.object(self.gc.images,
1124 'get_stores_info') as mock_stores_info:
1125 mock_stores_info.return_value = self.stores_info_response
1126 try:
1127 test_shell.do_image_create(self.gc, args)
1128 self.fail("utils.exit should have been called")
1129 except SystemExit:
1130 pass
1131
1132 mock_utils_exit.assert_called_once_with(expected_msg)
1133
1134 # NOTE(rosmaita): have to explicitly set to None the declared but unused
1135 # arguments (the configparser does that for us normally)
1136 base_args = {'name': 'Mortimer',
1137 'disk_format': 'raw',
1138 'container_format': 'bare',
1139 'progress': False,
1140 'file': None,
1141 'uri': None,
1142 'remote_region': None,
1143 'import_method': None}
1144
1145 import_info_response = {'import-methods': {
1146 'type': 'array',
1147 'description': 'Import methods available.',
1148 'value': ['glance-direct', 'web-download', 'copy-image',
1149 'glance-download']}}
1150
1151 def _mock_utils_exit(self, msg):
1152 sys.exit(msg)
1153
1154 @mock.patch('glanceclient.common.utils.exit')
1155 @mock.patch('os.access')
1156 @mock.patch('sys.stdin', autospec=True)
1157 def test_neg_image_create_via_import_no_method_with_file_and_stdin(
1158 self, mock_stdin, mock_access, mock_utils_exit):
1159 expected_msg = ('You cannot use both --file and stdin with the '
1160 'glance-direct import method.')
1161 my_args = self.base_args.copy()
1162 my_args['file'] = 'some.file'
1163 args = self._make_args(my_args)
1164 mock_stdin.isatty = lambda: False
1165 mock_access.return_value = True
1166 mock_utils_exit.side_effect = self._mock_utils_exit
1167 with mock.patch.object(self.gc.images,
1168 'get_import_info') as mocked_info:
1169 mocked_info.return_value = self.import_info_response
1170 try:
1171 test_shell.do_image_create_via_import(self.gc, args)
1172 self.fail("utils.exit should have been called")
1173 except SystemExit:
1174 pass
1175 mock_utils_exit.assert_called_once_with(expected_msg)
1176
1177 @mock.patch('glanceclient.common.utils.exit')
1178 def test_neg_image_create_via_import_copy_image(
1179 self, mock_utils_exit):
1180 expected_msg = ("Import method 'copy-image' cannot be used "
1181 "while creating the image.")
1182 mock_utils_exit.side_effect = self._mock_utils_exit
1183 my_args = self.base_args.copy()
1184 my_args.update(
1185 {'id': 'IMG-01', 'import_method': 'copy-image'})
1186 args = self._make_args(my_args)
1187
1188 with mock.patch.object(self.gc.images,
1189 'get_import_info') as mocked_info:
1190 mocked_info.return_value = self.import_info_response
1191 try:
1192 test_shell.do_image_create_via_import(self.gc, args)
1193 self.fail("utils.exit should have been called")
1194 except SystemExit:
1195 pass
1196 mock_utils_exit.assert_called_once_with(expected_msg)
1197
1198 @mock.patch('glanceclient.common.utils.exit')
1199 def test_neg_image_create_via_import_stores_all_stores_specified(
1200 self, mock_utils_exit):
1201 expected_msg = ('Only one of --store, --stores and --all-stores can '
1202 'be provided')
1203 mock_utils_exit.side_effect = self._mock_utils_exit
1204 my_args = self.base_args.copy()
1205 my_args.update(
1206 {'id': 'IMG-01', 'import_method': 'glance-direct',
1207 'stores': 'file1,file2', 'os_all_stores': True,
1208 'file': 'some.mufile',
1209 'disk_format': 'raw',
1210 'container_format': 'bare',
1211 })
1212 args = self._make_args(my_args)
1213
1214 with mock.patch.object(self.gc.images,
1215 'get_import_info') as mocked_info:
1216 mocked_info.return_value = self.import_info_response
1217 try:
1218 test_shell.do_image_create_via_import(self.gc, args)
1219 self.fail("utils.exit should have been called")
1220 except SystemExit:
1221 pass
1222 mock_utils_exit.assert_called_once_with(expected_msg)
1223
1224 @mock.patch('glanceclient.common.utils.exit')
1225 @mock.patch('sys.stdin', autospec=True)
1226 def test_neg_image_create_via_import_stores_without_file(
1227 self, mock_stdin, mock_utils_exit):
1228 expected_msg = ('--stores option should only be provided with --file '
1229 'option or stdin for the glance-direct import method.')
1230 mock_utils_exit.side_effect = self._mock_utils_exit
1231 mock_stdin.isatty = lambda: True
1232 my_args = self.base_args.copy()
1233 my_args.update(
1234 {'id': 'IMG-01', 'import_method': 'glance-direct',
1235 'stores': 'file1,file2',
1236 'disk_format': 'raw',
1237 'container_format': 'bare',
1238 })
1239 args = self._make_args(my_args)
1240
1241 with mock.patch.object(self.gc.images,
1242 'get_import_info') as mocked_info:
1243 with mock.patch.object(self.gc.images,
1244 'get_stores_info') as mocked_stores_info:
1245 mocked_stores_info.return_value = self.stores_info_response
1246 mocked_info.return_value = self.import_info_response
1247 try:
1248 test_shell.do_image_create_via_import(self.gc, args)
1249 self.fail("utils.exit should have been called")
1250 except SystemExit:
1251 pass
1252 mock_utils_exit.assert_called_once_with(expected_msg)
1253
1254 @mock.patch('glanceclient.common.utils.exit')
1255 @mock.patch('sys.stdin', autospec=True)
1256 def test_neg_image_create_via_import_all_stores_without_file(
1257 self, mock_stdin, mock_utils_exit):
1258 expected_msg = ('--all-stores option should only be provided with '
1259 '--file option or stdin for the glance-direct import '
1260 'method.')
1261 mock_utils_exit.side_effect = self._mock_utils_exit
1262 mock_stdin.isatty = lambda: True
1263 my_args = self.base_args.copy()
1264 my_args.update(
1265 {'id': 'IMG-01', 'import_method': 'glance-direct',
1266 'os_all_stores': True,
1267 'disk_format': 'raw',
1268 'container_format': 'bare',
1269 })
1270 args = self._make_args(my_args)
1271
1272 with mock.patch.object(self.gc.images,
1273 'get_import_info') as mocked_info:
1274 mocked_info.return_value = self.import_info_response
1275 try:
1276 test_shell.do_image_create_via_import(self.gc, args)
1277 self.fail("utils.exit should have been called")
1278 except SystemExit:
1279 pass
1280 mock_utils_exit.assert_called_once_with(expected_msg)
1281
1282 @mock.patch('glanceclient.common.utils.exit')
1283 @mock.patch('os.access')
1284 @mock.patch('sys.stdin', autospec=True)
1285 def test_neg_image_create_via_import_no_file_and_stdin_with_store(
1286 self, mock_stdin, mock_access, mock_utils_exit):
1287 expected_msg = ('--store option should only be provided with --file '
1288 'option or stdin for the glance-direct import method.')
1289 my_args = self.base_args.copy()
1290 my_args['import_method'] = 'glance-direct'
1291 my_args['store'] = 'file1'
1292 args = self._make_args(my_args)
1293
1294 mock_stdin.isatty = lambda: True
1295 mock_access.return_value = False
1296 mock_utils_exit.side_effect = self._mock_utils_exit
1297 with mock.patch.object(self.gc.images,
1298 'get_import_info') as mocked_info:
1299 with mock.patch.object(self.gc.images,
1300 'get_stores_info') as mocked_stores_info:
1301 mocked_stores_info.return_value = self.stores_info_response
1302 mocked_info.return_value = self.import_info_response
1303 try:
1304 test_shell.do_image_create_via_import(self.gc, args)
1305 self.fail("utils.exit should have been called")
1306 except SystemExit:
1307 pass
1308 mock_utils_exit.assert_called_once_with(expected_msg)
1309
1310 @mock.patch('glanceclient.common.utils.exit')
1311 @mock.patch('sys.stdin', autospec=True)
1312 def test_neg_image_create_via_import_no_uri_with_store(
1313 self, mock_stdin, mock_utils_exit):
1314 expected_msg = ('--store option should only be provided with --uri '
1315 'option for the web-download import method.')
1316 my_args = self.base_args.copy()
1317 my_args['import_method'] = 'web-download'
1318 my_args['store'] = 'file1'
1319 args = self._make_args(my_args)
1320 mock_utils_exit.side_effect = self._mock_utils_exit
1321 with mock.patch.object(self.gc.images,
1322 'get_import_info') as mocked_info:
1323 with mock.patch.object(self.gc.images,
1324 'get_stores_info') as mocked_stores_info:
1325 mocked_stores_info.return_value = self.stores_info_response
1326 mocked_info.return_value = self.import_info_response
1327 try:
1328 test_shell.do_image_create_via_import(self.gc, args)
1329 self.fail("utils.exit should have been called")
1330 except SystemExit:
1331 pass
1332 mock_utils_exit.assert_called_once_with(expected_msg)
1333
1334 @mock.patch('glanceclient.common.utils.exit')
1335 @mock.patch('os.access')
1336 @mock.patch('sys.stdin', autospec=True)
1337 def test_neg_image_create_via_import_invalid_store(
1338 self, mock_stdin, mock_access, mock_utils_exit):
1339 expected_msg = ("Store 'dummy' is not valid for this cloud. "
1340 "Valid values can be retrieved with stores-info"
1341 " command.")
1342 my_args = self.base_args.copy()
1343 my_args['import_method'] = 'glance-direct'
1344 my_args['store'] = 'dummy'
1345 args = self._make_args(my_args)
1346
1347 mock_stdin.isatty = lambda: True
1348 mock_access.return_value = False
1349 mock_utils_exit.side_effect = self._mock_utils_exit
1350 with mock.patch.object(self.gc.images,
1351 'get_import_info') as mocked_info:
1352 with mock.patch.object(self.gc.images,
1353 'get_stores_info') as mocked_stores_info:
1354 mocked_stores_info.return_value = self.stores_info_response
1355 mocked_info.return_value = self.import_info_response
1356 try:
1357 test_shell.do_image_create_via_import(self.gc, args)
1358 self.fail("utils.exit should have been called")
1359 except SystemExit:
1360 pass
1361 mock_utils_exit.assert_called_once_with(expected_msg)
1362
1363 @mock.patch('glanceclient.common.utils.exit')
1364 @mock.patch('sys.stdin', autospec=True)
1365 def test_neg_image_create_via_import_no_method_passing_uri(
1366 self, mock_stdin, mock_utils_exit):
1367 expected_msg = ('You cannot use --uri without specifying an import '
1368 'method.')
1369 my_args = self.base_args.copy()
1370 my_args['uri'] = 'http://example.com/whatever'
1371 args = self._make_args(my_args)
1372 mock_stdin.isatty = lambda: True
1373 mock_utils_exit.side_effect = self._mock_utils_exit
1374 with mock.patch.object(self.gc.images,
1375 'get_import_info') as mocked_info:
1376 mocked_info.return_value = self.import_info_response
1377 try:
1378 test_shell.do_image_create_via_import(self.gc, args)
1379 self.fail("utils.exit should have been called")
1380 except SystemExit:
1381 pass
1382 mock_utils_exit.assert_called_once_with(expected_msg)
1383
1384 @mock.patch('glanceclient.common.utils.exit')
1385 @mock.patch('sys.stdin', autospec=True)
1386 def test_neg_image_create_via_import_glance_direct_no_data(
1387 self, mock_stdin, mock_utils_exit):
1388 expected_msg = ('You must specify a --file or provide data via stdin '
1389 'for the glance-direct import method.')
1390 my_args = self.base_args.copy()
1391 my_args['import_method'] = 'glance-direct'
1392 args = self._make_args(my_args)
1393 mock_stdin.isatty = lambda: True
1394 mock_utils_exit.side_effect = self._mock_utils_exit
1395 with mock.patch.object(self.gc.images,
1396 'get_import_info') as mocked_info:
1397 mocked_info.return_value = self.import_info_response
1398 try:
1399 test_shell.do_image_create_via_import(self.gc, args)
1400 self.fail("utils.exit should have been called")
1401 except SystemExit:
1402 pass
1403 mock_utils_exit.assert_called_once_with(expected_msg)
1404
1405 @mock.patch('glanceclient.common.utils.exit')
1406 @mock.patch('sys.stdin', autospec=True)
1407 def test_neg_image_create_via_import_glance_direct_with_uri(
1408 self, mock_stdin, mock_utils_exit):
1409 expected_msg = ('You cannot specify a --uri with the glance-direct '
1410 'import method.')
1411 my_args = self.base_args.copy()
1412 my_args['import_method'] = 'glance-direct'
1413 my_args['uri'] = 'https://example.com/some/stuff'
1414 args = self._make_args(my_args)
1415 mock_stdin.isatty = lambda: True
1416 mock_utils_exit.side_effect = self._mock_utils_exit
1417 with mock.patch.object(self.gc.images,
1418 'get_import_info') as mocked_info:
1419 mocked_info.return_value = self.import_info_response
1420 try:
1421 test_shell.do_image_create_via_import(self.gc, args)
1422 self.fail("utils.exit should have been called")
1423 except SystemExit:
1424 pass
1425 mock_utils_exit.assert_called_once_with(expected_msg)
1426
1427 @mock.patch('glanceclient.common.utils.exit')
1428 @mock.patch('os.access')
1429 @mock.patch('sys.stdin', autospec=True)
1430 def test_neg_image_create_via_import_glance_direct_with_file_and_uri(
1431 self, mock_stdin, mock_access, mock_utils_exit):
1432 expected_msg = ('You cannot specify a --uri with the glance-direct '
1433 'import method.')
1434 my_args = self.base_args.copy()
1435 my_args['import_method'] = 'glance-direct'
1436 my_args['uri'] = 'https://example.com/some/stuff'
1437 my_args['file'] = 'my.browncow'
1438 args = self._make_args(my_args)
1439 mock_stdin.isatty = lambda: True
1440 mock_access.return_value = True
1441 mock_utils_exit.side_effect = self._mock_utils_exit
1442 with mock.patch.object(self.gc.images,
1443 'get_import_info') as mocked_info:
1444 mocked_info.return_value = self.import_info_response
1445 try:
1446 test_shell.do_image_create_via_import(self.gc, args)
1447 self.fail("utils.exit should have been called")
1448 except SystemExit:
1449 pass
1450 mock_utils_exit.assert_called_once_with(expected_msg)
1451
1452 @mock.patch('glanceclient.common.utils.exit')
1453 @mock.patch('sys.stdin', autospec=True)
1454 def test_neg_image_create_via_import_glance_direct_with_data_and_uri(
1455 self, mock_stdin, mock_utils_exit):
1456 expected_msg = ('You cannot specify a --uri with the glance-direct '
1457 'import method.')
1458 my_args = self.base_args.copy()
1459 my_args['import_method'] = 'glance-direct'
1460 my_args['uri'] = 'https://example.com/some/stuff'
1461 args = self._make_args(my_args)
1462 mock_stdin.isatty = lambda: False
1463 mock_utils_exit.side_effect = self._mock_utils_exit
1464 with mock.patch.object(self.gc.images,
1465 'get_import_info') as mocked_info:
1466 mocked_info.return_value = self.import_info_response
1467 try:
1468 test_shell.do_image_create_via_import(self.gc, args)
1469 self.fail("utils.exit should have been called")
1470 except SystemExit:
1471 pass
1472 mock_utils_exit.assert_called_once_with(expected_msg)
1473
1474 @mock.patch('glanceclient.common.utils.exit')
1475 @mock.patch('sys.stdin', autospec=True)
1476 def test_neg_image_create_via_import_web_download_no_uri(
1477 self, mock_stdin, mock_utils_exit):
1478 expected_msg = ('URI is required for web-download import method. '
1479 'Please use \'--uri <uri>\'.')
1480 my_args = self.base_args.copy()
1481 my_args['import_method'] = 'web-download'
1482 args = self._make_args(my_args)
1483 mock_stdin.isatty = lambda: True
1484 mock_utils_exit.side_effect = self._mock_utils_exit
1485 with mock.patch.object(self.gc.images,
1486 'get_import_info') as mocked_info:
1487 mocked_info.return_value = self.import_info_response
1488 try:
1489 test_shell.do_image_create_via_import(self.gc, args)
1490 self.fail("utils.exit should have been called")
1491 except SystemExit:
1492 pass
1493 mock_utils_exit.assert_called_once_with(expected_msg)
1494
1495 @mock.patch('glanceclient.common.utils.exit')
1496 def test_neg_image_create_via_import_stores_without_uri(
1497 self, mock_utils_exit):
1498 expected_msg = ('--stores option should only be provided with --uri '
1499 'option for the web-download import method.')
1500 mock_utils_exit.side_effect = self._mock_utils_exit
1501 my_args = self.base_args.copy()
1502 my_args.update(
1503 {'id': 'IMG-01', 'import_method': 'web-download',
1504 'stores': 'file1,file2',
1505 'disk_format': 'raw',
1506 'container_format': 'bare',
1507 })
1508 args = self._make_args(my_args)
1509
1510 with mock.patch.object(self.gc.images,
1511 'get_import_info') as mocked_info:
1512 with mock.patch.object(self.gc.images,
1513 'get_stores_info') as mocked_stores_info:
1514 mocked_stores_info.return_value = self.stores_info_response
1515 mocked_info.return_value = self.import_info_response
1516 try:
1517 test_shell.do_image_create_via_import(self.gc, args)
1518 self.fail("utils.exit should have been called")
1519 except SystemExit:
1520 pass
1521 mock_utils_exit.assert_called_once_with(expected_msg)
1522
1523 @mock.patch('glanceclient.common.utils.exit')
1524 def test_neg_image_create_via_import_all_stores_without_uri(
1525 self, mock_utils_exit):
1526 expected_msg = ('--all-stores option should only be provided with '
1527 '--uri option for the web-download import '
1528 'method.')
1529 mock_utils_exit.side_effect = self._mock_utils_exit
1530 my_args = self.base_args.copy()
1531 my_args.update(
1532 {'id': 'IMG-01', 'import_method': 'web-download',
1533 'os_all_stores': True,
1534 'disk_format': 'raw',
1535 'container_format': 'bare',
1536 })
1537 args = self._make_args(my_args)
1538
1539 with mock.patch.object(self.gc.images,
1540 'get_import_info') as mocked_info:
1541 mocked_info.return_value = self.import_info_response
1542 try:
1543 test_shell.do_image_create_via_import(self.gc, args)
1544 self.fail("utils.exit should have been called")
1545 except SystemExit:
1546 pass
1547 mock_utils_exit.assert_called_once_with(expected_msg)
1548
1549 @mock.patch('glanceclient.common.utils.exit')
1550 @mock.patch('sys.stdin', autospec=True)
1551 def test_neg_image_create_via_import_web_download_no_uri_with_file(
1552 self, mock_stdin, mock_utils_exit):
1553 expected_msg = ('URI is required for web-download import method. '
1554 'Please use \'--uri <uri>\'.')
1555 my_args = self.base_args.copy()
1556 my_args['import_method'] = 'web-download'
1557 my_args['file'] = 'my.browncow'
1558 args = self._make_args(my_args)
1559 mock_stdin.isatty = lambda: True
1560 mock_utils_exit.side_effect = self._mock_utils_exit
1561 with mock.patch.object(self.gc.images,
1562 'get_import_info') as mocked_info:
1563 mocked_info.return_value = self.import_info_response
1564 try:
1565 test_shell.do_image_create_via_import(self.gc, args)
1566 self.fail("utils.exit should have been called")
1567 except SystemExit:
1568 pass
1569 mock_utils_exit.assert_called_once_with(expected_msg)
1570
1571 @mock.patch('glanceclient.common.utils.exit')
1572 @mock.patch('sys.stdin', autospec=True)
1573 def test_neg_image_create_via_import_web_download_no_uri_with_data(
1574 self, mock_stdin, mock_utils_exit):
1575 expected_msg = ('URI is required for web-download import method. '
1576 'Please use \'--uri <uri>\'.')
1577 my_args = self.base_args.copy()
1578 my_args['import_method'] = 'web-download'
1579 my_args['file'] = 'my.browncow'
1580 args = self._make_args(my_args)
1581 mock_stdin.isatty = lambda: False
1582 mock_utils_exit.side_effect = self._mock_utils_exit
1583 with mock.patch.object(self.gc.images,
1584 'get_import_info') as mocked_info:
1585 mocked_info.return_value = self.import_info_response
1586 try:
1587 test_shell.do_image_create_via_import(self.gc, args)
1588 self.fail("utils.exit should have been called")
1589 except SystemExit:
1590 pass
1591 mock_utils_exit.assert_called_once_with(expected_msg)
1592
1593 @mock.patch('glanceclient.common.utils.exit')
1594 @mock.patch('sys.stdin', autospec=True)
1595 def test_neg_image_create_via_import_web_download_with_data_and_uri(
1596 self, mock_stdin, mock_utils_exit):
1597 expected_msg = ('You cannot pass data via stdin with the web-download '
1598 'import method.')
1599 my_args = self.base_args.copy()
1600 my_args['import_method'] = 'web-download'
1601 my_args['uri'] = 'https://example.com/some/stuff'
1602 args = self._make_args(my_args)
1603 mock_stdin.isatty = lambda: False
1604 mock_utils_exit.side_effect = self._mock_utils_exit
1605 with mock.patch.object(self.gc.images,
1606 'get_import_info') as mocked_info:
1607 mocked_info.return_value = self.import_info_response
1608 try:
1609 test_shell.do_image_create_via_import(self.gc, args)
1610 self.fail("utils.exit should have been called")
1611 except SystemExit:
1612 pass
1613 mock_utils_exit.assert_called_once_with(expected_msg)
1614
1615 @mock.patch('glanceclient.common.utils.exit')
1616 @mock.patch('sys.stdin', autospec=True)
1617 def test_neg_image_create_via_import_web_download_with_file_and_uri(
1618 self, mock_stdin, mock_utils_exit):
1619 expected_msg = ('You cannot specify a --file with the web-download '
1620 'import method.')
1621 my_args = self.base_args.copy()
1622 my_args['import_method'] = 'web-download'
1623 my_args['uri'] = 'https://example.com/some/stuff'
1624 my_args['file'] = 'my.browncow'
1625 args = self._make_args(my_args)
1626 mock_stdin.isatty = lambda: True
1627 mock_utils_exit.side_effect = self._mock_utils_exit
1628 with mock.patch.object(self.gc.images,
1629 'get_import_info') as mocked_info:
1630 mocked_info.return_value = self.import_info_response
1631 try:
1632 test_shell.do_image_create_via_import(self.gc, args)
1633 self.fail("utils.exit should have been called")
1634 except SystemExit:
1635 pass
1636 mock_utils_exit.assert_called_once_with(expected_msg)
1637
1638 @mock.patch('glanceclient.common.utils.exit')
1639 @mock.patch('sys.stdin', autospec=True)
1640 def test_neg_image_create_via_import_glance_download_no_region_and_id(
1641 self, mock_stdin, mock_utils_exit):
1642 expected_msg = ('REMOTE GlANCE REGION and REMOTE IMAGE ID are '
1643 'required for glance-download import method. '
1644 'Please use --remote-region <region> and '
1645 '--remote-image-id <remote-image-id>.')
1646 my_args = self.base_args.copy()
1647 my_args['import_method'] = 'glance-download'
1648 args = self._make_args(my_args)
1649 mock_stdin.isatty = lambda: True
1650 mock_utils_exit.side_effect = self._mock_utils_exit
1651 with mock.patch.object(self.gc.images,
1652 'get_import_info') as mocked_info:
1653 mocked_info.return_value = self.import_info_response
1654 try:
1655 test_shell.do_image_create_via_import(self.gc, args)
1656 self.fail("utils.exit should have been called")
1657 except SystemExit:
1658 pass
1659 mock_utils_exit.assert_called_once_with(expected_msg)
1660
1661 @mock.patch('glanceclient.common.utils.exit')
1662 @mock.patch('sys.stdin', autospec=True)
1663 def test_neg_image_create_via_import_glance_download_with_uri(
1664 self, mock_stdin, mock_utils_exit):
1665 expected_msg = ('You cannot specify a --uri with the '
1666 'glance-download import method.')
1667 my_args = self.base_args.copy()
1668 my_args['import_method'] = 'glance-download'
1669 my_args['remote_region'] = 'REGION2'
1670 my_args['remote_image_id'] = 'IMG2'
1671 my_args['uri'] = 'https://example.com/some/stuff'
1672 args = self._make_args(my_args)
1673 mock_stdin.isatty = lambda: True
1674 mock_utils_exit.side_effect = self._mock_utils_exit
1675 with mock.patch.object(self.gc.images,
1676 'get_import_info') as mocked_info:
1677 mocked_info.return_value = self.import_info_response
1678 try:
1679 test_shell.do_image_create_via_import(self.gc, args)
1680 self.fail("utils.exit should have been called")
1681 except SystemExit:
1682 pass
1683 mock_utils_exit.assert_called_once_with(expected_msg)
1684
1685 @mock.patch('glanceclient.common.utils.exit')
1686 @mock.patch('sys.stdin', autospec=True)
1687 def test_neg_image_create_via_import_glance_download_with_file(
1688 self, mock_stdin, mock_utils_exit):
1689 expected_msg = ('You cannot specify a --file with the '
1690 'glance-download import method.')
1691 my_args = self.base_args.copy()
1692 my_args['import_method'] = 'glance-download'
1693 my_args['remote_region'] = 'REGION2'
1694 my_args['remote_image_id'] = 'IMG2'
1695 my_args['file'] = 'my.browncow'
1696 args = self._make_args(my_args)
1697 mock_stdin.isatty = lambda: True
1698 mock_utils_exit.side_effect = self._mock_utils_exit
1699 with mock.patch.object(self.gc.images,
1700 'get_import_info') as mocked_info:
1701 mocked_info.return_value = self.import_info_response
1702 try:
1703 test_shell.do_image_create_via_import(self.gc, args)
1704 self.fail("utils.exit should have been called")
1705 except SystemExit:
1706 pass
1707 mock_utils_exit.assert_called_once_with(expected_msg)
1708
1709 @mock.patch('glanceclient.common.utils.exit')
1710 @mock.patch('sys.stdin', autospec=True)
1711 def test_neg_image_create_via_import_glance_download_with_data(
1712 self, mock_stdin, mock_utils_exit):
1713 expected_msg = ('You cannot pass data via stdin with the '
1714 'glance-download import method.')
1715 my_args = self.base_args.copy()
1716 my_args['import_method'] = 'glance-download'
1717 my_args['remote_region'] = 'REGION2'
1718 my_args['remote_image_id'] = 'IMG2'
1719 args = self._make_args(my_args)
1720 mock_stdin.isatty = lambda: False
1721 mock_utils_exit.side_effect = self._mock_utils_exit
1722 with mock.patch.object(self.gc.images,
1723 'get_import_info') as mocked_info:
1724 mocked_info.return_value = self.import_info_response
1725 try:
1726 test_shell.do_image_create_via_import(self.gc, args)
1727 self.fail("utils.exit should have been called")
1728 except SystemExit:
1729 pass
1730 mock_utils_exit.assert_called_once_with(expected_msg)
1731
1732 @mock.patch('glanceclient.common.utils.exit')
1733 @mock.patch('sys.stdin', autospec=True)
1734 def test_neg_image_create_via_import_bad_method(
1735 self, mock_stdin, mock_utils_exit):
1736 expected_msg = ('Import method \'swift-party-time\' is not valid '
1737 'for this cloud. Valid values can be retrieved with '
1738 'import-info command.')
1739 my_args = self.base_args.copy()
1740 my_args['import_method'] = 'swift-party-time'
1741 args = self._make_args(my_args)
1742 mock_stdin.isatty = lambda: True
1743 mock_utils_exit.side_effect = self._mock_utils_exit
1744 with mock.patch.object(self.gc.images,
1745 'get_import_info') as mocked_info:
1746 mocked_info.return_value = self.import_info_response
1747 try:
1748 test_shell.do_image_create_via_import(self.gc, args)
1749 self.fail("utils.exit should have been called")
1750 except SystemExit:
1751 pass
1752 mock_utils_exit.assert_called_once_with(expected_msg)
1753
1754 @mock.patch('glanceclient.common.utils.exit')
1755 @mock.patch('sys.stdin', autospec=True)
1756 def test_neg_image_create_via_import_no_method_with_data_and_method_NA(
1757 self, mock_stdin, mock_utils_exit):
1758 expected_msg = ('Import method \'glance-direct\' is not valid '
1759 'for this cloud. Valid values can be retrieved with '
1760 'import-info command.')
1761 args = self._make_args(self.base_args)
1762 # need to fake some data, or this is "just like" a
1763 # create-image-record-only call
1764 mock_stdin.isatty = lambda: False
1765 mock_utils_exit.side_effect = self._mock_utils_exit
1766 my_import_info_response = deepcopy(self.import_info_response)
1767 my_import_info_response['import-methods']['value'] = ['web-download']
1768 with mock.patch.object(self.gc.images,
1769 'get_import_info') as mocked_info:
1770 mocked_info.return_value = my_import_info_response
1771 try:
1772 test_shell.do_image_create_via_import(self.gc, args)
1773 self.fail("utils.exit should have been called")
1774 except SystemExit:
1775 pass
1776 mock_utils_exit.assert_called_once_with(expected_msg)
1777
1778 @mock.patch('glanceclient.common.utils.exit')
1779 @mock.patch('sys.stdin', autospec=True)
1780 def test_neg_image_create_via_import_good_method_not_available(
1781 self, mock_stdin, mock_utils_exit):
1782 """Make sure the good method names aren't hard coded somewhere"""
1783 expected_msg = ('Import method \'glance-direct\' is not valid for '
1784 'this cloud. Valid values can be retrieved with '
1785 'import-info command.')
1786 my_args = self.base_args.copy()
1787 my_args['import_method'] = 'glance-direct'
1788 args = self._make_args(my_args)
1789 mock_stdin.isatty = lambda: True
1790 mock_utils_exit.side_effect = self._mock_utils_exit
1791 my_import_info_response = deepcopy(self.import_info_response)
1792 my_import_info_response['import-methods']['value'] = ['bad-bad-method']
1793 with mock.patch.object(self.gc.images,
1794 'get_import_info') as mocked_info:
1795 mocked_info.return_value = my_import_info_response
1796 try:
1797 test_shell.do_image_create_via_import(self.gc, args)
1798 self.fail("utils.exit should have been called")
1799 except SystemExit:
1800 pass
1801 mock_utils_exit.assert_called_once_with(expected_msg)
1802
1803 @mock.patch('glanceclient.v2.shell.do_image_import')
1804 @mock.patch('glanceclient.v2.shell.do_image_stage')
1805 @mock.patch('sys.stdin', autospec=True)
1806 def test_image_create_via_import_no_method_with_stdin(
1807 self, mock_stdin, mock_do_stage, mock_do_import):
1808 """Backward compat -> handle this like a glance-direct"""
1809 mock_stdin.isatty = lambda: False
1810 self.mock_get_data_file.return_value = io.StringIO()
1811 args = self._make_args(self.base_args)
1812 with mock.patch.object(self.gc.images, 'create') as mocked_create:
1813 with mock.patch.object(self.gc.images, 'get') as mocked_get:
1814 with mock.patch.object(self.gc.images,
1815 'get_import_info') as mocked_info:
1816
1817 ignore_fields = ['self', 'access', 'schema']
1818 expect_image = dict([(field, field) for field in
1819 ignore_fields])
1820 expect_image['id'] = 'via-stdin'
1821 expect_image['name'] = 'Mortimer'
1822 expect_image['disk_format'] = 'raw'
1823 expect_image['container_format'] = 'bare'
1824 mocked_create.return_value = expect_image
1825 mocked_get.return_value = expect_image
1826 mocked_info.return_value = self.import_info_response
1827
1828 test_shell.do_image_create_via_import(self.gc, args)
1829 mocked_create.assert_called_once()
1830 mock_do_stage.assert_called_once()
1831 mock_do_import.assert_called_once()
1832 mocked_get.assert_called_with('via-stdin')
1833 utils.print_dict.assert_called_with({
1834 'id': 'via-stdin', 'name': 'Mortimer',
1835 'disk_format': 'raw', 'container_format': 'bare'})
1836
1837 def _image_create_via_import_with_file_helper(
1838 self, with_access=True):
1839 """Helper for image create via import with file tests."""
1840 @mock.patch('glanceclient.common.utils.get_file_size')
1841 @mock.patch('glanceclient.v2.shell.do_image_import')
1842 @mock.patch('os.access')
1843 @mock.patch('sys.stdin', autospec=True)
1844 def _test_with_access(mock_stdin, mock_access,
1845 mock_do_import, mock_size):
1846 mock_stdin.isatty = lambda: True
1847 self.mock_get_data_file.return_value = io.StringIO()
1848 mock_access.return_value = with_access
1849 mock_size.return_value = 14
1850 with open(tempfile.mktemp(), 'w+') as f:
1851 f.write('Some data here')
1852 f.flush()
1853 f.seek(0)
1854 file_name = f.name
1855 self.addCleanup(
1856 lambda: os.remove(file_name) if os.path.exists(
1857 file_name) else None)
1858 my_args = self.base_args.copy()
1859 my_args.update({'file': file_name})
1860 args = self._make_args(my_args)
1861 with mock.patch.object(
1862 self.gc.images, 'create') as mocked_create, \
1863 mock.patch.object(
1864 self.gc.images, 'get') as mocked_get, \
1865 mock.patch.object(
1866 self.gc.images, 'get_import_info') as mocked_info:
1867 ignore_fields = ['self', 'access', 'schema']
1868 expect_image = dict(
1869 [(field, field) for field in ignore_fields])
1870 expect_image['id'] = 'fake-image-id'
1871 expect_image['name'] = 'Mortimer'
1872 expect_image['disk_format'] = 'raw'
1873 expect_image['container_format'] = 'bare'
1874 mocked_create.return_value = expect_image
1875 mocked_get.return_value = expect_image
1876 mocked_info.return_value = self.import_info_response
1877
1878 test_shell.do_image_create_via_import(self.gc, args)
1879 mocked_create.assert_called_once()
1880 mock_do_import.assert_called_once()
1881 mocked_get.assert_called_with(expect_image['id'])
1882 mock_size.assert_called_once()
1883 utils.print_dict.assert_called_with({
1884 'id': expect_image['id'], 'name': 'Mortimer',
1885 'disk_format': 'raw', 'container_format': 'bare'
1886 })
1887
1888 _test_with_access()
1889
1890 def test_image_create_via_import_with_file(self):
1891 self._image_create_via_import_with_file_helper()
1892
1893 def test_do_image_create_via_import_with_size_exits(self):
1894 args = self._make_args({'name': 'test-image', 'size': 1234})
1895 expected_msg = ("Setting 'size' during image creation is not "
1896 "supported. Please use --size only when "
1897 "uploading data.")
1898 with mock.patch('glanceclient.common.utils.exit') as mock_exit:
1899 mock_exit.side_effect = self._mock_utils_exit
1900 try:
1901 test_shell.do_image_create(self.gc, args)
1902 self.fail("utils.exit should have been called")
1903 except SystemExit:
1904 pass
1905
1906 mock_exit.assert_called_once_with(expected_msg)
1907
1908 @mock.patch('glanceclient.v2.shell.do_image_import')
1909 @mock.patch('glanceclient.v2.shell.do_image_stage')
1910 @mock.patch('os.access')
1911 @mock.patch('sys.stdin', autospec=True)
1912 def test_image_create_via_import_no_method_passing_file(
1913 self, mock_stdin, mock_access, mock_do_stage, mock_do_import):
1914 """Backward compat -> handle this like a glance-direct"""
1915 mock_stdin.isatty = lambda: True
1916 self.mock_get_data_file.return_value = io.StringIO()
1917 mock_access.return_value = True
1918 my_args = self.base_args.copy()
1919 my_args['file'] = 'fake-image-file.browncow'
1920 args = self._make_args(my_args)
1921 with mock.patch.object(self.gc.images, 'create') as mocked_create:
1922 with mock.patch.object(self.gc.images, 'get') as mocked_get:
1923 with mock.patch.object(self.gc.images,
1924 'get_import_info') as mocked_info:
1925
1926 ignore_fields = ['self', 'access', 'schema']
1927 expect_image = dict([(field, field) for field in
1928 ignore_fields])
1929 expect_image['id'] = 'via-file'
1930 expect_image['name'] = 'Mortimer'
1931 expect_image['disk_format'] = 'raw'
1932 expect_image['container_format'] = 'bare'
1933 mocked_create.return_value = expect_image
1934 mocked_get.return_value = expect_image
1935 mocked_info.return_value = self.import_info_response
1936
1937 test_shell.do_image_create_via_import(self.gc, args)
1938 mocked_create.assert_called_once()
1939 mock_do_stage.assert_called_once()
1940 mock_do_import.assert_called_once()
1941 mocked_get.assert_called_with('via-file')
1942 utils.print_dict.assert_called_with({
1943 'id': 'via-file', 'name': 'Mortimer',
1944 'disk_format': 'raw', 'container_format': 'bare'})
1945
1946 @mock.patch('glanceclient.v2.shell.do_image_import')
1947 @mock.patch('glanceclient.v2.shell.do_image_stage')
1948 @mock.patch('sys.stdin', autospec=True)
1949 def test_do_image_create_via_import_with_no_method_no_data(
1950 self, mock_stdin, mock_do_image_stage, mock_do_image_import):
1951 """Create an image record without calling do_stage or do_import"""
1952 img_create_args = {'name': 'IMG-11',
1953 'os_architecture': 'powerpc',
1954 'id': 'watch-out-for-ossn-0075',
1955 'progress': False}
1956 client_args = {'import_method': None,
1957 'file': None,
1958 'uri': None}
1959 temp_args = img_create_args.copy()
1960 temp_args.update(client_args)
1961 args = self._make_args(temp_args)
1962 with mock.patch.object(self.gc.images, 'create') as mocked_create:
1963 with mock.patch.object(self.gc.images, 'get') as mocked_get:
1964 with mock.patch.object(self.gc.images,
1965 'get_import_info') as mocked_info:
1966
1967 ignore_fields = ['self', 'access', 'schema']
1968 expect_image = dict([(field, field) for field in
1969 ignore_fields])
1970 expect_image['name'] = 'IMG-11'
1971 expect_image['id'] = 'watch-out-for-ossn-0075'
1972 expect_image['os_architecture'] = 'powerpc'
1973 mocked_create.return_value = expect_image
1974 mocked_get.return_value = expect_image
1975 mocked_info.return_value = self.import_info_response
1976 mock_stdin.isatty = lambda: True
1977
1978 test_shell.do_image_create_via_import(self.gc, args)
1979 mocked_create.assert_called_once_with(**img_create_args)
1980 mocked_get.assert_called_with('watch-out-for-ossn-0075')
1981 mock_do_image_stage.assert_not_called()
1982 mock_do_image_import.assert_not_called()
1983 utils.print_dict.assert_called_with({
1984 'name': 'IMG-11', 'os_architecture': 'powerpc',
1985 'id': 'watch-out-for-ossn-0075'})
1986
1987 @mock.patch('glanceclient.v2.shell.do_image_import')
1988 @mock.patch('glanceclient.v2.shell.do_image_stage')
1989 @mock.patch('sys.stdin', autospec=True)
1990 def test_do_image_create_via_import_with_web_download(
1991 self, mock_stdin, mock_do_image_stage, mock_do_image_import):
1992 temp_args = {'name': 'IMG-01',
1993 'disk_format': 'vhd',
1994 'container_format': 'bare',
1995 'uri': 'http://example.com/image.qcow',
1996 'import_method': 'web-download',
1997 'progress': False}
1998 args = self._make_args(temp_args)
1999 with mock.patch.object(self.gc.images, 'create') as mocked_create:
2000 with mock.patch.object(self.gc.images, 'get') as mocked_get:
2001 with mock.patch.object(self.gc.images,
2002 'get_import_info') as mocked_info:
2003
2004 ignore_fields = ['self', 'access', 'schema']
2005 expect_image = dict([(field, field) for field in
2006 ignore_fields])
2007 expect_image['id'] = 'pass'
2008 expect_image['name'] = 'IMG-01'
2009 expect_image['disk_format'] = 'vhd'
2010 expect_image['container_format'] = 'bare'
2011 expect_image['status'] = 'queued'
2012 mocked_create.return_value = expect_image
2013 mocked_get.return_value = expect_image
2014 mocked_info.return_value = self.import_info_response
2015 mock_stdin.isatty = lambda: True
2016
2017 test_shell.do_image_create_via_import(self.gc, args)
2018 mock_do_image_stage.assert_not_called()
2019 mock_do_image_import.assert_called_once()
2020 mocked_create.assert_called_once_with(**temp_args)
2021 mocked_get.assert_called_with('pass')
2022 utils.print_dict.assert_called_with({
2023 'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd',
2024 'container_format': 'bare', 'status': 'queued'})
2025
2026 @mock.patch('glanceclient.v2.shell.do_image_import')
2027 @mock.patch('glanceclient.v2.shell.do_image_stage')
2028 @mock.patch('sys.stdin', autospec=True)
2029 def test_do_image_create_via_import_with_web_download_with_stores(
2030 self, mock_stdin, mock_do_image_stage, mock_do_image_import):
2031 temp_args = {'name': 'IMG-01',
2032 'disk_format': 'vhd',
2033 'container_format': 'bare',
2034 'uri': 'http://example.com/image.qcow',
2035 'import_method': 'web-download',
2036 'progress': False,
2037 'stores': 'file1,file2'}
2038 tmp2_args = {'name': 'IMG-01',
2039 'disk_format': 'vhd',
2040 'container_format': 'bare',
2041 'uri': 'http://example.com/image.qcow',
2042 'import_method': 'web-download',
2043 'progress': False}
2044 args = self._make_args(temp_args)
2045 with mock.patch.object(self.gc.images, 'create') as mocked_create:
2046 with mock.patch.object(self.gc.images, 'get') as mocked_get:
2047 with mock.patch.object(self.gc.images,
2048 'get_import_info') as mocked_info:
2049 with mock.patch.object(self.gc.images,
2050 'get_stores_info') as m_stores_info:
2051
2052 ignore_fields = ['self', 'access', 'schema']
2053 expect_image = dict([(field, field) for field in
2054 ignore_fields])
2055 expect_image['id'] = 'pass'
2056 expect_image['name'] = 'IMG-01'
2057 expect_image['disk_format'] = 'vhd'
2058 expect_image['container_format'] = 'bare'
2059 expect_image['status'] = 'queued'
2060 mocked_create.return_value = expect_image
2061 mocked_get.return_value = expect_image
2062 mocked_info.return_value = self.import_info_response
2063 m_stores_info.return_value = self.stores_info_response
2064 mock_stdin.isatty = lambda: True
2065
2066 test_shell.do_image_create_via_import(self.gc, args)
2067 mock_do_image_stage.assert_not_called()
2068 mock_do_image_import.assert_called_once()
2069 mocked_create.assert_called_once_with(**tmp2_args)
2070 mocked_get.assert_called_with('pass')
2071 utils.print_dict.assert_called_with({
2072 'id': 'pass', 'name': 'IMG-01',
2073 'disk_format': 'vhd',
2074 'container_format': 'bare', 'status': 'queued'})
2075
2076 def test_do_image_update_no_user_props(self):
2077 args = self._make_args({'id': 'pass', 'name': 'IMG-01',
2078 'disk_format': 'vhd',
2079 'container_format': 'bare'})
2080 with mock.patch.object(self.gc.images, 'update') as mocked_update:
2081 ignore_fields = ['self', 'access', 'file', 'schema']
2082 expect_image = dict([(field, field) for field in ignore_fields])
2083 expect_image['id'] = 'pass'
2084 expect_image['name'] = 'IMG-01'
2085 expect_image['disk_format'] = 'vhd'
2086 expect_image['container_format'] = 'bare'
2087 mocked_update.return_value = expect_image
2088
2089 test_shell.do_image_update(self.gc, args)
2090
2091 mocked_update.assert_called_once_with('pass',
2092 None,
2093 name='IMG-01',
2094 disk_format='vhd',
2095 container_format='bare')
2096 utils.print_dict.assert_called_once_with({
2097 'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd',
2098 'container_format': 'bare'})
2099
2100 def test_do_image_update_hide_image(self):
2101 args = self._make_args({'id': 'pass', 'os_hidden': 'true'})
2102 with mock.patch.object(self.gc.images, 'update') as mocked_update:
2103 ignore_fields = ['self', 'access', 'file', 'schema']
2104 expect_image = dict([(field, field) for field in ignore_fields])
2105 expect_image['id'] = 'pass'
2106 expect_image['name'] = 'IMG-01'
2107 expect_image['disk_format'] = 'vhd'
2108 expect_image['container_format'] = 'bare'
2109 expect_image['os_hidden'] = True
2110 mocked_update.return_value = expect_image
2111
2112 test_shell.do_image_update(self.gc, args)
2113
2114 mocked_update.assert_called_once_with('pass',
2115 None,
2116 os_hidden='true')
2117 utils.print_dict.assert_called_once_with({
2118 'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd',
2119 'container_format': 'bare', 'os_hidden': True})
2120
2121 def test_do_image_update_revert_hide_image(self):
2122 args = self._make_args({'id': 'pass', 'os_hidden': 'false'})
2123 with mock.patch.object(self.gc.images, 'update') as mocked_update:
2124 ignore_fields = ['self', 'access', 'file', 'schema']
2125 expect_image = dict([(field, field) for field in ignore_fields])
2126 expect_image['id'] = 'pass'
2127 expect_image['name'] = 'IMG-01'
2128 expect_image['disk_format'] = 'vhd'
2129 expect_image['container_format'] = 'bare'
2130 expect_image['os_hidden'] = False
2131 mocked_update.return_value = expect_image
2132
2133 test_shell.do_image_update(self.gc, args)
2134
2135 mocked_update.assert_called_once_with('pass',
2136 None,
2137 os_hidden='false')
2138 utils.print_dict.assert_called_once_with({
2139 'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd',
2140 'container_format': 'bare', 'os_hidden': False})
2141
2142 def test_do_image_update_with_user_props(self):
2143 args = self._make_args({'id': 'pass', 'name': 'IMG-01',
2144 'property': ['myprop=myval']})
2145 with mock.patch.object(self.gc.images, 'update') as mocked_update:
2146 ignore_fields = ['self', 'access', 'file', 'schema']
2147 expect_image = dict([(field, field) for field in ignore_fields])
2148 expect_image['id'] = 'pass'
2149 expect_image['name'] = 'IMG-01'
2150 expect_image['myprop'] = 'myval'
2151 mocked_update.return_value = expect_image
2152
2153 test_shell.do_image_update(self.gc, args)
2154
2155 mocked_update.assert_called_once_with('pass',
2156 None,
2157 name='IMG-01',
2158 myprop='myval')
2159 utils.print_dict.assert_called_once_with({
2160 'id': 'pass', 'name': 'IMG-01', 'myprop': 'myval'})
2161
2162 def test_do_image_update_with_remove_props(self):
2163 args = self._make_args({'id': 'pass', 'name': 'IMG-01',
2164 'disk_format': 'vhd',
2165 'remove-property': ['container_format']})
2166 with mock.patch.object(self.gc.images, 'update') as mocked_update:
2167 ignore_fields = ['self', 'access', 'file', 'schema']
2168 expect_image = dict([(field, field) for field in ignore_fields])
2169 expect_image['id'] = 'pass'
2170 expect_image['name'] = 'IMG-01'
2171 expect_image['disk_format'] = 'vhd'
2172
2173 mocked_update.return_value = expect_image
2174
2175 test_shell.do_image_update(self.gc, args)
2176
2177 mocked_update.assert_called_once_with('pass',
2178 ['container_format'],
2179 name='IMG-01',
2180 disk_format='vhd')
2181 utils.print_dict.assert_called_once_with({
2182 'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd'})
2183
2184 def test_do_explain(self):
2185 input = {
2186 'page_size': 18,
2187 'id': 'pass',
2188 'schemas': 'test',
2189 'model': 'test',
2190 }
2191 args = self._make_args(input)
2192 with mock.patch.object(utils, 'print_list'):
2193 test_shell.do_explain(self.gc, args)
2194
2195 self.gc.schemas.get.assert_called_once_with('test')
2196
2197 def test_do_location_add(self):
2198 gc = self.gc
2199 loc = {'url': 'http://foo.com/',
2200 'metadata': {'foo': 'bar'},
2201 'validation_data': {'checksum': 'csum',
2202 'os_hash_algo': 'algo',
2203 'os_hash_value': 'value'}}
2204 args = {'id': 'pass',
2205 'url': loc['url'],
2206 'metadata': json.dumps(loc['metadata']),
2207 'checksum': 'csum',
2208 'hash_algo': 'algo',
2209 'hash_value': 'value'}
2210 with mock.patch.object(gc.images, 'add_location') as mocked_addloc:
2211 expect_image = {'id': 'pass', 'locations': [loc]}
2212 mocked_addloc.return_value = expect_image
2213
2214 test_shell.do_location_add(self.gc, self._make_args(args))
2215 mocked_addloc.assert_called_once_with(
2216 'pass', loc['url'], loc['metadata'],
2217 validation_data=loc['validation_data'])
2218 utils.print_dict.assert_called_once_with(expect_image)
2219
2220 def test_do_location_delete(self):
2221 gc = self.gc
2222 loc_set = set(['http://foo/bar', 'http://spam/ham'])
2223 args = self._make_args({'id': 'pass', 'url': loc_set})
2224
2225 with mock.patch.object(gc.images, 'delete_locations') as mocked_rmloc:
2226 test_shell.do_location_delete(self.gc, args)
2227 mocked_rmloc.assert_called_once_with('pass', loc_set)
2228
2229 def test_do_location_update(self):
2230 gc = self.gc
2231 loc = {'url': 'http://foo.com/', 'metadata': {'foo': 'bar'}}
2232 args = self._make_args({'id': 'pass',
2233 'url': loc['url'],
2234 'metadata': json.dumps(loc['metadata'])})
2235 with mock.patch.object(gc.images, 'update_location') as mocked_modloc:
2236 expect_image = {'id': 'pass', 'locations': [loc]}
2237 mocked_modloc.return_value = expect_image
2238
2239 test_shell.do_location_update(self.gc, args)
2240 mocked_modloc.assert_called_once_with('pass',
2241 loc['url'],
2242 loc['metadata'])
2243 utils.print_dict.assert_called_once_with(expect_image)
2244
2245 def test_do_add_location(self):
2246 gc = self.gc
2247 url = 'http://foo.com/',
2248 validation_data = {'os_hash_algo': 'sha512',
2249 'os_hash_value': 'value'}
2250 args = {'id': 'IMG-01',
2251 'url': url,
2252 'validation_data': json.dumps(validation_data)}
2253 with mock.patch.object(gc.images,
2254 'add_image_location') as mock_addloc:
2255 expect_image = {'id': 'pass'}
2256 mock_addloc.return_value = expect_image
2257
2258 test_shell.do_add_location(self.gc, self._make_args(args))
2259 mock_addloc.assert_called_once_with(
2260 'IMG-01', url, validation_data=validation_data)
2261 utils.print_dict.assert_called_once_with(expect_image)
2262
2263 @mock.patch('glanceclient.common.utils.exit')
2264 def test_do_add_location_with_checksum_in_validation_data(self,
2265 mock_exit):
2266 validation_data = {'checksum': 'value',
2267 'os_hash_algo': 'sha512',
2268 'os_hash_value': 'value'}
2269
2270 args = self._make_args(
2271 {'id': 'IMG-01', 'url': 'http://foo.com/',
2272 'validation_data': json.dumps(validation_data)})
2273 expected_msg = ('Validation Data should contain only os_hash_algo'
2274 ' and os_hash_value. `checksum` is not allowed')
2275 mock_exit.side_effect = self._mock_utils_exit
2276 try:
2277 test_shell.do_add_location(self.gc, args)
2278 self.fail("utils.exit should have been called")
2279 except SystemExit:
2280 pass
2281
2282 mock_exit.assert_called_once_with(expected_msg)
2283
2284 @mock.patch('glanceclient.common.utils.exit')
2285 def test_do_add_location_with_invalid_algo_in_validation_data(self,
2286 mock_exit):
2287 validation_data = {'os_hash_algo': 'algo',
2288 'os_hash_value': 'value'}
2289
2290 args = self._make_args(
2291 {'id': 'IMG-01', 'url': 'http://foo.com/',
2292 'validation_data': json.dumps(validation_data)})
2293 allowed_hash_algo = ['sha512', 'sha256', 'sha1', 'md5']
2294 expected_msg = ('os_hash_algo: `%s` is incorrect, '
2295 'allowed hashing algorithms: %s' %
2296 (validation_data['os_hash_algo'],
2297 allowed_hash_algo))
2298 mock_exit.side_effect = self._mock_utils_exit
2299 try:
2300 test_shell.do_add_location(self.gc, args)
2301 self.fail("utils.exit should have been called")
2302 except SystemExit:
2303 pass
2304
2305 mock_exit.assert_called_once_with(expected_msg)
2306
2307 def test_image_upload(self):
2308 args = self._make_args(
2309 {'id': 'IMG-01', 'file': 'test', 'size': 1024, 'progress': False})
2310
2311 with mock.patch.object(self.gc.images, 'upload') as mocked_upload:
2312 expected_data = '*' * 1024
2313 utils.get_data_file = mock.Mock(return_value=expected_data)
2314 utils.get_file_size = mock.Mock(return_value=1024)
2315 mocked_upload.return_value = None
2316 test_shell.do_image_upload(self.gc, args)
2317 mocked_upload.assert_called_once_with('IMG-01', expected_data,
2318 1024, backend=None)
2319
2320 @mock.patch('glanceclient.common.utils.exit')
2321 def test_image_upload_invalid_store(self, mock_utils_exit):
2322 expected_msg = ("Store 'dummy' is not valid for this cloud. "
2323 "Valid values can be retrieved with stores-info "
2324 "command.")
2325 mock_utils_exit.side_effect = self._mock_utils_exit
2326
2327 args = self._make_args(
2328 {'id': 'IMG-01', 'file': 'test', 'size': 1024, 'progress': False,
2329 'store': 'dummy'})
2330
2331 with mock.patch.object(self.gc.images,
2332 'get_stores_info') as mock_stores_info:
2333 mock_stores_info.return_value = self.stores_info_response
2334 try:
2335 test_shell.do_image_upload(self.gc, args)
2336 self.fail("utils.exit should have been called")
2337 except SystemExit:
2338 pass
2339
2340 mock_utils_exit.assert_called_once_with(expected_msg)
2341
2342 @mock.patch('glanceclient.common.utils.exit')
2343 def test_neg_image_import_not_available(self, mock_utils_exit):
2344 expected_msg = 'Target Glance does not support Image Import workflow'
2345 mock_utils_exit.side_effect = self._mock_utils_exit
2346 args = self._make_args(
2347 {'id': 'IMG-01', 'import_method': 'smarty-pants', 'uri': None})
2348 with mock.patch.object(self.gc.images, 'import') as mocked_import:
2349 with mock.patch.object(self.gc.images,
2350 'get_import_info') as mocked_info:
2351 mocked_info.side_effect = exc.HTTPNotFound
2352 try:
2353 test_shell.do_image_import(self.gc, args)
2354 self.fail("utils.exit should have been called")
2355 except SystemExit:
2356 pass
2357 mock_utils_exit.assert_called_once_with(expected_msg)
2358 mocked_import.assert_not_called()
2359
2360 @mock.patch('glanceclient.common.utils.exit')
2361 def test_neg_image_import_bad_method(self, mock_utils_exit):
2362 expected_msg = ('Import method \'smarty-pants\' is not valid for this '
2363 'cloud. Valid values can be retrieved with '
2364 'import-info command.')
2365 mock_utils_exit.side_effect = self._mock_utils_exit
2366 args = self._make_args(
2367 {'id': 'IMG-01', 'import_method': 'smarty-pants', 'uri': None})
2368 with mock.patch.object(self.gc.images,
2369 'get_import_info') as mocked_info:
2370 mocked_info.return_value = self.import_info_response
2371 try:
2372 test_shell.do_image_import(self.gc, args)
2373 self.fail("utils.exit should have been called")
2374 except SystemExit:
2375 pass
2376 mock_utils_exit.assert_called_once_with(expected_msg)
2377
2378 @mock.patch('glanceclient.common.utils.exit')
2379 def test_neg_image_import_no_methods_configured(self, mock_utils_exit):
2380 expected_msg = ('Import method \'glance-direct\' is not valid for '
2381 'this cloud. Valid values can be retrieved with '
2382 'import-info command.')
2383 mock_utils_exit.side_effect = self._mock_utils_exit
2384 args = self._make_args(
2385 {'id': 'IMG-01', 'import_method': 'glance-direct', 'uri': None})
2386 with mock.patch.object(self.gc.images,
2387 'get_import_info') as mocked_info:
2388 mocked_info.return_value = {"import-methods": {"value": []}}
2389 try:
2390 test_shell.do_image_import(self.gc, args)
2391 self.fail("utils.exit should have been called")
2392 except SystemExit:
2393 pass
2394 mock_utils_exit.assert_called_once_with(expected_msg)
2395
2396 @mock.patch('glanceclient.common.utils.exit')
2397 def test_neg_image_import_glance_direct_image_not_uploading_status(
2398 self, mock_utils_exit):
2399 expected_msg = ('The \'glance-direct\' import method can only be '
2400 'applied to an image in status \'uploading\'')
2401 mock_utils_exit.side_effect = self._mock_utils_exit
2402 args = self._make_args(
2403 {'id': 'IMG-01', 'import_method': 'glance-direct', 'uri': None})
2404 with mock.patch.object(self.gc.images,
2405 'get_import_info') as mocked_info:
2406 with mock.patch.object(self.gc.images, 'get') as mocked_get:
2407 mocked_get.return_value = {'status': 'queued',
2408 'container_format': 'bare',
2409 'disk_format': 'raw'}
2410 mocked_info.return_value = self.import_info_response
2411 try:
2412 test_shell.do_image_import(self.gc, args)
2413 self.fail("utils.exit should have been called")
2414 except SystemExit:
2415 pass
2416 mock_utils_exit.assert_called_once_with(expected_msg)
2417
2418 @mock.patch('glanceclient.common.utils.exit')
2419 def test_neg_image_import_web_download_image_not_queued_status(
2420 self, mock_utils_exit):
2421 expected_msg = ('The \'web-download\' import method can only be '
2422 'applied to an image in status \'queued\'')
2423 mock_utils_exit.side_effect = self._mock_utils_exit
2424 args = self._make_args(
2425 {'id': 'IMG-01', 'import_method': 'web-download',
2426 'uri': 'http://joes-image-shack.com/funky.qcow2'})
2427 with mock.patch.object(self.gc.images,
2428 'get_import_info') as mocked_info:
2429 with mock.patch.object(self.gc.images, 'get') as mocked_get:
2430 mocked_get.return_value = {'status': 'uploading',
2431 'container_format': 'bare',
2432 'disk_format': 'raw'}
2433 mocked_info.return_value = self.import_info_response
2434 try:
2435 test_shell.do_image_import(self.gc, args)
2436 self.fail("utils.exit should have been called")
2437 except SystemExit:
2438 pass
2439 mock_utils_exit.assert_called_once_with(expected_msg)
2440
2441 @mock.patch('glanceclient.common.utils.exit')
2442 def test_neg_image_import_image_no_container_format(
2443 self, mock_utils_exit):
2444 expected_msg = ('The \'container_format\' and \'disk_format\' '
2445 'properties must be set on an image before it can be '
2446 'imported.')
2447 mock_utils_exit.side_effect = self._mock_utils_exit
2448 args = self._make_args(
2449 {'id': 'IMG-01', 'import_method': 'web-download',
2450 'uri': 'http://joes-image-shack.com/funky.qcow2'})
2451 with mock.patch.object(self.gc.images,
2452 'get_import_info') as mocked_info:
2453 with mock.patch.object(self.gc.images, 'get') as mocked_get:
2454 mocked_get.return_value = {'status': 'uploading',
2455 'disk_format': 'raw'}
2456 mocked_info.return_value = self.import_info_response
2457 try:
2458 test_shell.do_image_import(self.gc, args)
2459 self.fail("utils.exit should have been called")
2460 except SystemExit:
2461 pass
2462 mock_utils_exit.assert_called_once_with(expected_msg)
2463
2464 @mock.patch('glanceclient.common.utils.exit')
2465 def test_neg_image_import_image_no_disk_format(
2466 self, mock_utils_exit):
2467 expected_msg = ('The \'container_format\' and \'disk_format\' '
2468 'properties must be set on an image before it can be '
2469 'imported.')
2470 mock_utils_exit.side_effect = self._mock_utils_exit
2471 args = self._make_args(
2472 {'id': 'IMG-01', 'import_method': 'web-download',
2473 'uri': 'http://joes-image-shack.com/funky.qcow2'})
2474 with mock.patch.object(self.gc.images,
2475 'get_import_info') as mocked_info:
2476 with mock.patch.object(self.gc.images, 'get') as mocked_get:
2477 mocked_get.return_value = {'status': 'uploading',
2478 'container_format': 'bare'}
2479 mocked_info.return_value = self.import_info_response
2480 try:
2481 test_shell.do_image_import(self.gc, args)
2482 self.fail("utils.exit should have been called")
2483 except SystemExit:
2484 pass
2485 mock_utils_exit.assert_called_once_with(expected_msg)
2486
2487 @mock.patch('glanceclient.common.utils.exit')
2488 def test_image_import_invalid_store(self, mock_utils_exit):
2489 expected_msg = ("Store 'dummy' is not valid for this cloud. "
2490 "Valid values can be retrieved with stores-info "
2491 "command.")
2492 mock_utils_exit.side_effect = self._mock_utils_exit
2493
2494 args = self._make_args(
2495 {'id': 'IMG-01', 'import_method': 'glance-direct', 'uri': None,
2496 'store': 'dummy'})
2497
2498 with mock.patch.object(self.gc.images, 'get') as mocked_get:
2499 with mock.patch.object(self.gc.images,
2500 'get_import_info') as mocked_info:
2501 mocked_get.return_value = {'status': 'uploading',
2502 'container_format': 'bare',
2503 'disk_format': 'raw'}
2504 with mock.patch.object(self.gc.images,
2505 'get_stores_info') as mock_stores_info:
2506 mocked_info.return_value = self.import_info_response
2507 mock_stores_info.return_value = self.stores_info_response
2508 try:
2509 test_shell.do_image_import(self.gc, args)
2510 self.fail("utils.exit should have been called")
2511 except SystemExit:
2512 pass
2513
2514 mock_utils_exit.assert_called_once_with(expected_msg)
2515
2516 def test_image_import_glance_direct(self):
2517 args = self._make_args(
2518 {'id': 'IMG-01', 'import_method': 'glance-direct', 'uri': None})
2519 with mock.patch.object(self.gc.images, 'image_import') as mock_import:
2520 with mock.patch.object(self.gc.images, 'get') as mocked_get:
2521 with mock.patch.object(self.gc.images,
2522 'get_import_info') as mocked_info:
2523 mocked_get.return_value = {'status': 'uploading',
2524 'container_format': 'bare',
2525 'disk_format': 'raw'}
2526 mocked_info.return_value = self.import_info_response
2527 mock_import.return_value = None
2528 test_shell.do_image_import(self.gc, args)
2529 mock_import.assert_called_once_with(
2530 'IMG-01', 'glance-direct', uri=None,
2531 remote_region=None, remote_image_id=None,
2532 remote_service_interface=None,
2533 backend=None, all_stores=None,
2534 allow_failure=True, stores=None)
2535
2536 def test_image_import_web_download(self):
2537 args = self._make_args(
2538 {'id': 'IMG-01', 'uri': 'http://example.com/image.qcow',
2539 'import_method': 'web-download'})
2540 with mock.patch.object(self.gc.images, 'image_import') as mock_import:
2541 with mock.patch.object(self.gc.images, 'get') as mocked_get:
2542 with mock.patch.object(self.gc.images,
2543 'get_import_info') as mocked_info:
2544 mocked_get.return_value = {'status': 'queued',
2545 'container_format': 'bare',
2546 'disk_format': 'raw'}
2547 mocked_info.return_value = self.import_info_response
2548 mock_import.return_value = None
2549 test_shell.do_image_import(self.gc, args)
2550 mock_import.assert_called_once_with(
2551 'IMG-01', 'web-download',
2552 uri='http://example.com/image.qcow',
2553 remote_region=None, remote_image_id=None,
2554 remote_service_interface=None,
2555 all_stores=None, allow_failure=True,
2556 backend=None, stores=None)
2557
2558 def test_image_import_glance_download(self):
2559 args = self._make_args(
2560 {'id': 'IMG-01', 'uri': None, 'remote_region': 'REGION2',
2561 'remote_image_id': 'IMG-02',
2562 'import_method': 'glance-download',
2563 'remote_service_interface': 'public'})
2564 with mock.patch.object(self.gc.images, 'image_import') as mock_import:
2565 with mock.patch.object(self.gc.images, 'get') as mocked_get:
2566 with mock.patch.object(self.gc.images,
2567 'get_import_info') as mocked_info:
2568 mocked_get.return_value = {'status': 'queued',
2569 'container_format': 'bare',
2570 'disk_format': 'raw'}
2571 mocked_info.return_value = self.import_info_response
2572 mock_import.return_value = None
2573 test_shell.do_image_import(self.gc, args)
2574 mock_import.assert_called_once_with(
2575 'IMG-01', 'glance-download',
2576 uri=None, remote_region='REGION2',
2577 remote_image_id='IMG-02',
2578 remote_service_interface='public',
2579 all_stores=None, allow_failure=True,
2580 backend=None, stores=None)
2581
2582 @mock.patch('glanceclient.common.utils.exit')
2583 def test_image_import_neg_no_glance_download_with_remote_region(
2584 self, mock_utils_exit):
2585 expected_msg = ("Import method should be 'glance-download' if "
2586 "REMOTE REGION is provided.")
2587 my_args = self.base_args.copy()
2588 my_args['id'] = 'IMG-01'
2589 my_args['remote_region'] = 'REGION2'
2590 my_args['import_method'] = 'web-download'
2591 my_args['uri'] = 'https://example.com/some/stuff'
2592 args = self._make_args(my_args)
2593 mock_utils_exit.side_effect = self._mock_utils_exit
2594 with mock.patch.object(self.gc.images,
2595 'get_import_info') as mocked_info:
2596 mocked_info.return_value = self.import_info_response
2597 try:
2598 test_shell.do_image_import(self.gc, args)
2599 self.fail("utils.exit should have been called")
2600 except SystemExit:
2601 pass
2602 mock_utils_exit.assert_called_once_with(expected_msg)
2603
2604 @mock.patch('glanceclient.common.utils.exit')
2605 def test_image_import_neg_no_glance_download_with_remote_id(
2606 self, mock_utils_exit):
2607 expected_msg = ("Import method should be 'glance-download' if "
2608 "REMOTE IMAGE ID is provided.")
2609 my_args = self.base_args.copy()
2610 my_args['id'] = 'IMG-01'
2611 my_args['remote_image_id'] = 'IMG-02'
2612 my_args['import_method'] = 'web-download'
2613 my_args['uri'] = 'https://example.com/some/stuff'
2614 args = self._make_args(my_args)
2615 mock_utils_exit.side_effect = self._mock_utils_exit
2616 with mock.patch.object(self.gc.images,
2617 'get_import_info') as mocked_info:
2618 mocked_info.return_value = self.import_info_response
2619 try:
2620 test_shell.do_image_import(self.gc, args)
2621 self.fail("utils.exit should have been called")
2622 except SystemExit:
2623 pass
2624 mock_utils_exit.assert_called_once_with(expected_msg)
2625
2626 def test_image_import_glance_download_without_remote_service_interface(
2627 self):
2628 args = self._make_args(
2629 {'id': 'IMG-01', 'uri': None, 'remote_region': 'REGION2',
2630 'remote_image_id': 'IMG-02',
2631 'import_method': 'glance-download'})
2632 with mock.patch.object(self.gc.images, 'image_import') as mock_import:
2633 with mock.patch.object(self.gc.images, 'get') as mocked_get:
2634 with mock.patch.object(self.gc.images,
2635 'get_import_info') as mocked_info:
2636 mocked_get.return_value = {'status': 'queued',
2637 'container_format': 'bare',
2638 'disk_format': 'raw'}
2639 mocked_info.return_value = self.import_info_response
2640 mock_import.return_value = None
2641 test_shell.do_image_import(self.gc, args)
2642 mock_import.assert_called_once_with(
2643 'IMG-01', 'glance-download',
2644 uri=None, remote_region='REGION2',
2645 remote_image_id='IMG-02',
2646 remote_service_interface=None,
2647 all_stores=None, allow_failure=True,
2648 backend=None, stores=None)
2649
2650 @mock.patch('glanceclient.common.utils.print_image')
2651 def test_image_import_no_print_image(self, mocked_utils_print_image):
2652 args = self._make_args(
2653 {'id': 'IMG-02', 'uri': None, 'import_method': 'glance-direct',
2654 'from_create': True})
2655 with mock.patch.object(self.gc.images, 'image_import') as mock_import:
2656 with mock.patch.object(self.gc.images, 'get') as mocked_get:
2657 with mock.patch.object(self.gc.images,
2658 'get_import_info') as mocked_info:
2659 mocked_get.return_value = {'status': 'uploading',
2660 'container_format': 'bare',
2661 'disk_format': 'raw'}
2662 mocked_info.return_value = self.import_info_response
2663 mock_import.return_value = None
2664 test_shell.do_image_import(self.gc, args)
2665 mock_import.assert_called_once_with(
2666 'IMG-02', 'glance-direct', None, stores=None,
2667 all_stores=None, allow_failure=True,
2668 remote_region=None, remote_image_id=None,
2669 remote_service_interface=None, backend=None)
2670 mocked_utils_print_image.assert_not_called()
2671
2672 @mock.patch('glanceclient.common.utils.print_image')
2673 @mock.patch('glanceclient.v2.shell._validate_backend')
2674 def test_image_import_multiple_stores(self, mocked_utils_print_image,
2675 msvb):
2676 args = self._make_args(
2677 {'id': 'IMG-02', 'uri': None, 'import_method': 'glance-direct',
2678 'from_create': False, 'stores': 'site1,site2'})
2679 with mock.patch.object(self.gc.images, 'image_import') as mock_import:
2680 with mock.patch.object(self.gc.images, 'get') as mocked_get:
2681 with mock.patch.object(self.gc.images,
2682 'get_import_info') as mocked_info:
2683 mocked_get.return_value = {'status': 'uploading',
2684 'container_format': 'bare',
2685 'disk_format': 'raw'}
2686 mocked_info.return_value = self.import_info_response
2687 mock_import.return_value = None
2688 test_shell.do_image_import(self.gc, args)
2689 mock_import.assert_called_once_with(
2690 'IMG-02', 'glance-direct', uri=None,
2691 remote_region=None, remote_image_id=None,
2692 remote_service_interface=None,
2693 all_stores=None, allow_failure=True,
2694 stores=['site1', 'site2'], backend=None)
2695
2696 @mock.patch('glanceclient.common.utils.print_image')
2697 @mock.patch('glanceclient.v2.shell._validate_backend')
2698 def test_image_import_copy_image(self, mocked_utils_print_image,
2699 msvb):
2700 args = self._make_args(
2701 {'id': 'IMG-02', 'uri': None, 'import_method': 'copy-image',
2702 'from_create': False, 'stores': 'file1,file2'})
2703 with mock.patch.object(self.gc.images, 'image_import') as mock_import:
2704 with mock.patch.object(self.gc.images, 'get') as mocked_get:
2705 with mock.patch.object(self.gc.images,
2706 'get_import_info') as mocked_info:
2707 mocked_get.return_value = {'status': 'active',
2708 'container_format': 'bare',
2709 'disk_format': 'raw'}
2710 mocked_info.return_value = self.import_info_response
2711 mock_import.return_value = None
2712 test_shell.do_image_import(self.gc, args)
2713 mock_import.assert_called_once_with(
2714 'IMG-02', 'copy-image', uri=None,
2715 remote_region=None, remote_image_id=None,
2716 remote_service_interface=None,
2717 all_stores=None, allow_failure=True,
2718 stores=['file1', 'file2'], backend=None)
2719
2720 @mock.patch('glanceclient.common.utils.exit')
2721 def test_neg_image_import_copy_image_not_active(
2722 self, mock_utils_exit):
2723 expected_msg = ("The 'copy-image' import method can only be used on "
2724 "an image with status 'active'.")
2725 mock_utils_exit.side_effect = self._mock_utils_exit
2726 args = self._make_args(
2727 {'id': 'IMG-02', 'uri': None, 'import_method': 'copy-image',
2728 'disk_format': 'raw',
2729 'container_format': 'bare',
2730 'from_create': False, 'stores': 'file1,file2'})
2731 with mock.patch.object(
2732 self.gc.images,
2733 'get_stores_info') as mocked_stores_info:
2734 with mock.patch.object(self.gc.images, 'get') as mocked_get:
2735 with mock.patch.object(self.gc.images,
2736 'get_import_info') as mocked_info:
2737
2738 mocked_stores_info.return_value = self.stores_info_response
2739 mocked_get.return_value = {'status': 'uploading',
2740 'container_format': 'bare',
2741 'disk_format': 'raw'}
2742 mocked_info.return_value = self.import_info_response
2743 try:
2744 test_shell.do_image_import(self.gc, args)
2745 self.fail("utils.exit should have been called")
2746 except SystemExit:
2747 pass
2748 mock_utils_exit.assert_called_once_with(expected_msg)
2749
2750 @mock.patch('glanceclient.common.utils.exit')
2751 def test_neg_image_import_stores_all_stores_not_specified(
2752 self, mock_utils_exit):
2753 expected_msg = ("Provide either --stores or --all-stores for "
2754 "'copy-image' import method.")
2755 mock_utils_exit.side_effect = self._mock_utils_exit
2756 my_args = self.base_args.copy()
2757 my_args.update(
2758 {'id': 'IMG-01', 'import_method': 'copy-image',
2759 'disk_format': 'raw',
2760 'container_format': 'bare',
2761 })
2762 args = self._make_args(my_args)
2763
2764 with mock.patch.object(self.gc.images,
2765 'get_import_info') as mocked_info:
2766 mocked_info.return_value = self.import_info_response
2767 try:
2768 test_shell.do_image_import(self.gc, args)
2769 self.fail("utils.exit should have been called")
2770 except SystemExit:
2771 pass
2772 mock_utils_exit.assert_called_once_with(expected_msg)
2773
2774 def test_image_download(self):
2775 args = self._make_args(
2776 {'id': 'IMG-01', 'file': 'test', 'progress': True,
2777 'allow_md5_fallback': False})
2778
2779 with mock.patch.object(self.gc.images, 'data') as mocked_data, \
2780 mock.patch.object(utils, '_extract_request_id'):
2781 mocked_data.return_value = utils.RequestIdProxy(
2782 [c for c in 'abcdef'])
2783
2784 test_shell.do_image_download(self.gc, args)
2785 mocked_data.assert_called_once_with('IMG-01',
2786 allow_md5_fallback=False)
2787
2788 # check that non-default value is being passed correctly
2789 args.allow_md5_fallback = True
2790 with mock.patch.object(self.gc.images, 'data') as mocked_data, \
2791 mock.patch.object(utils, '_extract_request_id'):
2792 mocked_data.return_value = utils.RequestIdProxy(
2793 [c for c in 'abcdef'])
2794
2795 test_shell.do_image_download(self.gc, args)
2796 mocked_data.assert_called_once_with('IMG-01',
2797 allow_md5_fallback=True)
2798
2799 @mock.patch.object(utils, 'exit')
2800 @mock.patch('sys.stdout', autospec=True)
2801 def test_image_download_no_file_arg(self, mocked_stdout,
2802 mocked_utils_exit):
2803 # Indicate that no file name was given as command line argument
2804 args = self._make_args({'id': '1234', 'file': None, 'progress': False,
2805 'allow_md5_fallback': False})
2806 # Indicate that no file is specified for output redirection
2807 mocked_stdout.isatty = lambda: True
2808 test_shell.do_image_download(self.gc, args)
2809 mocked_utils_exit.assert_called_once_with(
2810 'No redirection or local file specified for downloaded image'
2811 ' data. Please specify a local file with --file to save'
2812 ' downloaded image or redirect output to another source.')
2813
2814 def test_do_image_delete(self):
2815 args = argparse.Namespace(id=['image1', 'image2'])
2816 with mock.patch.object(self.gc.images, 'delete') as mocked_delete:
2817 mocked_delete.return_value = 0
2818
2819 test_shell.do_image_delete(self.gc, args)
2820 self.assertEqual(2, mocked_delete.call_count)
2821
2822 def test_do_image_deactivate(self):
2823 args = argparse.Namespace(id='image1')
2824 with mock.patch.object(self.gc.images,
2825 'deactivate') as mocked_deactivate:
2826 mocked_deactivate.return_value = 0
2827
2828 test_shell.do_image_deactivate(self.gc, args)
2829 self.assertEqual(1, mocked_deactivate.call_count)
2830
2831 def test_do_image_reactivate(self):
2832 args = argparse.Namespace(id='image1')
2833 with mock.patch.object(self.gc.images,
2834 'reactivate') as mocked_reactivate:
2835 mocked_reactivate.return_value = 0
2836
2837 test_shell.do_image_reactivate(self.gc, args)
2838 self.assertEqual(1, mocked_reactivate.call_count)
2839
2840 @mock.patch.object(utils, 'exit')
2841 @mock.patch.object(utils, 'print_err')
2842 def test_do_image_delete_with_invalid_ids(self, mocked_print_err,
2843 mocked_utils_exit):
2844 args = argparse.Namespace(id=['image1', 'image2'])
2845 with mock.patch.object(self.gc.images, 'delete') as mocked_delete:
2846 mocked_delete.side_effect = exc.HTTPNotFound
2847
2848 test_shell.do_image_delete(self.gc, args)
2849
2850 self.assertEqual(2, mocked_delete.call_count)
2851 self.assertEqual(2, mocked_print_err.call_count)
2852 mocked_utils_exit.assert_called_once_with()
2853
2854 @mock.patch.object(utils, 'exit')
2855 def test_do_image_delete_from_store_not_found(self, mocked_utils_exit):
2856 args = argparse.Namespace(id='image1', store='store1')
2857 with mock.patch.object(self.gc.images,
2858 'delete_from_store') as mocked_delete:
2859 mocked_delete.side_effect = exc.HTTPNotFound
2860
2861 test_shell.do_stores_delete(self.gc, args)
2862
2863 self.assertEqual(1, mocked_delete.call_count)
2864 mocked_utils_exit.assert_called_once_with('Multi Backend support '
2865 'is not enabled or '
2866 'Image/store not found.')
2867
2868 def test_do_image_delete_from_store(self):
2869 args = argparse.Namespace(id='image1', store='store1')
2870 with mock.patch.object(self.gc.images,
2871 'delete_from_store') as mocked_delete:
2872 test_shell.do_stores_delete(self.gc, args)
2873
2874 mocked_delete.assert_called_once_with('store1',
2875 'image1')
2876
2877 @mock.patch.object(utils, 'exit')
2878 @mock.patch.object(utils, 'print_err')
2879 def test_do_image_delete_with_forbidden_ids(self, mocked_print_err,
2880 mocked_utils_exit):
2881 args = argparse.Namespace(id=['image1', 'image2'])
2882 with mock.patch.object(self.gc.images, 'delete') as mocked_delete:
2883 mocked_delete.side_effect = exc.HTTPForbidden
2884
2885 test_shell.do_image_delete(self.gc, args)
2886
2887 self.assertEqual(2, mocked_delete.call_count)
2888 self.assertEqual(2, mocked_print_err.call_count)
2889 mocked_utils_exit.assert_called_once_with()
2890
2891 @mock.patch.object(utils, 'exit')
2892 @mock.patch.object(utils, 'print_err')
2893 def test_do_image_delete_with_image_in_use(self, mocked_print_err,
2894 mocked_utils_exit):
2895 args = argparse.Namespace(id=['image1', 'image2'])
2896 with mock.patch.object(self.gc.images, 'delete') as mocked_delete:
2897 mocked_delete.side_effect = exc.HTTPConflict
2898
2899 test_shell.do_image_delete(self.gc, args)
2900
2901 self.assertEqual(2, mocked_delete.call_count)
2902 self.assertEqual(2, mocked_print_err.call_count)
2903 mocked_utils_exit.assert_called_once_with()
2904
2905 def test_do_image_delete_deleted(self):
2906 image_id = 'deleted-img'
2907 args = argparse.Namespace(id=[image_id])
2908 with mock.patch.object(self.gc.images, 'delete') as mocked_delete:
2909 mocked_delete.side_effect = exc.HTTPNotFound
2910
2911 self.assert_exits_with_msg(func=test_shell.do_image_delete,
2912 func_args=args)
2913
2914 @mock.patch('sys.stdout', autospec=True)
2915 @mock.patch.object(utils, 'print_err')
2916 def test_do_image_download_with_forbidden_id(self, mocked_print_err,
2917 mocked_stdout):
2918 args = self._make_args({'id': 'IMG-01', 'file': None,
2919 'progress': False,
2920 'allow_md5_fallback': False})
2921 mocked_stdout.isatty = lambda: False
2922 with mock.patch.object(self.gc.images, 'data') as mocked_data:
2923 mocked_data.side_effect = exc.HTTPForbidden
2924 try:
2925 test_shell.do_image_download(self.gc, args)
2926 self.fail('Exit not called')
2927 except SystemExit:
2928 pass
2929
2930 self.assertEqual(1, mocked_data.call_count)
2931 self.assertEqual(1, mocked_print_err.call_count)
2932
2933 @mock.patch('sys.stdout', autospec=True)
2934 @mock.patch.object(utils, 'print_err')
2935 def test_do_image_download_with_500(self, mocked_print_err, mocked_stdout):
2936 args = self._make_args({'id': 'IMG-01', 'file': None,
2937 'progress': False,
2938 'allow_md5_fallback': False})
2939 mocked_stdout.isatty = lambda: False
2940 with mock.patch.object(self.gc.images, 'data') as mocked_data:
2941 mocked_data.side_effect = exc.HTTPInternalServerError
2942 try:
2943 test_shell.do_image_download(self.gc, args)
2944 self.fail('Exit not called')
2945 except SystemExit:
2946 pass
2947
2948 self.assertEqual(1, mocked_data.call_count)
2949 self.assertEqual(1, mocked_print_err.call_count)
2950
2951 def test_do_member_list(self):
2952 args = self._make_args({'image_id': 'IMG-01'})
2953 with mock.patch.object(self.gc.image_members, 'list') as mocked_list:
2954 mocked_list.return_value = {}
2955
2956 test_shell.do_member_list(self.gc, args)
2957
2958 mocked_list.assert_called_once_with('IMG-01')
2959 columns = ['Image ID', 'Member ID', 'Status']
2960 utils.print_list.assert_called_once_with({}, columns)
2961
2962 def test_do_member_get(self):
2963 args = self._make_args({'image_id': 'IMG-01', 'member_id': 'MEM-01'})
2964 with mock.patch.object(self.gc.image_members, 'get') as mock_get:
2965 mock_get.return_value = {}
2966
2967 test_shell.do_member_get(self.gc, args)
2968
2969 mock_get.assert_called_once_with('IMG-01', 'MEM-01')
2970 utils.print_dict.assert_called_once_with({})
2971
2972 def test_do_member_create(self):
2973 args = self._make_args({'image_id': 'IMG-01', 'member_id': 'MEM-01'})
2974 with mock.patch.object(self.gc.image_members, 'create') as mock_create:
2975 mock_create.return_value = {}
2976
2977 test_shell.do_member_create(self.gc, args)
2978
2979 mock_create.assert_called_once_with('IMG-01', 'MEM-01')
2980 columns = ['Image ID', 'Member ID', 'Status']
2981 utils.print_list.assert_called_once_with([{}], columns)
2982
2983 def test_do_member_create_with_few_arguments(self):
2984 args = self._make_args({'image_id': None, 'member_id': 'MEM-01'})
2985 msg = 'Unable to create member. Specify image_id and member_id'
2986
2987 self.assert_exits_with_msg(func=test_shell.do_member_create,
2988 func_args=args,
2989 err_msg=msg)
2990
2991 def test_do_member_update(self):
2992 input = {
2993 'image_id': 'IMG-01',
2994 'member_id': 'MEM-01',
2995 'member_status': 'status',
2996 }
2997 args = self._make_args(input)
2998 with mock.patch.object(self.gc.image_members, 'update') as mock_update:
2999 mock_update.return_value = {}
3000
3001 test_shell.do_member_update(self.gc, args)
3002
3003 mock_update.assert_called_once_with('IMG-01', 'MEM-01', 'status')
3004 columns = ['Image ID', 'Member ID', 'Status']
3005 utils.print_list.assert_called_once_with([{}], columns)
3006
3007 def test_do_member_update_with_few_arguments(self):
3008 input = {
3009 'image_id': 'IMG-01',
3010 'member_id': 'MEM-01',
3011 'member_status': None,
3012 }
3013 args = self._make_args(input)
3014 msg = 'Unable to update member. Specify image_id, member_id' \
3015 ' and member_status'
3016
3017 self.assert_exits_with_msg(func=test_shell.do_member_update,
3018 func_args=args,
3019 err_msg=msg)
3020
3021 def test_do_member_delete(self):
3022 args = self._make_args({'image_id': 'IMG-01', 'member_id': 'MEM-01'})
3023 with mock.patch.object(self.gc.image_members, 'delete') as mock_delete:
3024 test_shell.do_member_delete(self.gc, args)
3025
3026 mock_delete.assert_called_once_with('IMG-01', 'MEM-01')
3027
3028 def test_do_member_delete_with_few_arguments(self):
3029 args = self._make_args({'image_id': None, 'member_id': 'MEM-01'})
3030 msg = 'Unable to delete member. Specify image_id and member_id'
3031
3032 self.assert_exits_with_msg(func=test_shell.do_member_delete,
3033 func_args=args,
3034 err_msg=msg)
3035
3036 def test_image_tag_update(self):
3037 args = self._make_args({'image_id': 'IMG-01', 'tag_value': 'tag01'})
3038 with mock.patch.object(self.gc.image_tags, 'update') as mocked_update:
3039 self.gc.images.get = mock.Mock(return_value={})
3040 mocked_update.return_value = None
3041
3042 test_shell.do_image_tag_update(self.gc, args)
3043
3044 mocked_update.assert_called_once_with('IMG-01', 'tag01')
3045
3046 def test_image_tag_update_with_few_arguments(self):
3047 args = self._make_args({'image_id': None, 'tag_value': 'tag01'})
3048 msg = 'Unable to update tag. Specify image_id and tag_value'
3049
3050 self.assert_exits_with_msg(func=test_shell.do_image_tag_update,
3051 func_args=args,
3052 err_msg=msg)
3053
3054 def test_image_tag_delete(self):
3055 args = self._make_args({'image_id': 'IMG-01', 'tag_value': 'tag01'})
3056 with mock.patch.object(self.gc.image_tags, 'delete') as mocked_delete:
3057 mocked_delete.return_value = None
3058
3059 test_shell.do_image_tag_delete(self.gc, args)
3060
3061 mocked_delete.assert_called_once_with('IMG-01', 'tag01')
3062
3063 def test_image_tag_delete_with_few_arguments(self):
3064 args = self._make_args({'image_id': 'IMG-01', 'tag_value': None})
3065 msg = 'Unable to delete tag. Specify image_id and tag_value'
3066
3067 self.assert_exits_with_msg(func=test_shell.do_image_tag_delete,
3068 func_args=args,
3069 err_msg=msg)
3070
3071 def test_do_md_namespace_create(self):
3072 args = self._make_args({'namespace': 'MyNamespace',
3073 'protected': True})
3074 with mock.patch.object(self.gc.metadefs_namespace,
3075 'create') as mocked_create:
3076 expect_namespace = {
3077 'namespace': 'MyNamespace',
3078 'protected': True
3079 }
3080
3081 mocked_create.return_value = expect_namespace
3082
3083 test_shell.do_md_namespace_create(self.gc, args)
3084
3085 mocked_create.assert_called_once_with(namespace='MyNamespace',
3086 protected=True)
3087 utils.print_dict.assert_called_once_with(expect_namespace)
3088
3089 def test_do_md_namespace_import(self):
3090 args = self._make_args({'file': 'test'})
3091
3092 expect_namespace = {
3093 'namespace': 'MyNamespace',
3094 'protected': True
3095 }
3096
3097 with mock.patch.object(self.gc.metadefs_namespace,
3098 'create') as mocked_create:
3099 mock_read = mock.Mock(return_value=json.dumps(expect_namespace))
3100 mock_file = mock.Mock(read=mock_read)
3101 utils.get_data_file = mock.Mock(return_value=mock_file)
3102 mocked_create.return_value = expect_namespace
3103
3104 test_shell.do_md_namespace_import(self.gc, args)
3105
3106 mocked_create.assert_called_once_with(**expect_namespace)
3107 utils.print_dict.assert_called_once_with(expect_namespace)
3108
3109 def test_do_md_namespace_import_invalid_json(self):
3110 args = self._make_args({'file': 'test'})
3111 mock_read = mock.Mock(return_value='Invalid')
3112 mock_file = mock.Mock(read=mock_read)
3113 utils.get_data_file = mock.Mock(return_value=mock_file)
3114
3115 self.assertRaises(SystemExit, test_shell.do_md_namespace_import,
3116 self.gc, args)
3117
3118 def test_do_md_namespace_import_no_input(self):
3119 args = self._make_args({'file': None})
3120 utils.get_data_file = mock.Mock(return_value=None)
3121
3122 self.assertRaises(SystemExit, test_shell.do_md_namespace_import,
3123 self.gc, args)
3124
3125 def test_do_md_namespace_update(self):
3126 args = self._make_args({'id': 'MyNamespace',
3127 'protected': True})
3128 with mock.patch.object(self.gc.metadefs_namespace,
3129 'update') as mocked_update:
3130 expect_namespace = {
3131 'namespace': 'MyNamespace',
3132 'protected': True
3133 }
3134
3135 mocked_update.return_value = expect_namespace
3136
3137 test_shell.do_md_namespace_update(self.gc, args)
3138
3139 mocked_update.assert_called_once_with('MyNamespace',
3140 id='MyNamespace',
3141 protected=True)
3142 utils.print_dict.assert_called_once_with(expect_namespace)
3143
3144 def test_do_md_namespace_show(self):
3145 args = self._make_args({'namespace': 'MyNamespace',
3146 'max_column_width': 80,
3147 'resource_type': None})
3148 with mock.patch.object(self.gc.metadefs_namespace,
3149 'get') as mocked_get:
3150 expect_namespace = {'namespace': 'MyNamespace'}
3151
3152 mocked_get.return_value = expect_namespace
3153
3154 test_shell.do_md_namespace_show(self.gc, args)
3155
3156 mocked_get.assert_called_once_with('MyNamespace')
3157 utils.print_dict.assert_called_once_with(expect_namespace, 80)
3158
3159 def test_do_md_namespace_show_resource_type(self):
3160 args = self._make_args({'namespace': 'MyNamespace',
3161 'max_column_width': 80,
3162 'resource_type': 'RESOURCE'})
3163 with mock.patch.object(self.gc.metadefs_namespace,
3164 'get') as mocked_get:
3165 expect_namespace = {'namespace': 'MyNamespace'}
3166
3167 mocked_get.return_value = expect_namespace
3168
3169 test_shell.do_md_namespace_show(self.gc, args)
3170
3171 mocked_get.assert_called_once_with('MyNamespace',
3172 resource_type='RESOURCE')
3173 utils.print_dict.assert_called_once_with(expect_namespace, 80)
3174
3175 def test_do_md_namespace_list(self):
3176 args = self._make_args({'resource_type': None,
3177 'visibility': None,
3178 'page_size': None})
3179 with mock.patch.object(self.gc.metadefs_namespace,
3180 'list') as mocked_list:
3181 expect_namespaces = [{'namespace': 'MyNamespace'}]
3182
3183 mocked_list.return_value = expect_namespaces
3184
3185 test_shell.do_md_namespace_list(self.gc, args)
3186
3187 mocked_list.assert_called_once_with(filters={})
3188 utils.print_list.assert_called_once_with(expect_namespaces,
3189 ['namespace'])
3190
3191 def test_do_md_namespace_list_page_size(self):
3192 args = self._make_args({'resource_type': None,
3193 'visibility': None,
3194 'page_size': 2})
3195 with mock.patch.object(self.gc.metadefs_namespace,
3196 'list') as mocked_list:
3197 expect_namespaces = [{'namespace': 'MyNamespace'}]
3198
3199 mocked_list.return_value = expect_namespaces
3200
3201 test_shell.do_md_namespace_list(self.gc, args)
3202
3203 mocked_list.assert_called_once_with(filters={}, page_size=2)
3204 utils.print_list.assert_called_once_with(expect_namespaces,
3205 ['namespace'])
3206
3207 def test_do_md_namespace_list_one_filter(self):
3208 args = self._make_args({'resource_types': ['OS::Compute::Aggregate'],
3209 'visibility': None,
3210 'page_size': None})
3211 with mock.patch.object(self.gc.metadefs_namespace, 'list') as \
3212 mocked_list:
3213 expect_namespaces = [{'namespace': 'MyNamespace'}]
3214
3215 mocked_list.return_value = expect_namespaces
3216
3217 test_shell.do_md_namespace_list(self.gc, args)
3218
3219 mocked_list.assert_called_once_with(filters={
3220 'resource_types': ['OS::Compute::Aggregate']})
3221 utils.print_list.assert_called_once_with(expect_namespaces,
3222 ['namespace'])
3223
3224 def test_do_md_namespace_list_all_filters(self):
3225 args = self._make_args({'resource_types': ['OS::Compute::Aggregate'],
3226 'visibility': 'public',
3227 'page_size': None})
3228 with mock.patch.object(self.gc.metadefs_namespace,
3229 'list') as mocked_list:
3230 expect_namespaces = [{'namespace': 'MyNamespace'}]
3231
3232 mocked_list.return_value = expect_namespaces
3233
3234 test_shell.do_md_namespace_list(self.gc, args)
3235
3236 mocked_list.assert_called_once_with(filters={
3237 'resource_types': ['OS::Compute::Aggregate'],
3238 'visibility': 'public'})
3239 utils.print_list.assert_called_once_with(expect_namespaces,
3240 ['namespace'])
3241
3242 def test_do_md_namespace_list_unknown_filter(self):
3243 args = self._make_args({'resource_type': None,
3244 'visibility': None,
3245 'some_arg': 'some_value',
3246 'page_size': None})
3247 with mock.patch.object(self.gc.metadefs_namespace,
3248 'list') as mocked_list:
3249 expect_namespaces = [{'namespace': 'MyNamespace'}]
3250
3251 mocked_list.return_value = expect_namespaces
3252
3253 test_shell.do_md_namespace_list(self.gc, args)
3254
3255 mocked_list.assert_called_once_with(filters={})
3256 utils.print_list.assert_called_once_with(expect_namespaces,
3257 ['namespace'])
3258
3259 def test_do_md_namespace_delete(self):
3260 args = self._make_args({'namespace': 'MyNamespace',
3261 'content': False})
3262 with mock.patch.object(self.gc.metadefs_namespace, 'delete') as \
3263 mocked_delete:
3264 test_shell.do_md_namespace_delete(self.gc, args)
3265
3266 mocked_delete.assert_called_once_with('MyNamespace')
3267
3268 def test_do_md_resource_type_associate(self):
3269 args = self._make_args({'namespace': 'MyNamespace',
3270 'name': 'MyResourceType',
3271 'prefix': 'PREFIX:'})
3272 with mock.patch.object(self.gc.metadefs_resource_type,
3273 'associate') as mocked_associate:
3274 expect_rt = {
3275 'namespace': 'MyNamespace',
3276 'name': 'MyResourceType',
3277 'prefix': 'PREFIX:'
3278 }
3279
3280 mocked_associate.return_value = expect_rt
3281
3282 test_shell.do_md_resource_type_associate(self.gc, args)
3283
3284 mocked_associate.assert_called_once_with('MyNamespace',
3285 **expect_rt)
3286 utils.print_dict.assert_called_once_with(expect_rt)
3287
3288 def test_do_md_resource_type_deassociate(self):
3289 args = self._make_args({'namespace': 'MyNamespace',
3290 'resource_type': 'MyResourceType'})
3291 with mock.patch.object(self.gc.metadefs_resource_type,
3292 'deassociate') as mocked_deassociate:
3293 test_shell.do_md_resource_type_deassociate(self.gc, args)
3294
3295 mocked_deassociate.assert_called_once_with('MyNamespace',
3296 'MyResourceType')
3297
3298 def test_do_md_resource_type_list(self):
3299 args = self._make_args({})
3300 with mock.patch.object(self.gc.metadefs_resource_type,
3301 'list') as mocked_list:
3302 expect_objects = ['MyResourceType1', 'MyResourceType2']
3303
3304 mocked_list.return_value = expect_objects
3305
3306 test_shell.do_md_resource_type_list(self.gc, args)
3307
3308 self.assertEqual(1, mocked_list.call_count)
3309
3310 def test_do_md_namespace_resource_type_list(self):
3311 args = self._make_args({'namespace': 'MyNamespace'})
3312 with mock.patch.object(self.gc.metadefs_resource_type,
3313 'get') as mocked_get:
3314 expect_objects = [{'namespace': 'MyNamespace',
3315 'object': 'MyObject'}]
3316
3317 mocked_get.return_value = expect_objects
3318
3319 test_shell.do_md_namespace_resource_type_list(self.gc, args)
3320
3321 mocked_get.assert_called_once_with('MyNamespace')
3322 utils.print_list.assert_called_once_with(expect_objects,
3323 ['name', 'prefix',
3324 'properties_target'])
3325
3326 def test_do_md_property_create(self):
3327 args = self._make_args({'namespace': 'MyNamespace',
3328 'name': "MyProperty",
3329 'title': "Title",
3330 'type': 'boolean',
3331 'schema': '{}'})
3332 with mock.patch.object(self.gc.metadefs_property,
3333 'create') as mocked_create:
3334 expect_property = {
3335 'namespace': 'MyNamespace',
3336 'name': 'MyProperty',
3337 'title': 'Title',
3338 'type': 'boolean',
3339 }
3340
3341 mocked_create.return_value = expect_property
3342
3343 test_shell.do_md_property_create(self.gc, args)
3344
3345 mocked_create.assert_called_once_with('MyNamespace',
3346 name='MyProperty',
3347 title='Title',
3348 type='boolean')
3349 utils.print_dict.assert_called_once_with(expect_property)
3350
3351 def test_do_md_property_create_invalid_schema(self):
3352 args = self._make_args({'namespace': 'MyNamespace',
3353 'name': "MyProperty",
3354 'title': "Title",
3355 'type': "boolean",
3356 'schema': 'Invalid'})
3357 self.assertRaises(SystemExit, test_shell.do_md_property_create,
3358 self.gc, args)
3359
3360 def test_do_md_property_update(self):
3361 args = self._make_args({'namespace': 'MyNamespace',
3362 'property': 'MyProperty',
3363 'name': 'NewName',
3364 'title': "Title",
3365 'schema': '{}'})
3366 with mock.patch.object(self.gc.metadefs_property,
3367 'update') as mocked_update:
3368 expect_property = {
3369 'namespace': 'MyNamespace',
3370 'name': 'MyProperty',
3371 'title': 'Title'
3372 }
3373
3374 mocked_update.return_value = expect_property
3375
3376 test_shell.do_md_property_update(self.gc, args)
3377
3378 mocked_update.assert_called_once_with('MyNamespace', 'MyProperty',
3379 name='NewName',
3380 title='Title')
3381 utils.print_dict.assert_called_once_with(expect_property)
3382
3383 def test_do_md_property_update_invalid_schema(self):
3384 args = self._make_args({'namespace': 'MyNamespace',
3385 'property': 'MyProperty',
3386 'name': "MyObject",
3387 'title': "Title",
3388 'schema': 'Invalid'})
3389 self.assertRaises(SystemExit, test_shell.do_md_property_update,
3390 self.gc, args)
3391
3392 def test_do_md_property_show(self):
3393 args = self._make_args({'namespace': 'MyNamespace',
3394 'property': 'MyProperty',
3395 'max_column_width': 80})
3396 with mock.patch.object(self.gc.metadefs_property, 'get') as mocked_get:
3397 expect_property = {
3398 'namespace': 'MyNamespace',
3399 'property': 'MyProperty',
3400 'title': 'Title'
3401 }
3402
3403 mocked_get.return_value = expect_property
3404
3405 test_shell.do_md_property_show(self.gc, args)
3406
3407 mocked_get.assert_called_once_with('MyNamespace', 'MyProperty')
3408 utils.print_dict.assert_called_once_with(expect_property, 80)
3409
3410 def test_do_md_property_delete(self):
3411 args = self._make_args({'namespace': 'MyNamespace',
3412 'property': 'MyProperty'})
3413 with mock.patch.object(self.gc.metadefs_property,
3414 'delete') as mocked_delete:
3415 test_shell.do_md_property_delete(self.gc, args)
3416
3417 mocked_delete.assert_called_once_with('MyNamespace', 'MyProperty')
3418
3419 def test_do_md_namespace_property_delete(self):
3420 args = self._make_args({'namespace': 'MyNamespace'})
3421 with mock.patch.object(self.gc.metadefs_property,
3422 'delete_all') as mocked_delete_all:
3423 test_shell.do_md_namespace_properties_delete(self.gc, args)
3424
3425 mocked_delete_all.assert_called_once_with('MyNamespace')
3426
3427 def test_do_md_property_list(self):
3428 args = self._make_args({'namespace': 'MyNamespace'})
3429 with mock.patch.object(self.gc.metadefs_property,
3430 'list') as mocked_list:
3431 expect_objects = [{'namespace': 'MyNamespace',
3432 'property': 'MyProperty',
3433 'title': 'MyTitle'}]
3434
3435 mocked_list.return_value = expect_objects
3436
3437 test_shell.do_md_property_list(self.gc, args)
3438
3439 mocked_list.assert_called_once_with('MyNamespace')
3440 utils.print_list.assert_called_once_with(expect_objects,
3441 ['name', 'title', 'type'])
3442
3443 def test_do_md_object_create(self):
3444 args = self._make_args({'namespace': 'MyNamespace',
3445 'name': "MyObject",
3446 'schema': '{}'})
3447 with mock.patch.object(self.gc.metadefs_object,
3448 'create') as mocked_create:
3449 expect_object = {
3450 'namespace': 'MyNamespace',
3451 'name': 'MyObject'
3452 }
3453
3454 mocked_create.return_value = expect_object
3455
3456 test_shell.do_md_object_create(self.gc, args)
3457
3458 mocked_create.assert_called_once_with('MyNamespace',
3459 name='MyObject')
3460 utils.print_dict.assert_called_once_with(expect_object)
3461
3462 def test_do_md_object_create_invalid_schema(self):
3463 args = self._make_args({'namespace': 'MyNamespace',
3464 'name': "MyObject",
3465 'schema': 'Invalid'})
3466 self.assertRaises(SystemExit, test_shell.do_md_object_create,
3467 self.gc, args)
3468
3469 def test_do_md_object_update(self):
3470 args = self._make_args({'namespace': 'MyNamespace',
3471 'object': 'MyObject',
3472 'name': 'NewName',
3473 'schema': '{}'})
3474 with mock.patch.object(self.gc.metadefs_object,
3475 'update') as mocked_update:
3476 expect_object = {
3477 'namespace': 'MyNamespace',
3478 'name': 'MyObject'
3479 }
3480
3481 mocked_update.return_value = expect_object
3482
3483 test_shell.do_md_object_update(self.gc, args)
3484
3485 mocked_update.assert_called_once_with('MyNamespace', 'MyObject',
3486 name='NewName')
3487 utils.print_dict.assert_called_once_with(expect_object)
3488
3489 def test_do_md_object_update_invalid_schema(self):
3490 args = self._make_args({'namespace': 'MyNamespace',
3491 'object': 'MyObject',
3492 'name': "MyObject",
3493 'schema': 'Invalid'})
3494 self.assertRaises(SystemExit, test_shell.do_md_object_update,
3495 self.gc, args)
3496
3497 def test_do_md_object_show(self):
3498 args = self._make_args({'namespace': 'MyNamespace',
3499 'object': 'MyObject',
3500 'max_column_width': 80})
3501 with mock.patch.object(self.gc.metadefs_object, 'get') as mocked_get:
3502 expect_object = {
3503 'namespace': 'MyNamespace',
3504 'object': 'MyObject'
3505 }
3506
3507 mocked_get.return_value = expect_object
3508
3509 test_shell.do_md_object_show(self.gc, args)
3510
3511 mocked_get.assert_called_once_with('MyNamespace', 'MyObject')
3512 utils.print_dict.assert_called_once_with(expect_object, 80)
3513
3514 def test_do_md_object_property_show(self):
3515 args = self._make_args({'namespace': 'MyNamespace',
3516 'object': 'MyObject',
3517 'property': 'MyProperty',
3518 'max_column_width': 80})
3519 with mock.patch.object(self.gc.metadefs_object, 'get') as mocked_get:
3520 expect_object = {'name': 'MyObject',
3521 'properties': {
3522 'MyProperty': {'type': 'string'}
3523 }}
3524
3525 mocked_get.return_value = expect_object
3526
3527 test_shell.do_md_object_property_show(self.gc, args)
3528
3529 mocked_get.assert_called_once_with('MyNamespace', 'MyObject')
3530 utils.print_dict.assert_called_once_with({'type': 'string',
3531 'name': 'MyProperty'},
3532 80)
3533
3534 def test_do_md_object_property_show_non_existing(self):
3535 args = self._make_args({'namespace': 'MyNamespace',
3536 'object': 'MyObject',
3537 'property': 'MyProperty',
3538 'max_column_width': 80})
3539 with mock.patch.object(self.gc.metadefs_object, 'get') as mocked_get:
3540 expect_object = {'name': 'MyObject', 'properties': {}}
3541 mocked_get.return_value = expect_object
3542
3543 self.assertRaises(SystemExit,
3544 test_shell.do_md_object_property_show,
3545 self.gc, args)
3546 mocked_get.assert_called_once_with('MyNamespace', 'MyObject')
3547
3548 def test_do_md_object_delete(self):
3549 args = self._make_args({'namespace': 'MyNamespace',
3550 'object': 'MyObject'})
3551 with mock.patch.object(self.gc.metadefs_object,
3552 'delete') as mocked_delete:
3553 test_shell.do_md_object_delete(self.gc, args)
3554
3555 mocked_delete.assert_called_once_with('MyNamespace', 'MyObject')
3556
3557 def test_do_md_namespace_objects_delete(self):
3558 args = self._make_args({'namespace': 'MyNamespace'})
3559 with mock.patch.object(self.gc.metadefs_object,
3560 'delete_all') as mocked_delete_all:
3561 test_shell.do_md_namespace_objects_delete(self.gc, args)
3562
3563 mocked_delete_all.assert_called_once_with('MyNamespace')
3564
3565 def test_do_md_object_list(self):
3566 args = self._make_args({'namespace': 'MyNamespace'})
3567 with mock.patch.object(self.gc.metadefs_object, 'list') as mocked_list:
3568 expect_objects = [{'namespace': 'MyNamespace',
3569 'object': 'MyObject'}]
3570
3571 mocked_list.return_value = expect_objects
3572
3573 test_shell.do_md_object_list(self.gc, args)
3574
3575 mocked_list.assert_called_once_with('MyNamespace')
3576 utils.print_list.assert_called_once_with(
3577 expect_objects,
3578 ['name', 'description'],
3579 field_settings={
3580 'description': {'align': 'l', 'max_width': 50}})
3581
3582 def test_do_md_tag_create(self):
3583 args = self._make_args({'namespace': 'MyNamespace',
3584 'name': 'MyTag'})
3585 with mock.patch.object(self.gc.metadefs_tag,
3586 'create') as mocked_create:
3587 expect_tag = {
3588 'namespace': 'MyNamespace',
3589 'name': 'MyTag'
3590 }
3591
3592 mocked_create.return_value = expect_tag
3593
3594 test_shell.do_md_tag_create(self.gc, args)
3595
3596 mocked_create.assert_called_once_with('MyNamespace', 'MyTag')
3597 utils.print_dict.assert_called_once_with(expect_tag)
3598
3599 def test_do_md_tag_update(self):
3600 args = self._make_args({'namespace': 'MyNamespace',
3601 'tag': 'MyTag',
3602 'name': 'NewTag'})
3603 with mock.patch.object(self.gc.metadefs_tag,
3604 'update') as mocked_update:
3605 expect_tag = {
3606 'namespace': 'MyNamespace',
3607 'name': 'NewTag'
3608 }
3609
3610 mocked_update.return_value = expect_tag
3611
3612 test_shell.do_md_tag_update(self.gc, args)
3613
3614 mocked_update.assert_called_once_with('MyNamespace', 'MyTag',
3615 name='NewTag')
3616 utils.print_dict.assert_called_once_with(expect_tag)
3617
3618 def test_do_md_tag_show(self):
3619 args = self._make_args({'namespace': 'MyNamespace',
3620 'tag': 'MyTag',
3621 'sort_dir': 'desc'})
3622 with mock.patch.object(self.gc.metadefs_tag, 'get') as mocked_get:
3623 expect_tag = {
3624 'namespace': 'MyNamespace',
3625 'tag': 'MyTag'
3626 }
3627
3628 mocked_get.return_value = expect_tag
3629
3630 test_shell.do_md_tag_show(self.gc, args)
3631
3632 mocked_get.assert_called_once_with('MyNamespace', 'MyTag')
3633 utils.print_dict.assert_called_once_with(expect_tag)
3634
3635 def test_do_md_tag_delete(self):
3636 args = self._make_args({'namespace': 'MyNamespace',
3637 'tag': 'MyTag'})
3638 with mock.patch.object(self.gc.metadefs_tag,
3639 'delete') as mocked_delete:
3640 test_shell.do_md_tag_delete(self.gc, args)
3641
3642 mocked_delete.assert_called_once_with('MyNamespace', 'MyTag')
3643
3644 def test_do_md_namespace_tags_delete(self):
3645 args = self._make_args({'namespace': 'MyNamespace'})
3646 with mock.patch.object(self.gc.metadefs_tag,
3647 'delete_all') as mocked_delete_all:
3648 test_shell.do_md_namespace_tags_delete(self.gc, args)
3649
3650 mocked_delete_all.assert_called_once_with('MyNamespace')
3651
3652 def test_do_md_tag_list(self):
3653 args = self._make_args({'namespace': 'MyNamespace'})
3654 with mock.patch.object(self.gc.metadefs_tag, 'list') as mocked_list:
3655 expect_tags = [{'namespace': 'MyNamespace',
3656 'tag': 'MyTag'}]
3657
3658 mocked_list.return_value = expect_tags
3659
3660 test_shell.do_md_tag_list(self.gc, args)
3661
3662 mocked_list.assert_called_once_with('MyNamespace')
3663 utils.print_list.assert_called_once_with(
3664 expect_tags,
3665 ['name'],
3666 field_settings={
3667 'description': {'align': 'l', 'max_width': 50}})
3668
3669 def test_do_md_tag_create_multiple(self):
3670 args = self._make_args({'namespace': 'MyNamespace',
3671 'delim': ',',
3672 'names': 'MyTag1, MyTag2',
3673 'append': False})
3674 with mock.patch.object(
3675 self.gc.metadefs_tag, 'create_multiple') as mocked_create_tags:
3676 expect_tags = [{'tags': [{'name': 'MyTag1'}, {'name': 'MyTag2'}]}]
3677
3678 mocked_create_tags.return_value = expect_tags
3679
3680 test_shell.do_md_tag_create_multiple(self.gc, args)
3681
3682 mocked_create_tags.assert_called_once_with(
3683 'MyNamespace', tags=['MyTag1', 'MyTag2'], append=False)
3684 utils.print_list.assert_called_once_with(
3685 expect_tags,
3686 ['name'],
3687 field_settings={
3688 'description': {'align': 'l', 'max_width': 50}})
3689
3690 def test_do_md_tag_create_multiple_with_append(self):
3691 args = self._make_args({'namespace': 'MyNamespace',
3692 'delim': ',',
3693 'names': 'MyTag1, MyTag2',
3694 'append': True})
3695 with mock.patch.object(
3696 self.gc.metadefs_tag, 'create_multiple') as mocked_create_tags:
3697 expect_tags = [{'tags': [{'name': 'MyTag1'}, {'name': 'MyTag2'}]}]
3698
3699 mocked_create_tags.return_value = expect_tags
3700
3701 test_shell.do_md_tag_create_multiple(self.gc, args)
3702
3703 mocked_create_tags.assert_called_once_with(
3704 'MyNamespace', tags=['MyTag1', 'MyTag2'], append=True)
3705 utils.print_list.assert_called_once_with(
3706 expect_tags,
3707 ['name'],
3708 field_settings={
3709 'description': {'align': 'l', 'max_width': 50}})
3710
3711 def _test_do_cache_list(self, supported=True):
3712 args = self._make_args({})
3713 expected_output = {
3714 "cached_images": [
3715 {
3716 "image_id": "pass",
3717 "last_accessed": 0,
3718 "last_modified": 0,
3719 "size": "fake_size",
3720 "hits": "fake_hits",
3721 }
3722 ],
3723 "queued_images": ['fake_image']
3724 }
3725
3726 with mock.patch.object(self.gc.cache, 'list') as mocked_cache_list:
3727 if supported:
3728 mocked_cache_list.return_value = expected_output
3729 else:
3730 mocked_cache_list.side_effect = exc.HTTPNotImplemented
3731 test_shell.do_cache_list(self.gc, args)
3732 mocked_cache_list.assert_called()
3733 if supported:
3734 utils.print_cached_images.assert_called_once_with(
3735 expected_output)
3736
3737 def test_do_cache_list(self):
3738 self._test_do_cache_list()
3739
3740 def test_do_cache_list_unsupported(self):
3741 self.assertRaises(exc.HTTPNotImplemented,
3742 self._test_do_cache_list, supported=False)
3743
3744 def test_do_cache_list_endpoint_not_provided(self):
3745 args = self._make_args({})
3746 self.gc.endpoint_provided = False
3747 with mock.patch('glanceclient.common.utils.exit') as mock_exit:
3748 test_shell.do_cache_list(self.gc, args)
3749 mock_exit.assert_called_once_with(
3750 'Direct server endpoint needs to be provided. Do '
3751 'not use loadbalanced or catalog endpoints.')
3752
3753 def _test_cache_queue(self, supported=True, forbidden=False,):
3754 args = argparse.Namespace(id=['image1'])
3755 with mock.patch.object(self.gc.cache, 'queue') as mocked_cache_queue:
3756 if supported:
3757 mocked_cache_queue.return_value = None
3758 else:
3759 mocked_cache_queue.side_effect = exc.HTTPNotImplemented
3760 if forbidden:
3761 mocked_cache_queue.side_effect = exc.HTTPForbidden
3762
3763 test_shell.do_cache_queue(self.gc, args)
3764 if supported:
3765 mocked_cache_queue.assert_called_once_with('image1')
3766
3767 def test_do_cache_queue(self):
3768 self._test_cache_queue()
3769
3770 def test_do_cache_queue_unsupported(self):
3771 with mock.patch(
3772 'glanceclient.common.utils.print_err') as mock_print_err:
3773 self._test_cache_queue(supported=False)
3774 mock_print_err.assert_called_once_with(
3775 "'HTTP HTTPNotImplemented': Unable to queue image "
3776 "'image1' for caching.")
3777
3778 def test_do_cache_queue_forbidden(self):
3779 with mock.patch(
3780 'glanceclient.common.utils.print_err') as mock_print_err:
3781 self._test_cache_queue(forbidden=True)
3782 mock_print_err.assert_called_once_with(
3783 "You are not permitted to queue the image 'image1' for "
3784 "caching.")
3785
3786 def test_do_cache_queue_endpoint_not_provided(self):
3787 args = argparse.Namespace(id=['image1'])
3788 self.gc.endpoint_provided = False
3789 with mock.patch('glanceclient.common.utils.exit') as mock_exit:
3790 test_shell.do_cache_queue(self.gc, args)
3791 mock_exit.assert_called_once_with(
3792 'Direct server endpoint needs to be provided. Do '
3793 'not use loadbalanced or catalog endpoints.')
3794
3795 def _test_cache_delete(self, supported=True, forbidden=False,):
3796 args = argparse.Namespace(id=['image1'])
3797 with mock.patch.object(self.gc.cache, 'delete') as mocked_cache_delete:
3798 if supported:
3799 mocked_cache_delete.return_value = None
3800 else:
3801 mocked_cache_delete.side_effect = exc.HTTPNotImplemented
3802 if forbidden:
3803 mocked_cache_delete.side_effect = exc.HTTPForbidden
3804
3805 test_shell.do_cache_delete(self.gc, args)
3806 if supported:
3807 mocked_cache_delete.assert_called_once_with('image1')
3808
3809 def test_do_cache_delete(self):
3810 self._test_cache_delete()
3811
3812 def test_do_cache_delete_unsupported(self):
3813 with mock.patch(
3814 'glanceclient.common.utils.print_err') as mock_print_err:
3815 self._test_cache_delete(supported=False)
3816 mock_print_err.assert_called_once_with(
3817 "'HTTP HTTPNotImplemented': Unable to delete image "
3818 "'image1' from cache.")
3819
3820 def test_do_cache_delete_forbidden(self):
3821 with mock.patch(
3822 'glanceclient.common.utils.print_err') as mock_print_err:
3823 self._test_cache_delete(forbidden=True)
3824 mock_print_err.assert_called_once_with(
3825 "You are not permitted to "
3826 "delete the image 'image1' from cache.")
3827
3828 def test_do_cache_delete_endpoint_not_provided(self):
3829 args = argparse.Namespace(id=['image1'])
3830 self.gc.endpoint_provided = False
3831 with mock.patch('glanceclient.common.utils.exit') as mock_exit:
3832 test_shell.do_cache_delete(self.gc, args)
3833 mock_exit.assert_called_once_with(
3834 'Direct server endpoint needs to be provided. Do '
3835 'not use loadbalanced or catalog endpoints.')
3836
3837 def _test_cache_clear(self, target='both', supported=True,
3838 forbidden=False,):
3839 args = self._make_args({'target': target})
3840 with mock.patch.object(self.gc.cache, 'clear') as mocked_cache_clear:
3841 if supported:
3842 mocked_cache_clear.return_value = None
3843 else:
3844 mocked_cache_clear.side_effect = exc.HTTPNotImplemented
3845 if forbidden:
3846 mocked_cache_clear.side_effect = exc.HTTPForbidden
3847
3848 test_shell.do_cache_clear(self.gc, args)
3849 if supported:
3850 mocked_cache_clear.mocked_cache_clear(target)
3851
3852 def test_do_cache_clear_all(self):
3853 self._test_cache_clear()
3854
3855 def test_do_cache_clear_queued_only(self):
3856 self._test_cache_clear(target='queue')
3857
3858 def test_do_cache_clear_cached_only(self):
3859 self._test_cache_clear(target='cache')
3860
3861 def test_do_cache_clear_unsupported(self):
3862 with mock.patch(
3863 'glanceclient.common.utils.print_err') as mock_print_err:
3864 self._test_cache_clear(supported=False)
3865 mock_print_err.assert_called_once_with(
3866 "'HTTP HTTPNotImplemented': Unable to delete image(s) "
3867 "from cache.")
3868
3869 def test_do_cache_clear_forbidden(self):
3870 with mock.patch(
3871 'glanceclient.common.utils.print_err') as mock_print_err:
3872 self._test_cache_clear(forbidden=True)
3873 mock_print_err.assert_called_once_with(
3874 "You are not permitted to "
3875 "delete image(s) from cache.")
3876
3877 def test_do_cache_clear_endpoint_not_provided(self):
3878 args = self._make_args({'target': 'both'})
3879 self.gc.endpoint_provided = False
3880 with mock.patch('glanceclient.common.utils.exit') as mock_exit:
3881 test_shell.do_cache_clear(self.gc, args)
3882 mock_exit.assert_called_once_with(
3883 'Direct server endpoint needs to be provided. Do '
3884 'not use loadbalanced or catalog endpoints.')