diff options
Diffstat (limited to 'openstackclient/tests')
| -rw-r--r-- | openstackclient/tests/network/v2/fakes.py | 69 | ||||
| -rw-r--r-- | openstackclient/tests/network/v2/test_network_agent.py | 219 | ||||
| -rw-r--r-- | openstackclient/tests/network/v2/test_network_rbac.py | 4 | ||||
| -rw-r--r-- | openstackclient/tests/test_shell.py | 588 |
4 files changed, 392 insertions, 488 deletions
diff --git a/openstackclient/tests/network/v2/fakes.py b/openstackclient/tests/network/v2/fakes.py index 9182fe55..a6de75e2 100644 --- a/openstackclient/tests/network/v2/fakes.py +++ b/openstackclient/tests/network/v2/fakes.py @@ -491,6 +491,73 @@ class FakePort(object): return mock.MagicMock(side_effect=ports) +class FakeNetworkAgent(object): + """Fake one or more network agents.""" + + @staticmethod + def create_one_network_agent(attrs=None): + """Create a fake network agent + + :param Dictionary attrs: + A dictionary with all attributes + :return: + A FakeResource object, with id, agent_type, and so on. + """ + attrs = attrs or {} + + # Set default attributes + agent_attrs = { + 'id': 'agent-id-' + uuid.uuid4().hex, + 'agent_type': 'agent-type-' + uuid.uuid4().hex, + 'host': 'host-' + uuid.uuid4().hex, + 'availability_zone': 'zone-' + uuid.uuid4().hex, + 'alive': True, + 'admin_state_up': True, + 'binary': 'binary-' + uuid.uuid4().hex, + 'configurations': {'subnet': 2, 'networks': 1}, + } + agent_attrs.update(attrs) + agent = fakes.FakeResource(info=copy.deepcopy(agent_attrs), + loaded=True) + return agent + + @staticmethod + def create_network_agents(attrs=None, count=2): + """Create multiple fake network agents. + + :param Dictionary attrs: + A dictionary with all attributes + :param int count: + The number of network agents to fake + :return: + A list of FakeResource objects faking the network agents + """ + agents = [] + for i in range(0, count): + agents.append(FakeNetworkAgent.create_one_network_agent(attrs)) + + return agents + + @staticmethod + def get_network_agents(agents=None, count=2): + """Get an iterable MagicMock object with a list of faked network agents. + + If network agents list is provided, then initialize the Mock object + with the list. Otherwise create one. + + :param List agents: + A list of FakeResource objects faking network agents + :param int count: + The number of network agents to fake + :return: + An iterable Mock object with side_effect set to a list of faked + network agents + """ + if agents is None: + agents = FakeNetworkAgent.create_network_agents(count) + return mock.MagicMock(side_effect=agents) + + class FakeNetworkRBAC(object): """Fake one or more network rbac policies.""" @@ -520,7 +587,7 @@ class FakeNetworkRBAC(object): loaded=True) # Set attributes with special mapping in OpenStack SDK. rbac.project_id = rbac_attrs['tenant_id'] - rbac.target_project = rbac_attrs['target_tenant'] + rbac.target_project_id = rbac_attrs['target_tenant'] return rbac @staticmethod diff --git a/openstackclient/tests/network/v2/test_network_agent.py b/openstackclient/tests/network/v2/test_network_agent.py new file mode 100644 index 00000000..3cf9a530 --- /dev/null +++ b/openstackclient/tests/network/v2/test_network_agent.py @@ -0,0 +1,219 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# + +import mock +from mock import call + +from osc_lib import exceptions +from osc_lib import utils + +from openstackclient.network.v2 import network_agent +from openstackclient.tests.network.v2 import fakes as network_fakes +from openstackclient.tests import utils as tests_utils + + +class TestNetworkAgent(network_fakes.TestNetworkV2): + + def setUp(self): + super(TestNetworkAgent, self).setUp() + + # Get a shortcut to the network client + self.network = self.app.client_manager.network + + +class TestDeleteNetworkAgent(TestNetworkAgent): + + network_agents = ( + network_fakes.FakeNetworkAgent.create_network_agents(count=2)) + + def setUp(self): + super(TestDeleteNetworkAgent, self).setUp() + self.network.delete_agent = mock.Mock(return_value=None) + self.network.get_agent = ( + network_fakes.FakeNetworkAgent.get_network_agents( + agents=self.network_agents) + ) + + # Get the command object to test + self.cmd = network_agent.DeleteNetworkAgent(self.app, self.namespace) + + def test_network_agent_delete(self): + arglist = [ + self.network_agents[0].id, + ] + verifylist = [ + ('network_agent', [self.network_agents[0].id]), + ] + + parsed_args = self.check_parser(self.cmd, arglist, verifylist) + + result = self.cmd.take_action(parsed_args) + self.network.get_agent.assert_called_once_with( + self.network_agents[0].id, ignore_missing=False) + self.network.delete_agent.assert_called_once_with( + self.network_agents[0]) + self.assertIsNone(result) + + def test_multi_network_agents_delete(self): + arglist = [] + verifylist = [] + + for n in self.network_agents: + arglist.append(n.id) + verifylist = [ + ('network_agent', arglist), + ] + parsed_args = self.check_parser(self.cmd, arglist, verifylist) + + result = self.cmd.take_action(parsed_args) + + calls = [] + for n in self.network_agents: + calls.append(call(n)) + self.network.delete_agent.assert_has_calls(calls) + self.assertIsNone(result) + + def test_multi_network_agents_delete_with_exception(self): + arglist = [ + self.network_agents[0].id, + 'unexist_network_agent', + ] + verifylist = [ + ('network_agent', + [self.network_agents[0].id, 'unexist_network_agent']), + ] + parsed_args = self.check_parser(self.cmd, arglist, verifylist) + + find_mock_result = [self.network_agents[0], exceptions.CommandError] + self.network.get_agent = ( + mock.MagicMock(side_effect=find_mock_result) + ) + + try: + self.cmd.take_action(parsed_args) + self.fail('CommandError should be raised.') + except exceptions.CommandError as e: + self.assertEqual('1 of 2 network agents failed to delete.', str(e)) + + self.network.get_agent.assert_any_call( + self.network_agents[0].id, ignore_missing=False) + self.network.get_agent.assert_any_call( + 'unexist_network_agent', ignore_missing=False) + self.network.delete_agent.assert_called_once_with( + self.network_agents[0] + ) + + +class TestListNetworkAgent(TestNetworkAgent): + + network_agents = ( + network_fakes.FakeNetworkAgent.create_network_agents(count=3)) + + columns = ( + 'ID', + 'Agent Type', + 'Host', + 'Availability Zone', + 'Alive', + 'State', + 'Binary' + ) + data = [] + for agent in network_agents: + data.append(( + agent.id, + agent.agent_type, + agent.host, + agent.availability_zone, + agent.alive, + network_agent._format_admin_state(agent.admin_state_up), + agent.binary, + )) + + def setUp(self): + super(TestListNetworkAgent, self).setUp() + self.network.agents = mock.Mock( + return_value=self.network_agents) + + # Get the command object to test + self.cmd = network_agent.ListNetworkAgent(self.app, self.namespace) + + def test_network_agents_list(self): + arglist = [] + verifylist = [] + + parsed_args = self.check_parser(self.cmd, arglist, verifylist) + columns, data = self.cmd.take_action(parsed_args) + + self.network.agents.assert_called_once_with(**{}) + self.assertEqual(self.columns, columns) + self.assertEqual(self.data, list(data)) + + +class TestShowNetworkAgent(TestNetworkAgent): + + _network_agent = ( + network_fakes.FakeNetworkAgent.create_one_network_agent()) + + columns = ( + 'admin_state_up', + 'agent_type', + 'alive', + 'availability_zone', + 'binary', + 'configurations', + 'host', + 'id', + ) + data = ( + network_agent._format_admin_state(_network_agent.admin_state_up), + _network_agent.agent_type, + _network_agent.alive, + _network_agent.availability_zone, + _network_agent.binary, + utils.format_dict(_network_agent.configurations), + _network_agent.host, + _network_agent.id, + ) + + def setUp(self): + super(TestShowNetworkAgent, self).setUp() + self.network.get_agent = mock.Mock( + return_value=self._network_agent) + + # Get the command object to test + self.cmd = network_agent.ShowNetworkAgent(self.app, self.namespace) + + def test_show_no_options(self): + arglist = [] + verifylist = [] + + # Missing required args should bail here + self.assertRaises(tests_utils.ParserException, self.check_parser, + self.cmd, arglist, verifylist) + + def test_show_all_options(self): + arglist = [ + self._network_agent.id, + ] + verifylist = [ + ('network_agent', self._network_agent.id), + ] + + parsed_args = self.check_parser(self.cmd, arglist, verifylist) + columns, data = self.cmd.take_action(parsed_args) + + self.network.get_agent.assert_called_once_with( + self._network_agent.id, ignore_missing=False) + self.assertEqual(self.columns, columns) + self.assertEqual(list(self.data), list(data)) diff --git a/openstackclient/tests/network/v2/test_network_rbac.py b/openstackclient/tests/network/v2/test_network_rbac.py index 6255ada7..9250e91b 100644 --- a/openstackclient/tests/network/v2/test_network_rbac.py +++ b/openstackclient/tests/network/v2/test_network_rbac.py @@ -49,7 +49,7 @@ class TestCreateNetworkRBAC(TestNetworkRBAC): 'object_id', 'object_type', 'project_id', - 'target_project', + 'target_project_id', ) data = [ @@ -383,7 +383,7 @@ class TestShowNetworkRBAC(TestNetworkRBAC): 'object_id', 'object_type', 'project_id', - 'target_project', + 'target_project_id', ) data = [ diff --git a/openstackclient/tests/test_shell.py b/openstackclient/tests/test_shell.py index 7d0bbd12..87cd7f51 100644 --- a/openstackclient/tests/test_shell.py +++ b/openstackclient/tests/test_shell.py @@ -13,14 +13,15 @@ # under the License. # -import copy -import fixtures import mock import os -import testtools +import sys + +from osc_lib.tests import utils as osc_lib_test_utils +from oslo_utils import importutils +import wrapt from openstackclient import shell -from openstackclient.tests import utils DEFAULT_AUTH_URL = "http://127.0.0.1:5000/v2.0/" @@ -116,173 +117,97 @@ global_options = { '--os-interface': (DEFAULT_INTERFACE, True, True) } -auth_options = { - '--os-auth-url': (DEFAULT_AUTH_URL, True, True), - '--os-project-id': (DEFAULT_PROJECT_ID, True, True), - '--os-project-name': (DEFAULT_PROJECT_NAME, True, True), - '--os-domain-id': (DEFAULT_DOMAIN_ID, True, True), - '--os-domain-name': (DEFAULT_DOMAIN_NAME, True, True), - '--os-user-domain-id': (DEFAULT_USER_DOMAIN_ID, True, True), - '--os-user-domain-name': (DEFAULT_USER_DOMAIN_NAME, True, True), - '--os-project-domain-id': (DEFAULT_PROJECT_DOMAIN_ID, True, True), - '--os-project-domain-name': (DEFAULT_PROJECT_DOMAIN_NAME, True, True), - '--os-username': (DEFAULT_USERNAME, True, True), - '--os-password': (DEFAULT_PASSWORD, True, True), - '--os-region-name': (DEFAULT_REGION_NAME, True, True), - '--os-trust-id': ("1234", True, True), - '--os-auth-type': ("v2password", True, True), - '--os-token': (DEFAULT_TOKEN, True, True), - '--os-url': (DEFAULT_SERVICE_URL, True, True), - '--os-interface': (DEFAULT_INTERFACE, True, True), -} - - -def opt2attr(opt): - if opt.startswith('--os-'): - attr = opt[5:] - elif opt.startswith('--'): - attr = opt[2:] - else: - attr = opt - return attr.lower().replace('-', '_') - - -def opt2env(opt): - return opt[2:].upper().replace('-', '_') - - -def make_shell(): - """Create a new command shell and mock out some bits.""" - _shell = shell.OpenStackShell() - _shell.command_manager = mock.Mock() - - return _shell +# Wrap the osc_lib make_shell() function to set the shell class since +# osc-lib's TestShell class doesn't allow us to specify it yet. +# TODO(dtroyer): remove this once the shell_class_patch patch is released +# in osc-lib +def make_shell_wrapper(func, inst, args, kwargs): + if 'shell_class' not in kwargs: + kwargs['shell_class'] = shell.OpenStackShell + return func(*args, **kwargs) -def fake_execute(shell, cmd): - """Pretend to execute shell commands.""" - return shell.run(cmd.split()) +wrapt.wrap_function_wrapper( + osc_lib_test_utils, + 'make_shell', + make_shell_wrapper, +) -class EnvFixture(fixtures.Fixture): - """Environment Fixture. - This fixture replaces os.environ with provided env or an empty env. - """ +class TestShell(osc_lib_test_utils.TestShell): - def __init__(self, env=None): - self.new_env = env or {} + # Full name of the OpenStackShell class to test (cliff.app.App subclass) + shell_class_name = "openstackclient.shell.OpenStackShell" - def _setUp(self): - self.orig_env, os.environ = os.environ, self.new_env - self.addCleanup(self.revert) - - def revert(self): - os.environ = self.orig_env - - -class TestShell(utils.TestCase): + # TODO(dtroyer): remove this once the shell_class_patch patch is released + # in osc-lib + app_patch = shell_class_name def setUp(self): super(TestShell, self).setUp() - patch = "openstackclient.shell.OpenStackShell.run_subcommand" - self.cmd_patch = mock.patch(patch) - self.cmd_save = self.cmd_patch.start() - self.addCleanup(self.cmd_patch.stop) - self.app = mock.Mock("Test Shell") - - def _assert_initialize_app_arg(self, cmd_options, default_args): - """Check the args passed to initialize_app() - - The argv argument to initialize_app() is the remainder from parsing - global options declared in both cliff.app and - openstackclient.OpenStackShell build_option_parser(). Any global - options passed on the commmad line should not be in argv but in - _shell.options. - """ + # TODO(dtroyer): remove this once the shell_class_patch patch is + # released in osc-lib + self.shell_class = importutils.import_class(self.shell_class_name) + def _assert_token_endpoint_auth(self, cmd_options, default_args): with mock.patch( - "openstackclient.shell.OpenStackShell.initialize_app", + self.shell_class_name + ".initialize_app", self.app, ): - _shell, _cmd = make_shell(), cmd_options + " list project" - fake_execute(_shell, _cmd) - - self.app.assert_called_with(["list", "project"]) - for k in default_args.keys(): - self.assertEqual( - default_args[k], - vars(_shell.options)[k], - "%s does not match" % k, - ) - - def _assert_cloud_config_arg(self, cmd_options, default_args): - """Check the args passed to cloud_config.get_one_cloud() - - The argparse argument to get_one_cloud() is an argparse.Namespace - object that contains all of the options processed to this point in - initialize_app(). - """ - - cloud = mock.Mock(name="cloudy") - cloud.config = {} - self.occ_get_one = mock.Mock(return_value=cloud) - with mock.patch( - "os_client_config.config.OpenStackConfig.get_one_cloud", - self.occ_get_one, - ): - _shell, _cmd = make_shell(), cmd_options + " list project" - fake_execute(_shell, _cmd) - - opts = self.occ_get_one.call_args[1]['argparse'] - for k in default_args.keys(): - self.assertEqual( - default_args[k], - vars(opts)[k], - "%s does not match" % k, - ) - - def _assert_token_auth(self, cmd_options, default_args): - with mock.patch("openstackclient.shell.OpenStackShell.initialize_app", - self.app): - _shell, _cmd = make_shell(), cmd_options + " list role" - fake_execute(_shell, _cmd) + _shell = osc_lib_test_utils.make_shell( + shell_class=self.shell_class, + ) + _cmd = cmd_options + " list role" + osc_lib_test_utils.fake_execute(_shell, _cmd) + print("_shell: %s" % _shell) self.app.assert_called_with(["list", "role"]) self.assertEqual( default_args.get("token", ''), _shell.options.token, - "token" + "token", ) self.assertEqual( - default_args.get("auth_url", ''), - _shell.options.auth_url, - "auth_url" + default_args.get("url", ''), + _shell.options.url, + "url", ) - def _assert_token_endpoint_auth(self, cmd_options, default_args): - with mock.patch("openstackclient.shell.OpenStackShell.initialize_app", - self.app): - _shell, _cmd = make_shell(), cmd_options + " list role" - fake_execute(_shell, _cmd) + def _assert_token_auth(self, cmd_options, default_args): + with mock.patch( + self.app_patch + ".initialize_app", + self.app, + ): + _shell = osc_lib_test_utils.make_shell( + shell_class=self.shell_class, + ) + _cmd = cmd_options + " list role" + osc_lib_test_utils.fake_execute(_shell, _cmd) + print("_shell: %s" % _shell) self.app.assert_called_with(["list", "role"]) self.assertEqual( default_args.get("token", ''), _shell.options.token, - "token", + "token" ) self.assertEqual( - default_args.get("url", ''), - _shell.options.url, - "url", + default_args.get("auth_url", ''), + _shell.options.auth_url, + "auth_url" ) def _assert_cli(self, cmd_options, default_args): - with mock.patch("openstackclient.shell.OpenStackShell.initialize_app", - self.app): - _shell, _cmd = make_shell(), cmd_options + " list server" - fake_execute(_shell, _cmd) + with mock.patch( + self.shell_class_name + ".initialize_app", + self.app, + ): + _shell = osc_lib_test_utils.make_shell( + shell_class=self.shell_class, + ) + _cmd = cmd_options + " list server" + osc_lib_test_utils.fake_execute(_shell, _cmd) self.app.assert_called_with(["list", "server"]) self.assertEqual(default_args["compute_api_version"], @@ -297,39 +222,17 @@ class TestShell(utils.TestCase): _shell.options.os_network_api_version) -class TestShellHelp(TestShell): - """Test the deferred help flag""" - - def setUp(self): - super(TestShellHelp, self).setUp() - self.useFixture(EnvFixture()) - - @testtools.skip("skip until bug 1444983 is resolved") - def test_help_options(self): - flag = "-h list server" - kwargs = { - "deferred_help": True, - } - with mock.patch("openstackclient.shell.OpenStackShell.initialize_app", - self.app): - _shell, _cmd = make_shell(), flag - fake_execute(_shell, _cmd) - - self.assertEqual(kwargs["deferred_help"], - _shell.options.deferred_help) - - class TestShellOptions(TestShell): def setUp(self): super(TestShellOptions, self).setUp() - self.useFixture(EnvFixture()) + self.useFixture(osc_lib_test_utils.EnvFixture()) def _test_options_init_app(self, test_opts): for opt in test_opts.keys(): if not test_opts[opt][1]: continue - key = opt2attr(opt) + key = osc_lib_test_utils.opt2attr(opt) if isinstance(test_opts[opt][0], str): cmd = opt + " " + test_opts[opt][0] else: @@ -343,7 +246,7 @@ class TestShellOptions(TestShell): for opt in test_opts.keys(): if not test_opts[opt][1]: continue - key = opt2attr(opt) + key = osc_lib_test_utils.opt2attr(opt) if isinstance(test_opts[opt][0], str): cmd = opt + " " + test_opts[opt][0] else: @@ -357,12 +260,12 @@ class TestShellOptions(TestShell): for opt in test_opts.keys(): if not test_opts[opt][2]: continue - key = opt2attr(opt) + key = osc_lib_test_utils.opt2attr(opt) kwargs = { key: test_opts[opt][0], } env = { - opt2env(opt): test_opts[opt][0], + osc_lib_test_utils.opt2env(opt): test_opts[opt][0], } os.environ = env.copy() self._assert_initialize_app_arg("", kwargs) @@ -371,37 +274,16 @@ class TestShellOptions(TestShell): for opt in test_opts.keys(): if not test_opts[opt][2]: continue - key = opt2attr(opt) + key = osc_lib_test_utils.opt2attr(opt) kwargs = { key: test_opts[opt][0], } env = { - opt2env(opt): test_opts[opt][0], + osc_lib_test_utils.opt2env(opt): test_opts[opt][0], } os.environ = env.copy() self._assert_cloud_config_arg("", kwargs) - def test_empty_auth(self): - os.environ = {} - self._assert_initialize_app_arg("", {}) - self._assert_cloud_config_arg("", {}) - - def test_global_options(self): - self._test_options_init_app(global_options) - self._test_options_get_one_cloud(global_options) - - def test_auth_options(self): - self._test_options_init_app(auth_options) - self._test_options_get_one_cloud(auth_options) - - def test_global_env(self): - self._test_env_init_app(global_options) - self._test_env_get_one_cloud(global_options) - - def test_auth_env(self): - self._test_env_init_app(auth_options) - self._test_env_get_one_cloud(auth_options) - class TestShellTokenAuthEnv(TestShell): @@ -411,7 +293,7 @@ class TestShellTokenAuthEnv(TestShell): "OS_TOKEN": DEFAULT_TOKEN, "OS_AUTH_URL": DEFAULT_AUTH_URL, } - self.useFixture(EnvFixture(env.copy())) + self.useFixture(osc_lib_test_utils.EnvFixture(env.copy())) def test_env(self): flag = "" @@ -455,7 +337,7 @@ class TestShellTokenEndpointAuthEnv(TestShell): "OS_TOKEN": DEFAULT_TOKEN, "OS_URL": DEFAULT_SERVICE_URL, } - self.useFixture(EnvFixture(env.copy())) + self.useFixture(osc_lib_test_utils.EnvFixture(env.copy())) def test_env(self): flag = "" @@ -463,7 +345,7 @@ class TestShellTokenEndpointAuthEnv(TestShell): "token": DEFAULT_TOKEN, "url": DEFAULT_SERVICE_URL, } - self._assert_token_auth(flag, kwargs) + self._assert_token_endpoint_auth(flag, kwargs) def test_only_token(self): flag = "--os-token xyzpdq" @@ -502,85 +384,7 @@ class TestShellCli(TestShell): "OS_VOLUME_API_VERSION": DEFAULT_VOLUME_API_VERSION, "OS_NETWORK_API_VERSION": DEFAULT_NETWORK_API_VERSION, } - self.useFixture(EnvFixture(env.copy())) - - def test_shell_args_no_options(self): - _shell = make_shell() - with mock.patch("openstackclient.shell.OpenStackShell.initialize_app", - self.app): - fake_execute(_shell, "list user") - self.app.assert_called_with(["list", "user"]) - - def test_shell_args_ca_options(self): - _shell = make_shell() - - # NOTE(dtroyer): The commented out asserts below are the desired - # behaviour and will be uncommented when the - # handling for --verify and --insecure is fixed. - - # Default - fake_execute(_shell, "list user") - self.assertIsNone(_shell.options.verify) - self.assertIsNone(_shell.options.insecure) - self.assertEqual('', _shell.options.cacert) - self.assertTrue(_shell.verify) - - # --verify - fake_execute(_shell, "--verify list user") - self.assertTrue(_shell.options.verify) - self.assertIsNone(_shell.options.insecure) - self.assertEqual('', _shell.options.cacert) - self.assertTrue(_shell.verify) - - # --insecure - fake_execute(_shell, "--insecure list user") - self.assertIsNone(_shell.options.verify) - self.assertTrue(_shell.options.insecure) - self.assertEqual('', _shell.options.cacert) - self.assertFalse(_shell.verify) - - # --os-cacert - fake_execute(_shell, "--os-cacert foo list user") - self.assertIsNone(_shell.options.verify) - self.assertIsNone(_shell.options.insecure) - self.assertEqual('foo', _shell.options.cacert) - self.assertTrue(_shell.verify) - - # --os-cacert and --verify - fake_execute(_shell, "--os-cacert foo --verify list user") - self.assertTrue(_shell.options.verify) - self.assertIsNone(_shell.options.insecure) - self.assertEqual('foo', _shell.options.cacert) - self.assertTrue(_shell.verify) - - # --os-cacert and --insecure - # NOTE(dtroyer): Per bug https://bugs.launchpad.net/bugs/1447784 - # in this combination --insecure now overrides any - # --os-cacert setting, where before --insecure - # was ignored if --os-cacert was set. - fake_execute(_shell, "--os-cacert foo --insecure list user") - self.assertIsNone(_shell.options.verify) - self.assertTrue(_shell.options.insecure) - self.assertEqual('foo', _shell.options.cacert) - self.assertFalse(_shell.verify) - - def test_shell_args_cert_options(self): - _shell = make_shell() - - # Default - fake_execute(_shell, "list user") - self.assertEqual('', _shell.options.cert) - self.assertEqual('', _shell.options.key) - - # --os-cert - fake_execute(_shell, "--os-cert mycert list user") - self.assertEqual('mycert', _shell.options.cert) - self.assertEqual('', _shell.options.key) - - # --os-key - fake_execute(_shell, "--os-key mickey list user") - self.assertEqual('', _shell.options.cert) - self.assertEqual('mickey', _shell.options.key) + self.useFixture(osc_lib_test_utils.EnvFixture(env.copy())) def test_default_env(self): flag = "" @@ -605,220 +409,34 @@ class TestShellCli(TestShell): } self._assert_cli(flag, kwargs) - @mock.patch("os_client_config.config.OpenStackConfig._load_config_file") - def test_shell_args_cloud_no_vendor(self, config_mock): - config_mock.return_value = ('file.yaml', copy.deepcopy(CLOUD_1)) - _shell = make_shell() - - fake_execute( - _shell, - "--os-cloud scc list user", - ) - self.assertEqual( - 'scc', - _shell.cloud.name, - ) - - # These come from clouds.yaml - self.assertEqual( - DEFAULT_AUTH_URL, - _shell.cloud.config['auth']['auth_url'], - ) - self.assertEqual( - DEFAULT_PROJECT_NAME, - _shell.cloud.config['auth']['project_name'], - ) - self.assertEqual( - 'zaphod', - _shell.cloud.config['auth']['username'], - ) - self.assertEqual( - 'occ-cloud', - _shell.cloud.config['region_name'], - ) - self.assertEqual( - 'glazed', - _shell.cloud.config['donut'], - ) - self.assertEqual( - 'public', - _shell.cloud.config['interface'], - ) - - @mock.patch("os_client_config.config.OpenStackConfig._load_vendor_file") - @mock.patch("os_client_config.config.OpenStackConfig._load_config_file") - def test_shell_args_cloud_public(self, config_mock, public_mock): - config_mock.return_value = ('file.yaml', copy.deepcopy(CLOUD_2)) - public_mock.return_value = ('file.yaml', copy.deepcopy(PUBLIC_1)) - _shell = make_shell() - - fake_execute( - _shell, - "--os-cloud megacloud list user", - ) - self.assertEqual( - 'megacloud', - _shell.cloud.name, - ) - - # These come from clouds-public.yaml - self.assertEqual( - DEFAULT_AUTH_URL, - _shell.cloud.config['auth']['auth_url'], - ) - self.assertEqual( - 'cake', - _shell.cloud.config['donut'], - ) - - # These come from clouds.yaml - self.assertEqual( - 'heart-o-gold', - _shell.cloud.config['auth']['project_name'], - ) - self.assertEqual( - 'zaphod', - _shell.cloud.config['auth']['username'], - ) - self.assertEqual( - 'occ-cloud', - _shell.cloud.config['region_name'], - ) - - self.assertEqual('mycert', _shell.cloud.config['cert']) - self.assertEqual('mickey', _shell.cloud.config['key']) - - @mock.patch("os_client_config.config.OpenStackConfig._load_vendor_file") - @mock.patch("os_client_config.config.OpenStackConfig._load_config_file") - def test_shell_args_precedence(self, config_mock, vendor_mock): - config_mock.return_value = ('file.yaml', copy.deepcopy(CLOUD_2)) - vendor_mock.return_value = ('file.yaml', copy.deepcopy(PUBLIC_1)) - _shell = make_shell() - - # Test command option overriding config file value - fake_execute( - _shell, - "--os-cloud megacloud --os-region-name krikkit list user", - ) - self.assertEqual( - 'megacloud', - _shell.cloud.name, - ) - - # These come from clouds-public.yaml - self.assertEqual( - DEFAULT_AUTH_URL, - _shell.cloud.config['auth']['auth_url'], - ) - self.assertEqual( - 'cake', - _shell.cloud.config['donut'], - ) - - # These come from clouds.yaml - self.assertEqual( - 'heart-o-gold', - _shell.cloud.config['auth']['project_name'], - ) - self.assertEqual( - 'zaphod', - _shell.cloud.config['auth']['username'], - ) - self.assertEqual( - 'krikkit', - _shell.cloud.config['region_name'], - ) - - -class TestShellCliEnv(TestShell): + +class TestShellArgV(TestShell): + """Test the deferred help flag""" def setUp(self): - super(TestShellCliEnv, self).setUp() - env = { - 'OS_REGION_NAME': 'occ-env', - } - self.useFixture(EnvFixture(env.copy())) - - @mock.patch("os_client_config.config.OpenStackConfig._load_vendor_file") - @mock.patch("os_client_config.config.OpenStackConfig._load_config_file") - def test_shell_args_precedence_1(self, config_mock, vendor_mock): - config_mock.return_value = ('file.yaml', copy.deepcopy(CLOUD_2)) - vendor_mock.return_value = ('file.yaml', copy.deepcopy(PUBLIC_1)) - _shell = make_shell() - - # Test env var - fake_execute( - _shell, - "--os-cloud megacloud list user", - ) - self.assertEqual( - 'megacloud', - _shell.cloud.name, - ) - - # These come from clouds-public.yaml - self.assertEqual( - DEFAULT_AUTH_URL, - _shell.cloud.config['auth']['auth_url'], - ) - self.assertEqual( - 'cake', - _shell.cloud.config['donut'], - ) - - # These come from clouds.yaml - self.assertEqual( - 'heart-o-gold', - _shell.cloud.config['auth']['project_name'], - ) - self.assertEqual( - 'zaphod', - _shell.cloud.config['auth']['username'], - ) - self.assertEqual( - 'occ-env', - _shell.cloud.config['region_name'], - ) - - @mock.patch("os_client_config.config.OpenStackConfig._load_vendor_file") - @mock.patch("os_client_config.config.OpenStackConfig._load_config_file") - def test_shell_args_precedence_2(self, config_mock, vendor_mock): - config_mock.return_value = ('file.yaml', copy.deepcopy(CLOUD_2)) - vendor_mock.return_value = ('file.yaml', copy.deepcopy(PUBLIC_1)) - _shell = make_shell() - - # Test command option overriding config file value - fake_execute( - _shell, - "--os-cloud megacloud --os-region-name krikkit list user", - ) - self.assertEqual( - 'megacloud', - _shell.cloud.name, - ) - - # These come from clouds-public.yaml - self.assertEqual( - DEFAULT_AUTH_URL, - _shell.cloud.config['auth']['auth_url'], - ) - self.assertEqual( - 'cake', - _shell.cloud.config['donut'], - ) - - # These come from clouds.yaml - self.assertEqual( - 'heart-o-gold', - _shell.cloud.config['auth']['project_name'], - ) - self.assertEqual( - 'zaphod', - _shell.cloud.config['auth']['username'], - ) - - # These come from the command line - self.assertEqual( - 'krikkit', - _shell.cloud.config['region_name'], - ) + super(TestShellArgV, self).setUp() + + def test_shell_argv(self): + """Test argv decoding + + Python 2 does nothing with argv while Python 3 decodes it into + Unicode before we ever see it. We manually decode when running + under Python 2 so verify that we get the right argv types. + + Use the argv supplied by the test runner so we get actual Python + runtime behaviour; we only need to check the type of argv[0] + which will alwyas be present. + """ + + with mock.patch( + self.shell_class_name + ".run", + self.app, + ): + # Ensure type gets through unmolested through shell.main() + argv = sys.argv + shell.main(sys.argv) + self.assertEqual(type(argv[0]), type(self.app.call_args[0][0][0])) + + # When shell.main() gets sys.argv itself it should be decoded + shell.main() + self.assertEqual(type(u'x'), type(self.app.call_args[0][0][0])) |
