diff options
Diffstat (limited to 'tests/unit')
23 files changed, 1312 insertions, 485 deletions
diff --git a/tests/unit/benchmark/contexts/standalone/test_model.py b/tests/unit/benchmark/contexts/standalone/test_model.py index ddbc1a4bb..31ec2b7d1 100644 --- a/tests/unit/benchmark/contexts/standalone/test_model.py +++ b/tests/unit/benchmark/contexts/standalone/test_model.py @@ -16,70 +16,137 @@ # Unittest for yardstick.benchmark.contexts.standalone.model - from __future__ import absolute_import +import copy import os import unittest -import errno import mock -from yardstick.common import constants as consts -from yardstick.benchmark.contexts.standalone.model import Libvirt -from yardstick.benchmark.contexts.standalone.model import StandaloneContextHelper -from yardstick.benchmark.contexts.standalone import model -from yardstick.network_services.utils import PciAddress +from xml.etree import ElementTree +from yardstick.benchmark.contexts.standalone import model +from yardstick.network_services import utils +from yardstick.network_services.helpers import cpu + + +XML_SAMPLE = """<?xml version="1.0"?> +<domain type="kvm"> + <devices> + </devices> +</domain> +""" + +XML_SAMPLE_INTERFACE = """<?xml version="1.0"?> +<domain type="kvm"> + <devices> + <interface> + </interface> + </devices> +</domain> +""" class ModelLibvirtTestCase(unittest.TestCase): + def setUp(self): + self.xml = ElementTree.ElementTree( + element=ElementTree.fromstring(XML_SAMPLE)) + self.pci_address_str = '0001:04:03.2' + self.pci_address = utils.PciAddress(self.pci_address_str) + self.mac = '00:00:00:00:00:01' + self._mock_write_xml = mock.patch.object(ElementTree.ElementTree, + 'write') + self.mock_write_xml = self._mock_write_xml.start() + + self.addCleanup(self._cleanup) + + def _cleanup(self): + self._mock_write_xml.stop() + def test_check_if_vm_exists_and_delete(self): with mock.patch("yardstick.ssh.SSH") as ssh: ssh_mock = mock.Mock(autospec=ssh.SSH) - ssh_mock.execute = \ - mock.Mock(return_value=(0, "a", "")) + ssh_mock.execute = mock.Mock(return_value=(0, "a", "")) ssh.return_value = ssh_mock - result = Libvirt.check_if_vm_exists_and_delete("vm_0", ssh_mock) - self.assertIsNone(result) + # NOTE(ralonsoh): this test doesn't cover function execution. + model.Libvirt.check_if_vm_exists_and_delete("vm_0", ssh_mock) def test_virsh_create_vm(self): with mock.patch("yardstick.ssh.SSH") as ssh: ssh_mock = mock.Mock(autospec=ssh.SSH) - ssh_mock.execute = \ - mock.Mock(return_value=(0, "a", "")) + ssh_mock.execute = mock.Mock(return_value=(0, "a", "")) ssh.return_value = ssh_mock - result = Libvirt.virsh_create_vm(ssh_mock, "vm_0") - self.assertIsNone(result) + # NOTE(ralonsoh): this test doesn't cover function execution. + model.Libvirt.virsh_create_vm(ssh_mock, "vm_0") def test_virsh_destroy_vm(self): with mock.patch("yardstick.ssh.SSH") as ssh: ssh_mock = mock.Mock(autospec=ssh.SSH) - ssh_mock.execute = \ - mock.Mock(return_value=(0, "a", "")) + ssh_mock.execute = mock.Mock(return_value=(0, "a", "")) ssh.return_value = ssh_mock - result = Libvirt.virsh_destroy_vm("vm_0", ssh_mock) - self.assertIsNone(result) - - @mock.patch('yardstick.benchmark.contexts.standalone.model.ET') - def test_add_interface_address(self, mock_et): - pci_address = PciAddress.parse_address("0000:00:04.0", multi_line=True) - result = Libvirt.add_interface_address("<interface/>", pci_address) - self.assertIsNotNone(result) - - @mock.patch('yardstick.benchmark.contexts.standalone.model.Libvirt.add_interface_address') - @mock.patch('yardstick.benchmark.contexts.standalone.model.ET') - def test_add_ovs_interfaces(self, mock_et, mock_add_interface_address): - pci_address = PciAddress.parse_address("0000:00:04.0", multi_line=True) - result = Libvirt.add_ovs_interface("/usr/local", 0, "0000:00:04.0", - "00:00:00:00:00:01", "xml") - self.assertIsNone(result) - - @mock.patch('yardstick.benchmark.contexts.standalone.model.Libvirt.add_interface_address') - @mock.patch('yardstick.benchmark.contexts.standalone.model.ET') - def test_add_sriov_interfaces(self, mock_et, mock_add_interface_address): - pci_address = PciAddress.parse_address("0000:00:04.0", multi_line=True) - result = Libvirt.add_sriov_interfaces("0000:00:05.0", "0000:00:04.0", - "00:00:00:00:00:01", "xml") - self.assertIsNone(result) + # NOTE(ralonsoh): this test doesn't cover function execution. + model.Libvirt.virsh_destroy_vm("vm_0", ssh_mock) + + def test_add_interface_address(self): + xml = ElementTree.ElementTree( + element=ElementTree.fromstring(XML_SAMPLE_INTERFACE)) + interface = xml.find('devices').find('interface') + result = model.Libvirt._add_interface_address(interface, self.pci_address) + self.assertEqual('pci', result.get('type')) + self.assertEqual('0x{}'.format(self.pci_address.domain), + result.get('domain')) + self.assertEqual('0x{}'.format(self.pci_address.bus), + result.get('bus')) + self.assertEqual('0x{}'.format(self.pci_address.slot), + result.get('slot')) + self.assertEqual('0x{}'.format(self.pci_address.function), + result.get('function')) + + def test_add_ovs_interfaces(self): + xml_input = mock.Mock() + with mock.patch.object(ElementTree, 'parse', return_value=self.xml) \ + as mock_parse: + xml = copy.deepcopy(self.xml) + mock_parse.return_value = xml + model.Libvirt.add_ovs_interface( + '/usr/local', 0, self.pci_address_str, self.mac, xml_input) + mock_parse.assert_called_once_with(xml_input) + self.mock_write_xml.assert_called_once_with(xml_input) + interface = xml.find('devices').find('interface') + self.assertEqual('vhostuser', interface.get('type')) + mac = interface.find('mac') + self.assertEqual(self.mac, mac.get('address')) + source = interface.find('source') + self.assertEqual('unix', source.get('type')) + self.assertEqual('/usr/local/var/run/openvswitch/dpdkvhostuser0', + source.get('path')) + self.assertEqual('client', source.get('mode')) + _model = interface.find('model') + self.assertEqual('virtio', _model.get('type')) + driver = interface.find('driver') + self.assertEqual('4', driver.get('queues')) + host = driver.find('host') + self.assertEqual('off', host.get('mrg_rxbuf')) + self.assertIsNotNone(interface.find('address')) + + def test_add_sriov_interfaces(self): + xml_input = mock.Mock() + with mock.patch.object(ElementTree, 'parse', return_value=self.xml) \ + as mock_parse: + xml = copy.deepcopy(self.xml) + mock_parse.return_value = xml + vf_pci = '0001:05:04.2' + model.Libvirt.add_sriov_interfaces( + self.pci_address_str, vf_pci, self.mac, xml_input) + mock_parse.assert_called_once_with(xml_input) + self.mock_write_xml.assert_called_once_with(xml_input) + interface = xml.find('devices').find('interface') + self.assertEqual('yes', interface.get('managed')) + self.assertEqual('hostdev', interface.get('type')) + mac = interface.find('mac') + self.assertEqual(self.mac, mac.get('address')) + source = interface.find('source') + self.assertIsNotNone(source.find('address')) + self.assertIsNotNone(interface.find('address')) def test_create_snapshot_qemu(self): result = "/var/lib/libvirt/images/0.qcow2" @@ -88,13 +155,15 @@ class ModelLibvirtTestCase(unittest.TestCase): ssh_mock.execute = \ mock.Mock(return_value=(0, "a", "")) ssh.return_value = ssh_mock - image = Libvirt.create_snapshot_qemu(ssh_mock, "0", "ubuntu.img") + image = model.Libvirt.create_snapshot_qemu(ssh_mock, "0", "ubuntu.img") self.assertEqual(image, result) - @mock.patch("yardstick.benchmark.contexts.standalone.model.Libvirt.create_snapshot_qemu") - @mock.patch('yardstick.benchmark.contexts.standalone.model.open') - @mock.patch('yardstick.benchmark.contexts.standalone.model.write_file') - def test_build_vm_xml(self, mock_open, mock_write_file, mock_create_snapshot_qemu): + @mock.patch.object(model.Libvirt, 'pin_vcpu_for_perf') + @mock.patch.object(model.Libvirt, 'create_snapshot_qemu') + def test_build_vm_xml(self, mock_create_snapshot_qemu, + *args): + # NOTE(ralonsoh): this test doesn't cover function execution. This test + # should also check mocked function calls. result = [4] with mock.patch("yardstick.ssh.SSH") as ssh: ssh_mock = mock.Mock(autospec=ssh.SSH) @@ -102,16 +171,9 @@ class ModelLibvirtTestCase(unittest.TestCase): mock.Mock(return_value=(0, "a", "")) ssh.return_value = ssh_mock mock_create_snapshot_qemu.return_value = "0.img" - status = Libvirt.build_vm_xml(ssh_mock, {}, "test", "vm_0", 0) - self.assertEqual(status[0], result[0]) - def test_split_cpu_list(self): - result = Libvirt.split_cpu_list("1,2,3") - self.assertEqual(result, [1, 2, 3]) - - def test_get_numa_nodes(self): - result = Libvirt.get_numa_nodes() - self.assertIsNotNone(result) + status = model.Libvirt.build_vm_xml(ssh_mock, {}, "test", "vm_0", 0) + self.assertEqual(status[0], result[0]) def test_update_interrupts_hugepages_perf(self): with mock.patch("yardstick.ssh.SSH") as ssh: @@ -119,20 +181,21 @@ class ModelLibvirtTestCase(unittest.TestCase): ssh_mock.execute = \ mock.Mock(return_value=(0, "a", "")) ssh.return_value = ssh_mock - status = Libvirt.update_interrupts_hugepages_perf(ssh_mock) - self.assertIsNone(status) + # NOTE(ralonsoh): this test doesn't cover function execution. This test + # should also check mocked function calls. + model.Libvirt.update_interrupts_hugepages_perf(ssh_mock) + + @mock.patch.object(cpu.CpuSysCores, 'get_core_socket') + def test_pin_vcpu_for_perf(self, mock_get_core_socket): + mock_get_core_socket.return_value = { + 'cores_per_socket': 1, + 'thread_per_core': 1, + '0': [1, 2] + } + # NOTE(ralonsoh): this test doesn't cover function execution. This + # function needs more tests. + model.Libvirt.pin_vcpu_for_perf(mock.Mock()) - @mock.patch("yardstick.benchmark.contexts.standalone.model.Libvirt.get_numa_nodes") - @mock.patch("yardstick.benchmark.contexts.standalone.model.Libvirt.update_interrupts_hugepages_perf") - def test_pin_vcpu_for_perf(self, mock_update_interrupts_hugepages_perf, mock_get_numa_nodes): - with mock.patch("yardstick.ssh.SSH") as ssh: - ssh_mock = mock.Mock(autospec=ssh.SSH) - ssh_mock.execute = \ - mock.Mock(return_value=(0, "a", "")) - ssh.return_value = ssh_mock - mock_get_numa_nodes.return_value = {'1': [18, 19, 20, 21], '0': [0, 1, 2, 3]} - status = Libvirt.pin_vcpu_for_perf(ssh_mock, "vm_0", 4) - self.assertIsNone(status) class StandaloneContextHelperTestCase(unittest.TestCase): @@ -154,7 +217,7 @@ class StandaloneContextHelperTestCase(unittest.TestCase): } def setUp(self): - self.helper = StandaloneContextHelper() + self.helper = model.StandaloneContextHelper() def test___init__(self): self.assertIsNone(self.helper.file_path) @@ -165,8 +228,9 @@ class StandaloneContextHelperTestCase(unittest.TestCase): ssh_mock.execute = \ mock.Mock(return_value=(1, "a", "")) ssh.return_value = ssh_mock - status = StandaloneContextHelper.install_req_libs(ssh_mock) - self.assertIsNone(status) + # NOTE(ralonsoh): this test doesn't cover function execution. This test + # should also check mocked function calls. + model.StandaloneContextHelper.install_req_libs(ssh_mock) def test_get_kernel_module(self): with mock.patch("yardstick.ssh.SSH") as ssh: @@ -174,10 +238,12 @@ class StandaloneContextHelperTestCase(unittest.TestCase): ssh_mock.execute = \ mock.Mock(return_value=(1, "i40e", "")) ssh.return_value = ssh_mock - status = StandaloneContextHelper.get_kernel_module(ssh_mock, "05:00.0", None) - self.assertEqual(status, "i40e") + # NOTE(ralonsoh): this test doesn't cover function execution. This test + # should also check mocked function calls. + model.StandaloneContextHelper.get_kernel_module( + ssh_mock, "05:00.0", None) - @mock.patch('yardstick.benchmark.contexts.standalone.model.StandaloneContextHelper.get_kernel_module') + @mock.patch.object(model.StandaloneContextHelper, 'get_kernel_module') def test_get_nic_details(self, mock_get_kernel_module): with mock.patch("yardstick.ssh.SSH") as ssh: ssh_mock = mock.Mock(autospec=ssh.SSH) @@ -185,8 +251,10 @@ class StandaloneContextHelperTestCase(unittest.TestCase): mock.Mock(return_value=(1, "i40e ixgbe", "")) ssh.return_value = ssh_mock mock_get_kernel_module.return_value = "i40e" - status = StandaloneContextHelper.get_nic_details(ssh_mock, self.NETWORKS, "dpdk-devbind.py") - self.assertIsNotNone(status) + # NOTE(ralonsoh): this test doesn't cover function execution. This test + # should also check mocked function calls. + model.StandaloneContextHelper.get_nic_details( + ssh_mock, self.NETWORKS, 'dpdk-devbind.py') def test_get_virtual_devices(self): pattern = "PCI_SLOT_NAME=0000:05:00.0" @@ -195,8 +263,10 @@ class StandaloneContextHelperTestCase(unittest.TestCase): ssh_mock.execute = \ mock.Mock(return_value=(1, pattern, "")) ssh.return_value = ssh_mock - status = StandaloneContextHelper.get_virtual_devices(ssh_mock, "0000:00:05.0") - self.assertIsNotNone(status) + # NOTE(ralonsoh): this test doesn't cover function execution. This test + # should also check mocked function calls. + model.StandaloneContextHelper.get_virtual_devices( + ssh_mock, '0000:00:05.0') def _get_file_abspath(self, filename): curr_path = os.path.dirname(os.path.abspath(__file__)) @@ -210,40 +280,48 @@ class StandaloneContextHelperTestCase(unittest.TestCase): def test_parse_pod_file(self): self.helper.file_path = self._get_file_abspath("dummy") - self.assertRaises(IOError, self.helper.parse_pod_file, self.helper.file_path) + self.assertRaises(IOError, self.helper.parse_pod_file, + self.helper.file_path) self.helper.file_path = self._get_file_abspath(self.NODE_SAMPLE) - self.assertRaises(TypeError, self.helper.parse_pod_file, self.helper.file_path) + self.assertRaises(TypeError, self.helper.parse_pod_file, + self.helper.file_path) self.helper.file_path = self._get_file_abspath(self.NODE_SRIOV_SAMPLE) self.assertIsNotNone(self.helper.parse_pod_file(self.helper.file_path)) def test_get_mac_address(self): - status = StandaloneContextHelper.get_mac_address() + status = model.StandaloneContextHelper.get_mac_address() self.assertIsNotNone(status) @mock.patch('yardstick.ssh.SSH') - def test_get_mgmt_ip(self, mock_ssh): + def test_get_mgmt_ip(self, *args): with mock.patch("yardstick.ssh.SSH") as ssh: ssh_mock = mock.Mock(autospec=ssh.SSH) - ssh_mock.execute = \ - mock.Mock(return_value=(1, "1.2.3.4 00:00:00:00:00:01", "")) + ssh_mock.execute = mock.Mock( + return_value=(1, "1.2.3.4 00:00:00:00:00:01", "")) ssh.return_value = ssh_mock - status = StandaloneContextHelper.get_mgmt_ip(ssh_mock, "00:00:00:00:00:01", "1.1.1.1/24", {}) + # NOTE(ralonsoh): this test doesn't cover function execution. This test + # should also check mocked function calls. + status = model.StandaloneContextHelper.get_mgmt_ip( + ssh_mock, "00:00:00:00:00:01", "1.1.1.1/24", {}) self.assertIsNotNone(status) @mock.patch('yardstick.ssh.SSH') - def test_get_mgmt_ip_no(self, mock_ssh): + def test_get_mgmt_ip_no(self, *args): with mock.patch("yardstick.ssh.SSH") as ssh: ssh_mock = mock.Mock(autospec=ssh.SSH) ssh_mock.execute = \ mock.Mock(return_value=(1, "", "")) ssh.return_value = ssh_mock - + # NOTE(ralonsoh): this test doesn't cover function execution. This test + # should also check mocked function calls. model.WAIT_FOR_BOOT = 0 - status = StandaloneContextHelper.get_mgmt_ip(ssh_mock, "99", "1.1.1.1/24", {}) + status = model.StandaloneContextHelper.get_mgmt_ip( + ssh_mock, "99", "1.1.1.1/24", {}) self.assertIsNone(status) + class ServerTestCase(unittest.TestCase): NETWORKS = { @@ -263,6 +341,7 @@ class ServerTestCase(unittest.TestCase): 'cidr': '152.16.40.10/24', 'gateway_ip': '152.16.100.20'} } + def setUp(self): self.server = model.Server() @@ -288,7 +367,8 @@ class ServerTestCase(unittest.TestCase): 'xe1': ['public_0'], } } - status = self.server.generate_vnf_instance({}, self.NETWORKS, "1.1.1.1/24", 'vm_0', vnf, '00:00:00:00:00:01') + status = self.server.generate_vnf_instance( + {}, self.NETWORKS, '1.1.1.1/24', 'vm_0', vnf, '00:00:00:00:00:01') self.assertIsNotNone(status) class OvsDeployTestCase(unittest.TestCase): @@ -318,14 +398,17 @@ class OvsDeployTestCase(unittest.TestCase): self.assertIsNotNone(self.ovs_deploy.connection) @mock.patch('yardstick.benchmark.contexts.standalone.model.os') - def test_prerequisite(self, mock_ssh): + def test_prerequisite(self, *args): + # NOTE(ralonsoh): this test should check mocked function calls. self.ovs_deploy.helper = mock.Mock() self.assertIsNone(self.ovs_deploy.prerequisite()) @mock.patch('yardstick.benchmark.contexts.standalone.model.os') - def test_prerequisite(self, mock_ssh): + def test_prerequisite_2(self, *args): + # NOTE(ralonsoh): this test should check mocked function calls. Rename + # this test properly. self.ovs_deploy.helper = mock.Mock() - self.ovs_deploy.connection.execute = \ - mock.Mock(return_value=(1, "1.2.3.4 00:00:00:00:00:01", "")) + self.ovs_deploy.connection.execute = mock.Mock( + return_value=(1, '1.2.3.4 00:00:00:00:00:01', '')) self.ovs_deploy.prerequisite = mock.Mock() self.assertIsNone(self.ovs_deploy.ovs_deploy()) diff --git a/tests/unit/benchmark/contexts/standalone/test_sriov.py b/tests/unit/benchmark/contexts/standalone/test_sriov.py index 50ae5fe13..3ea673abc 100644 --- a/tests/unit/benchmark/contexts/standalone/test_sriov.py +++ b/tests/unit/benchmark/contexts/standalone/test_sriov.py @@ -17,12 +17,10 @@ from __future__ import absolute_import import os import unittest -import errno import mock -from yardstick.common import constants as consts +from yardstick import ssh from yardstick.benchmark.contexts.standalone import sriov -from yardstick.network_services.utils import PciAddress class SriovContextTestCase(unittest.TestCase): @@ -66,6 +64,9 @@ class SriovContextTestCase(unittest.TestCase): @mock.patch('yardstick.benchmark.contexts.standalone.sriov.Libvirt') @mock.patch('yardstick.benchmark.contexts.standalone.model.Server') def test___init__(self, mock_helper, mock_libvirt, mock_server): + # pylint: disable=unused-argument + # NOTE(ralonsoh): this test doesn't cover function execution. + # The pylint exception should be removed. self.sriov.helper = mock_helper self.sriov.vnf_node = mock_server self.assertIsNone(self.sriov.file_path) @@ -75,14 +76,11 @@ class SriovContextTestCase(unittest.TestCase): self.sriov.helper.parse_pod_file = mock.Mock(return_value=[{}, {}, {}]) self.assertIsNone(self.sriov.init(self.ATTRS)) - @mock.patch('yardstick.ssh.SSH') + @mock.patch.object(ssh, 'SSH', return_value=(0, "a", "")) def test_deploy(self, mock_ssh): - with mock.patch("yardstick.ssh.SSH") as ssh: - ssh_mock = mock.Mock(autospec=ssh.SSH) - ssh_mock.execute = \ - mock.Mock(return_value=(0, "a", "")) - ssh.return_value = ssh_mock - + # pylint: disable=unused-argument + # NOTE(ralonsoh): this test doesn't cover function execution. + # The pylint exception should be removed. self.sriov.vm_deploy = False self.assertIsNone(self.sriov.deploy()) @@ -94,20 +92,16 @@ class SriovContextTestCase(unittest.TestCase): self.sriov.wait_for_vnfs_to_start = mock.Mock(return_value={}) self.assertIsNone(self.sriov.deploy()) - @mock.patch('yardstick.ssh.SSH') + @mock.patch.object(ssh, 'SSH', return_value=(0, "a", "")) @mock.patch('yardstick.benchmark.contexts.standalone.sriov.Libvirt') def test_undeploy(self, mock_libvirt, mock_ssh): - with mock.patch("yardstick.ssh.SSH") as ssh: - ssh_mock = mock.Mock(autospec=ssh.SSH) - ssh_mock.execute = \ - mock.Mock(return_value=(0, "a", "")) - ssh.return_value = ssh_mock - + # pylint: disable=unused-argument + # NOTE(ralonsoh): the pylint exception should be removed. self.sriov.vm_deploy = False self.assertIsNone(self.sriov.undeploy()) self.sriov.vm_deploy = True - self.sriov.connection = ssh_mock + self.sriov.connection = mock_ssh self.sriov.vm_names = ['vm_0', 'vm_1'] self.sriov.drivers = ['vm_0', 'vm_1'] self.assertIsNone(self.sriov.undeploy()) @@ -246,27 +240,27 @@ class SriovContextTestCase(unittest.TestCase): self.sriov.drivers = [] self.sriov.networks = self.NETWORKS self.sriov.helper.get_mac_address = mock.Mock(return_value="") - self.sriov.get_vf_data = mock.Mock(return_value="") + self.sriov._get_vf_data = mock.Mock(return_value="") self.assertIsNone(self.sriov.configure_nics_for_sriov()) + @mock.patch.object(ssh, 'SSH', return_value=(0, "a", "")) @mock.patch('yardstick.benchmark.contexts.standalone.sriov.Libvirt') - def test__enable_interfaces(self, mock_libvirt): - with mock.patch("yardstick.ssh.SSH") as ssh: - ssh_mock = mock.Mock(autospec=ssh.SSH) - ssh_mock.execute = \ - mock.Mock(return_value=(0, "a", "")) - ssh.return_value = ssh_mock + def test__enable_interfaces(self, mock_libvirt, mock_ssh): + # pylint: disable=unused-argument + # NOTE(ralonsoh): the pylint exception should be removed. self.sriov.vm_deploy = True - self.sriov.connection = ssh_mock + self.sriov.connection = mock_ssh self.sriov.vm_names = ['vm_0', 'vm_1'] self.sriov.drivers = [] self.sriov.networks = self.NETWORKS - self.sriov.get_vf_data = mock.Mock(return_value="") + self.sriov._get_vf_data = mock.Mock(return_value="") self.assertIsNone(self.sriov._enable_interfaces(0, 0, ["private_0"], 'test')) @mock.patch('yardstick.benchmark.contexts.standalone.model.Server') @mock.patch('yardstick.benchmark.contexts.standalone.sriov.Libvirt') def test_setup_sriov_context(self, mock_libvirt, mock_server): + # pylint: disable=unused-argument + # NOTE(ralonsoh): the pylint exception should be removed. with mock.patch("yardstick.ssh.SSH") as ssh: ssh_mock = mock.Mock(autospec=ssh.SSH) ssh_mock.execute = \ @@ -296,7 +290,7 @@ class SriovContextTestCase(unittest.TestCase): self.sriov.vnf_node.generate_vnf_instance = mock.Mock(return_value={}) self.assertIsNotNone(self.sriov.setup_sriov_context()) - def test_get_vf_data(self): + def test__get_vf_data(self): with mock.patch("yardstick.ssh.SSH") as ssh: ssh_mock = mock.Mock(autospec=ssh.SSH) ssh_mock.execute = \ @@ -318,5 +312,7 @@ class SriovContextTestCase(unittest.TestCase): } } self.sriov.networks = self.NETWORKS - self.sriov.helper.get_virtual_devices = mock.Mock(return_value={"0000:00:01.0": ""}) - self.assertIsNotNone(self.sriov.get_vf_data("", "0000:00:01.0", "00:00:00:00:00:01", "if0")) + self.sriov.helper.get_virtual_devices = mock.Mock( + return_value={'0000:00:01.0': ''}) + self.assertIsNotNone(self.sriov._get_vf_data( + '0000:00:01.0', '00:00:00:00:00:01', 'if0')) diff --git a/tests/unit/benchmark/contexts/test_heat.py b/tests/unit/benchmark/contexts/test_heat.py index 223d64060..f2e725df2 100644 --- a/tests/unit/benchmark/contexts/test_heat.py +++ b/tests/unit/benchmark/contexts/test_heat.py @@ -119,8 +119,12 @@ class HeatContextTestCase(unittest.TestCase): "2f2e4997-0a8e-4eb7-9fa4-f3f8fbbc393b") mock_template.add_security_group.assert_called_with("foo-secgroup") # mock_template.add_network.assert_called_with("bar-fool-network", 'physnet1', None) - mock_template.add_router.assert_called_with("bar-fool-network-router", netattrs["external_network"], "bar-fool-network-subnet") - mock_template.add_router_interface.assert_called_with("bar-fool-network-router-if0", "bar-fool-network-router", "bar-fool-network-subnet") + mock_template.add_router.assert_called_with("bar-fool-network-router", + netattrs["external_network"], + "bar-fool-network-subnet") + mock_template.add_router_interface.assert_called_with("bar-fool-network-router-if0", + "bar-fool-network-router", + "bar-fool-network-subnet") @mock.patch('yardstick.benchmark.contexts.heat.HeatTemplate') def test_attrs_get(self, mock_template): diff --git a/tests/unit/benchmark/contexts/test_model.py b/tests/unit/benchmark/contexts/test_model.py index 5444c2bc8..53b035b82 100644 --- a/tests/unit/benchmark/contexts/test_model.py +++ b/tests/unit/benchmark/contexts/test_model.py @@ -179,6 +179,7 @@ class NetworkTestCase(unittest.TestCase): test_network = model.Network('foo', self.mock_context, attrs) self.assertIsNone(test_network.gateway_ip) + class ServerTestCase(unittest.TestCase): def setUp(self): @@ -190,7 +191,6 @@ class ServerTestCase(unittest.TestCase): netattrs = {'cidr': '10.0.0.0/24', 'provider': None, 'external_network': 'ext_net'} self.mock_context.networks = [model.Network("some-network", self.mock_context, netattrs)] - def test_construct_defaults(self): attrs = None @@ -227,8 +227,9 @@ class ServerTestCase(unittest.TestCase): @mock.patch('yardstick.benchmark.contexts.heat.HeatTemplate') def test__add_instance(self, mock_template): - - attrs = {'image': 'some-image', 'flavor': 'some-flavor', 'floating_ip': '192.168.1.10', 'floating_ip_assoc': 'some-vm'} + attrs = {'image': 'some-image', 'flavor': 'some-flavor', 'floating_ip': '192.168.1.10', + 'floating_ip_assoc': 'some-vm', + 'availability_zone': 'zone'} test_server = model.Server('foo', self.mock_context, attrs) self.mock_context.flavors = ['flavor1', 'flavor2', 'some-flavor'] @@ -241,7 +242,8 @@ class ServerTestCase(unittest.TestCase): mock_network.subnet_stack_name = 'some-network-stack-subnet' mock_network.provider = 'sriov' mock_network.external_network = 'ext_net' - mock_network.router = model.Router('some-router', 'some-network', self.mock_context, 'ext_net') + mock_network.router = model.Router('some-router', 'some-network', self.mock_context, + 'ext_net') test_server._add_instance(mock_template, 'some-server', [mock_network], 'hints') @@ -277,7 +279,180 @@ class ServerTestCase(unittest.TestCase): user=self.mock_context.user, key_name=self.mock_context.keypair_name, user_data='', - scheduler_hints='hints') + scheduler_hints='hints', + availability_zone='zone') + + def test_override_ip(self): + network_ports = { + 'mgmt': ['mgmt'], + 'uplink_0': [ + {'xe0': {'local_ip': '10.44.0.20', 'netmask': '255.255.255.0'}}, + ], + 'downlink_0': [ + {'xe1': {'local_ip': '10.44.0.30', 'netmask': '255.255.255.0'}}, + ], + } + attrs = { + 'image': 'some-image', 'flavor': 'some-flavor', + } + test_server = model.Server('foo', self.mock_context, attrs) + test_server.interfaces = { + "xe0": { + "local_ip": "1.2.3.4", + "netmask": "255.255.255.0", + }, + "xe1": { + "local_ip": "1.2.3.5", + "netmask": "255.255.255.0" + } + } + test_server.network_ports = network_ports + + test_server.override_ip("uplink_0", {"port": "xe0"}) + self.assertEqual(test_server.interfaces["xe0"], network_ports["uplink_0"][0]["xe0"]) + + def test_override_ip_multiple(self): + network_ports = { + 'mgmt': ['mgmt'], + 'uplink_0': [ + {'xe0': {'local_ip': '10.44.0.20', 'netmask': '255.255.255.0'}}, + {'xe0': {'local_ip': '10.44.0.21', 'netmask': '255.255.255.0'}}, + ], + 'downlink_0': [ + {'xe1': {'local_ip': '10.44.0.30', 'netmask': '255.255.255.0'}}, + ], + } + attrs = { + 'image': 'some-image', 'flavor': 'some-flavor', + } + test_server = model.Server('foo', self.mock_context, attrs) + test_server.interfaces = { + "xe0": { + "local_ip": "1.2.3.4", + "netmask": "255.255.255.0", + }, + "xe1": { + "local_ip": "1.2.3.5", + "netmask": "255.255.255.0" + } + } + test_server.network_ports = network_ports + test_server.override_ip("uplink_0", {"port": "xe0"}) + self.assertEqual(test_server.interfaces["xe0"], network_ports["uplink_0"][0]["xe0"]) + + def test_override_ip_mixed(self): + network_ports = { + 'mgmt': ['mgmt'], + 'uplink_0': [ + 'xe0', + {'xe0': {'local_ip': '10.44.0.21', 'netmask': '255.255.255.0'}}, + ], + 'downlink_0': [ + {'xe1': {'local_ip': '10.44.0.30', 'netmask': '255.255.255.0'}}, + ], + } + attrs = { + 'image': 'some-image', 'flavor': 'some-flavor', + } + test_server = model.Server('foo', self.mock_context, attrs) + test_server.interfaces = { + "xe0": { + "local_ip": "1.2.3.4", + "netmask": "255.255.255.0", + }, + "xe1": { + "local_ip": "1.2.3.5", + "netmask": "255.255.255.0" + } + } + test_server.network_ports = network_ports + test_server.override_ip("uplink_0", {"port": "xe0"}) + self.assertEqual(test_server.interfaces["xe0"], network_ports["uplink_0"][1]["xe0"]) + + @mock.patch('yardstick.benchmark.contexts.heat.HeatTemplate') + def test__add_instance_with_ip_override_invalid_syntax(self, mock_template): + network_ports = { + 'mgmt': ['mgmt'], + 'uplink_0': 'xe0', + 'downlink_0': [ + {'xe1': {'local_ip': '10.44.0.30', 'netmask': '255.255.255.0'}}, + ], + } + attrs = { + 'image': 'some-image', 'flavor': 'some-flavor', + } + test_server = model.Server('foo', self.mock_context, attrs) + test_server.network_ports = network_ports + context = type("Context", (object,), {}) + # can't use Mock because Mock.name is reserved + context.name = "context" + networks = [model.Network(n, context, {}) for n in network_ports] + + with self.assertRaises(SyntaxError): + test_server._add_instance(mock_template, 'some-server', + networks, 'hints') + + @mock.patch('yardstick.benchmark.contexts.heat.HeatTemplate') + def test__add_instance_with_ip_override(self, mock_template): + network_ports = { + 'mgmt': ['mgmt'], + 'uplink_0': [ + {'xe0': {'local_ip': '10.44.0.20', 'netmask': '255.255.255.0'}}, + ], + 'downlink_0': [ + {'xe1': {'local_ip': '10.44.0.30', 'netmask': '255.255.255.0'}}, + ], + } + attrs = { + 'image': 'some-image', 'flavor': 'some-flavor', + } + test_server = model.Server('foo', self.mock_context, attrs) + test_server.network_ports = network_ports + context = type("Context", (object,), {}) + # can't use Mock because Mock.name is reserved + context.name = "context" + networks = [model.Network(n, context, {}) for n in network_ports] + + test_server._add_instance(mock_template, 'some-server', + networks, 'hints') + self.assertEqual(test_server.ports, { + 'downlink_0': [{'port': 'xe1', 'stack_name': 'some-server-xe1-port'}], + 'mgmt': [{'port': 'mgmt', 'stack_name': 'some-server-mgmt-port'}], + 'uplink_0': [{'port': 'xe0', 'stack_name': 'some-server-xe0-port'}] + }) + + @mock.patch('yardstick.benchmark.contexts.heat.HeatTemplate') + def test__add_instance_with_multiple_ip_override(self, mock_template): + network_ports = { + 'mgmt': ['mgmt'], + 'uplink_0': [ + {'xe0': {'local_ip': '10.44.0.20', 'netmask': '255.255.255.0'}}, + {'xe0': {'local_ip': '10.44.0.21', 'netmask': '255.255.255.0'}}, + ], + 'downlink_0': [ + {'xe1': {'local_ip': '10.44.0.30', 'netmask': '255.255.255.0'}}, + ], + } + attrs = { + 'image': 'some-image', 'flavor': 'some-flavor', + } + test_server = model.Server('foo', self.mock_context, attrs) + test_server.network_ports = network_ports + context = type("Context", (object,), {}) + # can't use Mock because Mock.name is reserved + context.name = "context" + networks = [model.Network(n, context, {}) for n in network_ports] + + test_server._add_instance(mock_template, 'some-server', + networks, 'hints') + self.assertEqual(test_server.ports, { + 'downlink_0': [{'port': 'xe1', 'stack_name': 'some-server-xe1-port'}], + 'mgmt': [{'port': 'mgmt', 'stack_name': 'some-server-mgmt-port'}], + 'uplink_0': [{'port': 'xe0', 'stack_name': 'some-server-xe0-port'}, + # this is not an error, we can produce this, it is left to Heat + # to detect duplicate ports and error + {'port': 'xe0', 'stack_name': 'some-server-xe0-port'}] + }) @mock.patch('yardstick.benchmark.contexts.heat.HeatTemplate') def test__add_instance_with_user_data(self, mock_template): @@ -299,7 +474,30 @@ class ServerTestCase(unittest.TestCase): user=self.mock_context.user, key_name=self.mock_context.keypair_name, user_data=user_data, - scheduler_hints='hints') + scheduler_hints='hints', + availability_zone=None) + + @mock.patch('yardstick.benchmark.contexts.heat.HeatTemplate') + def test__add_instance_with_availablity_zone(self, mock_template): + attrs = { + 'image': 'some-image', 'flavor': 'some-flavor', + 'availability_zone': 'zone', + } + test_server = model.Server('foo', self.mock_context, attrs) + + test_server._add_instance(mock_template, 'some-server', + [], 'hints') + + mock_template.add_server.assert_called_with( + 'some-server', 'some-image', + flavor='some-flavor', + flavors=self.mock_context.flavors, + ports=[], + user=self.mock_context.user, + key_name=self.mock_context.keypair_name, + user_data='', + scheduler_hints='hints', + availability_zone='zone') @mock.patch('yardstick.benchmark.contexts.heat.HeatTemplate') def test__add_instance_plus_flavor(self, mock_template): @@ -339,7 +537,8 @@ class ServerTestCase(unittest.TestCase): user=self.mock_context.user, key_name=self.mock_context.keypair_name, user_data=user_data, - scheduler_hints='hints') + scheduler_hints='hints', + availability_zone=None) @mock.patch('yardstick.benchmark.contexts.heat.HeatTemplate') def test__add_instance_misc(self, mock_template): @@ -351,7 +550,7 @@ class ServerTestCase(unittest.TestCase): } test_server = model.Server('ServerFlavor-3', self.mock_context, attrs) - self.mock_context.flavors = ['flavor2'] + self.mock_context.flavors = ['flavor2'] self.mock_context.flavor = {'vcpus': 4} mock_network = mock.Mock() mock_network.name = 'some-network' @@ -361,7 +560,6 @@ class ServerTestCase(unittest.TestCase): test_server._add_instance(mock_template, 'ServerFlavor-3', [mock_network], 'hints') - mock_template.add_port( 'ServerFlavor-3-some-network-port', mock_network.stack_name, @@ -387,5 +585,5 @@ class ServerTestCase(unittest.TestCase): user=self.mock_context.user, key_name=self.mock_context.keypair_name, user_data=user_data, - scheduler_hints='hints') - + scheduler_hints='hints', + availability_zone=None) diff --git a/tests/unit/benchmark/scenarios/compute/test_qemumigrate.py b/tests/unit/benchmark/scenarios/compute/test_qemumigrate.py index 9514729ba..1f0ff3c29 100644 --- a/tests/unit/benchmark/scenarios/compute/test_qemumigrate.py +++ b/tests/unit/benchmark/scenarios/compute/test_qemumigrate.py @@ -142,7 +142,7 @@ class QemuMigrateTestCase(unittest.TestCase): q.setup() sample_output = '{"totaltime": 15, "downtime": 2, "setuptime": 1}' - + mock_ssh.SSH.from_node().execute.return_value = (0, sample_output, '') self.assertRaises(AssertionError, q.run, result) diff --git a/tests/unit/benchmark/scenarios/lib/test_check_connectivity.py b/tests/unit/benchmark/scenarios/lib/test_check_connectivity.py new file mode 100644 index 000000000..1fb2f89ca --- /dev/null +++ b/tests/unit/benchmark/scenarios/lib/test_check_connectivity.py @@ -0,0 +1,84 @@ +############################################################################## +# Copyright (c) 2017 Huawei Technologies Co.,Ltd and others. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Apache License, Version 2.0 +# which accompanies this distribution, and is available at +# http://www.apache.org/licenses/LICENSE-2.0 +############################################################################## + +# Unittest for yardstick.benchmark.scenarios.lib.check_connectivity.CheckConnectivity + +from __future__ import absolute_import + +import mock +import unittest + +from yardstick.benchmark.scenarios.lib import check_connectivity + + +class CheckConnectivityTestCase(unittest.TestCase): + + def setUp(self): + self.ctx = { + 'host': { + 'ip': '172.16.0.137', + 'user': 'root', + 'key_filename': 'mykey.key', + 'ssh_port': '22' + }, + 'target': { + 'ipaddr': '172.16.0.138' + } + } + + @mock.patch('yardstick.benchmark.scenarios.lib.check_connectivity.ssh') + def test_check_connectivity(self, mock_ssh): + + args = { + 'options': {'src_ip_addr': '192.168.23.2', + 'dest_ip_addr': '192.168.23.10', + 'ssh_user': 'root', + 'ssh_passwd': 'root', + 'ssh_port': '22', + 'ssh_timeout': 600, + 'ping_parameter': "-s 2048" + }, + 'sla': {'status': 'True', + 'action': 'assert'} + } + + result = {} + + obj = check_connectivity.CheckConnectivity(args, {}) + obj.setup() + mock_ssh.SSH.execute.return_value = (0, '100', '') + + + @mock.patch('yardstick.benchmark.scenarios.lib.check_connectivity.ssh') + def test_check_connectivity_key(self, mock_ssh): + + args = { + 'options': {'ssh_user': 'root', + 'ssh_key': '/root/.ssh/id_rsa', + 'ssh_port': '22', + 'ssh_timeout': 600, + 'ping_parameter': "-s 2048" + }, + 'sla': {'status': 'True', + 'action': 'assert'} + } + + result = {} + + obj = check_connectivity.CheckConnectivity(args, self.ctx) + obj.setup() + + mock_ssh.SSH.execute.return_value = (0, '100', '') + +def main(): + unittest.main() + + +if __name__ == '__main__': + main() diff --git a/tests/unit/benchmark/scenarios/test_base.py b/tests/unit/benchmark/scenarios/test_base.py new file mode 100644 index 000000000..78e342978 --- /dev/null +++ b/tests/unit/benchmark/scenarios/test_base.py @@ -0,0 +1,53 @@ +# Copyright 2017: Intel Ltd. +# 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 unittest + +from yardstick.benchmark.scenarios import base + + +class ScenarioTestCase(unittest.TestCase): + + def test_get_scenario_type(self): + scenario_type = 'dummy scenario' + + class DummyScenario(base.Scenario): + __scenario_type__ = scenario_type + + self.assertEqual(scenario_type, DummyScenario.get_scenario_type()) + + def test_get_scenario_type_not_defined(self): + class DummyScenario(base.Scenario): + pass + + self.assertEqual(str(None), DummyScenario.get_scenario_type()) + + def test_get_description(self): + docstring = """First line + Second line + Third line + """ + + class DummyScenario(base.Scenario): + __doc__ = docstring + + self.assertEqual(docstring.splitlines()[0], + DummyScenario.get_description()) + + def test_get_description_empty(self): + class DummyScenario(base.Scenario): + pass + + self.assertEqual(str(None), DummyScenario.get_description()) diff --git a/tests/unit/common/test_ansible_common.py b/tests/unit/common/test_ansible_common.py index a1eaf969e..1ef8eee5f 100644 --- a/tests/unit/common/test_ansible_common.py +++ b/tests/unit/common/test_ansible_common.py @@ -23,6 +23,7 @@ import mock import unittest from six.moves.configparser import ConfigParser +from six.moves import StringIO from yardstick.common import ansible_common @@ -30,19 +31,18 @@ PREFIX = 'yardstick.common.ansible_common' class OverwriteDictTestCase(unittest.TestCase): - def test_overwrite_dict_cfg(self): c = ConfigParser(allow_no_value=True) d = { "section_a": "empty_value", - "section_b": {"key_c": "val_d", "key_d": "val_d"}, + "section_b": {"key_c": "Val_d", "key_d": "VAL_D"}, "section_c": ["key_c", "key_d"], } ansible_common.overwrite_dict_to_cfg(c, d) # Python3 and Python2 convert empty values into None or '' # we don't really care but we need to compare correctly for unittest self.assertTrue(c.has_option("section_a", "empty_value")) - self.assertEqual(sorted(c.items("section_b")), [('key_c', 'val_d'), ('key_d', 'val_d')]) + self.assertEqual(sorted(c.items("section_b")), [('key_c', 'Val_d'), ('key_d', 'VAL_D')]) self.assertTrue(c.has_option("section_c", "key_c")) self.assertTrue(c.has_option("section_c", "key_d")) @@ -50,23 +50,23 @@ class OverwriteDictTestCase(unittest.TestCase): class FilenameGeneratorTestCase(unittest.TestCase): @mock.patch('{}.NamedTemporaryFile'.format(PREFIX)) def test__handle_existing_file(self, mock_tmp): - f = ansible_common.FileNameGenerator._handle_existing_file("/dev/null") + ansible_common.FileNameGenerator._handle_existing_file("/dev/null") def test_get_generator_from_file(self): - f = ansible_common.FileNameGenerator.get_generator_from_filename("/dev/null", "", "", "") + ansible_common.FileNameGenerator.get_generator_from_filename("/dev/null", "", "", "") def test_get_generator_from_file_middle(self): - f = ansible_common.FileNameGenerator.get_generator_from_filename("/dev/null", "", "", - "null") + ansible_common.FileNameGenerator.get_generator_from_filename("/dev/null", "", "", + "null") def test_get_generator_from_file_prefix(self): - f = ansible_common.FileNameGenerator.get_generator_from_filename("/dev/null", "", "null", - "middle") + ansible_common.FileNameGenerator.get_generator_from_filename("/dev/null", "", "null", + "middle") class AnsibleNodeTestCase(unittest.TestCase): def test_ansible_node(self): - a = ansible_common.AnsibleNode() + ansible_common.AnsibleNode() def test_ansible_node_len(self): a = ansible_common.AnsibleNode() @@ -104,42 +104,51 @@ class AnsibleNodeTestCase(unittest.TestCase): class AnsibleNodeDictTestCase(unittest.TestCase): def test_ansible_node_dict(self): - n = ansible_common.AnsibleNode() - a = ansible_common.AnsibleNodeDict(n, {}) + n = ansible_common.AnsibleNode + ansible_common.AnsibleNodeDict(n, {}) def test_ansible_node_dict_len(self): - n = ansible_common.AnsibleNode() + n = ansible_common.AnsibleNode a = ansible_common.AnsibleNodeDict(n, {}) len(a) def test_ansible_node_dict_repr(self): - n = ansible_common.AnsibleNode() + n = ansible_common.AnsibleNode a = ansible_common.AnsibleNodeDict(n, {}) repr(a) def test_ansible_node_dict_iter(self): - n = ansible_common.AnsibleNode() + n = ansible_common.AnsibleNode a = ansible_common.AnsibleNodeDict(n, {}) for _ in a: pass def test_ansible_node_dict_get(self): - n = ansible_common.AnsibleNode() + n = ansible_common.AnsibleNode a = ansible_common.AnsibleNodeDict(n, {}) self.assertIsNone(a.get("")) def test_gen_inventory_lines_for_all_of_type(self): - n = ansible_common.AnsibleNode() + n = ansible_common.AnsibleNode a = ansible_common.AnsibleNodeDict(n, {}) self.assertEqual(a.gen_inventory_lines_for_all_of_type(""), []) + def test_gen_inventory_lines(self): + n = ansible_common.AnsibleNode + a = ansible_common.AnsibleNodeDict(n, [{ + "name": "name", "user": "user", "password": "PASS", + "role": "role", + }]) + self.assertEqual(a.gen_all_inventory_lines(), + ["name ansible_ssh_pass=PASS ansible_user=user"]) + class AnsibleCommonTestCase(unittest.TestCase): def test_get_timeouts(self): self.assertAlmostEquals(ansible_common.AnsibleCommon.get_timeout(-100), 1200.0) def test__init__(self): - a = ansible_common.AnsibleCommon({}) + ansible_common.AnsibleCommon({}) def test_reset(self): a = ansible_common.AnsibleCommon({}) @@ -150,9 +159,16 @@ class AnsibleCommonTestCase(unittest.TestCase): self.assertRaises(OSError, a.do_install, '', '') def test_gen_inventory_dict(self): - a = ansible_common.AnsibleCommon({}) - a.inventory_dict = {} - self.assertIsNone(a.gen_inventory_ini_dict()) + nodes = [{ + "name": "name", "user": "user", "password": "PASS", + "role": "role", + }] + a = ansible_common.AnsibleCommon(nodes) + a.gen_inventory_ini_dict() + self.assertEqual(a.inventory_dict, { + 'nodes': ['name ansible_ssh_pass=PASS ansible_user=user'], + 'role': ['name'] + }) def test_deploy_dir(self): a = ansible_common.AnsibleCommon({}) @@ -178,6 +194,25 @@ class AnsibleCommonTestCase(unittest.TestCase): @mock.patch('{}.NamedTemporaryFile'.format(PREFIX)) @mock.patch('{}.open'.format(PREFIX)) + def test__gen_ansible_inventory_file(self, mock_open, mock_tmp): + nodes = [{ + "name": "name", "user": "user", "password": "PASS", + "role": "role", + }] + d = tempfile.mkdtemp() + try: + a = ansible_common.AnsibleCommon(nodes) + a.gen_inventory_ini_dict() + inv_context = a._gen_ansible_inventory_file(d) + with inv_context: + c = StringIO() + inv_context.write_func(c) + self.assertIn("ansible_ssh_pass=PASS", c.getvalue()) + finally: + os.rmdir(d) + + @mock.patch('{}.NamedTemporaryFile'.format(PREFIX)) + @mock.patch('{}.open'.format(PREFIX)) def test__gen_ansible_playbook_file_list_multiple(self, mock_open, mock_tmp): d = tempfile.mkdtemp() try: diff --git a/tests/unit/common/test_process.py b/tests/unit/common/test_process.py index 5eee55bcc..1c6dfec27 100644 --- a/tests/unit/common/test_process.py +++ b/tests/unit/common/test_process.py @@ -11,10 +11,13 @@ # 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 unittest import mock +import unittest + +from oslo_utils import encodeutils +from yardstick.common import exceptions from yardstick.common import process @@ -44,3 +47,104 @@ class TerminateChildrenTestcase(unittest.TestCase): def test_no_children(self, mock_multiprocessing): mock_multiprocessing.active_children.return_value = [] process.terminate_children() + + +class ExecuteTestCase(unittest.TestCase): + + RET_CODE_OK = 0 + RET_CODE_WRONG = 1 + + def setUp(self): + self._mock_create_process = mock.patch.object(process, + 'create_process') + self.mock_create_process = self._mock_create_process.start() + self.obj = mock.Mock() + self.cmd = mock.Mock() + self.obj.communicate = mock.Mock() + self.stdout = 'std out' + self.stderr = 'std err' + self.obj.communicate.return_value = (self.stdout, self.stderr) + self.mock_create_process.return_value = (self.obj, self.cmd) + self.input_cmd = 'input cmd' + self.additional_env = mock.Mock() + + def test_execute_with_input(self): + process_input = 'process input' + self.obj.returncode = self.RET_CODE_OK + out = process.execute(self.input_cmd, process_input=process_input, + additional_env=self.additional_env) + self.obj.communicate.assert_called_once_with( + encodeutils.to_utf8(process_input)) + self.mock_create_process.assert_called_once_with( + self.input_cmd, run_as_root=False, + additional_env=self.additional_env) + self.assertEqual(self.stdout, out) + + def test_execute_no_input(self): + self.obj.returncode = self.RET_CODE_OK + out = process.execute(self.input_cmd, + additional_env=self.additional_env) + self.obj.communicate.assert_called_once_with(None) + self.mock_create_process.assert_called_once_with( + self.input_cmd, run_as_root=False, + additional_env=self.additional_env) + self.assertEqual(self.stdout, out) + + def test_execute_exception(self): + self.obj.returncode = self.RET_CODE_WRONG + self.assertRaises(exceptions.ProcessExecutionError, process.execute, + self.input_cmd, additional_env=self.additional_env) + self.obj.communicate.assert_called_once_with(None) + + def test_execute_with_extra_code(self): + self.obj.returncode = self.RET_CODE_WRONG + out = process.execute(self.input_cmd, + additional_env=self.additional_env, + extra_ok_codes=[self.RET_CODE_WRONG]) + self.obj.communicate.assert_called_once_with(None) + self.mock_create_process.assert_called_once_with( + self.input_cmd, run_as_root=False, + additional_env=self.additional_env) + self.assertEqual(self.stdout, out) + + def test_execute_exception_no_check(self): + self.obj.returncode = self.RET_CODE_WRONG + out = process.execute(self.input_cmd, + additional_env=self.additional_env, + check_exit_code=False) + self.obj.communicate.assert_called_once_with(None) + self.mock_create_process.assert_called_once_with( + self.input_cmd, run_as_root=False, + additional_env=self.additional_env) + self.assertEqual(self.stdout, out) + + +class CreateProcessTestCase(unittest.TestCase): + + @mock.patch.object(process, 'subprocess_popen') + def test_process_string_command(self, mock_subprocess_popen): + cmd = 'command' + obj = mock.Mock() + mock_subprocess_popen.return_value = obj + out1, out2 = process.create_process(cmd) + self.assertEqual(obj, out1) + self.assertEqual([cmd], out2) + + @mock.patch.object(process, 'subprocess_popen') + def test_process_list_command(self, mock_subprocess_popen): + cmd = ['command'] + obj = mock.Mock() + mock_subprocess_popen.return_value = obj + out1, out2 = process.create_process(cmd) + self.assertEqual(obj, out1) + self.assertEqual(cmd, out2) + + @mock.patch.object(process, 'subprocess_popen') + def test_process_with_env(self, mock_subprocess_popen): + cmd = ['command'] + obj = mock.Mock() + additional_env = {'var1': 'value1'} + mock_subprocess_popen.return_value = obj + out1, out2 = process.create_process(cmd, additional_env=additional_env) + self.assertEqual(obj, out1) + self.assertEqual(['env', 'var1=value1'] + cmd, out2) diff --git a/tests/unit/common/test_utils.py b/tests/unit/common/test_utils.py index 42b75d1f0..452b93a56 100644 --- a/tests/unit/common/test_utils.py +++ b/tests/unit/common/test_utils.py @@ -11,15 +11,15 @@ from __future__ import absolute_import -import ipaddress -import os -import unittest from copy import deepcopy -from itertools import product, chain - import errno +import ipaddress +from itertools import product, chain import mock +import os +import six from six.moves import configparser +import unittest import yardstick from yardstick.common import utils @@ -775,7 +775,8 @@ class RemoveFileTestCase(unittest.TestCase): def test_remove_file(self): try: utils.remove_file('notexistfile.txt') - except Exception as e: + except Exception as e: # pylint: disable=broad-except + # NOTE(ralonsoh): to narrow the scope of this exception. self.assertTrue(isinstance(e, OSError)) @@ -997,7 +998,8 @@ class TestUtilsIpAddrMethods(unittest.TestCase): self.assertEqual(utils.safe_ip_address(addr), expected, addr) @mock.patch("yardstick.common.utils.logging") - def test_safe_ip_address_negative(self, mock_logging): + def test_safe_ip_address_negative(self, *args): + # NOTE(ralonsoh): check the calls to mocked functions. for value in self.INVALID_IP_ADDRESS_STR_LIST: self.assertIsNone(utils.safe_ip_address(value), value) @@ -1026,7 +1028,8 @@ class TestUtilsIpAddrMethods(unittest.TestCase): self.assertEqual(utils.get_ip_version(addr), 6, addr) @mock.patch("yardstick.common.utils.logging") - def test_get_ip_version_negative(self, mock_logging): + def test_get_ip_version_negative(self, *args): + # NOTE(ralonsoh): check the calls to mocked functions. for value in self.INVALID_IP_ADDRESS_STR_LIST: self.assertIsNone(utils.get_ip_version(value), value) @@ -1055,7 +1058,8 @@ class TestUtilsIpAddrMethods(unittest.TestCase): self.assertEqual(utils.ip_to_hex(value), value) @mock.patch("yardstick.common.utils.logging") - def test_ip_to_hex_negative(self, mock_logging): + def test_ip_to_hex_negative(self, *args): + # NOTE(ralonsoh): check the calls to mocked functions. addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST mask_list = self.GOOD_IP_V4_MASK_STR_LIST value_iter = (''.join(pair) for pair in product(addr_list, mask_list)) @@ -1063,6 +1067,17 @@ class TestUtilsIpAddrMethods(unittest.TestCase): self.assertEqual(utils.ip_to_hex(value), value) +class SafeDecodeUtf8TestCase(unittest.TestCase): + + @unittest.skipIf(six.PY2, + 'This test should only be launched with Python 3.x') + def test_safe_decode_utf8(self): + _bytes = b'this is a byte array' + out = utils.safe_decode_utf8(_bytes) + self.assertIs(type(out), str) + self.assertEqual('this is a byte array', out) + + def main(): unittest.main() diff --git a/tests/unit/network_services/helpers/test_samplevnf_helper.py b/tests/unit/network_services/helpers/test_samplevnf_helper.py index bff3a7722..05acdfaa9 100644 --- a/tests/unit/network_services/helpers/test_samplevnf_helper.py +++ b/tests/unit/network_services/helpers/test_samplevnf_helper.py @@ -797,7 +797,7 @@ class TestMultiPortConfig(unittest.TestCase): def test_generate_arp_route_tbl(self, *_): topology_file = mock.Mock() config_tpl = mock.Mock() - tmp_file = mock.Mock() + tmp_file = "" vnfd_mock = mock.MagicMock() vnfd_mock.port_num.side_effect = ['32', '1', '987'] vnfd_mock.find_interface.side_effect = [ diff --git a/tests/unit/network_services/nfvi/test_resource.py b/tests/unit/network_services/nfvi/test_resource.py index f3244fdbd..5c2f890e8 100644 --- a/tests/unit/network_services/nfvi/test_resource.py +++ b/tests/unit/network_services/nfvi/test_resource.py @@ -99,7 +99,7 @@ class TestResourceProfile(unittest.TestCase): port_names = \ self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]['vdu'][0]['external-interface'] self.resource_profile = \ - ResourceProfile(mgmt, port_names, [1, 2, 3]) + ResourceProfile(mgmt, port_names) self.resource_profile.connection = self.ssh_mock def test___init__(self): @@ -134,10 +134,6 @@ class TestResourceProfile(unittest.TestCase): self.assertIsNone( self.resource_profile._prepare_collectd_conf("/opt/nsb_bin")) - def test__setup_intel_pmu(self): - self.assertIsNone( - self.resource_profile._setup_intel_pmu(self.ssh_mock, "/opt/nsb_bin")) - def test__setup_ovs_stats(self): self.assertIsNone( self.resource_profile._setup_ovs_stats(self.ssh_mock)) diff --git a/tests/unit/network_services/test_utils.py b/tests/unit/network_services/test_utils.py index 993adbeae..bf98a4474 100644 --- a/tests/unit/network_services/test_utils.py +++ b/tests/unit/network_services/test_utils.py @@ -15,8 +15,6 @@ # Unittest for yardstick.network_services.utils -from __future__ import absolute_import - import os import unittest import mock @@ -62,3 +60,84 @@ class UtilsTestCase(unittest.TestCase): ssh.return_value = ssh_mock tool_path = utils.provision_tool(ssh_mock, self.DPDK_PATH) self.assertEqual(tool_path, self.DPDK_PATH) + + +class PciAddressTestCase(unittest.TestCase): + + PCI_ADDRESS_DBSF = '000A:07:03.2' + PCI_ADDRESS_BSF = '06:02.1' + PCI_ADDRESS_DBSF_MULTILINE_1 = '0001:08:04.3\nother text\n' + PCI_ADDRESS_DBSF_MULTILINE_2 = 'first line\n 0001:08:04.3 \nother text\n' + # Will match and return the first address found. + PCI_ADDRESS_DBSF_MULTILINE_3 = ' 0001:08:04.1 \n 05:03.1 \nother\n' + PCI_ADDRESS_BSF_MULTILINE_1 = 'first line\n 08:04.3 \n 0002:05:03.1\n' + BAD_INPUT_1 = 'no address found' + BAD_INPUT_2 = '001:08:04.1' + BAD_INPUT_3 = '08:4.1' + + def test_pciaddress_dbsf(self): + pci_address = utils.PciAddress(PciAddressTestCase.PCI_ADDRESS_DBSF) + self.assertEqual('000a', pci_address.domain) + self.assertEqual('07', pci_address.bus) + self.assertEqual('03', pci_address.slot) + self.assertEqual('2', pci_address.function) + + def test_pciaddress_bsf(self): + pci_address = utils.PciAddress(PciAddressTestCase.PCI_ADDRESS_BSF) + self.assertEqual('0000', pci_address.domain) + self.assertEqual('06', pci_address.bus) + self.assertEqual('02', pci_address.slot) + self.assertEqual('1', pci_address.function) + + def test_pciaddress_dbsf_multiline_1(self): + pci_address = utils.PciAddress( + PciAddressTestCase.PCI_ADDRESS_DBSF_MULTILINE_1) + self.assertEqual('0001', pci_address.domain) + self.assertEqual('08', pci_address.bus) + self.assertEqual('04', pci_address.slot) + self.assertEqual('3', pci_address.function) + + def test_pciaddress_dbsf_multiline_2(self): + pci_address = utils.PciAddress( + PciAddressTestCase.PCI_ADDRESS_DBSF_MULTILINE_2) + self.assertEqual('0001', pci_address.domain) + self.assertEqual('08', pci_address.bus) + self.assertEqual('04', pci_address.slot) + self.assertEqual('3', pci_address.function) + + def test_pciaddress_dbsf_multiline_3(self): + pci_address = utils.PciAddress( + PciAddressTestCase.PCI_ADDRESS_DBSF_MULTILINE_3) + self.assertEqual('0001', pci_address.domain) + self.assertEqual('08', pci_address.bus) + self.assertEqual('04', pci_address.slot) + self.assertEqual('1', pci_address.function) + + def test_pciaddress_bsf_multiline_1(self): + pci_address = utils.PciAddress( + PciAddressTestCase.PCI_ADDRESS_BSF_MULTILINE_1) + self.assertEqual('0000', pci_address.domain) + self.assertEqual('08', pci_address.bus) + self.assertEqual('04', pci_address.slot) + self.assertEqual('3', pci_address.function) + + def test_pciaddress_bad_input_no_address(self): + with self.assertRaises(ValueError) as exception: + utils.PciAddress(PciAddressTestCase.BAD_INPUT_1) + self.assertEqual('Invalid PCI address: {}'.format( + PciAddressTestCase.BAD_INPUT_1), str(exception.exception)) + + def test_pciaddress_bad_input_dbsf_bad_formatted(self): + # In this test case, the domain has only 3 characters instead of 4. + pci_address = utils.PciAddress( + PciAddressTestCase.BAD_INPUT_2) + self.assertEqual('0000', pci_address.domain) + self.assertEqual('08', pci_address.bus) + self.assertEqual('04', pci_address.slot) + self.assertEqual('1', pci_address.function) + + def test_pciaddress_bad_input_bsf_bad_formatted(self): + with self.assertRaises(ValueError) as exception: + utils.PciAddress(PciAddressTestCase.BAD_INPUT_3) + self.assertEqual('Invalid PCI address: {}'.format( + PciAddressTestCase.BAD_INPUT_3), str(exception.exception)) diff --git a/tests/unit/network_services/traffic_profile/test_prox_mpls.py b/tests/unit/network_services/traffic_profile/test_prox_mpls.py deleted file mode 100644 index 00a690d2a..000000000 --- a/tests/unit/network_services/traffic_profile/test_prox_mpls.py +++ /dev/null @@ -1,95 +0,0 @@ -# Copyright (c) 2017 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. -# - -from __future__ import absolute_import - -import unittest -import mock - -from tests.unit import STL_MOCKS - -STLClient = mock.MagicMock() -stl_patch = mock.patch.dict("sys.modules", STL_MOCKS) -stl_patch.start() - -if stl_patch: - from yardstick.network_services.vnf_generic.vnf.prox_helpers import ProxTestDataTuple - from yardstick.network_services.traffic_profile.prox_mpls_tag_untag import ProxMplsTagUntagProfile - - -class TestProxMplsTagUntagProfile(unittest.TestCase): - - def test_mpls_1(self): - def target(*args, **kwargs): - runs.append(args[2]) - if args[2] < 0 or args[2] > 100: - raise RuntimeError(' '.join([str(args), str(runs)])) - if args[2] > 75.0: - return fail_tuple, {} - return success_tuple, {} - - tp_config = { - 'traffic_profile': { - 'packet_sizes': [200], - }, - } - - runs = [] - success_tuple = ProxTestDataTuple(10.0, 1, 2, 3, 4, [5.1, 5.2, 5.3], 995, 1000, 123.4) - fail_tuple = ProxTestDataTuple(10.0, 1, 2, 3, 4, [5.6, 5.7, 5.8], 850, 1000, 123.4) - - traffic_generator = mock.MagicMock() - - profile = ProxMplsTagUntagProfile(tp_config) - profile.init(mock.MagicMock()) - profile._profile_helper = profile_helper = mock.MagicMock() - profile_helper.run_test = target - - profile.execute_traffic(traffic_generator) - self.assertEqual(round(profile.current_lower, 2), 74.69) - self.assertEqual(round(profile.current_upper, 2), 75.39) - self.assertEqual(len(runs), 8) - - def test_mpls_2(self): - def target(*args, **kwargs): - runs.append(args[2]) - if args[2] < 0 or args[2] > 100: - raise RuntimeError(' '.join([str(args), str(runs)])) - if args[2] > 25.0: - return fail_tuple, {} - return success_tuple, {} - - tp_config = { - 'traffic_profile': { - 'packet_sizes': [200], - 'test_precision': 2.0, - }, - } - - runs = [] - success_tuple = ProxTestDataTuple(10.0, 1, 2, 3, 4, [5.1, 5.2, 5.3], 995, 1000, 123.4) - fail_tuple = ProxTestDataTuple(10.0, 1, 2, 3, 4, [5.6, 5.7, 5.8], 850, 1000, 123.4) - - traffic_generator = mock.MagicMock() - - profile = ProxMplsTagUntagProfile(tp_config) - profile.init(mock.MagicMock()) - profile._profile_helper = profile_helper = mock.MagicMock() - profile_helper.run_test = target - - profile.execute_traffic(traffic_generator) - self.assertEqual(round(profile.current_lower, 2), 24.06) - self.assertEqual(round(profile.current_upper, 2), 25.47) - self.assertEqual(len(runs), 7) diff --git a/tests/unit/network_services/vnf_generic/vnf/test_base.py b/tests/unit/network_services/vnf_generic/vnf/test_base.py index 478ce186b..f812d67ef 100644 --- a/tests/unit/network_services/vnf_generic/vnf/test_base.py +++ b/tests/unit/network_services/vnf_generic/vnf/test_base.py @@ -243,31 +243,13 @@ class TestGenericVNF(unittest.TestCase): class TestGenericTrafficGen(unittest.TestCase): - def test___init__(self): - vnfd = TestGenericVNF.VNFD['vnfd:vnfd-catalog']['vnfd'][0] - generic_traffic_gen = GenericTrafficGen('vnf1', vnfd) - assert generic_traffic_gen.name == "vnf1" - - def test_listen_traffic(self): - vnfd = TestGenericVNF.VNFD['vnfd:vnfd-catalog']['vnfd'][0] - generic_traffic_gen = GenericTrafficGen('vnf1', vnfd) - traffic_profile = {} - self.assertIsNone(generic_traffic_gen.listen_traffic(traffic_profile)) - - def test_run_traffic(self): - vnfd = TestGenericVNF.VNFD['vnfd:vnfd-catalog']['vnfd'][0] - generic_traffic_gen = GenericTrafficGen('vnf1', vnfd) - traffic_profile = {} - self.assertRaises(NotImplementedError, - generic_traffic_gen.run_traffic, traffic_profile) - - def test_terminate(self): - vnfd = TestGenericVNF.VNFD['vnfd:vnfd-catalog']['vnfd'][0] - generic_traffic_gen = GenericTrafficGen('vnf1', vnfd) - self.assertRaises(NotImplementedError, generic_traffic_gen.terminate) - def test_verify_traffic(self): + def test_definition(self): + """Make sure that the abstract class cannot be instantiated""" vnfd = TestGenericVNF.VNFD['vnfd:vnfd-catalog']['vnfd'][0] - generic_traffic_gen = GenericTrafficGen('vnf1', vnfd) - traffic_profile = {} - self.assertIsNone(generic_traffic_gen.verify_traffic(traffic_profile)) + name = 'vnf1' + with self.assertRaises(TypeError) as exc: + GenericTrafficGen(name, vnfd) + msg = ("Can't instantiate abstract class GenericTrafficGen with " + "abstract methods run_traffic, terminate") + self.assertEqual(msg, str(exc.exception)) diff --git a/tests/unit/network_services/vnf_generic/vnf/test_cgnapt_vnf.py b/tests/unit/network_services/vnf_generic/vnf/test_cgnapt_vnf.py index b0ef1da91..832509ea7 100644 --- a/tests/unit/network_services/vnf_generic/vnf/test_cgnapt_vnf.py +++ b/tests/unit/network_services/vnf_generic/vnf/test_cgnapt_vnf.py @@ -72,13 +72,12 @@ link 1 up self.assertNotIn("This is a header", out) def test__get_cgnapt_config(self): - vnfd_helper = mock.Mock() + vnfd_helper = mock.MagicMock() vnfd_helper.port_pairs.uplink_ports = [{"name": 'a'}, {"name": "b"}, {"name": "c"}] helper = CgnaptApproxSetupEnvHelper(vnfd_helper, mock.Mock(), mock.Mock()) - helper._get_ports_gateway = mock.Mock(side_effect=[3, 5, 2]) - result = helper._get_cgnapt_config([{"name": 'a'}, {}, {"name": "b"}, {}, {"name": "c"}]) - self.assertEqual(result, [3, 5, 2]) + result = helper._get_cgnapt_config() + self.assertIsNotNone(result) def test_scale(self): helper = CgnaptApproxSetupEnvHelper(mock.Mock(), mock.Mock(), mock.Mock()) diff --git a/tests/unit/network_services/vnf_generic/vnf/test_prox_helpers.py b/tests/unit/network_services/vnf_generic/vnf/test_prox_helpers.py index 3c073812c..84eb5dc0d 100644 --- a/tests/unit/network_services/vnf_generic/vnf/test_prox_helpers.py +++ b/tests/unit/network_services/vnf_generic/vnf/test_prox_helpers.py @@ -44,6 +44,7 @@ if stl_patch: from yardstick.network_services.vnf_generic.vnf.prox_helpers import ProxMplsProfileHelper from yardstick.network_services.vnf_generic.vnf.prox_helpers import ProxBngProfileHelper from yardstick.network_services.vnf_generic.vnf.prox_helpers import ProxVpeProfileHelper + from yardstick.network_services.vnf_generic.vnf.prox_helpers import ProxlwAFTRProfileHelper class TestCoreTuple(unittest.TestCase): @@ -533,20 +534,6 @@ class TestProxSocketHelper(unittest.TestCase): result = prox.hz() self.assertEqual(result, expected) - def test_rx_stats(self, mock_time): - core_stats = [ - '3,4,5,6', - '7,8,9,10,NaN', - '11,12,13,14,15', - ] - - mock_socket = mock.MagicMock() - prox = ProxSocketHelper(mock_socket) - prox.get_data = mock.MagicMock(side_effect=core_stats) - expected = 21, 24, 27, 14 - result = prox.rx_stats([3, 4, 5], 16) - self.assertEqual(result, expected) - def test_core_stats(self, mock_time): core_stats = [ '3,4,5,6', @@ -2215,3 +2202,117 @@ class TestProxVpeProfileHelper(unittest.TestCase): helper.run_test(120, 5, 6.5) helper.run_test(-1000, 5, 6.5) # negative pkt_size is the only way to make ratio > 1 + + +class TestProxlwAFTRProfileHelper(unittest.TestCase): + + def test_lwaftr_cores(self): + resource_helper = mock.MagicMock() + resource_helper.setup_helper.prox_config_data = [ + ('section1', []), + ('section2', [ + ('a', 'b'), + ('c', 'd'), + ]), + ('core 1', []), + ('core 2', [ + ('index', 8), + ('mode', ''), + ]), + ('core 3', [ + ('index', 5), + ('mode', 'gen'), + ('name', 'tun'), + ]), + ('core 4', [ + ('index', 7), + ('mode', 'gen'), + ('name', 'inet'), + ]), + ] + + helper = ProxlwAFTRProfileHelper(resource_helper) + helper._cpu_topology = { + 0: { + 1: { + 5: (5, 1, 0) + }, + 2: { + 6: (6, 2, 0) + }, + 3: { + 7: (7, 3, 0) + }, + 4: { + 8: (8, 3, 0) + }, + } + } + + expected_tun = [7] + expected_inet = [8] + expected_combined = (expected_tun, expected_inet) + + self.assertIsNone(helper._cores_tuple) + self.assertEqual(helper.tun_cores, expected_tun) + self.assertEqual(helper.inet_cores, expected_inet) + self.assertEqual(helper._cores_tuple, expected_combined) + + def test_tun_ports(self): + resource_helper = mock.MagicMock() + resource_helper.setup_helper.prox_config_data = [ + ('section1', []), + ('section2', [ + ('a', 'b'), + ('c', 'd'), + ]), + ('port 3', [ + ('index', '5'), + ('name', 'lwB4'), + ('mac', 'hardware'), + ]), + ('port 4', [ + ('index', '7'), + ('name', 'inet'), + ('mac', 'hardware'), + ]), + ] + + helper = ProxlwAFTRProfileHelper(resource_helper) + helper._port_list = { + 0: { + 1: { + 5: 'lwB4' + }, + 2: { + 6: 'inet' + }, + 3: { + 7: 'lwB4' + }, + 4: { + 8: 'inet' + }, + } + } + + expected_tun = [3] + expected_inet = [4] + expected_combined = (expected_tun, expected_inet) + + self.assertIsNone(helper._ports_tuple) + self.assertEqual(helper.tun_ports, expected_tun) + self.assertEqual(helper.inet_ports, expected_inet) + self.assertEqual(helper._ports_tuple, expected_combined) + + @mock.patch('yardstick.network_services.vnf_generic.vnf.prox_helpers.time') + def test_run_test(self, _): + resource_helper = mock.MagicMock() + resource_helper.step_delta = 0.4 + resource_helper.vnfd_helper.port_pairs.all_ports = list(range(2)) + resource_helper.sut.port_stats.return_value = list(range(10)) + + helper = ProxlwAFTRProfileHelper(resource_helper) + + helper.run_test(120, 5, 6.5) + helper.run_test(-1000, 5, 6.5) # negative pkt_size is the only way to make ratio > 1 diff --git a/tests/unit/network_services/vnf_generic/vnf/test_prox_vnf.py b/tests/unit/network_services/vnf_generic/vnf/test_prox_vnf.py index a6d40877d..e29e8ddcd 100644 --- a/tests/unit/network_services/vnf_generic/vnf/test_prox_vnf.py +++ b/tests/unit/network_services/vnf_generic/vnf/test_prox_vnf.py @@ -348,9 +348,9 @@ class TestProxApproxVnf(unittest.TestCase): prox_approx_vnf.resource_helper = resource_helper expected = { - 'packets_in': 7, + 'packets_in': 6, 'packets_dropped': 1, - 'packets_fwd': 6, + 'packets_fwd': 7, 'collect_stats': {'core': {'result': 234}}, } result = prox_approx_vnf.collect_kpi() diff --git a/tests/unit/network_services/vnf_generic/vnf/test_router_vnf.py b/tests/unit/network_services/vnf_generic/vnf/test_router_vnf.py new file mode 100644 index 000000000..9ed6fd5b3 --- /dev/null +++ b/tests/unit/network_services/vnf_generic/vnf/test_router_vnf.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python + +# Copyright (c) 2016-2017 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. +# + +from __future__ import absolute_import + +import unittest +import mock + +from tests.unit import STL_MOCKS +from tests.unit.network_services.vnf_generic.vnf.test_base import mock_ssh + + +STLClient = mock.MagicMock() +stl_patch = mock.patch.dict("sys.modules", STL_MOCKS) +stl_patch.start() + +if stl_patch: + from yardstick.network_services.vnf_generic.vnf.router_vnf import RouterVNF + + +TEST_FILE_YAML = 'nsb_test_case.yaml' +SSH_HELPER = 'yardstick.network_services.vnf_generic.vnf.sample_vnf.VnfSshHelper' + + +name = 'vnf__1' + + +class TestRouterVNF(unittest.TestCase): + VNFD = {'vnfd:vnfd-catalog': + {'vnfd': + [{'short-name': 'RouterVNF', + 'vdu': + [{'routing_table': [], + 'description': 'RouterVNF', + 'name': 'router-baremetal', + 'nd_route_tbl': [], + 'id': 'router-baremetal', + 'external-interface': + [{'virtual-interface': + {'dst_mac': '00:00:00:00:00:04', + 'vpci': '0000:05:00.0', + 'local_ip': '152.16.100.19', + 'type': 'PCI-PASSTHROUGH', + 'netmask': '255.255.255.0', + 'dpdk_port_num': 0, + 'bandwidth': '10 Gbps', + 'driver': "i40e", + 'dst_ip': '152.16.100.20', + 'local_iface_name': 'xe0', + 'local_mac': '00:00:00:00:00:02'}, + 'vnfd-connection-point-ref': 'xe0', + 'name': 'xe0'}, + {'virtual-interface': + {'dst_mac': '00:00:00:00:00:03', + 'vpci': '0000:05:00.1', + 'local_ip': '152.16.40.19', + 'type': 'PCI-PASSTHROUGH', + 'driver': "i40e", + 'netmask': '255.255.255.0', + 'dpdk_port_num': 1, + 'bandwidth': '10 Gbps', + 'dst_ip': '152.16.40.20', + 'local_iface_name': 'xe1', + 'local_mac': '00:00:00:00:00:01'}, + 'vnfd-connection-point-ref': 'xe1', + 'name': 'xe1'}]}], + 'description': 'RouterVNF', + 'mgmt-interface': + {'vdu-id': 'router-baremetal', + 'host': '1.2.1.1', + 'password': 'r00t', + 'user': 'root', + 'ip': '1.2.1.1'}, + 'benchmark': + {'kpi': ['packets_in', 'packets_fwd', 'packets_dropped']}, + 'connection-point': [{'type': 'VPORT', 'name': 'xe0'}, + {'type': 'VPORT', 'name': 'xe1'}], + 'id': 'RouterVNF', 'name': 'VPEVnfSsh'}]}} + + scenario_cfg = {'nodes': {'cpt__0': 'compute_0.compute_nodes', + 'tg__0': 'trafficgen_1.baremetal', + 'vnf__0': 'vnf.yardstick'}, + 'options': {'flow': {'count': 128000, + 'dst_ip': ['10.0.3.26-10.0.3.105'], + 'dst_port': ['2001-2004'], + 'src_ip': ['10.0.2.26-10.0.2.105'], + 'src_port': ['1234-1238']}, + 'framesize': {'downlink': {'1024B': 100}, + 'uplink': {'1024B': 100}}, + 'rfc2544': {'allowed_drop_rate': '0.0001 - 0.1'}, + 'tg__0': {'queues_per_port': 7}, + 'traffic_type': 4, + 'vnf__0': {'nfvi_enable': True}}, + 'runner': {'interval': 35, + 'iterations': 10, + 'type': 'Iteration'}, + 'topology': 'router-tg-topology.yaml', + 'traffic_profile': '../../traffic_profiles/ipv4_throughput.yaml', + 'type': 'NSPerf'} + + context_cfg = {'nodes': {'tg__1': + {'member-vnf-index': '1', + 'role': 'TrafficGen', + 'name': 'trafficgen_1.yardstick', + 'vnfd-id-ref': 'tg__1', + 'ip': '1.2.1.1', + 'interfaces': + {'xe0': {'local_iface_name': 'ens785f0', + 'vld_id': RouterVNF.UPLINK, + 'netmask': '255.255.255.0', + 'local_ip': '152.16.100.20', + 'dst_mac': '00:00:00:00:00:02', + 'local_mac': '00:00:00:00:00:04', + 'dst_ip': '152.16.100.19', + 'driver': 'i40e', + 'vpci': '0000:05:00.0', + 'dpdk_port_num': 0}, + 'xe1': {'local_iface_name': 'ens785f1', + 'netmask': '255.255.255.0', + 'local_ip': '152.16.100.21', + 'local_mac': '00:00:00:00:00:01', + 'driver': 'i40e', + 'vpci': '0000:05:00.1', + 'dpdk_port_num': 1}}, + 'password': 'r00t', + 'VNF model': 'tg_rfc2544_tpl.yaml', + 'user': 'root'}, + 'vnf__1': + {'name': 'vnf.yardstick', + 'vnfd-id-ref': 'vnf__1', + 'ip': '1.2.1.1', + 'interfaces': + {'xe0': {'local_iface_name': 'ens786f0', + 'vld_id': RouterVNF.UPLINK, + 'netmask': '255.255.255.0', + 'local_ip': '152.16.100.19', + 'dst_mac': '00:00:00:00:00:04', + 'local_mac': '00:00:00:00:00:02', + 'dst_ip': '152.16.100.20', + 'driver': 'i40e', + 'vpci': '0000:05:00.0', + 'dpdk_port_num': 0}, + 'xe1': {'local_iface_name': 'ens786f1', + 'vld_id': RouterVNF.DOWNLINK, + 'netmask': '255.255.255.0', + 'local_ip': '152.16.40.19', + 'dst_mac': '00:00:00:00:00:03', + 'local_mac': '00:00:00:00:00:01', + 'dst_ip': '152.16.40.20', + 'driver': 'i40e', + 'vpci': '0000:05:00.1', + 'dpdk_port_num': 1}}, + 'routing_table': [], + 'member-vnf-index': '2', + 'host': '1.2.1.1', + 'role': 'vnf', + 'user': 'root', + 'nd_route_tbl': [], + 'password': 'r00t', + 'VNF model': 'router_vnf.yaml'}}} + + IP_SHOW_STATS_OUTPUT = """\ +2: em1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000 + link/ether d4:c9:ef:52:7c:4d brd ff:ff:ff:ff:ff:ff + RX: bytes packets errors dropped overrun mcast + 2781945429 3202213 0 0 0 30131 + RX errors: length crc frame fifo missed + 0 0 0 0 0 + TX: bytes packets errors dropped carrier collsns + 646221183 2145799 0 0 0 0 + TX errors: aborted fifo window heartbeat + 0 0 0 0 +""" + STATS = { + 'RX:bytes': '2781945429', + 'RX:dropped': '0', + 'RX:errors': '0', + 'RX:mcast': '30131', + 'RX:overrun': '0', + 'RX:packets': '3202213', + 'RX errors:length': '0', + 'RX errors:crc': '0', + 'RX errors:frame': '0', + 'RX errors:fifo': '0', + 'RX errors:missed': '0', + 'TX:bytes': '646221183', + 'TX:carrier': '0', + 'TX:collsns': '0', + 'TX:dropped': '0', + 'TX:errors': '0', + 'TX:packets': '2145799', + 'TX errors:aborted': '0', + 'TX errors:fifo': '0', + 'TX errors:window': '0', + 'TX errors:heartbeat': '0', + } + + def test___init__(self): + vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0] + router_vnf = RouterVNF(name, vnfd) + self.assertIsNone(router_vnf._vnf_process) + + def test_get_stats(self): + stats = RouterVNF.get_stats(self.IP_SHOW_STATS_OUTPUT) + self.assertDictEqual(stats, self.STATS) + + @mock.patch("yardstick.network_services.vnf_generic.vnf.sample_vnf.time") + @mock.patch(SSH_HELPER) + def test_collect_kpi(self, ssh, _): + m = mock_ssh(ssh) + + vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0] + router_vnf = RouterVNF(name, vnfd) + router_vnf.ssh_helper = m + result = {'packets_dropped': 0, 'packets_fwd': 0, 'packets_in': 0, 'link_stats': {}} + self.assertEqual(result, router_vnf.collect_kpi()) + + @mock.patch(SSH_HELPER) + def test_run_router(self, ssh): + mock_ssh(ssh) + + vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0] + router_vnf = RouterVNF(name, vnfd) + router_vnf.scenario_helper.scenario_cfg = self.scenario_cfg + router_vnf._run() + router_vnf.ssh_helper.drop_connection.assert_called_once() + + @mock.patch("yardstick.network_services.vnf_generic.vnf.router_vnf.Context") + @mock.patch(SSH_HELPER) + def test_instantiate(self, ssh, _): + mock_ssh(ssh) + + vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0] + router_vnf = RouterVNF(name, vnfd) + router_vnf.WAIT_TIME = 0 + router_vnf.INTERFACE_WAIT = 0 + self.scenario_cfg.update({"nodes": {"vnf__1": ""}}) + self.assertIsNone(router_vnf.instantiate(self.scenario_cfg, + self.context_cfg)) + + @mock.patch("yardstick.network_services.vnf_generic.vnf.sample_vnf.time") + @mock.patch(SSH_HELPER) + def test_terminate(self, ssh, _): + mock_ssh(ssh) + + vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0] + router_vnf = RouterVNF(name, vnfd) + router_vnf._vnf_process = mock.MagicMock() + router_vnf._vnf_process.terminate = mock.Mock() + self.assertEqual(None, router_vnf.terminate()) + +if __name__ == '__main__': + unittest.main() diff --git a/tests/unit/network_services/vnf_generic/vnf/test_sample_vnf.py b/tests/unit/network_services/vnf_generic/vnf/test_sample_vnf.py index c41da2c45..85b10c5a9 100644 --- a/tests/unit/network_services/vnf_generic/vnf/test_sample_vnf.py +++ b/tests/unit/network_services/vnf_generic/vnf/test_sample_vnf.py @@ -29,7 +29,6 @@ from yardstick.benchmark.contexts.base import Context from yardstick.network_services.nfvi.resource import ResourceProfile from yardstick.network_services.traffic_profile.base import TrafficProfile from yardstick.network_services.vnf_generic.vnf.base import VnfdHelper -from yardstick.ssh import SSHError class MockError(BaseException): @@ -360,15 +359,6 @@ class TestSetupEnvHelper(unittest.TestCase): with self.assertRaises(NotImplementedError): setup_env_helper.build_config() - def test__get_ports_gateway(self): - vnfd_helper = VnfdHelper(self.VNFD_0) - setup_env_helper = SetupEnvHelper(vnfd_helper, mock.Mock(), mock.Mock()) - result = setup_env_helper._get_ports_gateway("xe0") - self.assertEqual(result, "152.16.100.20") - - result = setup_env_helper._get_ports_gateway("xe123") - self.assertIsNone(result) - def test_setup_vnf_environment(self): setup_env_helper = SetupEnvHelper(mock.Mock(), mock.Mock(), mock.Mock()) self.assertIsNone(setup_env_helper.setup_vnf_environment()) @@ -618,111 +608,6 @@ class TestDpdkVnfSetupEnvHelper(unittest.TestCase): dpdk_setup_helper._build_pipeline_kwargs() self.assertDictEqual(dpdk_setup_helper.pipeline_kwargs, expected) - def test__get_app_cpu(self): - vnfd_helper = VnfdHelper(self.VNFD_0) - ssh_helper = mock.Mock() - ssh_helper.provision_tool.return_value = 'tool_path' - scenario_helper = mock.Mock() - dpdk_setup_helper = DpdkVnfSetupEnvHelper(vnfd_helper, ssh_helper, scenario_helper) - - dpdk_setup_helper.CORES = expected = [5, 4, 3] - result = dpdk_setup_helper._get_app_cpu() - self.assertEqual(result, expected) - - @mock.patch('yardstick.network_services.vnf_generic.vnf.sample_vnf.CpuSysCores') - def test__get_app_cpu_no_cores_sw(self, mock_cpu_sys_cores_class): - mock_cpu_sys_cores = mock_cpu_sys_cores_class() - mock_cpu_sys_cores.get_core_socket.return_value = { - 'socket': [2, 4, 8, 10, 12], - } - vnfd_helper = VnfdHelper(self.VNFD_0) - ssh_helper = mock.Mock() - ssh_helper.provision_tool.return_value = 'tool_path' - scenario_helper = mock.Mock() - scenario_helper.vnf_cfg = { - 'worker_threads': '2', - } - dpdk_setup_helper = DpdkVnfSetupEnvHelper(vnfd_helper, ssh_helper, scenario_helper) - dpdk_setup_helper.CORES = [] - dpdk_setup_helper.SW_DEFAULT_CORE = 1 - dpdk_setup_helper.HW_DEFAULT_CORE = 2 - dpdk_setup_helper.socket = 'socket' - - expected = [2, 4, 8] - result = dpdk_setup_helper._get_app_cpu() - self.assertEqual(result, expected) - - @mock.patch('yardstick.network_services.vnf_generic.vnf.sample_vnf.CpuSysCores') - def test__get_app_cpu_no_cores_hw(self, mock_cpu_sys_cores_class): - mock_cpu_sys_cores = mock_cpu_sys_cores_class() - mock_cpu_sys_cores.get_core_socket.return_value = { - 'socket': [2, 4, 8, 10, 12], - } - vnfd_helper = VnfdHelper(self.VNFD_0) - ssh_helper = mock.Mock() - scenario_helper = mock.Mock() - scenario_helper.vnf_cfg = { - 'worker_threads': '2', - 'lb_config': 'HW', - } - dpdk_setup_helper = DpdkVnfSetupEnvHelper(vnfd_helper, ssh_helper, scenario_helper) - dpdk_setup_helper.CORES = [] - dpdk_setup_helper.SW_DEFAULT_CORE = 1 - dpdk_setup_helper.HW_DEFAULT_CORE = 2 - dpdk_setup_helper.socket = 'socket' - - expected = [2, 4, 8, 10] - result = dpdk_setup_helper._get_app_cpu() - self.assertEqual(result, expected) - - def test__get_cpu_sibling_list(self): - vnfd_helper = VnfdHelper(self.VNFD_0) - ssh_helper = mock.Mock() - ssh_helper.execute.side_effect = iter([(0, '5', ''), (0, '3,4', ''), (0, '10', '')]) - scenario_helper = mock.Mock() - dpdk_setup_helper = DpdkVnfSetupEnvHelper(vnfd_helper, ssh_helper, scenario_helper) - dpdk_setup_helper._get_app_cpu = mock.Mock(return_value=[]) - - expected = ['5', '3', '4', '10'] - result = dpdk_setup_helper._get_cpu_sibling_list([1, 3, 7]) - self.assertEqual(result, expected) - - def test__get_cpu_sibling_list_no_core_arg(self): - vnfd_helper = VnfdHelper(self.VNFD_0) - ssh_helper = mock.Mock() - ssh_helper.execute.side_effect = iter([(0, '5', ''), (0, '3,4', ''), (0, '10', '')]) - scenario_helper = mock.Mock() - dpdk_setup_helper = DpdkVnfSetupEnvHelper(vnfd_helper, ssh_helper, scenario_helper) - dpdk_setup_helper._get_app_cpu = mock.Mock(return_value=[1, 7]) - - expected = ['5', '3', '4'] - result = dpdk_setup_helper._get_cpu_sibling_list() - self.assertEqual(result, expected) - - def test__get_cpu_sibling_list_ssh_failure(self): - vnfd_helper = VnfdHelper(self.VNFD_0) - ssh_helper = mock.Mock() - ssh_helper.execute.side_effect = iter([(0, '5', ''), SSHError, (0, '10', '')]) - scenario_helper = mock.Mock() - dpdk_setup_helper = DpdkVnfSetupEnvHelper(vnfd_helper, ssh_helper, scenario_helper) - dpdk_setup_helper._get_app_cpu = mock.Mock(return_value=[]) - - expected = [] - result = dpdk_setup_helper._get_cpu_sibling_list([1, 3, 7]) - self.assertEqual(result, expected) - - def test__validate_cpu_cfg(self): - vnfd_helper = VnfdHelper(self.VNFD_0) - ssh_helper = mock.Mock() - ssh_helper.execute.side_effect = iter([(0, '5', ''), (0, '3,4', ''), (0, '10', '')]) - scenario_helper = mock.Mock() - dpdk_setup_helper = DpdkVnfSetupEnvHelper(vnfd_helper, ssh_helper, scenario_helper) - dpdk_setup_helper._get_app_cpu = mock.Mock(return_value=[1, 3, 7]) - - expected = ['5', '3', '4', '10'] - result = dpdk_setup_helper._validate_cpu_cfg() - self.assertEqual(result, expected) - @mock.patch('yardstick.network_services.vnf_generic.vnf.sample_vnf.time') @mock.patch('yardstick.ssh.SSH') def test_setup_vnf_environment(self, _, mock_time): @@ -1506,8 +1391,9 @@ class TestRfc2544ResourceHelper(unittest.TestCase): class TestSampleVNFDeployHelper(unittest.TestCase): + @mock.patch('yardstick.network_services.vnf_generic.vnf.sample_vnf.time') @mock.patch('subprocess.check_output') - def test_deploy_vnfs_disabled(self, mock_check_output): + def test_deploy_vnfs_disabled(self, mock_check_output, mock_time): vnfd_helper = mock.Mock() ssh_helper = mock.Mock() ssh_helper.join_bin_path.return_value = 'joined_path' @@ -2136,55 +2022,32 @@ class TestSampleVNFTrafficGen(unittest.TestCase): sample_vnf_tg.terminate() - @mock.patch('yardstick.network_services.vnf_generic.vnf.sample_vnf.time') - @mock.patch('yardstick.network_services.vnf_generic.vnf.sample_vnf.LOG') - def test_wait_for_instantiate(self, mock_logger, mock_time): + def test__wait_for_process(self): sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0) - sample_vnf_tg._check_status = mock.Mock(side_effect=iter([1, 0])) - sample_vnf_tg._tg_process = mock.Mock() - sample_vnf_tg._tg_process.is_alive.return_value = True - sample_vnf_tg._tg_process.exitcode = 234 - - self.assertEqual(sample_vnf_tg.wait_for_instantiate(), 234) - - @mock.patch('yardstick.network_services.vnf_generic.vnf.sample_vnf.time') - @mock.patch('yardstick.network_services.vnf_generic.vnf.sample_vnf.LOG') - def test_wait_for_instantiate_not_alive(self, mock_logger, mock_time): + with mock.patch.object(sample_vnf_tg, '_check_status', + return_value=0) as mock_status, \ + mock.patch.object(sample_vnf_tg, '_tg_process') as mock_proc: + mock_proc.is_alive.return_value = True + mock_proc.exitcode = 234 + self.assertEqual(sample_vnf_tg._wait_for_process(), 234) + mock_proc.is_alive.assert_called_once() + mock_status.assert_called_once() + + def test__wait_for_process_not_alive(self): sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0) - sample_vnf_tg._check_status = mock.Mock(return_value=1) - sample_vnf_tg._tg_process = mock.Mock() - sample_vnf_tg._tg_process.is_alive.side_effect = iter([True, False]) - sample_vnf_tg._tg_process.exitcode = 234 - - with self.assertRaises(RuntimeError): - sample_vnf_tg.wait_for_instantiate() - - @mock.patch('yardstick.network_services.vnf_generic.vnf.sample_vnf.time') - @mock.patch('yardstick.network_services.vnf_generic.vnf.sample_vnf.LOG') - @mock.patch('yardstick.network_services.vnf_generic.vnf.sample_vnf.Process') - def test_wait_for_instantiate_delayed(self, mock_process, mock_logger, mock_time): - class MockClientStarted(mock.Mock): - - def __init__(self, *args, **kwargs): - super(MockClientStarted, self).__init__(*args, **kwargs) - self.iter = iter([0, 0, 1]) - - @property - def value(self): - return next(self.iter) - - mock_traffic_profile = mock.Mock(autospec=TrafficProfile) - mock_traffic_profile.get_traffic_definition.return_value = "64" - mock_traffic_profile.execute_traffic.return_value = "64" - mock_traffic_profile.params = self.TRAFFIC_PROFILE + with mock.patch.object(sample_vnf_tg, '_tg_process') as mock_proc: + mock_proc.is_alive.return_value = False + self.assertRaises(RuntimeError, sample_vnf_tg._wait_for_process) + mock_proc.is_alive.assert_called_once() + def test__wait_for_process_delayed(self): sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0) - sample_vnf_tg._check_status = mock.Mock(side_effect=iter([1, 0])) - sample_vnf_tg._tg_process = mock.Mock() - sample_vnf_tg._tg_process.is_alive.return_value = True - sample_vnf_tg._tg_process.exitcode = 234 - sample_vnf_tg.resource_helper = mock.Mock() - sample_vnf_tg.resource_helper.client_started = MockClientStarted() - - self.assertTrue(sample_vnf_tg.run_traffic(mock_traffic_profile)) - self.assertEqual(mock_time.sleep.call_count, 2) + with mock.patch.object(sample_vnf_tg, '_check_status', + side_effect=[1, 0]) as mock_status, \ + mock.patch.object(sample_vnf_tg, + '_tg_process') as mock_proc: + mock_proc.is_alive.return_value = True + mock_proc.exitcode = 234 + self.assertEqual(sample_vnf_tg._wait_for_process(), 234) + mock_proc.is_alive.assert_has_calls([mock.call(), mock.call()]) + mock_status.assert_has_calls([mock.call(), mock.call()]) diff --git a/tests/unit/network_services/vnf_generic/vnf/test_tg_ping.py b/tests/unit/network_services/vnf_generic/vnf/test_tg_ping.py index c1b2d27eb..ab3570740 100644 --- a/tests/unit/network_services/vnf_generic/vnf/test_tg_ping.py +++ b/tests/unit/network_services/vnf_generic/vnf/test_tg_ping.py @@ -228,7 +228,7 @@ class TestPingTrafficGen(unittest.TestCase): CMD_KWARGS = { 'target_ip': u'152.16.100.20', 'local_ip': u'152.16.100.19', - 'local_if_name': u'xe0', + 'local_if_name': u'xe0_fake', } @mock.patch("yardstick.ssh.SSH") @@ -270,7 +270,7 @@ class TestPingTrafficGen(unittest.TestCase): mock_ssh(ssh, spec=VnfSshHelper, exec_result=(0, "success", "")) ping_traffic_gen = PingTrafficGen('vnf1', self.VNFD_0) ping_traffic_gen.setup_helper.ssh_helper = mock.MagicMock( - **{"execute.return_value": (0, "success", "")}) + **{"execute.return_value": (0, "xe0_fake", "")}) self.assertIsInstance(ping_traffic_gen.ssh_helper, mock.Mock) self.assertEqual(ping_traffic_gen._result, {}) @@ -278,12 +278,12 @@ class TestPingTrafficGen(unittest.TestCase): self.assertEqual( ping_traffic_gen.vnfd_helper.interfaces[0]['virtual-interface']['local_iface_name'], - 'success') + 'xe0_fake') self.assertEqual(self.CMD_KWARGS, ping_traffic_gen.resource_helper.cmd_kwargs) self.assertIsNotNone(ping_traffic_gen._result) @mock.patch("yardstick.ssh.SSH") - def test_listen_traffic(self, ssh): + def test_listen_traffic(self, *args): ping_traffic_gen = PingTrafficGen('vnf1', self.VNFD_0) self.assertIsNone(ping_traffic_gen.listen_traffic({})) diff --git a/tests/unit/network_services/vnf_generic/vnf/test_tg_trex.py b/tests/unit/network_services/vnf_generic/vnf/test_tg_trex.py index d08c62e0b..a2a5058fc 100644 --- a/tests/unit/network_services/vnf_generic/vnf/test_tg_trex.py +++ b/tests/unit/network_services/vnf_generic/vnf/test_tg_trex.py @@ -18,6 +18,8 @@ from __future__ import absolute_import import unittest + +import copy import mock SSH_HELPER = 'yardstick.network_services.vnf_generic.vnf.sample_vnf.VnfSshHelper' @@ -75,6 +77,8 @@ class TestTrexTrafficGen(unittest.TestCase): 'driver': "i40e", 'dst_ip': '152.16.100.20', 'local_iface_name': 'xe0', + 'vld_id': 'downlink_0', + 'ifname': 'xe0', 'local_mac': '00:00:00:00:00:02'}, 'vnfd-connection-point-ref': 'xe0', 'name': 'xe0'}, @@ -89,6 +93,8 @@ class TestTrexTrafficGen(unittest.TestCase): 'bandwidth': '10 Gbps', 'dst_ip': '152.16.40.20', 'local_iface_name': 'xe1', + 'vld_id': 'uplink_0', + 'ifname': 'xe1', 'local_mac': '00:00:00:00:00:01'}, 'vnfd-connection-point-ref': 'xe1', 'name': 'xe1'}]}], @@ -386,6 +392,8 @@ class TestTrexTrafficGen(unittest.TestCase): self.sut._connect_client.get_stats = mock.Mock(return_value="0") self.sut.resource_helper.RUN_DURATION = 0 self.sut.resource_helper.QUEUE_WAIT_TIME = 0 + # must generate cfg before we can run traffic so Trex port mapping is created + self.sut.resource_helper.generate_cfg() self.sut._traffic_runner(mock_traffic_profile) @mock.patch(SSH_HELPER) @@ -397,6 +405,52 @@ class TestTrexTrafficGen(unittest.TestCase): self.assertIsNone(trex_traffic_gen.resource_helper.generate_cfg()) @mock.patch(SSH_HELPER) + def test_build_ports_reversed_pci_ordering(self, ssh): + mock_ssh(ssh) + vnfd = copy.deepcopy(self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]) + vnfd['vdu'][0]['external-interface'] = [ + {'virtual-interface': + {'dst_mac': '00:00:00:00:00:04', + 'vpci': '0000:05:00.0', + 'local_ip': '152.16.100.19', + 'type': 'PCI-PASSTHROUGH', + 'netmask': '255.255.255.0', + 'dpdk_port_num': 2, + 'bandwidth': '10 Gbps', + 'driver': "i40e", + 'dst_ip': '152.16.100.20', + 'local_iface_name': 'xe0', + 'vld_id': 'downlink_0', + 'ifname': 'xe0', + 'local_mac': '00:00:00:00:00:02'}, + 'vnfd-connection-point-ref': 'xe0', + 'name': 'xe0'}, + {'virtual-interface': + {'dst_mac': '00:00:00:00:00:03', + 'vpci': '0000:04:00.0', + 'local_ip': '152.16.40.19', + 'type': 'PCI-PASSTHROUGH', + 'driver': "i40e", + 'netmask': '255.255.255.0', + 'dpdk_port_num': 0, + 'bandwidth': '10 Gbps', + 'dst_ip': '152.16.40.20', + 'local_iface_name': 'xe1', + 'vld_id': 'uplink_0', + 'ifname': 'xe1', + 'local_mac': '00:00:00:00:00:01'}, + 'vnfd-connection-point-ref': 'xe1', + 'name': 'xe1'}] + trex_traffic_gen = TrexTrafficGen(NAME, vnfd) + trex_traffic_gen.resource_helper.ssh_helper = mock.MagicMock() + trex_traffic_gen.resource_helper.generate_cfg() + trex_traffic_gen.resource_helper._build_ports() + self.assertEqual(sorted(trex_traffic_gen.resource_helper.all_ports), [0, 1]) + # there is a gap in ordering + self.assertEqual(dict(trex_traffic_gen.resource_helper.dpdk_to_trex_port_map), + {0: 0, 2: 1}) + + @mock.patch(SSH_HELPER) def test_run_traffic(self, ssh): mock_ssh(ssh) diff --git a/tests/unit/test_ssh.py b/tests/unit/test_ssh.py index b298c745b..88699fd85 100644 --- a/tests/unit/test_ssh.py +++ b/tests/unit/test_ssh.py @@ -546,6 +546,15 @@ class TestAutoConnectSSH(unittest.TestCase): with mock_scp_client_type() as mock_scp_client: self.assertEqual(mock_scp_client.put.call_count, 1) + @mock.patch('yardstick.ssh.SCPClient') + def test_get(self, mock_scp_client_type): + auto_connect_ssh = AutoConnectSSH('user1', 'host1') + auto_connect_ssh._client = mock.Mock() + + auto_connect_ssh.get('a', 'z') + with mock_scp_client_type() as mock_scp_client: + self.assertEqual(mock_scp_client.get.call_count, 1) + def test_put_file(self): auto_connect_ssh = AutoConnectSSH('user1', 'host1') auto_connect_ssh._client = mock.Mock() |