Best Python code snippet using Airtest
test_shell_v2.py
Source:test_shell_v2.py  
1# Copyright 2013 OpenStack Foundation2# Copyright (C) 2013 Yahoo! Inc.3# All Rights Reserved.4#5#    Licensed under the Apache License, Version 2.0 (the "License"); you may6#    not use this file except in compliance with the License. You may obtain7#    a copy of the License at8#9#         http://www.apache.org/licenses/LICENSE-2.010#11#    Unless required by applicable law or agreed to in writing, software12#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT13#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the14#    License for the specific language governing permissions and limitations15#    under the License.16import json17import mock18import testtools19from glanceclient.common import utils20from glanceclient.v2 import shell as test_shell21class ShellV2Test(testtools.TestCase):22    def setUp(self):23        super(ShellV2Test, self).setUp()24        self._mock_utils()25        self.gc = self._mock_glance_client()26    def _make_args(self, args):27        #NOTE(venkatesh): this conversion from a dict to an object28        # is required because the test_shell.do_xxx(gc, args) methods29        # expects the args to be attributes of an object. If passed as30        # dict directly, it throws an AttributeError.31        class Args():32            def __init__(self, entries):33                self.__dict__.update(entries)34        return Args(args)35    def _mock_glance_client(self):36        my_mocked_gc = mock.Mock()37        my_mocked_gc.schemas.return_value = 'test'38        my_mocked_gc.get.return_value = {}39        return my_mocked_gc40    def _mock_utils(self):41        utils.print_list = mock.Mock()42        utils.print_dict = mock.Mock()43        utils.save_image = mock.Mock()44    def assert_exits_with_msg(self, func, func_args, err_msg):45        with mock.patch.object(utils, 'exit') as mocked_utils_exit:46            mocked_utils_exit.return_value = '%s' % err_msg47            func(self.gc, func_args)48            mocked_utils_exit.assert_called_once_with(err_msg)49    def test_do_image_list(self):50        input = {51            'page_size': 18,52            'visibility': True,53            'member_status': 'Fake',54            'owner': 'test',55            'checksum': 'fake_checksum',56            'tag': 'fake tag',57            'properties': []58        }59        args = self._make_args(input)60        with mock.patch.object(self.gc.images, 'list') as mocked_list:61            mocked_list.return_value = {}62            test_shell.do_image_list(self.gc, args)63            exp_img_filters = {64                'owner': 'test',65                'member_status': 'Fake',66                'visibility': True,67                'checksum': 'fake_checksum',68                'tag': 'fake tag'69            }70            mocked_list.assert_called_once_with(page_size=18,71                                                filters=exp_img_filters)72            utils.print_list.assert_called_once_with({}, ['ID', 'Name'])73    def test_do_image_list_with_property_filter(self):74        input = {75            'page_size': 1,76            'visibility': True,77            'member_status': 'Fake',78            'owner': 'test',79            'checksum': 'fake_checksum',80            'tag': 'fake tag',81            'properties': ['os_distro=NixOS', 'architecture=x86_64']82        }83        args = self._make_args(input)84        with mock.patch.object(self.gc.images, 'list') as mocked_list:85            mocked_list.return_value = {}86            test_shell.do_image_list(self.gc, args)87            exp_img_filters = {88                'owner': 'test',89                'member_status': 'Fake',90                'visibility': True,91                'checksum': 'fake_checksum',92                'tag': 'fake tag',93                'os_distro': 'NixOS',94                'architecture': 'x86_64'95            }96            mocked_list.assert_called_once_with(page_size=1,97                                                filters=exp_img_filters)98            utils.print_list.assert_called_once_with({}, ['ID', 'Name'])99    def test_do_image_show(self):100        args = self._make_args({'id': 'pass', 'page_size': 18,101                                'max_column_width': 120})102        with mock.patch.object(self.gc.images, 'get') as mocked_list:103            ignore_fields = ['self', 'access', 'file', 'schema']104            expect_image = dict([(field, field) for field in ignore_fields])105            expect_image['id'] = 'pass'106            mocked_list.return_value = expect_image107            test_shell.do_image_show(self.gc, args)108            mocked_list.assert_called_once_with('pass')109            utils.print_dict.assert_called_once_with({'id': 'pass'},110                                                     max_column_width=120)111    def test_do_image_create_no_user_props(self):112        args = self._make_args({'name': 'IMG-01', 'disk_format': 'vhd',113                                'container_format': 'bare'})114        with mock.patch.object(self.gc.images, 'create') as mocked_create:115            ignore_fields = ['self', 'access', 'file', 'schema']116            expect_image = dict([(field, field) for field in ignore_fields])117            expect_image['id'] = 'pass'118            expect_image['name'] = 'IMG-01'119            expect_image['disk_format'] = 'vhd'120            expect_image['container_format'] = 'bare'121            mocked_create.return_value = expect_image122            test_shell.do_image_create(self.gc, args)123            mocked_create.assert_called_once_with(name='IMG-01',124                                                  disk_format='vhd',125                                                  container_format='bare')126            utils.print_dict.assert_called_once_with({127                'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd',128                'container_format': 'bare'})129    def test_do_image_create_with_user_props(self):130        args = self._make_args({'name': 'IMG-01',131                                'property': ['myprop=myval']})132        with mock.patch.object(self.gc.images, 'create') as mocked_create:133            ignore_fields = ['self', 'access', 'file', 'schema']134            expect_image = dict([(field, field) for field in ignore_fields])135            expect_image['id'] = 'pass'136            expect_image['name'] = 'IMG-01'137            expect_image['myprop'] = 'myval'138            mocked_create.return_value = expect_image139            test_shell.do_image_create(self.gc, args)140            mocked_create.assert_called_once_with(name='IMG-01',141                                                  myprop='myval')142            utils.print_dict.assert_called_once_with({143                'id': 'pass', 'name': 'IMG-01', 'myprop': 'myval'})144    def test_do_image_update_no_user_props(self):145        args = self._make_args({'id': 'pass', 'name': 'IMG-01',146                                'disk_format': 'vhd',147                                'container_format': 'bare'})148        with mock.patch.object(self.gc.images, 'update') as mocked_update:149            ignore_fields = ['self', 'access', 'file', 'schema']150            expect_image = dict([(field, field) for field in ignore_fields])151            expect_image['id'] = 'pass'152            expect_image['name'] = 'IMG-01'153            expect_image['disk_format'] = 'vhd'154            expect_image['container_format'] = 'bare'155            mocked_update.return_value = expect_image156            test_shell.do_image_update(self.gc, args)157            mocked_update.assert_called_once_with('pass',158                                                  None,159                                                  name='IMG-01',160                                                  disk_format='vhd',161                                                  container_format='bare')162            utils.print_dict.assert_called_once_with({163                'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd',164                'container_format': 'bare'})165    def test_do_image_update_with_user_props(self):166        args = self._make_args({'id': 'pass', 'name': 'IMG-01',167                                'property': ['myprop=myval']})168        with mock.patch.object(self.gc.images, 'update') as mocked_update:169            ignore_fields = ['self', 'access', 'file', 'schema']170            expect_image = dict([(field, field) for field in ignore_fields])171            expect_image['id'] = 'pass'172            expect_image['name'] = 'IMG-01'173            expect_image['myprop'] = 'myval'174            mocked_update.return_value = expect_image175            test_shell.do_image_update(self.gc, args)176            mocked_update.assert_called_once_with('pass',177                                                  None,178                                                  name='IMG-01',179                                                  myprop='myval')180            utils.print_dict.assert_called_once_with({181                'id': 'pass', 'name': 'IMG-01', 'myprop': 'myval'})182    def test_do_image_update_with_remove_props(self):183        args = self._make_args({'id': 'pass', 'name': 'IMG-01',184                                'disk_format': 'vhd',185                                'remove-property': ['container_format']})186        with mock.patch.object(self.gc.images, 'update') as mocked_update:187            ignore_fields = ['self', 'access', 'file', 'schema']188            expect_image = dict([(field, field) for field in ignore_fields])189            expect_image['id'] = 'pass'190            expect_image['name'] = 'IMG-01'191            expect_image['disk_format'] = 'vhd'192            mocked_update.return_value = expect_image193            test_shell.do_image_update(self.gc, args)194            mocked_update.assert_called_once_with('pass',195                                                  ['container_format'],196                                                  name='IMG-01',197                                                  disk_format='vhd')198            utils.print_dict.assert_called_once_with({199                'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd'})200    def test_do_explain(self):201        input = {202            'page_size': 18,203            'id': 'pass',204            'schemas': 'test',205            'model': 'test',206        }207        args = self._make_args(input)208        with mock.patch.object(utils, 'print_list'):209            test_shell.do_explain(self.gc, args)210            self.gc.schemas.get.assert_called_once_with('test')211    def test_do_location_add(self):212        gc = self.gc213        loc = {'url': 'http://foo.com/', 'metadata': {'foo': 'bar'}}214        args = self._make_args({'id': 'pass',215                                'url': loc['url'],216                                'metadata': json.dumps(loc['metadata'])})217        with mock.patch.object(gc.images, 'add_location') as mocked_addloc:218            expect_image = {'id': 'pass', 'locations': [loc]}219            mocked_addloc.return_value = expect_image220            test_shell.do_location_add(self.gc, args)221            mocked_addloc.assert_called_once_with('pass',222                                                  loc['url'],223                                                  loc['metadata'])224            utils.print_dict.assert_called_once_with(expect_image)225    def test_do_location_delete(self):226        gc = self.gc227        loc_set = set(['http://foo/bar', 'http://spam/ham'])228        args = self._make_args({'id': 'pass', 'url': loc_set})229        with mock.patch.object(gc.images, 'delete_locations') as mocked_rmloc:230            test_shell.do_location_delete(self.gc, args)231            mocked_rmloc.assert_called_once_with('pass', loc_set)232    def test_do_location_update(self):233        gc = self.gc234        loc = {'url': 'http://foo.com/', 'metadata': {'foo': 'bar'}}235        args = self._make_args({'id': 'pass',236                                'url': loc['url'],237                                'metadata': json.dumps(loc['metadata'])})238        with mock.patch.object(gc.images, 'update_location') as mocked_modloc:239            expect_image = {'id': 'pass', 'locations': [loc]}240            mocked_modloc.return_value = expect_image241            test_shell.do_location_update(self.gc, args)242            mocked_modloc.assert_called_once_with('pass',243                                                  loc['url'],244                                                  loc['metadata'])245            utils.print_dict.assert_called_once_with(expect_image)246    def test_image_upload(self):247        args = self._make_args(248            {'id': 'IMG-01', 'file': 'test', 'size': 1024, 'progress': False})249        with mock.patch.object(self.gc.images, 'upload') as mocked_upload:250            utils.get_data_file = mock.Mock(return_value='testfile')251            mocked_upload.return_value = None252            test_shell.do_image_upload(self.gc, args)253            mocked_upload.assert_called_once_with('IMG-01', 'testfile', 1024)254    def test_do_image_delete(self):255        args = self._make_args({'id': 'pass', 'file': 'test'})256        with mock.patch.object(self.gc.images, 'delete') as mocked_delete:257            mocked_delete.return_value = 0258            test_shell.do_image_delete(self.gc, args)259            mocked_delete.assert_called_once_with('pass')260    def test_do_member_list(self):261        args = self._make_args({'image_id': 'IMG-01'})262        with mock.patch.object(self.gc.image_members, 'list') as mocked_list:263            mocked_list.return_value = {}264            test_shell.do_member_list(self.gc, args)265            mocked_list.assert_called_once_with('IMG-01')266            columns = ['Image ID', 'Member ID', 'Status']267            utils.print_list.assert_called_once_with({}, columns)268    def test_do_member_create(self):269        args = self._make_args({'image_id': 'IMG-01', 'member_id': 'MEM-01'})270        with mock.patch.object(self.gc.image_members, 'create') as mock_create:271            mock_create.return_value = {}272            test_shell.do_member_create(self.gc, args)273            mock_create.assert_called_once_with('IMG-01', 'MEM-01')274            columns = ['Image ID', 'Member ID', 'Status']275            utils.print_list.assert_called_once_with([{}], columns)276    def test_do_member_create_with_few_arguments(self):277        args = self._make_args({'image_id': None, 'member_id': 'MEM-01'})278        msg = 'Unable to create member. Specify image_id and member_id'279        self.assert_exits_with_msg(func=test_shell.do_member_create,280                                   func_args=args,281                                   err_msg=msg)282    def test_do_member_update(self):283        input = {284            'image_id': 'IMG-01',285            'member_id': 'MEM-01',286            'member_status': 'status',287        }288        args = self._make_args(input)289        with mock.patch.object(self.gc.image_members, 'update') as mock_update:290            mock_update.return_value = {}291            test_shell.do_member_update(self.gc, args)292            mock_update.assert_called_once_with('IMG-01', 'MEM-01', 'status')293            columns = ['Image ID', 'Member ID', 'Status']294            utils.print_list.assert_called_once_with([{}], columns)295    def test_do_member_update_with_few_arguments(self):296        input = {297            'image_id': 'IMG-01',298            'member_id': 'MEM-01',299            'member_status': None,300        }301        args = self._make_args(input)302        msg = 'Unable to update member. Specify image_id, member_id' \303              ' and member_status'304        self.assert_exits_with_msg(func=test_shell.do_member_update,305                                   func_args=args,306                                   err_msg=msg)307    def test_do_member_delete(self):308        args = self._make_args({'image_id': 'IMG-01', 'member_id': 'MEM-01'})309        with mock.patch.object(self.gc.image_members, 'delete') as mock_delete:310            test_shell.do_member_delete(self.gc, args)311            mock_delete.assert_called_once_with('IMG-01', 'MEM-01')312    def test_do_member_delete_with_few_arguments(self):313        args = self._make_args({'image_id': None, 'member_id': 'MEM-01'})314        msg = 'Unable to delete member. Specify image_id and member_id'315        self.assert_exits_with_msg(func=test_shell.do_member_delete,316                                   func_args=args,317                                   err_msg=msg)318    def test_image_tag_update(self):319        args = self._make_args({'image_id': 'IMG-01', 'tag_value': 'tag01'})320        with mock.patch.object(self.gc.image_tags, 'update') as mocked_update:321            self.gc.images.get = mock.Mock(return_value={})322            mocked_update.return_value = None323            test_shell.do_image_tag_update(self.gc, args)324            mocked_update.assert_called_once_with('IMG-01', 'tag01')325    def test_image_tag_update_with_few_arguments(self):326        args = self._make_args({'image_id': None, 'tag_value': 'tag01'})327        msg = 'Unable to update tag. Specify image_id and tag_value'328        self.assert_exits_with_msg(func=test_shell.do_image_tag_update,329                                   func_args=args,330                                   err_msg=msg)331    def test_image_tag_delete(self):332        args = self._make_args({'image_id': 'IMG-01', 'tag_value': 'tag01'})333        with mock.patch.object(self.gc.image_tags, 'delete') as mocked_delete:334            mocked_delete.return_value = None335            test_shell.do_image_tag_delete(self.gc, args)336            mocked_delete.assert_called_once_with('IMG-01', 'tag01')337    def test_image_tag_delete_with_few_arguments(self):338        args = self._make_args({'image_id': 'IMG-01', 'tag_value': None})339        msg = 'Unable to delete tag. Specify image_id and tag_value'340        self.assert_exits_with_msg(func=test_shell.do_image_tag_delete,341                                   func_args=args,342                                   err_msg=msg)343    def test_do_md_namespace_create(self):344        args = self._make_args({'namespace': 'MyNamespace',345                                'protected': True})346        with mock.patch.object(self.gc.metadefs_namespace,347                               'create') as mocked_create:348            expect_namespace = {}349            expect_namespace['namespace'] = 'MyNamespace'350            expect_namespace['protected'] = True351            mocked_create.return_value = expect_namespace352            test_shell.do_md_namespace_create(self.gc, args)353            mocked_create.assert_called_once_with(namespace='MyNamespace',354                                                  protected=True)355            utils.print_dict.assert_called_once_with(expect_namespace)356    def test_do_md_namespace_import(self):357        args = self._make_args({'file': 'test'})358        expect_namespace = {}359        expect_namespace['namespace'] = 'MyNamespace'360        expect_namespace['protected'] = True361        with mock.patch.object(self.gc.metadefs_namespace,362                               'create') as mocked_create:363            mock_read = mock.Mock(return_value=json.dumps(expect_namespace))364            mock_file = mock.Mock(read=mock_read)365            utils.get_data_file = mock.Mock(return_value=mock_file)366            mocked_create.return_value = expect_namespace367            test_shell.do_md_namespace_import(self.gc, args)368            mocked_create.assert_called_once_with(**expect_namespace)369            utils.print_dict.assert_called_once_with(expect_namespace)370    def test_do_md_namespace_import_invalid_json(self):371        args = self._make_args({'file': 'test'})372        mock_read = mock.Mock(return_value='Invalid')373        mock_file = mock.Mock(read=mock_read)374        utils.get_data_file = mock.Mock(return_value=mock_file)375        self.assertRaises(SystemExit, test_shell.do_md_namespace_import,376                          self.gc, args)377    def test_do_md_namespace_import_no_input(self):378        args = self._make_args({'file': None})379        utils.get_data_file = mock.Mock(return_value=None)380        self.assertRaises(SystemExit, test_shell.do_md_namespace_import,381                          self.gc, args)382    def test_do_md_namespace_update(self):383        args = self._make_args({'id': 'MyNamespace',384                                'protected': True})385        with mock.patch.object(self.gc.metadefs_namespace,386                               'update') as mocked_update:387            expect_namespace = {}388            expect_namespace['namespace'] = 'MyNamespace'389            expect_namespace['protected'] = True390            mocked_update.return_value = expect_namespace391            test_shell.do_md_namespace_update(self.gc, args)392            mocked_update.assert_called_once_with('MyNamespace',393                                                  id='MyNamespace',394                                                  protected=True)395            utils.print_dict.assert_called_once_with(expect_namespace)396    def test_do_md_namespace_show(self):397        args = self._make_args({'namespace': 'MyNamespace',398                                'max_column_width': 80,399                                'resource_type': None})400        with mock.patch.object(self.gc.metadefs_namespace,401                               'get') as mocked_get:402            expect_namespace = {}403            expect_namespace['namespace'] = 'MyNamespace'404            mocked_get.return_value = expect_namespace405            test_shell.do_md_namespace_show(self.gc, args)406            mocked_get.assert_called_once_with('MyNamespace')407            utils.print_dict.assert_called_once_with(expect_namespace, 80)408    def test_do_md_namespace_show_resource_type(self):409        args = self._make_args({'namespace': 'MyNamespace',410                                'max_column_width': 80,411                                'resource_type': 'RESOURCE'})412        with mock.patch.object(self.gc.metadefs_namespace,413                               'get') as mocked_get:414            expect_namespace = {}415            expect_namespace['namespace'] = 'MyNamespace'416            mocked_get.return_value = expect_namespace417            test_shell.do_md_namespace_show(self.gc, args)418            mocked_get.assert_called_once_with('MyNamespace',419                                               resource_type='RESOURCE')420            utils.print_dict.assert_called_once_with(expect_namespace, 80)421    def test_do_md_namespace_list(self):422        args = self._make_args({'resource_type': None,423                                'visibility': None,424                                'page_size': None})425        with mock.patch.object(self.gc.metadefs_namespace,426                               'list') as mocked_list:427            expect_namespaces = [{'namespace': 'MyNamespace'}]428            mocked_list.return_value = expect_namespaces429            test_shell.do_md_namespace_list(self.gc, args)430            mocked_list.assert_called_once_with(filters={})431            utils.print_list.assert_called_once_with(expect_namespaces,432                                                     ['namespace'])433    def test_do_md_namespace_list_page_size(self):434        args = self._make_args({'resource_type': None,435                                'visibility': None,436                                'page_size': 2})437        with mock.patch.object(self.gc.metadefs_namespace,438                               'list') as mocked_list:439            expect_namespaces = [{'namespace': 'MyNamespace'}]440            mocked_list.return_value = expect_namespaces441            test_shell.do_md_namespace_list(self.gc, args)442            mocked_list.assert_called_once_with(filters={}, page_size=2)443            utils.print_list.assert_called_once_with(expect_namespaces,444                                                     ['namespace'])445    def test_do_md_namespace_list_one_filter(self):446        args = self._make_args({'resource_types': ['OS::Compute::Aggregate'],447                                'visibility': None,448                                'page_size': None})449        with mock.patch.object(self.gc.metadefs_namespace, 'list') as \450                mocked_list:451            expect_namespaces = [{'namespace': 'MyNamespace'}]452            mocked_list.return_value = expect_namespaces453            test_shell.do_md_namespace_list(self.gc, args)454            mocked_list.assert_called_once_with(filters={455                'resource_types': ['OS::Compute::Aggregate']})456            utils.print_list.assert_called_once_with(expect_namespaces,457                                                     ['namespace'])458    def test_do_md_namespace_list_all_filters(self):459        args = self._make_args({'resource_types': ['OS::Compute::Aggregate'],460                                'visibility': 'public',461                                'page_size': None})462        with mock.patch.object(self.gc.metadefs_namespace,463                               'list') as mocked_list:464            expect_namespaces = [{'namespace': 'MyNamespace'}]465            mocked_list.return_value = expect_namespaces466            test_shell.do_md_namespace_list(self.gc, args)467            mocked_list.assert_called_once_with(filters={468                'resource_types': ['OS::Compute::Aggregate'],469                'visibility': 'public'})470            utils.print_list.assert_called_once_with(expect_namespaces,471                                                     ['namespace'])472    def test_do_md_namespace_list_unknown_filter(self):473        args = self._make_args({'resource_type': None,474                                'visibility': None,475                                'some_arg': 'some_value',476                                'page_size': None})477        with mock.patch.object(self.gc.metadefs_namespace,478                               'list') as mocked_list:479            expect_namespaces = [{'namespace': 'MyNamespace'}]480            mocked_list.return_value = expect_namespaces481            test_shell.do_md_namespace_list(self.gc, args)482            mocked_list.assert_called_once_with(filters={})483            utils.print_list.assert_called_once_with(expect_namespaces,484                                                     ['namespace'])485    def test_do_md_namespace_delete(self):486        args = self._make_args({'namespace': 'MyNamespace',487                                'content': False})488        with mock.patch.object(self.gc.metadefs_namespace, 'delete') as \489                mocked_delete:490            test_shell.do_md_namespace_delete(self.gc, args)491            mocked_delete.assert_called_once_with('MyNamespace')492    def test_do_md_resource_type_associate(self):493        args = self._make_args({'namespace': 'MyNamespace',494                                'name': 'MyResourceType',495                                'prefix': 'PREFIX:'})496        with mock.patch.object(self.gc.metadefs_resource_type,497                               'associate') as mocked_associate:498            expect_rt = {}499            expect_rt['namespace'] = 'MyNamespace'500            expect_rt['name'] = 'MyResourceType'501            expect_rt['prefix'] = 'PREFIX:'502            mocked_associate.return_value = expect_rt503            test_shell.do_md_resource_type_associate(self.gc, args)504            mocked_associate.assert_called_once_with('MyNamespace',505                                                     **expect_rt)506            utils.print_dict.assert_called_once_with(expect_rt)507    def test_do_md_resource_type_deassociate(self):508        args = self._make_args({'namespace': 'MyNamespace',509                                'resource_type': 'MyResourceType'})510        with mock.patch.object(self.gc.metadefs_resource_type,511                               'deassociate') as mocked_deassociate:512            test_shell.do_md_resource_type_deassociate(self.gc, args)513            mocked_deassociate.assert_called_once_with('MyNamespace',514                                                       'MyResourceType')515    def test_do_md_resource_type_list(self):516        args = self._make_args({})517        with mock.patch.object(self.gc.metadefs_resource_type,518                               'list') as mocked_list:519            expect_objects = ['MyResourceType1', 'MyResourceType2']520            mocked_list.return_value = expect_objects521            test_shell.do_md_resource_type_list(self.gc, args)522            mocked_list.assert_called_once()523    def test_do_md_namespace_resource_type_list(self):524        args = self._make_args({'namespace': 'MyNamespace'})525        with mock.patch.object(self.gc.metadefs_resource_type,526                               'get') as mocked_get:527            expect_objects = [{'namespace': 'MyNamespace',528                               'object': 'MyObject'}]529            mocked_get.return_value = expect_objects530            test_shell.do_md_namespace_resource_type_list(self.gc, args)531            mocked_get.assert_called_once_with('MyNamespace')532            utils.print_list.assert_called_once_with(expect_objects,533                                                     ['name', 'prefix',534                                                      'properties_target'])535    def test_do_md_property_create(self):536        args = self._make_args({'namespace': 'MyNamespace',537                                'name': "MyProperty",538                                'title': "Title",539                                'schema': '{}'})540        with mock.patch.object(self.gc.metadefs_property,541                               'create') as mocked_create:542            expect_property = {}543            expect_property['namespace'] = 'MyNamespace'544            expect_property['name'] = 'MyProperty'545            expect_property['title'] = 'Title'546            mocked_create.return_value = expect_property547            test_shell.do_md_property_create(self.gc, args)548            mocked_create.assert_called_once_with('MyNamespace',549                                                  name='MyProperty',550                                                  title='Title')551            utils.print_dict.assert_called_once_with(expect_property)552    def test_do_md_property_create_invalid_schema(self):553        args = self._make_args({'namespace': 'MyNamespace',554                                'name': "MyProperty",555                                'title': "Title",556                                'schema': 'Invalid'})557        self.assertRaises(SystemExit, test_shell.do_md_property_create,558                          self.gc, args)559    def test_do_md_property_update(self):560        args = self._make_args({'namespace': 'MyNamespace',561                                'property': 'MyProperty',562                                'name': 'NewName',563                                'title': "Title",564                                'schema': '{}'})565        with mock.patch.object(self.gc.metadefs_property,566                               'update') as mocked_update:567            expect_property = {}568            expect_property['namespace'] = 'MyNamespace'569            expect_property['name'] = 'MyProperty'570            expect_property['title'] = 'Title'571            mocked_update.return_value = expect_property572            test_shell.do_md_property_update(self.gc, args)573            mocked_update.assert_called_once_with('MyNamespace', 'MyProperty',574                                                  name='NewName',575                                                  title='Title')576            utils.print_dict.assert_called_once_with(expect_property)577    def test_do_md_property_update_invalid_schema(self):578        args = self._make_args({'namespace': 'MyNamespace',579                                'property': 'MyProperty',580                                'name': "MyObject",581                                'title': "Title",582                                'schema': 'Invalid'})583        self.assertRaises(SystemExit, test_shell.do_md_property_update,584                          self.gc, args)585    def test_do_md_property_show(self):586        args = self._make_args({'namespace': 'MyNamespace',587                                'property': 'MyProperty',588                                'max_column_width': 80})589        with mock.patch.object(self.gc.metadefs_property, 'get') as mocked_get:590            expect_property = {}591            expect_property['namespace'] = 'MyNamespace'592            expect_property['property'] = 'MyProperty'593            expect_property['title'] = 'Title'594            mocked_get.return_value = expect_property595            test_shell.do_md_property_show(self.gc, args)596            mocked_get.assert_called_once_with('MyNamespace', 'MyProperty')597            utils.print_dict.assert_called_once_with(expect_property, 80)598    def test_do_md_property_delete(self):599        args = self._make_args({'namespace': 'MyNamespace',600                                'property': 'MyProperty'})601        with mock.patch.object(self.gc.metadefs_property,602                               'delete') as mocked_delete:603            test_shell.do_md_property_delete(self.gc, args)604            mocked_delete.assert_called_once_with('MyNamespace', 'MyProperty')605    def test_do_md_namespace_property_delete(self):606        args = self._make_args({'namespace': 'MyNamespace'})607        with mock.patch.object(self.gc.metadefs_property,608                               'delete_all') as mocked_delete_all:609            test_shell.do_md_namespace_properties_delete(self.gc, args)610            mocked_delete_all.assert_called_once_with('MyNamespace')611    def test_do_md_property_list(self):612        args = self._make_args({'namespace': 'MyNamespace'})613        with mock.patch.object(self.gc.metadefs_property,614                               'list') as mocked_list:615            expect_objects = [{'namespace': 'MyNamespace',616                               'property': 'MyProperty',617                               'title': 'MyTitle'}]618            mocked_list.return_value = expect_objects619            test_shell.do_md_property_list(self.gc, args)620            mocked_list.assert_called_once_with('MyNamespace')621            utils.print_list.assert_called_once_with(expect_objects,622                                                     ['name', 'title', 'type'])623    def test_do_md_object_create(self):624        args = self._make_args({'namespace': 'MyNamespace',625                                'name': "MyObject",626                                'schema': '{}'})627        with mock.patch.object(self.gc.metadefs_object,628                               'create') as mocked_create:629            expect_object = {}630            expect_object['namespace'] = 'MyNamespace'631            expect_object['name'] = 'MyObject'632            mocked_create.return_value = expect_object633            test_shell.do_md_object_create(self.gc, args)634            mocked_create.assert_called_once_with('MyNamespace',635                                                  name='MyObject')636            utils.print_dict.assert_called_once_with(expect_object)637    def test_do_md_object_create_invalid_schema(self):638        args = self._make_args({'namespace': 'MyNamespace',639                                'name': "MyObject",640                                'schema': 'Invalid'})641        self.assertRaises(SystemExit, test_shell.do_md_object_create,642                          self.gc, args)643    def test_do_md_object_update(self):644        args = self._make_args({'namespace': 'MyNamespace',645                                'object': 'MyObject',646                                'name': 'NewName',647                                'schema': '{}'})648        with mock.patch.object(self.gc.metadefs_object,649                               'update') as mocked_update:650            expect_object = {}651            expect_object['namespace'] = 'MyNamespace'652            expect_object['name'] = 'MyObject'653            mocked_update.return_value = expect_object654            test_shell.do_md_object_update(self.gc, args)655            mocked_update.assert_called_once_with('MyNamespace', 'MyObject',656                                                  name='NewName')657            utils.print_dict.assert_called_once_with(expect_object)658    def test_do_md_object_update_invalid_schema(self):659        args = self._make_args({'namespace': 'MyNamespace',660                                'object': 'MyObject',661                                'name': "MyObject",662                                'schema': 'Invalid'})663        self.assertRaises(SystemExit, test_shell.do_md_object_update,664                          self.gc, args)665    def test_do_md_object_show(self):666        args = self._make_args({'namespace': 'MyNamespace',667                                'object': 'MyObject',668                                'max_column_width': 80})669        with mock.patch.object(self.gc.metadefs_object, 'get') as mocked_get:670            expect_object = {}671            expect_object['namespace'] = 'MyNamespace'672            expect_object['object'] = 'MyObject'673            mocked_get.return_value = expect_object674            test_shell.do_md_object_show(self.gc, args)675            mocked_get.assert_called_once_with('MyNamespace', 'MyObject')676            utils.print_dict.assert_called_once_with(expect_object, 80)677    def test_do_md_object_property_show(self):678        args = self._make_args({'namespace': 'MyNamespace',679                                'object': 'MyObject',680                                'property': 'MyProperty',681                                'max_column_width': 80})682        with mock.patch.object(self.gc.metadefs_object, 'get') as mocked_get:683            expect_object = {'name': 'MyObject',684                             'properties': {685                                 'MyProperty': {'type': 'string'}686                             }}687            mocked_get.return_value = expect_object688            test_shell.do_md_object_property_show(self.gc, args)689            mocked_get.assert_called_once_with('MyNamespace', 'MyObject')690            utils.print_dict.assert_called_once_with({'type': 'string',691                                                      'name': 'MyProperty'},692                                                     80)693    def test_do_md_object_property_show_non_existing(self):694        args = self._make_args({'namespace': 'MyNamespace',695                                'object': 'MyObject',696                                'property': 'MyProperty',697                                'max_column_width': 80})698        with mock.patch.object(self.gc.metadefs_object, 'get') as mocked_get:699            expect_object = {'name': 'MyObject', 'properties': {}}700            mocked_get.return_value = expect_object701            self.assertRaises(SystemExit,702                              test_shell.do_md_object_property_show,703                              self.gc, args)704            mocked_get.assert_called_once_with('MyNamespace', 'MyObject')705    def test_do_md_object_delete(self):706        args = self._make_args({'namespace': 'MyNamespace',707                                'object': 'MyObject'})708        with mock.patch.object(self.gc.metadefs_object,709                               'delete') as mocked_delete:710            test_shell.do_md_object_delete(self.gc, args)711            mocked_delete.assert_called_once_with('MyNamespace', 'MyObject')712    def test_do_md_namespace_objects_delete(self):713        args = self._make_args({'namespace': 'MyNamespace'})714        with mock.patch.object(self.gc.metadefs_object,715                               'delete_all') as mocked_delete_all:716            test_shell.do_md_namespace_objects_delete(self.gc, args)717            mocked_delete_all.assert_called_once_with('MyNamespace')718    def test_do_md_object_list(self):719        args = self._make_args({'namespace': 'MyNamespace'})720        with mock.patch.object(self.gc.metadefs_object, 'list') as mocked_list:721            expect_objects = [{'namespace': 'MyNamespace',722                               'object': 'MyObject'}]723            mocked_list.return_value = expect_objects724            test_shell.do_md_object_list(self.gc, args)725            mocked_list.assert_called_once_with('MyNamespace')726            utils.print_list.assert_called_once_with(727                expect_objects,728                ['name', 'description'],729                field_settings={...test_legacy_shell.py
Source:test_legacy_shell.py  
1# Copyright 2013 OpenStack LLC.2# Copyright (C) 2013 Yahoo! Inc.3# All Rights Reserved.4#5#    Licensed under the Apache License, Version 2.0 (the "License"); you may6#    not use this file except in compliance with the License. You may obtain7#    a copy of the License at8#9#         http://www.apache.org/licenses/LICENSE-2.010#11#    Unless required by applicable law or agreed to in writing, software12#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT13#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the14#    License for the specific language governing permissions and limitations15#    under the License.16# vim: tabstop=4 shiftwidth=4 softtabstop=417import mock18import testtools19from glanceclient import client20from glanceclient import exc21from glanceclient.v1 import legacy_shell as test_shell22class LegacyShellV1Test(testtools.TestCase):23    def test_print_image_formatted(self):24        class FakeClient():25            endpoint = 'http://is.invalid'26        class FakeImage():27            id = 128            name = 'fake_image'29            is_public = False30            protected = False31            status = 'active'32            size = '1024'33            min_ram = 51234            min_disk = 1035            properties = {'a': 'b', 'c': 'd'}36            created_at = '04.03.2013'37            owner = 'test'38            updated_at = '04.03.2013'39            deleted_at = '04.03.2013'40        test_shell.print_image_formatted(FakeClient(), FakeImage())41    def test_print_image(self):42        class FakeImage():43            id = 144            name = 'fake_image'45            is_public = False46            protected = False47            status = 'active'48            size = '1024'49            min_ram = 51250            min_disk = 1051            properties = {'a': 'b', 'c': 'd'}52            created_at = '04.03.2013'53            owner = 'test'54            updated_at = '04.03.2013'55            deleted_at = '04.03.2013'56        gc = client.Client('1', 'http://is.invalid:8080')57        test_shell.print_image_formatted(gc, FakeImage())58    def test_get_image_fields_from_args(self):59        args = ["field=name"]60        actual = test_shell.get_image_fields_from_args(args)61        self.assertEqual({'field': 'name'}, actual)62    def test_get_image_fields_from_args_exception_raises(self):63        args = {"filed": "name"}64        self.assertRaises(65            RuntimeError, test_shell.get_image_fields_from_args, args)66    def test_get_filters_from_args(self):67        args = ["filter=name"]68        actual = test_shell.get_image_filters_from_args(args)69        self.assertEqual({'property-filter': 'name'}, actual)70    def test_get_image_filters_from_args_exception_raises(self):71        args = {"filter": "name"}72        actual = test_shell.get_image_filters_from_args(args)73        self.assertEqual(1, actual)74    def test_do_add_error(self):75        class FakeClient():76            endpoint = 'http://is.invalid'77        class args:78            fields = 'name'79        actual = test_shell.do_add(FakeClient(), args)80        self.assertEqual(1, actual)81    def test_do_add(self):82        gc = client.Client('1', 'http://is.invalid')83        class FakeImage():84            fields = ['name=test',85                      'status=active',86                      'id=test',87                      'is_public=True',88                      'protected=False',89                      'min_disk=10',90                      'container_format=ovi',91                      'status=active']92            dry_run = True93        test_args = FakeImage()94        actual = test_shell.do_add(gc, test_args)95        self.assertEqual(0, actual)96    def test_do_add_with_image_meta(self):97        gc = client.Client('1', 'http://is.invalid')98        class FakeImage():99            fields = ['name=test',100                      'status=active',101                      'is_public=True',102                      'id=test',103                      'protected=False',104                      'min_disk=10',105                      'container_format=ovi',106                      'status=active',107                      'size=256',108                      'location=test',109                      'checksum=1024',110                      'owner=test_user']111            dry_run = True112        test_args = FakeImage()113        actual = test_shell.do_add(gc, test_args)114        self.assertEqual(0, actual)115    def test_do_add_without_dry_run(self):116        gc = client.Client('1', 'http://is.invalid')117        class FakeImage():118            fields = ['name=test',119                      'status=active',120                      'is_public=True',121                      'id=test',122                      'protected=False',123                      'min_disk=10',124                      'container_format=ovi',125                      'status=active',126                      'size=256',127                      'location=test',128                      'checksum=1024',129                      'owner=test_user']130            dry_run = False131            id = 'test'132            verbose = False133        test_args = FakeImage()134        with mock.patch.object(gc.images, 'create') as mocked_create:135            mocked_create.return_value = FakeImage()136            actual = test_shell.do_add(gc, test_args)137            self.assertEqual(0, actual)138    def test_do_clear_force_true_error(self):139        class FakeImage1():140            id = 1141            name = 'fake_image'142            is_public = False143            protected = False144            status = 'active'145            size = '1024'146            min_ram = 512147            min_disk = 10148            properties = {'a': 'b', 'c': 'd'}149            created_at = '04.03.2013'150            owner = 'test'151            updated_at = '04.03.2013'152            deleted_at = '04.03.2013'153            force = True154            verbose = True155        class FakeImages():156            def __init__(self):157                self.id = 'test'158                self.name = 'test_image_name'159            def list(self):160                self.list = [FakeImage1(), FakeImage1()]161                return self.list162        class FakeClient():163            def __init__(self):164                self.images = FakeImages()165        test_args = FakeImage1()166        actual = test_shell.do_clear(FakeClient(), test_args)167        self.assertEqual(1, actual)168    def test_do_clear_force_true(self):169        class FakeImage1():170            def __init__(self):171                self.id = 1172                self.name = 'fake_image'173                self.is_public = False174                self.protected = False175                self.status = 'active'176                self.size = '1024'177                self.min_ram = 512178                self.min_disk = 10179                self.properties = {'a': 'b', 'c': 'd'}180                self.created_at = '04.03.2013'181                self.owner = 'test'182                self.updated_at = '04.03.2013'183                self.deleted_at = '04.03.2013'184                self.force = True185                self.verbose = True186            def delete(self):187                pass188        class FakeImages():189            def __init__(self):190                self.id = 'test'191                self.name = 'test_image_name'192            def list(self):193                self.list = [FakeImage1(), FakeImage1()]194                return self.list195        class FakeClient():196            def __init__(self):197                self.images = FakeImages()198        test_args = FakeImage1()199        actual = test_shell.do_clear(FakeClient(), test_args)200        self.assertEqual(0, actual)201    def test_do_update_error(self):202        class FakeClient():203            endpoint = 'http://is.invalid'204        class Image():205            fields = ['id', 'is_public', 'name']206        args = Image()207        fake_client = FakeClient()208        actual = test_shell.do_update(fake_client, args)209        self.assertEqual(1, actual)210    def test_do_update_invalid_endpoint(self):211        class Image():212            fields = ['id=test_updated', 'is_public=True', 'name=new_name']213            dry_run = False214            id = 'test'215        args = Image()216        gc = client.Client('1', 'http://is.invalid')217        self.assertRaises(218            exc.InvalidEndpoint, test_shell.do_update, gc, args)219    def test_do_update(self):220        class Image():221            fields = ['id=test_updated',222                      'status=active',223                      'is_public=True',224                      'name=new_name',225                      'protected=False']226            dry_run = True227            id = 'test'228        args = Image()229        gc = client.Client('1', 'http://is.invalid')230        actual = test_shell.do_update(gc, args)231        self.assertEqual(0, actual)232    def test_do_update_dry_run_false(self):233        class Image():234            fields = ['id=test_updated',235                      'status=active',236                      'is_public=True',237                      'name=new_name',238                      'protected=False',239                      'is_public=True']240            dry_run = False241            id = 'test'242            verbose = True243            is_public = True244            protected = False245            status = 'active'246            size = 1024247            min_ram = 512248            min_disk = 512249            properties = {'property': 'test'}250            created_at = '12.09.2013'251        args = Image()252        gc = client.Client('1', 'http://is.invalid')253        with mock.patch.object(gc.images, 'update') as mocked_update:254            mocked_update.return_value = Image()255            actual = test_shell.do_update(gc, args)256            self.assertEqual(0, actual)257    def test_do_delete(self):258        class FakeImage1():259            def __init__(self):260                self.id = 1261                self.name = 'fake_image'262                self.is_public = False263                self.protected = False264                self.status = 'active'265                self.size = '1024'266                self.min_ram = 512267                self.min_disk = 10268                self.properties = {'a': 'b', 'c': 'd'}269                self.created_at = '04.03.2013'270                self.owner = 'test'271                self.updated_at = '04.03.2013'272                self.deleted_at = '04.03.2013'273                self.force = True274                self.verbose = True275            def delete(self):276                pass277            def get(self, id):278                return FakeImage1()279        class FakeClient():280            def __init__(self):281                self.images = FakeImage1()282        actual = test_shell.do_delete(FakeClient(), FakeImage1())283    def test_show(self):284        class Image():285            fields = ['id=test_updated',286                      'status=active',287                      'is_public=True',288                      'name=new_name',289                      'protected=False']290            id = 'test_show'291            name = 'fake_image'292            is_public = False293            protected = False294            status = 'active'295            size = '1024'296            min_ram = 512297            min_disk = 10298            properties = {'a': 'b', 'c': 'd'}299            created_at = '04.03.2013'300            owner = 'test'301            updated_at = '04.03.2013'302        gc = client.Client('1', 'http://is.invalid')303        with mock.patch.object(gc.images, 'get') as mocked_get:304            mocked_get.return_value = Image()305            actual = test_shell.do_show(gc, Image())306            self.assertEqual(0, actual)307    def test_index(self):308        class Image():309            id = 'test'310            filters = {}311            limit = 18312            marker = False313            sort_key = 'test'314            kwarg = 'name'315            sort_dir = 'test'316            name = 'test'317            disk_format = 'ovi'318            container_format = 'ovi'319            size = 1024320        args = Image()321        gc = client.Client('1', 'http://is.invalid')322        with mock.patch.object(gc.images, 'list') as mocked_list:323            mocked_list.return_value = [Image(), Image()]324            actual = test_shell.do_index(gc, args)325    def test_index_return_empty(self):326        class Image():327            id = 'test'328            filters = {}329            limit = 18330            marker = False331            sort_key = 'test'332            kwarg = 'name'333            sort_dir = 'test'334            name = 'test'335            disk_format = 'ovi'336            container_format = 'ovi'337            size = 1024338        args = Image()339        gc = client.Client('1', 'http://is.invalid')340        with mock.patch.object(test_shell, '_get_images') as mocked_get:341            mocked_get.return_value = False342            actual = test_shell.do_index(gc, args)343            self.assertEqual(0, actual)344    def test_do_details(self):345        class Image():346            id = 'test'347            filters = {}348            limit = 18349            marker = False350            sort_key = 'test'351            kwarg = 'name'352            sort_dir = 'test'353            name = 'test'354            disk_format = 'ovi'355            container_format = 'ovi'356            size = 1024357            is_public = True358            protected = False359            status = 'active'360            min_ram = 512361            min_disk = 512362            properties = {}363            created_at = '12.12.12'364        args = Image()365        gc = client.Client('1', 'http://is.invalid')366        with mock.patch.object(gc.images, 'list') as mocked_list:367            mocked_list.return_value = [Image(), Image()]368            actual = test_shell.do_details(gc, args)369    def test_do_image_members(self):370        class FakeImage1():371            def __init__(self):372                self.image_id = 1373                self.name = 'fake_image'374                self.is_public = False375                self.protected = False376                self.status = 'active'377                self.size = '1024'378                self.min_ram = 512379                self.min_disk = 10380                self.properties = {'a': 'b', 'c': 'd'}381                self.created_at = '04.03.2013'382                self.owner = 'test'383                self.updated_at = '04.03.2013'384                self.deleted_at = '04.03.2013'385                self.force = True386                self.verbose = True387            def delete(self):388                pass389            def get(self, id):390                return FakeImage1()391        class FakeClient():392            def __init__(self):393                self.image_members = ImageMembers()394        class ImageMembers():395            def __init__(self):396                self.member_id = 'test'397                self.can_share = True398            def list(self, image):399                return [ImageMembers(), ImageMembers()]400        actual = test_shell.do_image_members(FakeClient(), FakeImage1())401    def test_do_member_add_error(self):402        class FakeClient():403            def __init__(self):404                self.image_members = ImageMembers()405        class FakeImage1():406            def __init__(self):407                self.member_id = 'test'408                self.fields = ["name", "id", "filter"]409                self.dry_run = True410                self.image_id = 'fake_image_id'411                self.can_share = True412            def delete(self):413                pass414            def get(self, id):415                return FakeImage1()416        class ImageMembers():417            def __init__(self):418                self.member_id = 'test'419                self.can_share = True420            def list(self, image):421                return [ImageMembers(), ImageMembers()]422        actual = test_shell.do_member_add(FakeClient(), FakeImage1())423    def test_do_member_images_empty_result(self):424        class FakeImage1():425            def __init__(self):426                self.member_id = 'test'427        gc = client.Client('1', 'http://is.invalid')428        with mock.patch.object(gc.image_members, 'list') as mocked_list:429            mocked_list.return_value = []430            actual = test_shell.do_member_images(gc, FakeImage1())431            self.assertEqual(0, actual)432    def test_do_member_replace(self):433        class FakeClient():434            def __init__(self):435                self.image_members = ImageMembers()436        class ImageMembers():437            def __init__(self):438                self.member_id = 'test'439                self.can_share = True440                self.dry_run = True441                self.image_id = "fake_image_id"442            def list(self, image):443                return [ImageMembers(), ImageMembers()]444        actual = test_shell.do_member_add(FakeClient(), ImageMembers())445    def test_do_members_replace_dry_run_true(self):446        class Fake():447            def __init__(self):448                self.dry_run = True449                self.can_share = True450                self.image_id = 'fake_id'451                self.member_id = 'test'452        gc = client.Client('1', 'http://is.invalid')453        actual = test_shell.do_members_replace(gc, Fake())454    def test_do_members_replace_dry_run_false(self):455        class Fake():456            def __init__(self):457                self.dry_run = False458                self.can_share = True459                self.image_id = 'fake_id'460                self.member_id = 'test'461        gc = client.Client('1', 'http://is.invalid')462        with mock.patch.object(gc.image_members, 'list') as mocked_list:463            mocked_list.return_value = []464            with mock.patch.object(gc.image_members, 'create'):465                actual = test_shell.do_members_replace(gc, Fake())466    def test_do_member_images(self):467        class FakeClient():468            def __init__(self):469                self.image_members = ImageMembers()470        class ImageMembers():471            def __init__(self):472                self.member_id = 'test'473                self.can_share = True474                self.dry_run = True475                self.image_id = "fake_image_id"476            def list(self, member):477                return [ImageMembers(), ImageMembers()]478        actual = test_shell.do_member_images(FakeClient(), ImageMembers())479    def test_create_pretty_table(self):480        class MyPrettyTable(test_shell.PrettyTable):481            def __init__(self):482                self.columns = []483        # Test add column484        my_pretty_table = MyPrettyTable()485        my_pretty_table.add_column(1, label='test')486        # Test make header487        test_res = my_pretty_table.make_header()488        self.assertEqual('t\n-', test_res)489        # Test make row490        result = my_pretty_table.make_row('t')491        self.assertEqual("t", result)492        result = my_pretty_table._clip_and_justify(493            data='test', width=4, just=1)...test_shell.py
Source:test_shell.py  
1#   Licensed under the Apache License, Version 2.0 (the "License"); you may2#   not use this file except in compliance with the License. You may obtain3#   a copy of the License at4#5#        http://www.apache.org/licenses/LICENSE-2.06#7#   Unless required by applicable law or agreed to in writing, software8#   distributed under the License is distributed on an "AS IS" BASIS, WITHOUT9#   WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the10#   License for the specific language governing permissions and limitations11#   under the License.12import copy13from unittest import mock14import fixtures15from osc_lib.tests import utils as osc_lib_utils16from openstackclient import shell17from openstackclient.tests.unit.integ import base as test_base18from openstackclient.tests.unit import test_shell19class TestIntegShellCliNoAuth(test_base.TestInteg):20    def setUp(self):21        super(TestIntegShellCliNoAuth, self).setUp()22        env = {}23        self.useFixture(osc_lib_utils.EnvFixture(copy.deepcopy(env)))24        # self.token = test_base.make_v2_token(self.requests_mock)25    def test_shell_args_no_options(self):26        _shell = shell.OpenStackShell()27        _shell.run("configuration show".split())28        # Check general calls29        self.assertEqual(len(self.requests_mock.request_history), 0)30    def test_shell_args_verify(self):31        _shell = shell.OpenStackShell()32        _shell.run("--verify configuration show".split())33        # Check general calls34        self.assertEqual(len(self.requests_mock.request_history), 0)35    def test_shell_args_insecure(self):36        _shell = shell.OpenStackShell()37        _shell.run("--insecure configuration show".split())38        # Check general calls39        self.assertEqual(len(self.requests_mock.request_history), 0)40    def test_shell_args_cacert(self):41        _shell = shell.OpenStackShell()42        _shell.run("--os-cacert xyzpdq configuration show".split())43        # Check general calls44        self.assertEqual(len(self.requests_mock.request_history), 0)45    def test_shell_args_cacert_insecure(self):46        _shell = shell.OpenStackShell()47        _shell.run("--os-cacert xyzpdq --insecure configuration show".split())48        # Check general calls49        self.assertEqual(len(self.requests_mock.request_history), 0)50class TestIntegShellCliV2(test_base.TestInteg):51    def setUp(self):52        super(TestIntegShellCliV2, self).setUp()53        env = {54            "OS_AUTH_URL": test_base.V2_AUTH_URL,55            "OS_PROJECT_NAME": test_shell.DEFAULT_PROJECT_NAME,56            "OS_USERNAME": test_shell.DEFAULT_USERNAME,57            "OS_PASSWORD": test_shell.DEFAULT_PASSWORD,58            "OS_IDENTITY_API_VERSION": "2",59        }60        self.useFixture(osc_lib_utils.EnvFixture(copy.deepcopy(env)))61        self.token = test_base.make_v2_token(self.requests_mock)62    def test_shell_args_no_options(self):63        _shell = shell.OpenStackShell()64        _shell.run("extension list".split())65        # Check general calls66        self.assertNotEqual(len(self.requests_mock.request_history), 0)67        # Check discovery request68        self.assertEqual(69            test_base.V2_AUTH_URL,70            self.requests_mock.request_history[0].url,71        )72        # Check auth request73        auth_req = self.requests_mock.request_history[1].json()74        self.assertEqual(75            test_shell.DEFAULT_PROJECT_NAME,76            auth_req['auth']['tenantName'],77        )78        self.assertEqual(79            test_shell.DEFAULT_USERNAME,80            auth_req['auth']['passwordCredentials']['username'],81        )82        self.assertEqual(83            test_shell.DEFAULT_PASSWORD,84            auth_req['auth']['passwordCredentials']['password'],85        )86    def test_shell_args_verify(self):87        _shell = shell.OpenStackShell()88        _shell.run("--verify extension list".split())89        # Check general calls90        self.assertNotEqual(len(self.requests_mock.request_history), 0)91        # Check verify92        self.assertTrue(self.requests_mock.request_history[0].verify)93    def test_shell_args_insecure(self):94        _shell = shell.OpenStackShell()95        _shell.run("--insecure extension list".split())96        # Check general calls97        self.assertNotEqual(len(self.requests_mock.request_history), 0)98        # Check verify99        self.assertFalse(self.requests_mock.request_history[0].verify)100    def test_shell_args_cacert(self):101        _shell = shell.OpenStackShell()102        _shell.run("--os-cacert xyzpdq extension list".split())103        # Check general calls104        self.assertNotEqual(len(self.requests_mock.request_history), 0)105        # Check verify106        self.assertEqual(107            'xyzpdq',108            self.requests_mock.request_history[0].verify,109        )110    def test_shell_args_cacert_insecure(self):111        _shell = shell.OpenStackShell()112        _shell.run("--os-cacert xyzpdq --insecure extension list".split())113        # Check general calls114        self.assertNotEqual(len(self.requests_mock.request_history), 0)115        # Check verify116        self.assertFalse(self.requests_mock.request_history[0].verify)117class TestIntegShellCliV2Ignore(test_base.TestInteg):118    def setUp(self):119        super(TestIntegShellCliV2Ignore, self).setUp()120        env = {121            "OS_AUTH_URL": test_base.V2_AUTH_URL,122            "OS_PROJECT_NAME": test_shell.DEFAULT_PROJECT_NAME,123            "OS_USERNAME": test_shell.DEFAULT_USERNAME,124            "OS_PASSWORD": test_shell.DEFAULT_PASSWORD,125            "OS_PROJECT_DOMAIN_ID": test_shell.DEFAULT_PROJECT_DOMAIN_ID,126            "OS_USER_DOMAIN_ID": test_shell.DEFAULT_USER_DOMAIN_ID,127            "OS_IDENTITY_API_VERSION": "2",128        }129        self.useFixture(osc_lib_utils.EnvFixture(copy.deepcopy(env)))130        self.token = test_base.make_v2_token(self.requests_mock)131    def test_shell_args_ignore_v3(self):132        _shell = shell.OpenStackShell()133        _shell.run("extension list".split())134        # Check general calls135        self.assertNotEqual(len(self.requests_mock.request_history), 0)136        # Check discovery request137        self.assertEqual(138            test_base.V2_AUTH_URL,139            self.requests_mock.request_history[0].url,140        )141        # Check auth request142        auth_req = self.requests_mock.request_history[1].json()143        self.assertEqual(144            test_shell.DEFAULT_PROJECT_NAME,145            auth_req['auth']['tenantName'],146        )147        self.assertEqual(148            test_shell.DEFAULT_USERNAME,149            auth_req['auth']['passwordCredentials']['username'],150        )151        self.assertEqual(152            test_shell.DEFAULT_PASSWORD,153            auth_req['auth']['passwordCredentials']['password'],154        )155class TestIntegShellCliV3(test_base.TestInteg):156    def setUp(self):157        super(TestIntegShellCliV3, self).setUp()158        env = {159            "OS_AUTH_URL": test_base.V3_AUTH_URL,160            "OS_PROJECT_DOMAIN_ID": test_shell.DEFAULT_PROJECT_DOMAIN_ID,161            "OS_USER_DOMAIN_ID": test_shell.DEFAULT_USER_DOMAIN_ID,162            "OS_USERNAME": test_shell.DEFAULT_USERNAME,163            "OS_PASSWORD": test_shell.DEFAULT_PASSWORD,164            "OS_IDENTITY_API_VERSION": "3",165        }166        self.useFixture(osc_lib_utils.EnvFixture(copy.deepcopy(env)))167        self.token = test_base.make_v3_token(self.requests_mock)168    def test_shell_args_no_options(self):169        _shell = shell.OpenStackShell()170        _shell.run("extension list".split())171        # Check general calls172        self.assertNotEqual(len(self.requests_mock.request_history), 0)173        # Check discovery request174        self.assertEqual(175            test_base.V3_AUTH_URL,176            self.requests_mock.request_history[0].url,177        )178        # Check auth request179        auth_req = self.requests_mock.request_history[1].json()180        self.assertEqual(181            test_shell.DEFAULT_PROJECT_DOMAIN_ID,182            auth_req['auth']['identity']['password']['user']['domain']['id'],183        )184        self.assertEqual(185            test_shell.DEFAULT_USERNAME,186            auth_req['auth']['identity']['password']['user']['name'],187        )188        self.assertEqual(189            test_shell.DEFAULT_PASSWORD,190            auth_req['auth']['identity']['password']['user']['password'],191        )192    def test_shell_args_verify(self):193        _shell = shell.OpenStackShell()194        _shell.run("--verify extension list".split())195        # Check general calls196        self.assertNotEqual(len(self.requests_mock.request_history), 0)197        # Check verify198        self.assertTrue(self.requests_mock.request_history[0].verify)199    def test_shell_args_insecure(self):200        _shell = shell.OpenStackShell()201        _shell.run("--insecure extension list".split())202        # Check general calls203        self.assertNotEqual(len(self.requests_mock.request_history), 0)204        # Check verify205        self.assertFalse(self.requests_mock.request_history[0].verify)206    def test_shell_args_cacert(self):207        _shell = shell.OpenStackShell()208        _shell.run("--os-cacert xyzpdq extension list".split())209        # Check general calls210        self.assertNotEqual(len(self.requests_mock.request_history), 0)211        # Check verify212        self.assertEqual(213            'xyzpdq',214            self.requests_mock.request_history[0].verify,215        )216    def test_shell_args_cacert_insecure(self):217        # This test verifies the outcome of bug 1447784218        # https://bugs.launchpad.net/python-openstackclient/+bug/1447784219        _shell = shell.OpenStackShell()220        _shell.run("--os-cacert xyzpdq --insecure extension list".split())221        # Check general calls222        self.assertNotEqual(len(self.requests_mock.request_history), 0)223        # Check verify224        self.assertFalse(self.requests_mock.request_history[0].verify)225class TestIntegShellCliV3Prompt(test_base.TestInteg):226    def setUp(self):227        super(TestIntegShellCliV3Prompt, self).setUp()228        env = {229            "OS_AUTH_URL": test_base.V3_AUTH_URL,230            "OS_PROJECT_DOMAIN_ID": test_shell.DEFAULT_PROJECT_DOMAIN_ID,231            "OS_USER_DOMAIN_ID": test_shell.DEFAULT_USER_DOMAIN_ID,232            "OS_USERNAME": test_shell.DEFAULT_USERNAME,233            "OS_IDENTITY_API_VERSION": "3",234        }235        self.useFixture(osc_lib_utils.EnvFixture(copy.deepcopy(env)))236        self.token = test_base.make_v3_token(self.requests_mock)237    @mock.patch("osc_lib.shell.prompt_for_password")238    def test_shell_callback(self, mock_prompt):239        mock_prompt.return_value = "qaz"240        _shell = shell.OpenStackShell()241        _shell.run("extension list".split())242        # Check general calls243        self.assertNotEqual(len(self.requests_mock.request_history), 0)244        # Check password callback set correctly245        self.assertEqual(246            mock_prompt,247            _shell.cloud._openstack_config._pw_callback248        )249        # Check auth request250        auth_req = self.requests_mock.request_history[1].json()251        # Check returned password from prompt function252        self.assertEqual(253            "qaz",254            auth_req['auth']['identity']['password']['user']['password'],255        )256class TestIntegShellCliPrecedence(test_base.TestInteg):257    """Validate option precedence rules without clouds.yaml258    Global option values may be set in three places:259    * command line options260    * environment variables261    * clouds.yaml262    Verify that the above order is the precedence used,263    i.e. a command line option overrides all others, etc264    """265    def setUp(self):266        super(TestIntegShellCliPrecedence, self).setUp()267        env = {268            "OS_AUTH_URL": test_base.V3_AUTH_URL,269            "OS_PROJECT_DOMAIN_ID": test_shell.DEFAULT_PROJECT_DOMAIN_ID,270            "OS_USER_DOMAIN_ID": test_shell.DEFAULT_USER_DOMAIN_ID,271            "OS_USERNAME": test_shell.DEFAULT_USERNAME,272            "OS_IDENTITY_API_VERSION": "3",273        }274        self.useFixture(osc_lib_utils.EnvFixture(copy.deepcopy(env)))275        self.token = test_base.make_v3_token(self.requests_mock)276        # Patch a v3 auth URL into the o-c-c data277        test_shell.PUBLIC_1['public-clouds']['megadodo']['auth']['auth_url'] \278            = test_base.V3_AUTH_URL279    def test_shell_args_options(self):280        """Verify command line options override environment variables"""281        _shell = shell.OpenStackShell()282        _shell.run(283            "--os-username zarquon --os-password qaz "284            "extension list".split(),285        )286        # Check general calls287        self.assertNotEqual(len(self.requests_mock.request_history), 0)288        # Check discovery request289        self.assertEqual(290            test_base.V3_AUTH_URL,291            self.requests_mock.request_history[0].url,292        )293        # Check auth request294        auth_req = self.requests_mock.request_history[1].json()295        # -env, -cli296        # No test, everything not specified tests this297        # -env, +cli298        self.assertEqual(299            'qaz',300            auth_req['auth']['identity']['password']['user']['password'],301        )302        # +env, -cli303        self.assertEqual(304            test_shell.DEFAULT_PROJECT_DOMAIN_ID,305            auth_req['auth']['identity']['password']['user']['domain']['id'],306        )307        # +env, +cli308        self.assertEqual(309            'zarquon',310            auth_req['auth']['identity']['password']['user']['name'],311        )312class TestIntegShellCliPrecedenceOCC(test_base.TestInteg):313    """Validate option precedence rules with clouds.yaml314    Global option values may be set in three places:315    * command line options316    * environment variables317    * clouds.yaml318    Verify that the above order is the precedence used,319    i.e. a command line option overrides all others, etc320    """321    def setUp(self):322        super(TestIntegShellCliPrecedenceOCC, self).setUp()323        env = {324            "OS_CLOUD": "megacloud",325            "OS_AUTH_URL": test_base.V3_AUTH_URL,326            "OS_PROJECT_DOMAIN_ID": test_shell.DEFAULT_PROJECT_DOMAIN_ID,327            "OS_USER_DOMAIN_ID": test_shell.DEFAULT_USER_DOMAIN_ID,328            "OS_USERNAME": test_shell.DEFAULT_USERNAME,329            "OS_IDENTITY_API_VERSION": "3",330            "OS_CLOUD_NAME": "qaz",331        }332        self.useFixture(osc_lib_utils.EnvFixture(copy.deepcopy(env)))333        self.token = test_base.make_v3_token(self.requests_mock)334        # Patch a v3 auth URL into the o-c-c data335        test_shell.PUBLIC_1['public-clouds']['megadodo']['auth']['auth_url'] \336            = test_base.V3_AUTH_URL337    def get_temp_file_path(self, filename):338        """Returns an absolute path for a temporary file.339        :param filename: filename340        :type filename: string341        :returns: absolute file path string342        """343        temp_dir = self.useFixture(fixtures.TempDir())344        return temp_dir.join(filename)345    @mock.patch("openstack.config.loader.OpenStackConfig._load_vendor_file")346    @mock.patch("openstack.config.loader.OpenStackConfig._load_config_file")347    def test_shell_args_precedence_1(self, config_mock, vendor_mock):348        """Precedence run 1349        Run 1 has --os-password on CLI350        """351        def config_mock_return():352            log_file = self.get_temp_file_path('test_log_file')353            cloud2 = test_shell.get_cloud(log_file)354            return ('file.yaml', cloud2)355        config_mock.side_effect = config_mock_return356        def vendor_mock_return():357            return ('file.yaml', copy.deepcopy(test_shell.PUBLIC_1))358        vendor_mock.side_effect = vendor_mock_return359        _shell = shell.OpenStackShell()360        _shell.run(361            "--os-password qaz extension list".split(),362        )363        # Check general calls364        self.assertNotEqual(len(self.requests_mock.request_history), 0)365        # Check discovery request366        self.assertEqual(367            test_base.V3_AUTH_URL,368            self.requests_mock.request_history[0].url,369        )370        # Check auth request371        auth_req = self.requests_mock.request_history[1].json()372        # -env, -cli, -occ373        # No test, everything not specified tests this374        # -env, -cli, +occ375        self.assertEqual(376            "heart-o-gold",377            auth_req['auth']['scope']['project']['name'],378        )379        # -env, +cli, -occ380        self.assertEqual(381            'qaz',382            auth_req['auth']['identity']['password']['user']['password'],383        )384        # -env, +cli, +occ385        # +env, -cli, -occ386        self.assertEqual(387            test_shell.DEFAULT_USER_DOMAIN_ID,388            auth_req['auth']['identity']['password']['user']['domain']['id'],389        )390        # +env, -cli, +occ391        print("auth_req: %s" % auth_req['auth'])392        self.assertEqual(393            test_shell.DEFAULT_USERNAME,394            auth_req['auth']['identity']['password']['user']['name'],395        )396        # +env, +cli, -occ397        # see test_shell_args_precedence_2()398        # +env, +cli, +occ399        # see test_shell_args_precedence_2()400    @mock.patch("openstack.config.loader.OpenStackConfig._load_vendor_file")401    @mock.patch("openstack.config.loader.OpenStackConfig._load_config_file")402    def test_shell_args_precedence_2(self, config_mock, vendor_mock):403        """Precedence run 2404        Run 2 has --os-username, --os-password, --os-project-domain-id on CLI405        """406        def config_mock_return():407            log_file = self.get_temp_file_path('test_log_file')408            cloud2 = test_shell.get_cloud(log_file)409            return ('file.yaml', cloud2)410        config_mock.side_effect = config_mock_return411        def vendor_mock_return():412            return ('file.yaml', copy.deepcopy(test_shell.PUBLIC_1))413        vendor_mock.side_effect = vendor_mock_return414        _shell = shell.OpenStackShell()415        _shell.run(416            "--os-username zarquon --os-password qaz "417            "--os-project-domain-id 5678 extension list".split(),418        )419        # Check general calls420        self.assertNotEqual(len(self.requests_mock.request_history), 0)421        # Check discovery request422        self.assertEqual(423            test_base.V3_AUTH_URL,424            self.requests_mock.request_history[0].url,425        )426        # Check auth request427        auth_req = self.requests_mock.request_history[1].json()428        # +env, +cli, -occ429        self.assertEqual(430            '5678',431            auth_req['auth']['scope']['project']['domain']['id'],432        )433        # +env, +cli, +occ434        print("auth_req: %s" % auth_req['auth'])435        self.assertEqual(436            'zarquon',437            auth_req['auth']['identity']['password']['user']['name'],...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
