Client for OpenStack services
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
python-openstackclient/openstackclient/tests/unit/compute/v2/test_server.py

8360 lines
270 KiB

# Copyright 2013 Nebula Inc.
#
# 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 argparse
import collections
import copy
import getpass
import json
import tempfile
from unittest import mock
from unittest.mock import call
import iso8601
from novaclient import api_versions
from openstack import exceptions as sdk_exceptions
from openstack import utils as sdk_utils
from osc_lib.cli import format_columns
from osc_lib import exceptions
from osc_lib import utils as common_utils
from openstackclient.compute.v2 import server
from openstackclient.tests.unit.compute.v2 import fakes as compute_fakes
from openstackclient.tests.unit.image.v2 import fakes as image_fakes
from openstackclient.tests.unit.network.v2 import fakes as network_fakes
from openstackclient.tests.unit import utils
from openstackclient.tests.unit.volume.v2 import fakes as volume_fakes
class TestPowerStateColumn(utils.TestCase):
def test_human_readable(self):
self.assertEqual(
'NOSTATE', server.PowerStateColumn(0x00).human_readable())
self.assertEqual(
'Running', server.PowerStateColumn(0x01).human_readable())
self.assertEqual(
'', server.PowerStateColumn(0x02).human_readable())
self.assertEqual(
'Paused', server.PowerStateColumn(0x03).human_readable())
self.assertEqual(
'Shutdown', server.PowerStateColumn(0x04).human_readable())
self.assertEqual(
'', server.PowerStateColumn(0x05).human_readable())
self.assertEqual(
'Crashed', server.PowerStateColumn(0x06).human_readable())
self.assertEqual(
'Suspended', server.PowerStateColumn(0x07).human_readable())
self.assertEqual(
'N/A', server.PowerStateColumn(0x08).human_readable())
class TestServer(compute_fakes.TestComputev2):
def setUp(self):
super(TestServer, self).setUp()
# Get a shortcut to the compute client ServerManager Mock
self.servers_mock = self.app.client_manager.compute.servers
self.servers_mock.reset_mock()
self.app.client_manager.sdk_connection = mock.Mock()
self.app.client_manager.sdk_connection.compute = mock.Mock()
self.sdk_client = self.app.client_manager.sdk_connection.compute
# Get a shortcut to the compute client ServerMigrationsManager Mock
self.server_migrations_mock = \
self.app.client_manager.compute.server_migrations
self.server_migrations_mock.reset_mock()
# Get a shortcut to the compute client VolumeManager mock
self.servers_volumes_mock = self.app.client_manager.compute.volumes
self.servers_volumes_mock.reset_mock()
# Get a shortcut to the compute client MigrationManager mock
self.migrations_mock = self.app.client_manager.compute.migrations
self.migrations_mock.reset_mock()
# Get a shortcut to the compute client FlavorManager Mock
self.flavors_mock = self.app.client_manager.compute.flavors
self.flavors_mock.reset_mock()
# Get a shortcut to the image client ImageManager Mock
self.images_mock = self.app.client_manager.image.images
self.images_mock.reset_mock()
self.find_image_mock = self.app.client_manager.image.find_image
self.find_image_mock.reset_mock()
self.get_image_mock = self.app.client_manager.image.get_image
self.get_image_mock.reset_mock()
# Get a shortcut to the volume client VolumeManager Mock
self.volumes_mock = self.app.client_manager.volume.volumes
self.volumes_mock.reset_mock()
self.app.client_manager.sdk_connection.volume = mock.Mock()
self.sdk_volume_client = self.app.client_manager.sdk_connection.volume
# Get a shortcut to the volume client VolumeManager Mock
self.snapshots_mock = self.app.client_manager.volume.volume_snapshots
self.snapshots_mock.reset_mock()
# Set object attributes to be tested. Could be overwritten in subclass.
self.attrs = {}
# Set object methods to be tested. Could be overwritten in subclass.
self.methods = {}
def setup_servers_mock(self, count):
# If we are creating more than one server, make one of them
# boot-from-volume
include_bfv = count > 1
servers = compute_fakes.FakeServer.create_servers(
attrs=self.attrs,
methods=self.methods,
count=count - 1 if include_bfv else count
)
if include_bfv:
attrs = copy.deepcopy(self.attrs)
attrs['image'] = ''
bfv_server = compute_fakes.FakeServer.create_one_server(
attrs=attrs,
methods=self.methods
)
servers.append(bfv_server)
# This is the return value for utils.find_resource()
self.servers_mock.get = compute_fakes.FakeServer.get_servers(servers,
0)
return servers
def setup_sdk_servers_mock(self, count):
servers = compute_fakes.FakeServer.create_sdk_servers(
attrs=self.attrs,
methods=self.methods,
count=count,
)
# This is the return value for compute_client.find_server()
self.sdk_client.find_server.side_effect = servers
return servers
def setup_sdk_volumes_mock(self, count):
volumes = volume_fakes.FakeVolume.create_sdk_volumes(count=count)
# This is the return value for volume_client.find_volume()
self.sdk_volume_client.find_volume.side_effect = volumes
return volumes
def run_method_with_servers(self, method_name, server_count):
servers = self.setup_servers_mock(server_count)
arglist = []
verifylist = []
for s in servers:
arglist.append(s.id)
verifylist = [
('server', arglist),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
for s in servers:
method = getattr(s, method_name)
if method_name == 'lock':
version = self.app.client_manager.compute.api_version
if version >= api_versions.APIVersion('2.73'):
method.assert_called_with(reason=None)
elif method_name == 'unshelve':
version = self.app.client_manager.compute.api_version
if version >= api_versions.APIVersion('2.77'):
method.assert_called_with(availability_zone=None)
else:
method.assert_called_with()
else:
method.assert_called_with()
self.assertIsNone(result)
def run_method_with_sdk_servers(self, method_name, server_count):
servers = self.setup_sdk_servers_mock(count=server_count)
arglist = [s.id for s in servers]
verifylist = [
('server', arglist),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
calls = [call(s.id) for s in servers]
method = getattr(self.sdk_client, method_name)
method.assert_has_calls(calls)
self.assertIsNone(result)
class TestServerAddFixedIP(TestServer):
def setUp(self):
super().setUp()
# Get the command object to test
self.cmd = server.AddFixedIP(self.app, None)
# Mock network methods
self.find_network = mock.Mock()
self.app.client_manager.network.find_network = self.find_network
@mock.patch.object(sdk_utils, 'supports_microversion')
def test_server_add_fixed_ip_pre_v244(self, sm_mock):
sm_mock.return_value = False
servers = self.setup_sdk_servers_mock(count=1)
network = compute_fakes.FakeNetwork.create_one_network()
with mock.patch.object(
self.app.client_manager,
'is_network_endpoint_enabled',
return_value=False
):
arglist = [
servers[0].id,
network['id'],
]
verifylist = [
('server', servers[0].id),
('network', network['id']),
('fixed_ip_address', None),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.sdk_client.add_fixed_ip_to_server.assert_called_once_with(
servers[0].id,
network['id']
)
# the legacy API operates asynchronously
self.assertEqual(((), ()), result)
@mock.patch.object(sdk_utils, 'supports_microversion')
def test_server_add_fixed_ip_pre_v244_with_fixed_ip(self, sm_mock):
sm_mock.return_value = False
servers = self.setup_sdk_servers_mock(count=1)
network = compute_fakes.FakeNetwork.create_one_network()
with mock.patch.object(
self.app.client_manager,
'is_network_endpoint_enabled',
return_value=False
):
arglist = [
servers[0].id,
network['id'],
'--fixed-ip-address', '5.6.7.8'
]
verifylist = [
('server', servers[0].id),
('network', network['id']),
('fixed_ip_address', '5.6.7.8'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.sdk_client.add_fixed_ip_to_server.assert_called_once_with(
servers[0].id,
network['id']
)
# the legacy API operates asynchronously
self.assertEqual(((), ()), result)
@mock.patch.object(sdk_utils, 'supports_microversion')
def test_server_add_fixed_ip_pre_v244_with_tag(self, sm_mock):
sm_mock.return_value = False
servers = self.setup_sdk_servers_mock(count=1)
network = compute_fakes.FakeNetwork.create_one_network()
with mock.patch.object(
self.app.client_manager,
'is_network_endpoint_enabled',
return_value=False
):
arglist = [
servers[0].id,
network['id'],
'--fixed-ip-address', '5.6.7.8',
'--tag', 'tag1'
]
verifylist = [
('server', servers[0].id),
('network', network['id']),
('fixed_ip_address', '5.6.7.8'),
('tag', 'tag1')
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
ex = self.assertRaises(
exceptions.CommandError,
self.cmd.take_action,
parsed_args)
self.assertIn(
'--os-compute-api-version 2.49 or greater is required',
str(ex))
@mock.patch.object(sdk_utils, 'supports_microversion')
def test_server_add_fixed_ip_pre_v249_with_tag(self, sm_mock):
sm_mock.side_effect = [False, True]
servers = self.setup_sdk_servers_mock(count=1)
network = compute_fakes.FakeNetwork.create_one_network()
with mock.patch.object(
self.app.client_manager,
'is_network_endpoint_enabled',
return_value=False
):
arglist = [
servers[0].id,
network['id'],
'--fixed-ip-address', '5.6.7.8',
'--tag', 'tag1'
]
verifylist = [
('server', servers[0].id),
('network', network['id']),
('fixed_ip_address', '5.6.7.8'),
('tag', 'tag1')
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
ex = self.assertRaises(
exceptions.CommandError,
self.cmd.take_action,
parsed_args)
self.assertIn(
'--os-compute-api-version 2.49 or greater is required',
str(ex))
@mock.patch.object(sdk_utils, 'supports_microversion')
def test_server_add_fixed_ip(self, sm_mock):
sm_mock.side_effect = [True, False]
servers = self.setup_sdk_servers_mock(count=1)
network = compute_fakes.FakeNetwork.create_one_network()
interface = compute_fakes.create_one_server_interface()
self.sdk_client.create_server_interface.return_value = interface
with mock.patch.object(
self.app.client_manager,
'is_network_endpoint_enabled',
return_value=False
):
arglist = [
servers[0].id,
network['id']
]
verifylist = [
('server', servers[0].id),
('network', network['id'])
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
expected_columns = (
'Port ID',
'Server ID',
'Network ID',
'MAC Address',
'Port State',
'Fixed IPs',
)
expected_data = (
interface.port_id,
interface.server_id,
interface.net_id,
interface.mac_addr,
interface.port_state,
format_columns.ListDictColumn(interface.fixed_ips),
)
columns, data = self.cmd.take_action(parsed_args)
self.assertEqual(expected_columns, columns)
self.assertEqual(expected_data, tuple(data))
self.sdk_client.create_server_interface.assert_called_once_with(
servers[0].id,
net_id=network['id'],
fixed_ip=None
)
@mock.patch.object(sdk_utils, 'supports_microversion')
def test_server_add_fixed_ip_with_fixed_ip(self, sm_mock):
sm_mock.side_effect = [True, True]
servers = self.setup_sdk_servers_mock(count=1)
network = compute_fakes.FakeNetwork.create_one_network()
interface = compute_fakes.create_one_server_interface()
self.sdk_client.create_server_interface.return_value = interface
with mock.patch.object(
self.app.client_manager,
'is_network_endpoint_enabled',
return_value=False
):
arglist = [
servers[0].id,
network['id'],
'--fixed-ip-address', '5.6.7.8'
]
verifylist = [
('server', servers[0].id),
('network', network['id']),
('fixed_ip_address', '5.6.7.8')
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
expected_columns = (
'Port ID',
'Server ID',
'Network ID',
'MAC Address',
'Port State',
'Fixed IPs',
'Tag',
)
expected_data = (
interface.port_id,
interface.server_id,
interface.net_id,
interface.mac_addr,
interface.port_state,
format_columns.ListDictColumn(interface.fixed_ips),
interface.tag,
)
columns, data = self.cmd.take_action(parsed_args)
self.assertEqual(expected_columns, columns)
self.assertEqual(expected_data, tuple(data))
self.sdk_client.create_server_interface.assert_called_once_with(
servers[0].id,
net_id=network['id'],
fixed_ip='5.6.7.8'
)
@mock.patch.object(sdk_utils, 'supports_microversion')
def test_server_add_fixed_ip_with_tag(self, sm_mock):
sm_mock.side_effect = [True, True, True]
servers = self.setup_sdk_servers_mock(count=1)
network = compute_fakes.FakeNetwork.create_one_network()
interface = compute_fakes.create_one_server_interface()
self.sdk_client.create_server_interface.return_value = interface
with mock.patch.object(
self.app.client_manager,
'is_network_endpoint_enabled',
return_value=False
):
arglist = [
servers[0].id,
network['id'],
'--fixed-ip-address', '5.6.7.8',
'--tag', 'tag1'
]
verifylist = [
('server', servers[0].id),
('network', network['id']),
('fixed_ip_address', '5.6.7.8'),
('tag', 'tag1')
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
expected_columns = (
'Port ID',
'Server ID',
'Network ID',
'MAC Address',
'Port State',
'Fixed IPs',
'Tag',
)
expected_data = (
interface.port_id,
interface.server_id,
interface.net_id,
interface.mac_addr,
interface.port_state,
format_columns.ListDictColumn(interface.fixed_ips),
interface.tag,
)
columns, data = self.cmd.take_action(parsed_args)
self.assertEqual(expected_columns, columns)
self.assertEqual(expected_data, tuple(data))
self.sdk_client.create_server_interface.assert_called_once_with(
servers[0].id,
net_id=network['id'],
fixed_ip='5.6.7.8',
tag='tag1',
)
@mock.patch(
'openstackclient.api.compute_v2.APIv2.floating_ip_add'
)
class TestServerAddFloatingIPCompute(compute_fakes.TestComputev2):
def setUp(self):
super(TestServerAddFloatingIPCompute, self).setUp()
self.app.client_manager.network_endpoint_enabled = False
# Get the command object to test
self.cmd = server.AddFloatingIP(self.app, None)
def test_server_add_floating_ip_default(self, fip_mock):
_floating_ip = compute_fakes.FakeFloatingIP.create_one_floating_ip()
arglist = [
'server1',
_floating_ip['ip'],
]
verifylist = [
('server', 'server1'),
('ip_address', _floating_ip['ip']),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.cmd.take_action(parsed_args)
fip_mock.assert_called_once_with(
'server1',
_floating_ip['ip'],
fixed_address=None,
)
def test_server_add_floating_ip_fixed(self, fip_mock):
_floating_ip = compute_fakes.FakeFloatingIP.create_one_floating_ip()
arglist = [
'--fixed-ip-address', _floating_ip['fixed_ip'],
'server1',
_floating_ip['ip'],
]
verifylist = [
('fixed_ip_address', _floating_ip['fixed_ip']),
('server', 'server1'),
('ip_address', _floating_ip['ip']),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.cmd.take_action(parsed_args)
fip_mock.assert_called_once_with(
'server1',
_floating_ip['ip'],
fixed_address=_floating_ip['fixed_ip'],
)
class TestServerAddFloatingIPNetwork(
TestServer,
network_fakes.TestNetworkV2,
):
def setUp(self):
super(TestServerAddFloatingIPNetwork, self).setUp()
self.app.client_manager.network = mock.Mock()
self.network = self.app.client_manager.network
self.network.update_ip = mock.Mock(return_value=None)
# Get the command object to test
self.cmd = server.AddFloatingIP(self.app, self.namespace)
def test_server_add_floating_ip(self):
_server = compute_fakes.FakeServer.create_one_server()
self.servers_mock.get.return_value = _server
_port = network_fakes.create_one_port()
_floating_ip = network_fakes.FakeFloatingIP.create_one_floating_ip()
self.network.find_ip = mock.Mock(return_value=_floating_ip)
self.network.ports = mock.Mock(return_value=[_port])
arglist = [
_server.id,
_floating_ip['floating_ip_address'],
]
verifylist = [
('server', _server.id),
('ip_address', _floating_ip['floating_ip_address']),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.cmd.take_action(parsed_args)
attrs = {
'port_id': _port.id,
}
self.network.find_ip.assert_called_once_with(
_floating_ip['floating_ip_address'],
ignore_missing=False,
)
self.network.ports.assert_called_once_with(
device_id=_server.id,
)
self.network.update_ip.assert_called_once_with(
_floating_ip,
**attrs
)
def test_server_add_floating_ip_no_ports(self):
server = compute_fakes.FakeServer.create_one_server()
floating_ip = network_fakes.FakeFloatingIP.create_one_floating_ip()
self.servers_mock.get.return_value = server
self.network.find_ip = mock.Mock(return_value=floating_ip)
self.network.ports = mock.Mock(return_value=[])
arglist = [
server.id,
floating_ip['floating_ip_address'],
]
verifylist = [
('server', server.id),
('ip_address', floating_ip['floating_ip_address']),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
ex = self.assertRaises(
exceptions.CommandError,
self.cmd.take_action,
parsed_args)
self.assertIn(
'No attached ports found to associate floating IP with',
str(ex))
self.network.find_ip.assert_called_once_with(
floating_ip['floating_ip_address'],
ignore_missing=False,
)
self.network.ports.assert_called_once_with(
device_id=server.id,
)
def test_server_add_floating_ip_no_external_gateway(self, success=False):
_server = compute_fakes.FakeServer.create_one_server()
self.servers_mock.get.return_value = _server
_port = network_fakes.create_one_port()
_floating_ip = network_fakes.FakeFloatingIP.create_one_floating_ip()
self.network.find_ip = mock.Mock(return_value=_floating_ip)
return_value = [_port]
# In the success case, we'll have two ports, where the first port is
# not attached to an external gateway but the second port is.
if success:
return_value.append(_port)
self.network.ports = mock.Mock(return_value=return_value)
side_effect = [sdk_exceptions.NotFoundException()]
if success:
side_effect.append(None)
self.network.update_ip = mock.Mock(side_effect=side_effect)
arglist = [
_server.id,
_floating_ip['floating_ip_address'],
]
verifylist = [
('server', _server.id),
('ip_address', _floating_ip['floating_ip_address']),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
if success:
self.cmd.take_action(parsed_args)
else:
self.assertRaises(sdk_exceptions.NotFoundException,
self.cmd.take_action, parsed_args)
attrs = {
'port_id': _port.id,
}
self.network.find_ip.assert_called_once_with(
_floating_ip['floating_ip_address'],
ignore_missing=False,
)
self.network.ports.assert_called_once_with(
device_id=_server.id,
)
if success:
self.assertEqual(2, self.network.update_ip.call_count)
calls = [mock.call(_floating_ip, **attrs)] * 2
self.network.update_ip.assert_has_calls(calls)
else:
self.network.update_ip.assert_called_once_with(
_floating_ip,
**attrs
)
def test_server_add_floating_ip_one_external_gateway(self):
self.test_server_add_floating_ip_no_external_gateway(success=True)
def test_server_add_floating_ip_with_fixed_ip(self):
_server = compute_fakes.FakeServer.create_one_server()
self.servers_mock.get.return_value = _server
_port = network_fakes.create_one_port()
_floating_ip = network_fakes.FakeFloatingIP.create_one_floating_ip()
self.network.find_ip = mock.Mock(return_value=_floating_ip)
self.network.ports = mock.Mock(return_value=[_port])
# The user has specified a fixed ip that matches one of the ports
# already attached to the instance.
arglist = [
'--fixed-ip-address', _port.fixed_ips[0]['ip_address'],
_server.id,
_floating_ip['floating_ip_address'],
]
verifylist = [
('fixed_ip_address', _port.fixed_ips[0]['ip_address']),
('server', _server.id),
('ip_address', _floating_ip['floating_ip_address']),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.cmd.take_action(parsed_args)
# We expect the update_ip call to specify a new fixed_ip_address which
# will overwrite the floating ip's existing fixed_ip_address.
attrs = {
'port_id': _port.id,
'fixed_ip_address': _port.fixed_ips[0]['ip_address'],
}
self.network.find_ip.assert_called_once_with(
_floating_ip['floating_ip_address'],
ignore_missing=False,
)
self.network.ports.assert_called_once_with(
device_id=_server.id,
)
self.network.update_ip.assert_called_once_with(
_floating_ip,
**attrs
)
def test_server_add_floating_ip_with_fixed_ip_no_port_found(self):
_server = compute_fakes.FakeServer.create_one_server()
self.servers_mock.get.return_value = _server
_port = network_fakes.create_one_port()
_floating_ip = network_fakes.FakeFloatingIP.create_one_floating_ip()
self.network.find_ip = mock.Mock(return_value=_floating_ip)
self.network.ports = mock.Mock(return_value=[_port])
# The user has specified a fixed ip that does not match any of the
# ports already attached to the instance.
nonexistent_ip = '10.0.0.9'
arglist = [
'--fixed-ip-address', nonexistent_ip,
_server.id,
_floating_ip['floating_ip_address'],
]
verifylist = [
('fixed_ip_address', nonexistent_ip),
('server', _server.id),
('ip_address', _floating_ip['floating_ip_address']),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.assertRaises(exceptions.CommandError, self.cmd.take_action,
parsed_args)
self.network.find_ip.assert_called_once_with(
_floating_ip['floating_ip_address'],
ignore_missing=False,
)
self.network.ports.assert_called_once_with(
device_id=_server.id,
)
self.network.update_ip.assert_not_called()
class TestServerAddPort(TestServer):
def setUp(self):
super(TestServerAddPort, self).setUp()
# Get the command object to test
self.cmd = server.AddPort(self.app, None)
# Set add_fixed_ip method to be tested.
self.methods = {
'interface_attach': None,
}
self.find_port = mock.Mock()
self.app.client_manager.network.find_port = self.find_port
def _test_server_add_port(self, port_id):
servers = self.setup_sdk_servers_mock(count=1)
port = 'fake-port'
arglist = [
servers[0].id,
port,
]
verifylist = [
('server', servers[0].id),
('port', port)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.sdk_client.create_server_interface.assert_called_once_with(
servers[0], port_id=port_id, fixed_ip=None)
self.assertIsNone(result)
def test_server_add_port(self):
self._test_server_add_port(self.find_port.return_value.id)
self.find_port.assert_called_once_with(
'fake-port', ignore_missing=False)
def test_server_add_port_no_neutron(self):
self.app.client_manager.network_endpoint_enabled = False
self._test_server_add_port('fake-port')
self.find_port.assert_not_called()
@mock.patch.object(sdk_utils, 'supports_microversion', return_value=True)
def test_server_add_port_with_tag(self, sm_mock):
self.app.client_manager.compute.api_version = api_versions.APIVersion(
'2.49')
servers = self.setup_sdk_servers_mock(count=1)
self.find_port.return_value.id = 'fake-port'
arglist = [
servers[0].id,
'fake-port',
'--tag', 'tag1',
]
verifylist = [
('server', servers[0].id),
('port', 'fake-port'),
('tag', 'tag1'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.assertIsNone(result)
self.sdk_client.create_server_interface.assert_called_once_with(
servers[0],
port_id='fake-port',
fixed_ip=None,
tag='tag1')
@mock.patch.object(sdk_utils, 'supports_microversion', return_value=False)
def test_server_add_port_with_tag_pre_v249(self, sm_mock):
self.app.client_manager.compute.api_version = api_versions.APIVersion(
'2.48')
servers = self.setup_servers_mock(count=1)
self.find_port.return_value.id = 'fake-port'
arglist = [
servers[0].id,
'fake-port',
'--tag', 'tag1',
]
verifylist = [
('server', servers[0].id),
('port', 'fake-port'),
('tag', 'tag1'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
ex = self.assertRaises(
exceptions.CommandError,
self.cmd.take_action,
parsed_args)
self.assertIn(
'--os-compute-api-version 2.49 or greater is required',
str(ex))
class TestServerVolume(TestServer):
def setUp(self):
super(TestServerVolume, self).setUp()
self.methods = {
'create_volume_attachment': None,
}
self.servers = self.setup_sdk_servers_mock(count=1)
self.volumes = self.setup_sdk_volumes_mock(count=1)
attrs = {
'server_id': self.servers[0].id,
'volume_id': self.volumes[0].id,
}
self.volume_attachment = \
compute_fakes.FakeVolumeAttachment.\
create_one_sdk_volume_attachment(attrs=attrs)
self.sdk_client.create_volume_attachment.return_value = \
self.volume_attachment
class TestServerAddVolume(TestServerVolume):
def setUp(self):
super(TestServerAddVolume, self).setUp()
# Get the command object to test
self.cmd = server.AddServerVolume(self.app, None)
@mock.patch.object(sdk_utils, 'supports_microversion', return_value=False)
def test_server_add_volume(self, sm_mock):
arglist = [
'--device', '/dev/sdb',
self.servers[0].id,
self.volumes[0].id,
]
verifylist = [
('server', self.servers[0].id),
('volume', self.volumes[0].id),
('device', '/dev/sdb'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
expected_columns = ('ID', 'Server ID', 'Volume ID', 'Device')
expected_data = (
self.volume_attachment.id,
self.volume_attachment.server_id,
self.volume_attachment.volume_id,
'/dev/sdb',
)
columns, data = self.cmd.take_action(parsed_args)
self.assertEqual(expected_columns, columns)
self.assertEqual(expected_data, data)
self.sdk_client.create_volume_attachment.assert_called_once_with(
self.servers[0], volumeId=self.volumes[0].id, device='/dev/sdb')
@mock.patch.object(sdk_utils, 'supports_microversion')
def test_server_add_volume_with_tag(self, sm_mock):
def side_effect(compute_client, version):
if version == '2.49':
return True
return False
sm_mock.side_effect = side_effect
arglist = [
'--device', '/dev/sdb',
'--tag', 'foo',
self.servers[0].id,
self.volumes[0].id,
]
verifylist = [
('server', self.servers[0].id),
('volume', self.volumes[0].id),
('device', '/dev/sdb'),
('tag', 'foo'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
expected_columns = ('ID', 'Server ID', 'Volume ID', 'Device', 'Tag')
expected_data = (
self.volume_attachment.id,
self.volume_attachment.server_id,
self.volume_attachment.volume_id,
self.volume_attachment.device,
self.volume_attachment.tag,
)
columns, data = self.cmd.take_action(parsed_args)
self.assertEqual(expected_columns, columns)
self.assertEqual(expected_data, data)
self.sdk_client.create_volume_attachment.assert_called_once_with(
self.servers[0],
volumeId=self.volumes[0].id,
device='/dev/sdb',
tag='foo')
@mock.patch.object(sdk_utils, 'supports_microversion', return_value=False)
def test_server_add_volume_with_tag_pre_v249(self, sm_mock):
arglist = [
self.servers[0].id,
self.volumes[0].id,
'--tag', 'foo',
]
verifylist = [
('server', self.servers[0].id),
('volume', self.volumes[0].id),
('tag', 'foo'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
ex = self.assertRaises(
exceptions.CommandError,
self.cmd.take_action,
parsed_args)
self.assertIn(
'--os-compute-api-version 2.49 or greater is required',
str(ex))
@mock.patch.object(sdk_utils, 'supports_microversion', return_value=True)
def test_server_add_volume_with_enable_delete_on_termination(
self,
sm_mock,
):
self.volume_attachment.delete_on_termination = True
arglist = [
'--enable-delete-on-termination',
'--device', '/dev/sdb',
self.servers[0].id,
self.volumes[0].id,
]
verifylist = [
('server', self.servers[0].id),
('volume', self.volumes[0].id),
('device', '/dev/sdb'),
('enable_delete_on_termination', True),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
expected_columns = (
'ID',
'Server ID',
'Volume ID',
'Device',
'Tag',
'Delete On Termination',
)
expected_data = (
self.volume_attachment.id,
self.volume_attachment.server_id,
self.volume_attachment.volume_id,
self.volume_attachment.device,
self.volume_attachment.tag,
self.volume_attachment.delete_on_termination,
)
columns, data = self.cmd.take_action(parsed_args)
self.assertEqual(expected_columns, columns)
self.assertEqual(expected_data, data)
self.sdk_client.create_volume_attachment.assert_called_once_with(
self.servers[0],
volumeId=self.volumes[0].id,
device='/dev/sdb',
delete_on_termination=True)
@mock.patch.object(sdk_utils, 'supports_microversion', return_value=True)
def test_server_add_volume_with_disable_delete_on_termination(
self,
sm_mock,
):
self.volume_attachment.delete_on_termination = False
arglist = [
'--disable-delete-on-termination',
'--device', '/dev/sdb',
self.servers[0].id,
self.volumes[0].id,
]
verifylist = [
('server', self.servers[0].id),
('volume', self.volumes[0].id),
('device', '/dev/sdb'),
('disable_delete_on_termination', True),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
expected_columns = (
'ID',
'Server ID',
'Volume ID',
'Device',
'Tag',
'Delete On Termination',
)
expected_data = (
self.volume_attachment.id,
self.volume_attachment.server_id,
self.volume_attachment.volume_id,
self.volume_attachment.device,
self.volume_attachment.tag,
self.volume_attachment.delete_on_termination,
)
columns, data = self.cmd.take_action(parsed_args)
self.assertEqual(expected_columns, columns)
self.assertEqual(expected_data, data)
self.sdk_client.create_volume_attachment.assert_called_once_with(
self.servers[0],
volumeId=self.volumes[0].id,
device='/dev/sdb',
delete_on_termination=False)
@mock.patch.object(sdk_utils, 'supports_microversion')
def test_server_add_volume_with_enable_delete_on_termination_pre_v279(
self,
sm_mock,
):
def side_effect(compute_client, version):
if version == '2.79':
return False
return True
sm_mock.side_effect = side_effect
arglist = [
self.servers[0].id,
self.volumes[0].id,
'--enable-delete-on-termination',
]
verifylist = [
('server', self.servers[0].id),
('volume', self.volumes[0].id),
('enable_delete_on_termination', True),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
ex = self.assertRaises(exceptions.CommandError,
self.cmd.take_action,
parsed_args)
self.assertIn('--os-compute-api-version 2.79 or greater is required',
str(ex))
@mock.patch.object(sdk_utils, 'supports_microversion')
def test_server_add_volume_with_disable_delete_on_termination_pre_v279(
self,
sm_mock,
):
def side_effect(compute_client, version):
if version == '2.79':
return False
return True
sm_mock.side_effect = side_effect
arglist = [
self.servers[0].id,
self.volumes[0].id,
'--disable-delete-on-termination',
]
verifylist = [
('server', self.servers[0].id),
('volume', self.volumes[0].id),
('disable_delete_on_termination', True),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
ex = self.assertRaises(exceptions.CommandError,
self.cmd.take_action,
parsed_args)
self.assertIn('--os-compute-api-version 2.79 or greater is required',
str(ex))
@mock.patch.object(sdk_utils, 'supports_microversion', return_value=True)
def test_server_add_volume_with_disable_and_enable_delete_on_termination(
self,
sm_mock,
):
arglist = [
'--enable-delete-on-termination',
'--disable-delete-on-termination',
'--device', '/dev/sdb',
self.servers[0].id,
self.volumes[0].id,
]
verifylist = [
('server', self.servers[0].id),
('volume', self.volumes[0].id),
('device', '/dev/sdb'),
('enable_delete_on_termination', True),
('disable_delete_on_termination', True),
]
ex = self.assertRaises(utils.ParserException,
self.check_parser,
self.cmd, arglist, verifylist)
self.assertIn('argument --disable-delete-on-termination: not allowed '
'with argument --enable-delete-on-termination', str(ex))
class TestServerRemoveVolume(TestServerVolume):
def setUp(self):
super(TestServerRemoveVolume, self).setUp()
# Get the command object to test
self.cmd = server.RemoveServerVolume(self.app, None)
def test_server_remove_volume(self):
arglist = [
self.servers[0].id,
self.volumes[0].id,
]
verifylist = [
('server', self.servers[0].id),
('volume', self.volumes[0].id),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.assertIsNone(result)
self.sdk_client.delete_volume_attachment.assert_called_once_with(
self.volumes[0],
self.servers[0],
ignore_missing=False,
)
class TestServerAddNetwork(TestServer):
def setUp(self):
super(TestServerAddNetwork, self).setUp()
# Get the command object to test
self.cmd = server.AddNetwork(self.app, None)
# Set add_fixed_ip method to be tested.
self.methods = {
'interface_attach': None,
}
self.find_network = mock.Mock()
self.app.client_manager.network.find_network = self.find_network
def _test_server_add_network(self, net_id):
servers = self.setup_sdk_servers_mock(count=1)
network = 'fake-network'
arglist = [
servers[0].id,
network,
]
verifylist = [
('server', servers[0].id),
('network', network)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.sdk_client.create_server_interface.assert_called_once_with(
servers[0], net_id=net_id, fixed_ip=None)
self.assertIsNone(result)
def test_server_add_network(self):
self._test_server_add_network(self.find_network.return_value.id)
self.find_network.assert_called_once_with(
'fake-network', ignore_missing=False)
def test_server_add_network_no_neutron(self):
self.app.client_manager.network_endpoint_enabled = False
self._test_server_add_network('fake-network')
self.find_network.assert_not_called()
@mock.patch.object(sdk_utils, 'supports_microversion', return_value=True)
def test_server_add_network_with_tag(self, sm_mock):
self.app.client_manager.compute.api_version = api_versions.APIVersion(
'2.49')
servers = self.setup_sdk_servers_mock(count=1)
self.find_network.return_value.id = 'fake-network'
arglist = [
servers[0].id,
'fake-network',
'--tag', 'tag1',
]
verifylist = [
('server', servers[0].id),
('network', 'fake-network'),
('tag', 'tag1'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.assertIsNone(result)
self.sdk_client.create_server_interface.assert_called_once_with(
servers[0],
net_id='fake-network',
fixed_ip=None,
tag='tag1'
)
@mock.patch.object(sdk_utils, 'supports_microversion', return_value=False)
def test_server_add_network_with_tag_pre_v249(self, sm_mock):
self.app.client_manager.compute.api_version = api_versions.APIVersion(
'2.48')
servers = self.setup_sdk_servers_mock(count=1)
self.find_network.return_value.id = 'fake-network'
arglist = [
servers[0].id,
'fake-network',
'--tag', 'tag1',
]
verifylist = [
('server', servers[0].id),
('network', 'fake-network'),
('tag', 'tag1'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
ex = self.assertRaises(
exceptions.CommandError,
self.cmd.take_action,
parsed_args)
self.assertIn(
'--os-compute-api-version 2.49 or greater is required',
str(ex))
@mock.patch(
'openstackclient.api.compute_v2.APIv2.security_group_find'
)
class TestServerAddSecurityGroup(TestServer):
def setUp(self):
super(TestServerAddSecurityGroup, self).setUp()
self.security_group = \
compute_fakes.FakeSecurityGroup.create_one_security_group()
attrs = {
'security_groups': [{'name': self.security_group['id']}]
}
methods = {
'add_security_group': None,
}
self.server = compute_fakes.FakeServer.create_one_server(
attrs=attrs,
methods=methods
)
# This is the return value for utils.find_resource() for server
self.servers_mock.get.return_value = self.server
# Get the command object to test
self.cmd = server.AddServerSecurityGroup(self.app, None)
def test_server_add_security_group(self, sg_find_mock):
sg_find_mock.return_value = self.security_group
arglist = [
self.server.id,
self.security_group['id']
]
verifylist = [
('server', self.server.id),
('group', self.security_group['id']),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
sg_find_mock.assert_called_with(
self.security_group['id'],
)
self.servers_mock.get.assert_called_with(self.server.id)
self.server.add_security_group.assert_called_with(
self.security_group['id'],
)
self.assertIsNone(result)
class TestServerCreate(TestServer):
columns = (
'OS-EXT-STS:power_state',
'addresses',
'flavor',
'id',
'image',
'name',
'networks',
'properties',
)
def datalist(self):
datalist = (
server.PowerStateColumn(
getattr(self.new_server, 'OS-EXT-STS:power_state')),
format_columns.DictListColumn({}),
self.flavor.name + ' (' + self.new_server.flavor.get('id') + ')',
self.new_server.id,
self.image.name + ' (' + self.new_server.image.get('id') + ')',
self.new_server.name,
self.new_server.networks,
format_columns.DictColumn(self.new_server.metadata),
)
return datalist
def setUp(self):
super(TestServerCreate, self).setUp()
attrs = {
'networks': {},
}
self.new_server = compute_fakes.FakeServer.create_one_server(
attrs=attrs)
# This is the return value for utils.find_resource().
# This is for testing --wait option.
self.servers_mock.get.return_value = self.new_server
self.servers_mock.create.return_value = self.new_server
self.image = image_fakes.create_one_image()
self.find_image_mock.return_value = self.image
self.get_image_mock.return_value = self.image
self.flavor = compute_fakes.FakeFlavor.create_one_flavor()
self.flavors_mock.get.return_value = self.flavor
self.volume = volume_fakes.FakeVolume.create_one_volume()
self.volumes_mock.get.return_value = self.volume
self.snapshot = volume_fakes.FakeSnapshot.create_one_snapshot()
self.snapshots_mock.get.return_value = self.snapshot
# Get the command object to test
self.cmd = server.CreateServer(self.app, None)
def test_server_create_no_options(self):
arglist = [
self.new_server.name,
]
verifylist = [
('server_name', self.new_server.name),
]
self.assertRaises(utils.ParserException, self.check_parser,
self.cmd, arglist, verifylist)
def test_server_create_minimal(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# In base command class ShowOne in cliff, abstract method take_action()
# returns a two-part tuple with a tuple of column names and a tuple of
# data to be shown.
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[],
userdata=None,
key_name=None,
availability_zone=None,
admin_pass=None,
block_device_mapping_v2=[],
nics=[],
scheduler_hints={},
config_drive=None,
)
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
self.assertFalse(self.images_mock.called)
self.assertFalse(self.flavors_mock.called)
def test_server_create_with_options(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--key-name', 'keyname',
'--property', 'Beta=b',
'--security-group', 'securitygroup',
'--use-config-drive',
'--password', 'passw0rd',
'--hint', 'a=b',
'--hint', 'a=c',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('key_name', 'keyname'),
('properties', {'Beta': 'b'}),
('security_group', ['securitygroup']),
('hint', {'a': ['b', 'c']}),
('config_drive', True),
('password', 'passw0rd'),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# In base command class ShowOne in cliff, abstract method take_action()
# returns a two-part tuple with a tuple of column names and a tuple of
# data to be shown.
fake_sg = network_fakes.FakeSecurityGroup.create_security_groups()
mock_find_sg = (
network_fakes.FakeSecurityGroup.get_security_groups(fake_sg)
)
self.app.client_manager.network.find_security_group = mock_find_sg
columns, data = self.cmd.take_action(parsed_args)
mock_find_sg.assert_called_once_with('securitygroup',
ignore_missing=False)
# Set expected values
kwargs = dict(
meta={'Beta': 'b'},
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[fake_sg[0].id],
userdata=None,
key_name='keyname',
availability_zone=None,
admin_pass='passw0rd',
block_device_mapping_v2=[],
nics=[],
scheduler_hints={'a': ['b', 'c']},
config_drive=True,
)
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
def test_server_create_with_not_exist_security_group(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--key-name', 'keyname',
'--security-group', 'securitygroup',
'--security-group', 'not_exist_sg',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('key_name', 'keyname'),
('security_group', ['securitygroup', 'not_exist_sg']),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
fake_sg = network_fakes.FakeSecurityGroup.create_security_groups(
count=1)
fake_sg.append(exceptions.NotFound(code=404))
mock_find_sg = (
network_fakes.FakeSecurityGroup.get_security_groups(fake_sg)
)
self.app.client_manager.network.find_security_group = mock_find_sg
self.assertRaises(exceptions.NotFound,
self.cmd.take_action,
parsed_args)
mock_find_sg.assert_called_with('not_exist_sg',
ignore_missing=False)
def test_server_create_with_security_group_in_nova_network(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--key-name', 'keyname',
'--security-group', 'securitygroup',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('key_name', 'keyname'),
('security_group', ['securitygroup']),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
with mock.patch.object(self.app.client_manager,
'is_network_endpoint_enabled',
return_value=False):
with mock.patch.object(self.app.client_manager.compute.api,
'security_group_find',
return_value={'name': 'fake_sg'}
) as mock_find:
columns, data = self.cmd.take_action(parsed_args)
mock_find.assert_called_once_with('securitygroup')
# Set expected values
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=['fake_sg'],
userdata=None,
key_name='keyname',
availability_zone=None,
admin_pass=None,
block_device_mapping_v2=[],
nics=[],
scheduler_hints={},
config_drive=None,
)
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
def test_server_create_with_network(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--network', 'net1',
'--nic', 'net-id=net1,v4-fixed-ip=10.0.0.2',
'--port', 'port1',
'--network', 'net1',
'--nic', 'port-id=port2',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('nics', [
{
'net-id': 'net1', 'port-id': '',
'v4-fixed-ip': '', 'v6-fixed-ip': '',
},
{
'net-id': 'net1', 'port-id': '',
'v4-fixed-ip': '10.0.0.2', 'v6-fixed-ip': '',
},
{
'net-id': '', 'port-id': 'port1',
'v4-fixed-ip': '', 'v6-fixed-ip': '',
},
{
'net-id': 'net1', 'port-id': '',
'v4-fixed-ip': '', 'v6-fixed-ip': '',
},
{
'net-id': '', 'port-id': 'port2',
'v4-fixed-ip': '', 'v6-fixed-ip': '',
},
]),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
get_endpoints = mock.Mock()
get_endpoints.return_value = {'network': []}
self.app.client_manager.auth_ref = mock.Mock()
self.app.client_manager.auth_ref.service_catalog = mock.Mock()
self.app.client_manager.auth_ref.service_catalog.get_endpoints = (
get_endpoints)
find_network = mock.Mock()
find_port = mock.Mock()
network_client = self.app.client_manager.network
network_client.find_network = find_network
network_client.find_port = find_port
network_resource = mock.Mock(id='net1_uuid')
port1_resource = mock.Mock(id='port1_uuid')
port2_resource = mock.Mock(id='port2_uuid')
find_network.return_value = network_resource
find_port.side_effect = (lambda port_id, ignore_missing:
{"port1": port1_resource,
"port2": port2_resource}[port_id])
# Mock sdk APIs.
_network = mock.Mock(id='net1_uuid')
_port1 = mock.Mock(id='port1_uuid')
_port2 = mock.Mock(id='port2_uuid')
find_network = mock.Mock()
find_port = mock.Mock()
find_network.return_value = _network
find_port.side_effect = (lambda port_id, ignore_missing:
{"port1": _port1,
"port2": _port2}[port_id])
self.app.client_manager.network.find_network = find_network
self.app.client_manager.network.find_port = find_port
# In base command class ShowOne in cliff, abstract method take_action()
# returns a two-part tuple with a tuple of column names and a tuple of
# data to be shown.
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[],
userdata=None,
key_name=None,
availability_zone=None,
admin_pass=None,
block_device_mapping_v2=[],
nics=[{'net-id': 'net1_uuid',
'v4-fixed-ip': '',
'v6-fixed-ip': '',
'port-id': ''},
{'net-id': 'net1_uuid',
'v4-fixed-ip': '10.0.0.2',
'v6-fixed-ip': '',
'port-id': ''},
{'net-id': '',
'v4-fixed-ip': '',
'v6-fixed-ip': '',
'port-id': 'port1_uuid'},
{'net-id': 'net1_uuid',
'v4-fixed-ip': '',
'v6-fixed-ip': '',
'port-id': ''},
{'net-id': '',
'v4-fixed-ip': '',
'v6-fixed-ip': '',
'port-id': 'port2_uuid'}],
scheduler_hints={},
config_drive=None,
)
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
def test_server_create_with_network_tag(self):
self.app.client_manager.compute.api_version = api_versions.APIVersion(
'2.43')
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--nic', 'net-id=net1,tag=foo',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('nics', [
{
'net-id': 'net1', 'port-id': '',
'v4-fixed-ip': '', 'v6-fixed-ip': '',
'tag': 'foo',
},
]),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
find_network = mock.Mock()
network_client = self.app.client_manager.network
network_client.find_network = find_network
network_resource = mock.Mock(id='net1_uuid')
find_network.return_value = network_resource
# Mock sdk APIs.
_network = mock.Mock(id='net1_uuid')
find_network = mock.Mock()
find_network.return_value = _network
self.app.client_manager.network.find_network = find_network
# In base command class ShowOne in cliff, abstract method take_action()
# returns a two-part tuple with a tuple of column names and a tuple of
# data to be shown.
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[],
userdata=None,
key_name=None,
availability_zone=None,
admin_pass=None,
block_device_mapping_v2=[],
nics=[
{
'net-id': 'net1_uuid',
'v4-fixed-ip': '',
'v6-fixed-ip': '',
'port-id': '',
'tag': 'foo',
},
],
scheduler_hints={},
config_drive=None,
)
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
network_client.find_network.assert_called_once()
self.app.client_manager.network.find_network.assert_called_once()
def test_server_create_with_network_tag_pre_v243(self):
self.app.client_manager.compute.api_version = api_versions.APIVersion(
'2.42')
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--nic', 'net-id=net1,tag=foo',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('nics', [
{
'net-id': 'net1', 'port-id': '',
'v4-fixed-ip': '', 'v6-fixed-ip': '',
'tag': 'foo',
},
]),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.assertRaises(
exceptions.CommandError, self.cmd.take_action, parsed_args)
def test_server_create_with_auto_network(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--nic', 'auto',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('nics', ['auto']),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[],
userdata=None,
key_name=None,
availability_zone=None,
admin_pass=None,
block_device_mapping_v2=[],
nics='auto',
scheduler_hints={},
config_drive=None,
)
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
def test_server_create_with_auto_network_default_v2_37(self):
"""Tests creating a server without specifying --nic using 2.37."""
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# Since check_parser doesn't handle compute global options like
# --os-compute-api-version, we have to mock the construction of
# the novaclient client object with our own APIVersion.
with mock.patch.object(self.app.client_manager.compute, 'api_version',
api_versions.APIVersion('2.37')):
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[],
userdata=None,
key_name=None,
availability_zone=None,
admin_pass=None,
block_device_mapping_v2=[],
nics='auto',
scheduler_hints={},
config_drive=None,
)
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
def test_server_create_with_none_network(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--nic', 'none',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('nics', ['none']),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[],
userdata=None,
key_name=None,
availability_zone=None,
admin_pass=None,
block_device_mapping_v2=[],
nics='none',
scheduler_hints={},
config_drive=None,
)
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
def test_server_create_with_conflict_network_options(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--nic', 'none',
'--nic', 'auto',
'--nic', 'port-id=port1',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('nics', [
'none',
'auto',
{
'net-id': '', 'port-id': 'port1',
'v4-fixed-ip': '', 'v6-fixed-ip': '',
},
]),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
get_endpoints = mock.Mock()
get_endpoints.return_value = {'network': []}
self.app.client_manager.auth_ref = mock.Mock()
self.app.client_manager.auth_ref.service_catalog = mock.Mock()
self.app.client_manager.auth_ref.service_catalog.get_endpoints = (
get_endpoints)
find_port = mock.Mock()
network_client = self.app.client_manager.network
network_client.find_port = find_port
port_resource = mock.Mock(id='port1_uuid')
find_port.return_value = port_resource
self.assertRaises(exceptions.CommandError,
self.cmd.take_action, parsed_args)
self.assertNotCalled(self.servers_mock.create)
def test_server_create_with_invalid_network_options(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--nic', 'abcdefgh',
self.new_server.name,
]
self.assertRaises(
argparse.ArgumentTypeError,
self.check_parser,
self.cmd, arglist, [])
self.assertNotCalled(self.servers_mock.create)
def test_server_create_with_invalid_network_key(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--nic', 'abcdefgh=12324',
self.new_server.name,
]
self.assertRaises(
argparse.ArgumentTypeError,
self.check_parser,
self.cmd, arglist, [])
self.assertNotCalled(self.servers_mock.create)
def test_server_create_with_empty_network_key_value(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--nic', 'net-id=',
self.new_server.name,
]
self.assertRaises(
argparse.ArgumentTypeError,
self.check_parser,
self.cmd, arglist, [])
self.assertNotCalled(self.servers_mock.create)
def test_server_create_with_only_network_key(self):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--nic', 'net-id',
self.new_server.name,
]
self.assertRaises(
argparse.ArgumentTypeError,
self.check_parser,
self.cmd, arglist, [])
self.assertNotCalled(self.servers_mock.create)
@mock.patch.object(common_utils, 'wait_for_status', return_value=True)
def test_server_create_with_wait_ok(self, mock_wait_for_status):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--wait',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('config_drive', False),
('wait', True),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
mock_wait_for_status.assert_called_once_with(
self.servers_mock.get,
self.new_server.id,
callback=mock.ANY,
)
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[],
userdata=None,
key_name=None,
availability_zone=None,
admin_pass=None,
block_device_mapping_v2=[],
nics=[],
scheduler_hints={},
config_drive=None,
)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
@mock.patch.object(common_utils, 'wait_for_status', return_value=False)
def test_server_create_with_wait_fails(self, mock_wait_for_status):
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--wait',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('config_drive', False),
('wait', True),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.assertRaises(SystemExit, self.cmd.take_action, parsed_args)
mock_wait_for_status.assert_called_once_with(
self.servers_mock.get,
self.new_server.id,
callback=mock.ANY,
)
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[],
userdata=None,
key_name=None,
availability_zone=None,
admin_pass=None,
block_device_mapping_v2=[],
nics=[],
scheduler_hints={},
config_drive=None,
)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
@mock.patch('openstackclient.compute.v2.server.io.open')
def test_server_create_userdata(self, mock_open):
mock_file = mock.Mock(name='File')
mock_open.return_value = mock_file
mock_open.read.return_value = '#!/bin/sh'
arglist = [
'--image', 'image1',
'--flavor', 'flavor1',
'--user-data', 'userdata.sh',
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', 'flavor1'),
('user_data', 'userdata.sh'),
('config_drive', False),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# In base command class ShowOne in cliff, abstract method take_action()
# returns a two-part tuple with a tuple of column names and a tuple of
# data to be shown.
columns, data = self.cmd.take_action(parsed_args)
# Ensure the userdata file is opened
mock_open.assert_called_with('userdata.sh')
# Ensure the userdata file is closed
mock_file.close.assert_called_with()
# Set expected values
kwargs = dict(
meta=None,
files={},
reservation_id=None,
min_count=1,
max_count=1,
security_groups=[],
userdata=mock_file,
key_name=None,
availability_zone=None,
admin_pass=None,
block_device_mapping_v2=[],
nics=[],
scheduler_hints={},
config_drive=None,
)
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
def test_server_create_with_volume(self):
arglist = [
'--flavor', self.flavor.id,
'--volume', self.volume.name,
self.new_server.name,
]
verifylist = [
('flavor', self.flavor.id),
('volume', self.volume.name),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# CreateServer.take_action() returns two tuples
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = {
'meta': None,
'files': {},
'reservation_id': None,
'min_count': 1,
'max_count': 1,
'security_groups': [],
'userdata': None,
'key_name': None,
'availability_zone': None,
'admin_pass': None,
'block_device_mapping_v2': [{
'uuid': self.volume.id,
'boot_index': '0',
'source_type': 'volume',
'destination_type': 'volume',
}],
'nics': [],
'scheduler_hints': {},
'config_drive': None,
}
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
None,
self.flavor,
**kwargs
)
self.volumes_mock.get.assert_called_once_with(
self.volume.name)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
def test_server_create_with_snapshot(self):
arglist = [
'--flavor', self.flavor.id,
'--snapshot', self.snapshot.name,
self.new_server.name,
]
verifylist = [
('flavor', self.flavor.id),
('snapshot', self.snapshot.name),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# CreateServer.take_action() returns two tuples
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = {
'meta': None,
'files': {},
'reservation_id': None,
'min_count': 1,
'max_count': 1,
'security_groups': [],
'userdata': None,
'key_name': None,
'availability_zone': None,
'admin_pass': None,
'block_device_mapping_v2': [{
'uuid': self.snapshot.id,
'boot_index': '0',
'source_type': 'snapshot',
'destination_type': 'volume',
'delete_on_termination': False,
}],
'nics': [],
'scheduler_hints': {},
'config_drive': None,
}
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
None,
self.flavor,
**kwargs
)
self.snapshots_mock.get.assert_called_once_with(
self.snapshot.name)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
def test_server_create_with_block_device(self):
block_device = f'uuid={self.volume.id},source_type=volume'
arglist = [
'--image', 'image1',
'--flavor', self.flavor.id,
'--block-device', block_device,
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', self.flavor.id),
('block_devices', [
{
'uuid': self.volume.id,
'source_type': 'volume',
},
]),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# CreateServer.take_action() returns two tuples
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = {
'meta': None,
'files': {},
'reservation_id': None,
'min_count': 1,
'max_count': 1,
'security_groups': [],
'userdata': None,
'key_name': None,
'availability_zone': None,
'admin_pass': None,
'block_device_mapping_v2': [{
'uuid': self.volume.id,
'source_type': 'volume',
'destination_type': 'volume',
}],
'nics': [],
'scheduler_hints': {},
'config_drive': None,
}
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,
self.flavor,
**kwargs
)
self.assertEqual(self.columns, columns)
self.assertEqual(self.datalist(), data)
def test_server_create_with_block_device_full(self):
self.app.client_manager.compute.api_version = api_versions.APIVersion(
'2.67')
block_device = (
f'uuid={self.volume.id},source_type=volume,'
f'destination_type=volume,disk_bus=ide,device_type=disk,'
f'device_name=sdb,guest_format=ext4,volume_size=64,'
f'volume_type=foo,boot_index=1,delete_on_termination=true,'
f'tag=foo'
)
arglist = [
'--image', 'image1',
'--flavor', self.flavor.id,
'--block-device', block_device,
self.new_server.name,
]
verifylist = [
('image', 'image1'),
('flavor', self.flavor.id),
('block_devices', [
{
'uuid': self.volume.id,
'source_type': 'volume',
'destination_type': 'volume',
'disk_bus': 'ide',
'device_type': 'disk',
'device_name': 'sdb',
'guest_format': 'ext4',
'volume_size': '64',
'volume_type': 'foo',
'boot_index': '1',
'delete_on_termination': 'true',
'tag': 'foo',
},
]),
('server_name', self.new_server.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# CreateServer.take_action() returns two tuples
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = {
'meta': None,
'files': {},
'reservation_id': None,
'min_count': 1,
'max_count': 1,
'security_groups': [],
'userdata': None,
'key_name': None,
'availability_zone': None,
'admin_pass': None,
'block_device_mapping_v2': [{
'uuid': self.volume.id,
'source_type': 'volume',
'destination_type': 'volume',
'disk_bus': 'ide',
'device_name': 'sdb',
'volume_size': '64',
'guest_format': 'ext4',
'boot_index': 1,
'device_type': 'disk',
'delete_on_termination': True,
'tag': 'foo',
'volume_type': 'foo',
}],
'nics': 'auto',
'scheduler_hints': {},
'config_drive': None,
}
# ServerManager.create(name, image, flavor, **kwargs)
self.servers_mock.create.assert_called_with(
self.new_server.name,
self.image,