diff options
-rw-r--r-- | INFO | 1 | ||||
-rw-r--r-- | INFO.yaml | 4 | ||||
-rw-r--r-- | ansible/roles/infra_destroy_previous_configuration/tasks/delete_vm.yml | 29 | ||||
-rw-r--r-- | ansible/roles/infra_destroy_previous_configuration/tasks/main.yml | 15 | ||||
-rw-r--r-- | samples/vnf_samples/nsut/vfw/tc_heat_rfc2544_ipv4_1rule_1flow_64B_trex.yaml | 7 | ||||
-rw-r--r-- | yardstick/benchmark/contexts/heat.py | 2 | ||||
-rw-r--r-- | yardstick/benchmark/core/task.py | 6 | ||||
-rw-r--r-- | yardstick/benchmark/scenarios/lib/delete_network.py | 9 | ||||
-rw-r--r-- | yardstick/common/openstack_utils.py | 52 | ||||
-rw-r--r-- | yardstick/tests/fixture.py | 47 | ||||
-rw-r--r-- | yardstick/tests/unit/benchmark/core/test_plugin.py | 204 | ||||
-rw-r--r-- | yardstick/tests/unit/benchmark/core/test_task.py | 132 | ||||
-rw-r--r-- | yardstick/tests/unit/benchmark/scenarios/lib/test_delete_network.py | 54 | ||||
-rw-r--r-- | yardstick/tests/unit/common/test_openstack_utils.py | 29 |
14 files changed, 369 insertions, 222 deletions
@@ -22,6 +22,7 @@ ross.b.brattain@intel.com chenjiankun1@huawei.com rodolfo.alonso.hernandez@intel.com emma.l.foley@intel.com +abhijit.sinha@intel.com Link to TSC approval: http://meetbot.opnfv.org/meetings/ Link to approval of additional submitters: @@ -74,6 +74,10 @@ committers: email: '14_ykl@tongji.edu.cn' company: 'tongji.edu.cn' id: 'tjuyinkanglin' + - name: 'Abhijit Sinha' + email: 'abhijit.sinha@intel.com' + company: 'intel.com' + id: 'abhijitsinha' tsc: # yamllint disable rule:line-length approval: 'http//meetbot.opnfv.org/meetings/' diff --git a/ansible/roles/infra_destroy_previous_configuration/tasks/delete_vm.yml b/ansible/roles/infra_destroy_previous_configuration/tasks/delete_vm.yml new file mode 100644 index 000000000..5e43ee81e --- /dev/null +++ b/ansible/roles/infra_destroy_previous_configuration/tasks/delete_vm.yml @@ -0,0 +1,29 @@ +# Copyright (c) 2017-2018 Intel Corporation. +# +# 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. +--- +# Ignore errors as VM can be destroyed without been undefined. +- name: Destroy old VMs + virt: + command: destroy + name: "{{ node_item.hostname }}" + when: node_item.hostname in virt_vms.list_vms + ignore_errors: yes + +# Ignore errors as VM can be running while undefined +- name: Undefine old VMs + virt: + command: undefine + name: "{{ node_item.hostname }}" + when: node_item.hostname in virt_vms.list_vms + ignore_errors: yes diff --git a/ansible/roles/infra_destroy_previous_configuration/tasks/main.yml b/ansible/roles/infra_destroy_previous_configuration/tasks/main.yml index 5595cd501..e6c2c0229 100644 --- a/ansible/roles/infra_destroy_previous_configuration/tasks/main.yml +++ b/ansible/roles/infra_destroy_previous_configuration/tasks/main.yml @@ -26,17 +26,10 @@ register: virt_vms - name: Destroy old VMs - virt: - command: destroy - name: "{{ item.hostname }}" - when: item.hostname in virt_vms.list_vms - with_items: "{{ infra_deploy_vars.nodes }}" - -- name: Undefine old VMs - virt: - command: undefine - name: "{{ item.hostname }}" - when: item.hostname in virt_vms.list_vms + include_tasks: delete_vm.yml + extra_vars: "{{ virt_vms }}" + loop_control: + loop_var: node_item with_items: "{{ infra_deploy_vars.nodes }}" - name: Delete old networks diff --git a/samples/vnf_samples/nsut/vfw/tc_heat_rfc2544_ipv4_1rule_1flow_64B_trex.yaml b/samples/vnf_samples/nsut/vfw/tc_heat_rfc2544_ipv4_1rule_1flow_64B_trex.yaml index 13fe5a5a5..2e096a126 100644 --- a/samples/vnf_samples/nsut/vfw/tc_heat_rfc2544_ipv4_1rule_1flow_64B_trex.yaml +++ b/samples/vnf_samples/nsut/vfw/tc_heat_rfc2544_ipv4_1rule_1flow_64B_trex.yaml @@ -15,6 +15,7 @@ --- {% set provider = provider or none %} {% set physical_networks = physical_networks or ['physnet1', 'physnet2'] %} +{% set segmentation_id = segmentation_id or none %} schema: yardstick:task:0.1 scenarios: @@ -74,6 +75,9 @@ context: {% if provider %} provider: {{ provider }} physical_network: {{ physical_networks[0] }} + {% if segmentation_id %} + segmentation_id: {{ segmentation_id }} + {% endif %} {% endif %} port_security_enabled: False enable_dhcp: 'false' @@ -83,6 +87,9 @@ context: {% if provider %} provider: {{ provider }} physical_network: {{ physical_networks[1] }} + {% if segmentation_id %} + segmentation_id: {{ segmentation_id }} + {% endif %} {% endif %} port_security_enabled: False enable_dhcp: 'false' diff --git a/yardstick/benchmark/contexts/heat.py b/yardstick/benchmark/contexts/heat.py index 4ba543b9e..d873ee8a1 100644 --- a/yardstick/benchmark/contexts/heat.py +++ b/yardstick/benchmark/contexts/heat.py @@ -95,8 +95,8 @@ class HeatContext(Context): return sorted_networks def init(self, attrs): - self.check_environment() """initializes itself from the supplied arguments""" + self.check_environment() self.name = attrs["name"] self._user = attrs.get("user") diff --git a/yardstick/benchmark/core/task.py b/yardstick/benchmark/core/task.py index 9b1b3f851..5fcc9182c 100644 --- a/yardstick/benchmark/core/task.py +++ b/yardstick/benchmark/core/task.py @@ -57,7 +57,7 @@ class Task(object): # pragma: no cover out_types = [s.strip() for s in dispatchers.split(',')] output_config['DEFAULT']['dispatcher'] = out_types - def start(self, args, **kwargs): + def start(self, args): """Start a benchmark scenario.""" atexit.register(self.atexit_handler) @@ -69,7 +69,7 @@ class Task(object): # pragma: no cover try: output_config = utils.parse_ini_file(CONF_FILE) - except Exception: + except Exception: # pylint: disable=broad-except # all error will be ignore, the default value is {} output_config = {} @@ -123,7 +123,7 @@ class Task(object): # pragma: no cover data = self._run(scenarios, run_in_parallel, args.output_file) except KeyboardInterrupt: raise - except Exception: + except Exception: # pylint: disable=broad-except LOG.error('Testcase: "%s" FAILED!!!', case_name, exc_info=True) testcases[case_name] = {'criteria': 'FAIL', 'tc_data': []} else: diff --git a/yardstick/benchmark/scenarios/lib/delete_network.py b/yardstick/benchmark/scenarios/lib/delete_network.py index e8796bf82..2e8b595f9 100644 --- a/yardstick/benchmark/scenarios/lib/delete_network.py +++ b/yardstick/benchmark/scenarios/lib/delete_network.py @@ -7,14 +7,12 @@ # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## -from __future__ import print_function -from __future__ import absolute_import - import logging from yardstick.benchmark.scenarios import base import yardstick.common.openstack_utils as op_utils + LOG = logging.getLogger(__name__) @@ -30,7 +28,7 @@ class DeleteNetwork(base.Scenario): self.network_id = self.options.get("network_id", None) - self.neutron_client = op_utils.get_neutron_client() + self.shade_client = op_utils.get_shade_client() self.setup_done = False @@ -45,7 +43,7 @@ class DeleteNetwork(base.Scenario): if not self.setup_done: self.setup() - status = op_utils.delete_neutron_net(self.neutron_client, + status = op_utils.delete_neutron_net(self.shade_client, network_id=self.network_id) if status: result.update({"delete_network": 1}) @@ -53,3 +51,4 @@ class DeleteNetwork(base.Scenario): else: result.update({"delete_network": 0}) LOG.error("Delete network failed!") + return status diff --git a/yardstick/common/openstack_utils.py b/yardstick/common/openstack_utils.py index c5b17c270..8f666e268 100644 --- a/yardstick/common/openstack_utils.py +++ b/yardstick/common/openstack_utils.py @@ -15,6 +15,7 @@ import logging from keystoneauth1 import loading from keystoneauth1 import session import shade +from shade import exc from cinderclient import client as cinderclient from novaclient import client as novaclient @@ -174,6 +175,7 @@ def get_glance_client(): # pragma: no cover def get_shade_client(): return shade.openstack_cloud() + # ********************************************* # NOVA # ********************************************* @@ -272,7 +274,8 @@ def create_aggregate_with_host(nova_client, aggregate_name, av_zone, def create_keypair(name, key_path=None): # pragma: no cover try: with open(key_path) as fpubkey: - keypair = get_nova_client().keypairs.create(name=name, public_key=fpubkey.read()) + keypair = get_nova_client().keypairs.create( + name=name, public_key=fpubkey.read()) return keypair except Exception: # pylint: disable=broad-except log.exception("Error [create_keypair(nova_client)]") @@ -304,9 +307,11 @@ def create_instance_and_wait_for_active(json_body): # pragma: no cover return None -def attach_server_volume(server_id, volume_id, device=None): # pragma: no cover +def attach_server_volume(server_id, volume_id, + device=None): # pragma: no cover try: - get_nova_client().volumes.create_server_volume(server_id, volume_id, device) + get_nova_client().volumes.create_server_volume(server_id, + volume_id, device) except Exception: # pylint: disable=broad-except log.exception("Error [attach_server_volume(nova_client, '%s', '%s')]", server_id, volume_id) @@ -370,7 +375,8 @@ def get_server_by_name(name): # pragma: no cover def create_flavor(name, ram, vcpus, disk, **kwargs): # pragma: no cover try: - return get_nova_client().flavors.create(name, ram, vcpus, disk, **kwargs) + return get_nova_client().flavors.create(name, ram, vcpus, + disk, **kwargs) except Exception: # pylint: disable=broad-except log.exception("Error [create_flavor(nova_client, %s, %s, %s, %s, %s)]", name, ram, disk, vcpus, kwargs['is_public']) @@ -455,13 +461,11 @@ def create_neutron_net(neutron_client, json_body): # pragma: no cover raise Exception("operation error") -def delete_neutron_net(neutron_client, network_id): # pragma: no cover +def delete_neutron_net(shade_client, network_id): try: - neutron_client.delete_network(network_id) - return True - except Exception: # pylint: disable=broad-except - log.error("Error [delete_neutron_net(neutron_client, '%s')]", - network_id) + return shade_client.delete_network(network_id) + except exc.OpenStackCloudException: + log.error("Error [delete_neutron_net(shade_client, '%s')]", network_id) return False @@ -558,7 +562,8 @@ def get_security_group_id(neutron_client, sg_name): # pragma: no cover return id -def create_security_group(neutron_client, sg_name, sg_description): # pragma: no cover +def create_security_group(neutron_client, sg_name, + sg_description): # pragma: no cover json_body = {'security_group': {'name': sg_name, 'description': sg_description}} try: @@ -611,8 +616,8 @@ def create_secgroup_rule(neutron_client, sg_id, direction, protocol, return False -def create_security_group_full(neutron_client, - sg_name, sg_description): # pragma: no cover +def create_security_group_full(neutron_client, sg_name, + sg_description): # pragma: no cover sg_id = get_security_group_id(neutron_client, sg_name) if sg_id != '': log.info("Using existing security group '%s'...", sg_name) @@ -670,22 +675,18 @@ def create_image(glance_client, image_name, file_path, disk_format, else: log.info("Creating image '%s' from '%s'...", image_name, file_path) - image = glance_client.images.create(name=image_name, - visibility=public, - disk_format=disk_format, - container_format=container_format, - min_disk=min_disk, - min_ram=min_ram, - tags=tag, - protected=protected, - **kwargs) + image = glance_client.images.create( + name=image_name, visibility=public, disk_format=disk_format, + container_format=container_format, min_disk=min_disk, + min_ram=min_ram, tags=tag, protected=protected, **kwargs) image_id = image.id with open(file_path) as image_data: glance_client.images.upload(image_id, image_data) return image_id except Exception: # pylint: disable=broad-except - log.error("Error [create_glance_image(glance_client, '%s', '%s', '%s')]", - image_name, file_path, public) + log.error( + "Error [create_glance_image(glance_client, '%s', '%s', '%s')]", + image_name, file_path, public) return None @@ -725,7 +726,8 @@ def create_volume(cinder_client, volume_name, volume_size, return None -def delete_volume(cinder_client, volume_id, forced=False): # pragma: no cover +def delete_volume(cinder_client, volume_id, + forced=False): # pragma: no cover try: if forced: try: diff --git a/yardstick/tests/fixture.py b/yardstick/tests/fixture.py new file mode 100644 index 000000000..94d20eb34 --- /dev/null +++ b/yardstick/tests/fixture.py @@ -0,0 +1,47 @@ +# Copyright 2017 Intel Corporation +# All Rights Reserved. +# +# 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 fixtures +import mock +import six + +from yardstick.common import task_template + + +class PluginParserFixture(fixtures.Fixture): + """PluginParser fixture. + + This class is intended to be used as a fixture within unit tests and + therefore consumers must register it using useFixture() within their + unit test class. + """ + + def __init__(self, rendered_plugin): + super(PluginParserFixture, self).__init__() + self._rendered_plugin = rendered_plugin + + def _setUp(self): + self.addCleanup(self._restore) + self._mock_tasktemplate_render = mock.patch.object( + task_template.TaskTemplate, 'render') + self.mock_tasktemplate_render = self._mock_tasktemplate_render.start() + self.mock_tasktemplate_render.return_value = self._rendered_plugin + self._mock_open = mock.patch.object(six.moves.builtins, 'open', create=True) + self.mock_open = self._mock_open.start() + self.mock_open.side_effect = mock.mock_open() + + def _restore(self): + self._mock_tasktemplate_render.stop() + self._mock_open.stop() diff --git a/yardstick/tests/unit/benchmark/core/test_plugin.py b/yardstick/tests/unit/benchmark/core/test_plugin.py index 1d6e80574..0d14e4e86 100644 --- a/yardstick/tests/unit/benchmark/core/test_plugin.py +++ b/yardstick/tests/unit/benchmark/core/test_plugin.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python - ############################################################################## # Copyright (c) 2016 Huawei Technologies Co.,Ltd and others. # @@ -9,94 +7,136 @@ # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## -# Unittest for yardstick.benchmark.core.plugin -from __future__ import absolute_import +import copy import os -from os.path import dirname as dirname +import pkg_resources -try: - from unittest import mock -except ImportError: - import mock -import unittest +import mock +import testtools +from yardstick import ssh from yardstick.benchmark.core import plugin +from yardstick.tests import fixture + +class PluginTestCase(testtools.TestCase): -class Arg(object): + FILE = """ +schema: "yardstick:plugin:0.1" - def __init__(self): - # self.input_file = ('plugin/sample_config.yaml',) - self.input_file = [ - os.path.join(os.path.abspath( - dirname(dirname(dirname(dirname(dirname(dirname(__file__))))))), - 'plugin/sample_config.yaml')] +plugins: + name: sample +deployment: + ip: 10.1.0.50 + user: root + password: root +""" -@mock.patch('yardstick.benchmark.core.plugin.ssh') -class pluginTestCase(unittest.TestCase): + NAME = 'sample' + DEPLOYMENT = {'ip': '10.1.0.50', 'user': 'root', 'password': 'root'} def setUp(self): - self.result = {} - - def test_install(self, mock_ssh): - p = plugin.Plugin() - mock_ssh.SSH.from_node().execute.return_value = (0, '', '') - input_file = Arg() - p.install(input_file) - expected_result = {} - self.assertEqual(self.result, expected_result) - - def test_remove(self, mock_ssh): - p = plugin.Plugin() - mock_ssh.SSH.from_node().execute.return_value = (0, '', '') - input_file = Arg() - p.remove(input_file) - expected_result = {} - self.assertEqual(self.result, expected_result) - - def test_install_setup_run(self, mock_ssh): - p = plugin.Plugin() - mock_ssh.SSH.from_node().execute.return_value = (0, '', '') - plugins = { - "name": "sample" - } - deployment = { - "ip": "10.1.0.50", - "user": "root", - "password": "root" - } - plugin_name = plugins.get("name") - p._install_setup(plugin_name, deployment) - self.assertIsNotNone(p.client) - - p._run(plugin_name) - expected_result = {} - self.assertEqual(self.result, expected_result) - - def test_remove_setup_run(self, mock_ssh): - p = plugin.Plugin() - mock_ssh.SSH.from_node().execute.return_value = (0, '', '') - plugins = { - "name": "sample" - } - deployment = { - "ip": "10.1.0.50", - "user": "root", - "password": "root" - } - plugin_name = plugins.get("name") - p._remove_setup(plugin_name, deployment) - self.assertIsNotNone(p.client) - - p._run(plugin_name) - expected_result = {} - self.assertEqual(self.result, expected_result) - - -def main(): - unittest.main() - - -if __name__ == '__main__': - main() + super(PluginTestCase, self).setUp() + self.plugin_parser = plugin.PluginParser(mock.Mock()) + self.plugin = plugin.Plugin() + self.useFixture(fixture.PluginParserFixture(PluginTestCase.FILE)) + + self._mock_ssh_from_node = mock.patch.object(ssh.SSH, 'from_node') + self.mock_ssh_from_node = self._mock_ssh_from_node.start() + self.mock_ssh_obj = mock.Mock() + self.mock_ssh_from_node.return_value = self.mock_ssh_obj + self.mock_ssh_obj.wait = mock.Mock() + self.mock_ssh_obj._put_file_shell = mock.Mock() + + self.addCleanup(self._cleanup) + + def _cleanup(self): + self._mock_ssh_from_node.stop() + + def test_install(self): + args = mock.Mock() + args.input_file = [mock.Mock()] + with mock.patch.object(self.plugin, '_install_setup') as \ + mock_install, \ + mock.patch.object(self.plugin, '_run') as mock_run: + self.plugin.install(args) + mock_install.assert_called_once_with(PluginTestCase.NAME, + PluginTestCase.DEPLOYMENT) + mock_run.assert_called_once_with(PluginTestCase.NAME) + + def test_remove(self): + args = mock.Mock() + args.input_file = [mock.Mock()] + with mock.patch.object(self.plugin, '_remove_setup') as \ + mock_remove, \ + mock.patch.object(self.plugin, '_run') as mock_run: + self.plugin.remove(args) + mock_remove.assert_called_once_with(PluginTestCase.NAME, + PluginTestCase.DEPLOYMENT) + mock_run.assert_called_once_with(PluginTestCase.NAME) + + @mock.patch.object(pkg_resources, 'resource_filename', + return_value='script') + def test__install_setup(self, mock_resource_filename): + plugin_name = 'plugin_name' + self.plugin._install_setup(plugin_name, PluginTestCase.DEPLOYMENT) + mock_resource_filename.assert_called_once_with( + 'yardstick.resources', 'scripts/install/' + plugin_name + '.bash') + self.mock_ssh_from_node.assert_called_once_with( + PluginTestCase.DEPLOYMENT) + self.mock_ssh_obj.wait.assert_called_once_with(timeout=600) + self.mock_ssh_obj._put_file_shell.assert_called_once_with( + 'script', '~/{0}.sh'.format(plugin_name)) + + @mock.patch.object(pkg_resources, 'resource_filename', + return_value='script') + @mock.patch.object(os, 'environ', return_value='1.2.3.4') + def test__install_setup_with_ip_local(self, mock_os_environ, + mock_resource_filename): + plugin_name = 'plugin_name' + deployment = copy.deepcopy(PluginTestCase.DEPLOYMENT) + deployment['ip'] = 'local' + self.plugin._install_setup(plugin_name, deployment) + mock_os_environ.__getitem__.assert_called_once_with('JUMP_HOST_IP') + mock_resource_filename.assert_called_once_with( + 'yardstick.resources', + 'scripts/install/' + plugin_name + '.bash') + self.mock_ssh_from_node.assert_called_once_with( + deployment, overrides={'ip': os.environ["JUMP_HOST_IP"]}) + self.mock_ssh_obj.wait.assert_called_once_with(timeout=600) + self.mock_ssh_obj._put_file_shell.assert_called_once_with( + 'script', '~/{0}.sh'.format(plugin_name)) + + @mock.patch.object(pkg_resources, 'resource_filename', + return_value='script') + def test__remove_setup(self, mock_resource_filename): + plugin_name = 'plugin_name' + self.plugin._remove_setup(plugin_name, PluginTestCase.DEPLOYMENT) + mock_resource_filename.assert_called_once_with( + 'yardstick.resources', + 'scripts/remove/' + plugin_name + '.bash') + self.mock_ssh_from_node.assert_called_once_with( + PluginTestCase.DEPLOYMENT) + self.mock_ssh_obj.wait.assert_called_once_with(timeout=600) + self.mock_ssh_obj._put_file_shell.assert_called_once_with( + 'script', '~/{0}.sh'.format(plugin_name)) + + @mock.patch.object(pkg_resources, 'resource_filename', + return_value='script') + @mock.patch.object(os, 'environ', return_value='1.2.3.4') + def test__remove_setup_with_ip_local(self, mock_os_environ, + mock_resource_filename): + plugin_name = 'plugin_name' + deployment = copy.deepcopy(PluginTestCase.DEPLOYMENT) + deployment['ip'] = 'local' + self.plugin._remove_setup(plugin_name, deployment) + mock_os_environ.__getitem__.assert_called_once_with('JUMP_HOST_IP') + mock_resource_filename.assert_called_once_with( + 'yardstick.resources', + 'scripts/remove/' + plugin_name + '.bash') + self.mock_ssh_from_node.assert_called_once_with( + deployment, overrides={'ip': os.environ["JUMP_HOST_IP"]}) + self.mock_ssh_obj.wait.assert_called_once_with(timeout=600) + self.mock_ssh_obj._put_file_shell.mock_os_environ( + 'script', '~/{0}.sh'.format(plugin_name)) diff --git a/yardstick/tests/unit/benchmark/core/test_task.py b/yardstick/tests/unit/benchmark/core/test_task.py index 3d9a10d88..bac035fb9 100644 --- a/yardstick/tests/unit/benchmark/core/test_task.py +++ b/yardstick/tests/unit/benchmark/core/test_task.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python - ############################################################################## # Copyright (c) 2015 Huawei Technologies Co.,Ltd and others. # @@ -9,43 +7,32 @@ # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## -# Unittest for yardstick.benchmark.core.task - -from __future__ import print_function - -from __future__ import absolute_import import os -import unittest - -try: - from unittest import mock -except ImportError: - import mock +import mock +import unittest from yardstick.benchmark.core import task from yardstick.common import constants as consts -# pylint: disable=unused-argument -# disable this for now because I keep forgetting mock patch arg ordering - - class TaskTestCase(unittest.TestCase): - @mock.patch('yardstick.benchmark.core.task.Context') - def test_parse_nodes_host_target_same_context(self, mock_context): - nodes = { - "host": "node1.LF", - "target": "node2.LF" + @mock.patch.object(task, 'Context') + def test_parse_nodes_with_context_same_context(self, mock_context): + scenario_cfg = { + "nodes": { + "host": "node1.LF", + "target": "node2.LF" + } } - scenario_cfg = {"nodes": nodes} server_info = { "ip": "10.20.0.3", "user": "root", "key_filename": "/root/.ssh/id_rsa" } mock_context.get_server.return_value = server_info + context_cfg = task.parse_nodes_with_context(scenario_cfg) self.assertEqual(context_cfg["host"], server_info) @@ -57,7 +44,7 @@ class TaskTestCase(unittest.TestCase): t._set_dispatchers(output_config) self.assertEqual(output_config, output_config) - @mock.patch('yardstick.benchmark.core.task.DispatcherBase') + @mock.patch.object(task, 'DispatcherBase') def test__do_output(self, mock_dispatcher): t = task.Task() output_config = {"DEFAULT": {"dispatcher": "file, http"}} @@ -65,7 +52,7 @@ class TaskTestCase(unittest.TestCase): mock.MagicMock()]) self.assertEqual(None, t._do_output(output_config, {})) - @mock.patch('yardstick.benchmark.core.task.Context') + @mock.patch.object(task, 'Context') def test_parse_networks_from_nodes(self, mock_context): nodes = { 'node1': { @@ -129,9 +116,9 @@ class TaskTestCase(unittest.TestCase): self.assertEqual(mock_context.get_network.call_count, expected_get_network_calls) self.assertDictEqual(networks, expected) - @mock.patch('yardstick.benchmark.core.task.Context') - @mock.patch('yardstick.benchmark.core.task.base_runner') - def test_run(self, mock_base_runner, mock_ctx): + @mock.patch.object(task, 'Context') + @mock.patch.object(task, 'base_runner') + def test_run(self, mock_base_runner, *args): scenario = { 'host': 'athena.demo', 'target': 'ares.demo', @@ -152,8 +139,8 @@ class TaskTestCase(unittest.TestCase): t._run([scenario], False, "yardstick.out") self.assertTrue(runner.run.called) - @mock.patch('yardstick.benchmark.core.task.os') - def test_check_precondition(self, mock_os): + @mock.patch.object(os, 'environ') + def test_check_precondition(self, mock_os_environ): cfg = { 'precondition': { 'installer_type': 'compass', @@ -163,7 +150,7 @@ class TaskTestCase(unittest.TestCase): } t = task.TaskParser('/opt') - mock_os.environ.get.side_effect = ['compass', + mock_os_environ.get.side_effect = ['compass', 'os-nosdn', 'huawei-pod1'] result = t._check_precondition(cfg) @@ -172,82 +159,75 @@ class TaskTestCase(unittest.TestCase): def test_parse_suite_no_constraint_no_args(self): SAMPLE_SCENARIO_PATH = "no_constraint_no_args_scenario_sample.yaml" t = task.TaskParser(self._get_file_abspath(SAMPLE_SCENARIO_PATH)) - with mock.patch('yardstick.benchmark.core.task.os.environ', + with mock.patch.object(os, 'environ', new={'NODE_NAME': 'huawei-pod1', 'INSTALLER_TYPE': 'compass'}): task_files, task_args, task_args_fnames = t.parse_suite() - print("files=%s, args=%s, fnames=%s" % (task_files, task_args, - task_args_fnames)) + self.assertEqual(task_files[0], self.change_to_abspath( 'tests/opnfv/test_cases/opnfv_yardstick_tc037.yaml')) self.assertEqual(task_files[1], self.change_to_abspath( 'tests/opnfv/test_cases/opnfv_yardstick_tc043.yaml')) - self.assertEqual(task_args[0], None) - self.assertEqual(task_args[1], None) - self.assertEqual(task_args_fnames[0], None) - self.assertEqual(task_args_fnames[1], None) - @mock.patch('yardstick.benchmark.core.task.os.environ') - def test_parse_suite_no_constraint_with_args(self, mock_environ): + self.assertIsNone(task_args[0]) + self.assertIsNone(task_args[1]) + self.assertIsNone(task_args_fnames[0]) + self.assertIsNone(task_args_fnames[1]) + + def test_parse_suite_no_constraint_with_args(self): SAMPLE_SCENARIO_PATH = "no_constraint_with_args_scenario_sample.yaml" t = task.TaskParser(self._get_file_abspath(SAMPLE_SCENARIO_PATH)) - with mock.patch('yardstick.benchmark.core.task.os.environ', + with mock.patch.object(os, 'environ', new={'NODE_NAME': 'huawei-pod1', 'INSTALLER_TYPE': 'compass'}): task_files, task_args, task_args_fnames = t.parse_suite() - print("files=%s, args=%s, fnames=%s" % (task_files, task_args, - task_args_fnames)) + self.assertEqual(task_files[0], self.change_to_abspath( 'tests/opnfv/test_cases/opnfv_yardstick_tc037.yaml')) self.assertEqual(task_files[1], self.change_to_abspath( 'tests/opnfv/test_cases/opnfv_yardstick_tc043.yaml')) - self.assertEqual(task_args[0], None) + self.assertIsNone(task_args[0]) self.assertEqual(task_args[1], '{"host": "node1.LF","target": "node2.LF"}') - self.assertEqual(task_args_fnames[0], None) - self.assertEqual(task_args_fnames[1], None) + self.assertIsNone(task_args_fnames[0]) + self.assertIsNone(task_args_fnames[1]) - @mock.patch('yardstick.benchmark.core.task.os.environ') - def test_parse_suite_with_constraint_no_args(self, mock_environ): + def test_parse_suite_with_constraint_no_args(self): SAMPLE_SCENARIO_PATH = "with_constraint_no_args_scenario_sample.yaml" t = task.TaskParser(self._get_file_abspath(SAMPLE_SCENARIO_PATH)) - with mock.patch('yardstick.benchmark.core.task.os.environ', + with mock.patch.object(os, 'environ', new={'NODE_NAME': 'huawei-pod1', 'INSTALLER_TYPE': 'compass'}): task_files, task_args, task_args_fnames = t.parse_suite() - print("files=%s, args=%s, fnames=%s" % (task_files, task_args, - task_args_fnames)) self.assertEqual(task_files[0], self.change_to_abspath( 'tests/opnfv/test_cases/opnfv_yardstick_tc037.yaml')) self.assertEqual(task_files[1], self.change_to_abspath( 'tests/opnfv/test_cases/opnfv_yardstick_tc043.yaml')) - self.assertEqual(task_args[0], None) - self.assertEqual(task_args[1], None) - self.assertEqual(task_args_fnames[0], None) - self.assertEqual(task_args_fnames[1], None) + self.assertIsNone(task_args[0]) + self.assertIsNone(task_args[1]) + self.assertIsNone(task_args_fnames[0]) + self.assertIsNone(task_args_fnames[1]) - @mock.patch('yardstick.benchmark.core.task.os.environ') - def test_parse_suite_with_constraint_with_args(self, mock_environ): + def test_parse_suite_with_constraint_with_args(self): SAMPLE_SCENARIO_PATH = "with_constraint_with_args_scenario_sample.yaml" t = task.TaskParser(self._get_file_abspath(SAMPLE_SCENARIO_PATH)) - with mock.patch('yardstick.benchmark.core.task.os.environ', + with mock.patch('os.environ', new={'NODE_NAME': 'huawei-pod1', 'INSTALLER_TYPE': 'compass'}): task_files, task_args, task_args_fnames = t.parse_suite() - print("files=%s, args=%s, fnames=%s" % (task_files, task_args, - task_args_fnames)) + self.assertEqual(task_files[0], self.change_to_abspath( 'tests/opnfv/test_cases/opnfv_yardstick_tc037.yaml')) self.assertEqual(task_files[1], self.change_to_abspath( 'tests/opnfv/test_cases/opnfv_yardstick_tc043.yaml')) - self.assertEqual(task_args[0], None) + self.assertIsNone(task_args[0]) self.assertEqual(task_args[1], '{"host": "node1.LF","target": "node2.LF"}') - self.assertEqual(task_args_fnames[0], None) - self.assertEqual(task_args_fnames[1], None) + self.assertIsNone(task_args_fnames[0]) + self.assertIsNone(task_args_fnames[1]) def test_parse_options(self): options = { 'openstack': { 'EXTERNAL_NETWORK': '$network' }, - 'ndoes': ['node1', '$node'], + 'nodes': ['node1', '$node'], 'host': '$host' } @@ -258,48 +238,50 @@ class TaskTestCase(unittest.TestCase): 'host': 'server.yardstick' } - idle_result = { + expected_result = { 'openstack': { 'EXTERNAL_NETWORK': 'ext-net' }, - 'ndoes': ['node1', 'node2'], + 'nodes': ['node1', 'node2'], 'host': 'server.yardstick' } actual_result = t._parse_options(options) - self.assertEqual(idle_result, actual_result) + self.assertEqual(expected_result, actual_result) + def test_change_server_name_host_str(self): scenario = {'host': 'demo'} suffix = '-8' task.change_server_name(scenario, suffix) - self.assertTrue(scenario['host'], 'demo-8') + self.assertEqual('demo-8', scenario['host']) def test_change_server_name_host_dict(self): scenario = {'host': {'name': 'demo'}} suffix = '-8' task.change_server_name(scenario, suffix) - self.assertTrue(scenario['host']['name'], 'demo-8') + self.assertEqual('demo-8', scenario['host']['name']) def test_change_server_name_target_str(self): scenario = {'target': 'demo'} suffix = '-8' task.change_server_name(scenario, suffix) - self.assertTrue(scenario['target'], 'demo-8') + self.assertEqual('demo-8', scenario['target']) def test_change_server_name_target_dict(self): scenario = {'target': {'name': 'demo'}} suffix = '-8' task.change_server_name(scenario, suffix) - self.assertTrue(scenario['target']['name'], 'demo-8') + self.assertEqual('demo-8', scenario['target']['name']) - @mock.patch('yardstick.benchmark.core.task.utils') - @mock.patch('yardstick.benchmark.core.task.logging') - def test_set_log(self, mock_logging, mock_utils): + @mock.patch('six.moves.builtins.open', side_effect=mock.mock_open()) + @mock.patch.object(task, 'utils') + @mock.patch('logging.root') + def test_set_log(self, mock_logging_root, *args): task_obj = task.Task() task_obj.task_id = 'task_id' task_obj._set_log() - self.assertTrue(mock_logging.root.addHandler.called) + mock_logging_root.addHandler.assert_called() def _get_file_abspath(self, filename): curr_path = os.path.dirname(os.path.abspath(__file__)) diff --git a/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_network.py b/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_network.py index 5f11713fa..aef99ee94 100644 --- a/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_network.py +++ b/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_network.py @@ -6,30 +6,44 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## + +from oslo_utils import uuidutils import unittest import mock -from yardstick.benchmark.scenarios.lib.delete_network import DeleteNetwork +import yardstick.common.openstack_utils as op_utils +from yardstick.benchmark.scenarios.lib import delete_network class DeleteNetworkTestCase(unittest.TestCase): - @mock.patch('yardstick.common.openstack_utils.get_neutron_client') - @mock.patch('yardstick.common.openstack_utils.delete_neutron_net') - def test_delete_network(self, mock_get_neutron_client, mock_delete_neutron_net): - options = { - 'network_id': '123-123-123' - } - args = {"options": options} - obj = DeleteNetwork(args, {}) - obj.run({}) - self.assertTrue(mock_get_neutron_client.called) - self.assertTrue(mock_delete_neutron_net.called) - - -def main(): - unittest.main() - - -if __name__ == '__main__': - main() + def setUp(self): + self._mock_delete_neutron_net = mock.patch.object( + op_utils, 'delete_neutron_net') + self.mock_delete_neutron_net = self._mock_delete_neutron_net.start() + self._mock_get_shade_client = mock.patch.object( + op_utils, 'get_shade_client') + self.mock_get_shade_client = self._mock_get_shade_client.start() + self._mock_log = mock.patch.object(delete_network, 'LOG') + self.mock_log = self._mock_log.start() + _uuid = uuidutils.generate_uuid() + self.args = {'options': {'network_id': _uuid}} + self._del_obj = delete_network.DeleteNetwork(self.args, mock.ANY) + + self.addCleanup(self._stop_mock) + + def _stop_mock(self): + self._mock_delete_neutron_net.stop() + self._mock_get_shade_client.stop() + self._mock_log.stop() + + def test_run(self): + self.mock_delete_neutron_net.return_value = True + self.assertTrue(self._del_obj.run({})) + self.mock_log.info.assert_called_once_with( + "Delete network successful!") + + def test_run_fail(self): + self.mock_delete_neutron_net.return_value = False + self.assertFalse(self._del_obj.run({})) + self.mock_log.error.assert_called_once_with("Delete network failed!") diff --git a/yardstick/tests/unit/common/test_openstack_utils.py b/yardstick/tests/unit/common/test_openstack_utils.py index b685e63be..8a2f5f95b 100644 --- a/yardstick/tests/unit/common/test_openstack_utils.py +++ b/yardstick/tests/unit/common/test_openstack_utils.py @@ -11,6 +11,7 @@ from oslo_utils import uuidutils import unittest import mock +from shade import exc from yardstick.common import openstack_utils @@ -54,3 +55,31 @@ class GetNetworkIdTestCase(unittest.TestCase): output = openstack_utils.get_network_id(mock_shade_client, 'network_name') self.assertEqual(None, output) + + +class DeleteNeutronNetTestCase(unittest.TestCase): + + def setUp(self): + self.mock_shade_client = mock.Mock() + self.mock_shade_client.delete_network = mock.Mock() + + def test_delete_neutron_net(self): + self.mock_shade_client.delete_network.return_value = True + output = openstack_utils.delete_neutron_net(self.mock_shade_client, + 'network_id') + self.assertTrue(output) + + def test_delete_neutron_net_fail(self): + self.mock_shade_client.delete_network.return_value = False + output = openstack_utils.delete_neutron_net(self.mock_shade_client, + 'network_id') + self.assertFalse(output) + + @mock.patch.object(openstack_utils, 'log') + def test_delete_neutron_net_exception(self, mock_logger): + self.mock_shade_client.delete_network.side_effect = ( + exc.OpenStackCloudException('error message')) + output = openstack_utils.delete_neutron_net(self.mock_shade_client, + 'network_id') + self.assertFalse(output) + mock_logger.error.assert_called_once() |