diff options
Diffstat (limited to 'yardstick/tests/unit')
-rw-r--r-- | yardstick/tests/unit/__init__.py | 65 | ||||
-rw-r--r-- | yardstick/tests/unit/base.py | 23 | ||||
-rw-r--r-- | yardstick/tests/unit/benchmark/core/test_task.py | 11 | ||||
-rw-r--r-- | yardstick/tests/unit/benchmark/runner/test_base.py | 17 | ||||
-rw-r--r-- | yardstick/tests/unit/benchmark/runner/test_search.py | 11 | ||||
-rw-r--r-- | yardstick/tests/unit/benchmark/scenarios/networking/test_vnf_generic.py | 239 | ||||
-rw-r--r-- | yardstick/tests/unit/benchmark/scenarios/test_base.py | 7 | ||||
-rw-r--r-- | yardstick/tests/unit/common/test_packages.py | 88 | ||||
-rw-r--r-- | yardstick/tests/unit/common/test_utils.py | 30 |
9 files changed, 303 insertions, 188 deletions
diff --git a/yardstick/tests/unit/__init__.py b/yardstick/tests/unit/__init__.py index a468b272b..c05f91c81 100644 --- a/yardstick/tests/unit/__init__.py +++ b/yardstick/tests/unit/__init__.py @@ -12,65 +12,12 @@ # See the License for the specific language governing permissions and
# limitations under the License.
-from __future__ import absolute_import
+import sys
+
import mock
+from yardstick import tests
+
-STL_MOCKS = {
- 'trex_stl_lib': mock.MagicMock(),
- 'trex_stl_lib.base64': mock.MagicMock(),
- 'trex_stl_lib.binascii': mock.MagicMock(),
- 'trex_stl_lib.collections': mock.MagicMock(),
- 'trex_stl_lib.copy': mock.MagicMock(),
- 'trex_stl_lib.datetime': mock.MagicMock(),
- 'trex_stl_lib.functools': mock.MagicMock(),
- 'trex_stl_lib.imp': mock.MagicMock(),
- 'trex_stl_lib.inspect': mock.MagicMock(),
- 'trex_stl_lib.json': mock.MagicMock(),
- 'trex_stl_lib.linecache': mock.MagicMock(),
- 'trex_stl_lib.math': mock.MagicMock(),
- 'trex_stl_lib.os': mock.MagicMock(),
- 'trex_stl_lib.platform': mock.MagicMock(),
- 'trex_stl_lib.pprint': mock.MagicMock(),
- 'trex_stl_lib.random': mock.MagicMock(),
- 'trex_stl_lib.re': mock.MagicMock(),
- 'trex_stl_lib.scapy': mock.MagicMock(),
- 'trex_stl_lib.socket': mock.MagicMock(),
- 'trex_stl_lib.string': mock.MagicMock(),
- 'trex_stl_lib.struct': mock.MagicMock(),
- 'trex_stl_lib.sys': mock.MagicMock(),
- 'trex_stl_lib.threading': mock.MagicMock(),
- 'trex_stl_lib.time': mock.MagicMock(),
- 'trex_stl_lib.traceback': mock.MagicMock(),
- 'trex_stl_lib.trex_stl_async_client': mock.MagicMock(),
- 'trex_stl_lib.trex_stl_client': mock.MagicMock(),
- 'trex_stl_lib.trex_stl_exceptions': mock.MagicMock(),
- 'trex_stl_lib.trex_stl_ext': mock.MagicMock(),
- 'trex_stl_lib.trex_stl_jsonrpc_client': mock.MagicMock(),
- 'trex_stl_lib.trex_stl_packet_builder_interface': mock.MagicMock(),
- 'trex_stl_lib.trex_stl_packet_builder_scapy': mock.MagicMock(),
- 'trex_stl_lib.trex_stl_port': mock.MagicMock(),
- 'trex_stl_lib.trex_stl_stats': mock.MagicMock(),
- 'trex_stl_lib.trex_stl_streams': mock.MagicMock(),
- 'trex_stl_lib.trex_stl_types': mock.MagicMock(),
- 'trex_stl_lib.types': mock.MagicMock(),
- 'trex_stl_lib.utils': mock.MagicMock(),
- 'trex_stl_lib.utils.argparse': mock.MagicMock(),
- 'trex_stl_lib.utils.collections': mock.MagicMock(),
- 'trex_stl_lib.utils.common': mock.MagicMock(),
- 'trex_stl_lib.utils.json': mock.MagicMock(),
- 'trex_stl_lib.utils.os': mock.MagicMock(),
- 'trex_stl_lib.utils.parsing_opts': mock.MagicMock(),
- 'trex_stl_lib.utils.pwd': mock.MagicMock(),
- 'trex_stl_lib.utils.random': mock.MagicMock(),
- 'trex_stl_lib.utils.re': mock.MagicMock(),
- 'trex_stl_lib.utils.string': mock.MagicMock(),
- 'trex_stl_lib.utils.sys': mock.MagicMock(),
- 'trex_stl_lib.utils.text_opts': mock.MagicMock(),
- 'trex_stl_lib.utils.text_tables': mock.MagicMock(),
- 'trex_stl_lib.utils.texttable': mock.MagicMock(),
- 'trex_stl_lib.warnings': mock.MagicMock(),
- 'trex_stl_lib.yaml': mock.MagicMock(),
- 'trex_stl_lib.zlib': mock.MagicMock(),
- 'trex_stl_lib.zmq': mock.MagicMock(),
-}
+mock_stl = mock.patch.dict(sys.modules, tests.STL_MOCKS)
+mock_stl.start()
diff --git a/yardstick/tests/unit/base.py b/yardstick/tests/unit/base.py new file mode 100644 index 000000000..b943efc2b --- /dev/null +++ b/yardstick/tests/unit/base.py @@ -0,0 +1,23 @@ +# Copyright 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. + +import abc + +import six +import unittest + + +@six.add_metaclass(abc.ABCMeta) +class BaseUnitTestCase(unittest.TestCase): + """Base class for unit tests""" diff --git a/yardstick/tests/unit/benchmark/core/test_task.py b/yardstick/tests/unit/benchmark/core/test_task.py index 2420df2d8..25a7a64b3 100644 --- a/yardstick/tests/unit/benchmark/core/test_task.py +++ b/yardstick/tests/unit/benchmark/core/test_task.py @@ -51,8 +51,15 @@ class TaskTestCase(unittest.TestCase): def test__do_output(self, mock_dispatcher): t = task.Task() output_config = {"DEFAULT": {"dispatcher": "file, http"}} - mock_dispatcher.get = mock.MagicMock(return_value=[mock.MagicMock(), - mock.MagicMock()]) + + dispatcher1 = mock.MagicMock() + dispatcher1.__dispatcher_type__ = 'file' + + dispatcher2 = mock.MagicMock() + dispatcher2.__dispatcher_type__ = 'http' + + mock_dispatcher.get = mock.MagicMock(return_value=[dispatcher1, + dispatcher2]) self.assertEqual(None, t._do_output(output_config, {})) @mock.patch.object(task, 'Context') diff --git a/yardstick/tests/unit/benchmark/runner/test_base.py b/yardstick/tests/unit/benchmark/runner/test_base.py index 0fdc42347..59739c54f 100644 --- a/yardstick/tests/unit/benchmark/runner/test_base.py +++ b/yardstick/tests/unit/benchmark/runner/test_base.py @@ -11,6 +11,8 @@ import time import mock import unittest +from subprocess import CalledProcessError + from yardstick.benchmark.runners import base from yardstick.benchmark.runners import iteration @@ -20,19 +22,19 @@ class ActionTestCase(unittest.TestCase): @mock.patch("yardstick.benchmark.runners.base.subprocess") def test__execute_shell_command(self, mock_subprocess): - mock_subprocess.check_output.side_effect = Exception() + mock_subprocess.check_output.side_effect = CalledProcessError(-1, '') self.assertEqual(base._execute_shell_command("")[0], -1) @mock.patch("yardstick.benchmark.runners.base.subprocess") def test__single_action(self, mock_subprocess): - mock_subprocess.check_output.side_effect = Exception() + mock_subprocess.check_output.side_effect = CalledProcessError(-1, '') base._single_action(0, "echo", mock.MagicMock()) @mock.patch("yardstick.benchmark.runners.base.subprocess") def test__periodic_action(self, mock_subprocess): - mock_subprocess.check_output.side_effect = Exception() + mock_subprocess.check_output.side_effect = CalledProcessError(-1, '') base._periodic_action(0, "echo", mock.MagicMock()) @@ -40,7 +42,14 @@ class ActionTestCase(unittest.TestCase): class RunnerTestCase(unittest.TestCase): def setUp(self): - self.runner = iteration.IterationRunner({}) + config = { + 'output_config': { + 'DEFAULT': { + 'dispatcher': 'file' + } + } + } + self.runner = iteration.IterationRunner(config) @mock.patch("yardstick.benchmark.runners.iteration.multiprocessing") def test_get_output(self, *args): diff --git a/yardstick/tests/unit/benchmark/runner/test_search.py b/yardstick/tests/unit/benchmark/runner/test_search.py index 1bc07448d..4e5b4fe77 100644 --- a/yardstick/tests/unit/benchmark/runner/test_search.py +++ b/yardstick/tests/unit/benchmark/runner/test_search.py @@ -17,15 +17,8 @@ import time import mock import unittest -from yardstick.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.benchmark.runners.search import SearchRunner - from yardstick.benchmark.runners.search import SearchRunnerHelper +from yardstick.benchmark.runners.search import SearchRunner +from yardstick.benchmark.runners.search import SearchRunnerHelper class TestSearchRunnerHelper(unittest.TestCase): diff --git a/yardstick/tests/unit/benchmark/scenarios/networking/test_vnf_generic.py b/yardstick/tests/unit/benchmark/scenarios/networking/test_vnf_generic.py index fb55b5ea0..83db6ae01 100644 --- a/yardstick/tests/unit/benchmark/scenarios/networking/test_vnf_generic.py +++ b/yardstick/tests/unit/benchmark/scenarios/networking/test_vnf_generic.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python - # Copyright (c) 2016-2017 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,28 +11,31 @@ # 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. -# - -# Unittest for yardstick.benchmark.scenarios.networking.test_vnf_generic - -from __future__ import absolute_import -import os +from copy import deepcopy import errno -import unittest -import mock +import os +import sys -from copy import deepcopy +import mock +import six +import unittest -from yardstick.tests.unit import STL_MOCKS -from yardstick.benchmark.scenarios.networking.vnf_generic import \ - SshManager, NetworkServiceTestCase, IncorrectConfig, \ - open_relative_file +from yardstick import tests +from yardstick.common import utils from yardstick.network_services.collector.subscriber import Collector +from yardstick.network_services.traffic_profile import base +from yardstick.network_services.vnf_generic import vnfdgen from yardstick.network_services.vnf_generic.vnf.base import \ GenericTrafficGen, GenericVNF +stl_patch = mock.patch.dict(sys.modules, tests.STL_MOCKS) +stl_patch.start() + +if stl_patch: + from yardstick.benchmark.scenarios.networking import vnf_generic + # pylint: disable=unused-argument # disable this for now because I keep forgetting mock patch arg ordering @@ -317,6 +318,7 @@ class TestNetworkServiceTestCase(unittest.TestCase): 'task_id': 'a70bdf4a-8e67-47a3-9dc1-273c14506eb7', 'tc': 'tc_ipv4_1Mflow_64B_packetsize', 'traffic_profile': 'ipv4_throughput_vpe.yaml', + 'extra_args': {'arg1': 'value1', 'arg2': 'value2'}, 'type': 'ISB', 'tc_options': { 'rfc2544': { @@ -345,7 +347,8 @@ class TestNetworkServiceTestCase(unittest.TestCase): }, } - self.s = NetworkServiceTestCase(self.scenario_cfg, self.context_cfg) + self.s = vnf_generic.NetworkServiceTestCase(self.scenario_cfg, + self.context_cfg) def _get_file_abspath(self, filename): curr_path = os.path.dirname(os.path.abspath(__file__)) @@ -358,8 +361,8 @@ class TestNetworkServiceTestCase(unittest.TestCase): ssh_mock.execute = \ mock.Mock(return_value=(0, SYS_CLASS_NET + IP_ADDR_SHOW, "")) ssh.from_node.return_value = ssh_mock - for _, node_dict in self.context_cfg["nodes"].items(): - with SshManager(node_dict) as conn: + for node_dict in self.context_cfg["nodes"].values(): + with vnf_generic.SshManager(node_dict) as conn: self.assertIsNotNone(conn) def test___init__(self): @@ -415,7 +418,10 @@ class TestNetworkServiceTestCase(unittest.TestCase): 'public_ip': ['1.1.1.1'], }, } - + # NOTE(ralonsoh): check the expected output. This test could be + # incorrect + # result = {'flow': {'dst_ip0': '152.16.40.2-152.16.40.254', + # 'src_ip0': '152.16.100.2-152.16.100.254'}} self.assertEqual({'flow': {}}, self.s._get_traffic_flow()) def test___get_traffic_flow_error(self): @@ -425,16 +431,16 @@ class TestNetworkServiceTestCase(unittest.TestCase): def test_get_vnf_imp(self): vnfd = COMPLETE_TREX_VNFD['vnfd:vnfd-catalog']['vnfd'][0]['class-name'] - with mock.patch.dict("sys.modules", STL_MOCKS): + with mock.patch.dict(sys.modules, tests.STL_MOCKS): self.assertIsNotNone(self.s.get_vnf_impl(vnfd)) - with self.assertRaises(IncorrectConfig) as raised: - self.s.get_vnf_impl('NonExistentClass') + with self.assertRaises(vnf_generic.IncorrectConfig) as raised: + self.s.get_vnf_impl('NonExistentClass') - exc_str = str(raised.exception) - print(exc_str) - self.assertIn('No implementation', exc_str) - self.assertIn('found in', exc_str) + exc_str = str(raised.exception) + print(exc_str) + self.assertIn('No implementation', exc_str) + self.assertIn('found in', exc_str) def test_load_vnf_models_invalid(self): self.context_cfg["nodes"]['tg__1']['VNF model'] = \ @@ -464,9 +470,9 @@ class TestNetworkServiceTestCase(unittest.TestCase): self.s.map_topology_to_infrastructure() nodes = self.context_cfg["nodes"] - self.assertEqual( - "../../vnf_descriptors/tg_rfc2544_tpl.yaml", nodes['tg__1']['VNF model']) - self.assertEqual("../../vnf_descriptors/vpe_vnf.yaml", + self.assertEqual('../../vnf_descriptors/tg_rfc2544_tpl.yaml', + nodes['tg__1']['VNF model']) + self.assertEqual('../../vnf_descriptors/vpe_vnf.yaml', nodes['vnf__1']['VNF model']) def test_map_topology_to_infrastructure_insufficient_nodes(self): @@ -477,7 +483,7 @@ class TestNetworkServiceTestCase(unittest.TestCase): mock.Mock(return_value=(1, SYS_CLASS_NET + IP_ADDR_SHOW, "")) ssh.from_node.return_value = ssh_mock - with self.assertRaises(IncorrectConfig): + with self.assertRaises(vnf_generic.IncorrectConfig): self.s.map_topology_to_infrastructure() def test_map_topology_to_infrastructure_config_invalid(self): @@ -489,7 +495,7 @@ class TestNetworkServiceTestCase(unittest.TestCase): mock.Mock(return_value=(0, SYS_CLASS_NET + IP_ADDR_SHOW, "")) ssh.from_node.return_value = ssh_mock - with self.assertRaises(IncorrectConfig): + with self.assertRaises(vnf_generic.IncorrectConfig): self.s.map_topology_to_infrastructure() def test__resolve_topology_invalid_config(self): @@ -503,10 +509,8 @@ class TestNetworkServiceTestCase(unittest.TestCase): for interface in self.tg__1['interfaces'].values(): del interface['local_mac'] - with mock.patch( - "yardstick.benchmark.scenarios.networking.vnf_generic.LOG"): - with self.assertRaises(IncorrectConfig) as raised: - self.s._resolve_topology() + with self.assertRaises(vnf_generic.IncorrectConfig) as raised: + self.s._resolve_topology() self.assertIn('not found', str(raised.exception)) @@ -518,10 +522,8 @@ class TestNetworkServiceTestCase(unittest.TestCase): self.s.topology["vld"][0]['vnfd-connection-point-ref'].append( self.s.topology["vld"][0]['vnfd-connection-point-ref'][0]) - with mock.patch( - "yardstick.benchmark.scenarios.networking.vnf_generic.LOG"): - with self.assertRaises(IncorrectConfig) as raised: - self.s._resolve_topology() + with self.assertRaises(vnf_generic.IncorrectConfig) as raised: + self.s._resolve_topology() self.assertIn('wrong endpoint count', str(raised.exception)) @@ -529,10 +531,8 @@ class TestNetworkServiceTestCase(unittest.TestCase): self.s.topology["vld"][0]['vnfd-connection-point-ref'] = \ self.s.topology["vld"][0]['vnfd-connection-point-ref'][:1] - with mock.patch( - "yardstick.benchmark.scenarios.networking.vnf_generic.LOG"): - with self.assertRaises(IncorrectConfig) as raised: - self.s._resolve_topology() + with self.assertRaises(vnf_generic.IncorrectConfig) as raised: + self.s._resolve_topology() self.assertIn('wrong endpoint count', str(raised.exception)) @@ -625,15 +625,48 @@ class TestNetworkServiceTestCase(unittest.TestCase): self.assertEqual({'imix': {'64B': 100}}, self.s._get_traffic_imix()) - def test__fill_traffic_profile(self): - with mock.patch.dict("sys.modules", STL_MOCKS): - self.scenario_cfg["traffic_profile"] = \ - self._get_file_abspath("ipv4_throughput_vpe.yaml") - self.scenario_cfg["traffic_options"]["flow"] = \ - self._get_file_abspath("ipv4_1flow_Packets_vpe.yaml") - self.scenario_cfg["traffic_options"]["imix"] = \ - self._get_file_abspath("imix_voice.yaml") - self.assertIsNotNone(self.s._fill_traffic_profile()) + @mock.patch.object(base.TrafficProfile, 'get') + @mock.patch.object(vnfdgen, 'generate_vnfd') + def test__fill_traffic_profile(self, mock_generate, mock_tprofile_get): + fake_tprofile = mock.Mock() + fake_vnfd = mock.Mock() + with mock.patch.object(self.s, '_get_traffic_profile', + return_value=fake_tprofile) as mock_get_tp: + mock_generate.return_value = fake_vnfd + self.s._fill_traffic_profile() + mock_get_tp.assert_called_once() + mock_generate.assert_called_once_with( + fake_tprofile, + {'downlink': {}, + 'extra_args': {'arg1': 'value1', 'arg2': 'value2'}, + 'flow': {'flow': {}}, + 'imix': {'imix': {'64B': 100}}, + 'uplink': {}} + ) + mock_tprofile_get.assert_called_once_with(fake_vnfd) + + @mock.patch.object(utils, 'open_relative_file') + def test__get_topology(self, mock_open_path): + self.s.scenario_cfg['topology'] = 'fake_topology' + self.s.scenario_cfg['task_path'] = 'fake_path' + mock_open_path.side_effect = mock.mock_open(read_data='fake_data') + self.assertEqual('fake_data', self.s._get_topology()) + mock_open_path.assert_called_once_with('fake_topology', 'fake_path') + + @mock.patch.object(vnfdgen, 'generate_vnfd') + def test__render_topology(self, mock_generate): + fake_topology = 'fake_topology' + mock_generate.return_value = {'nsd:nsd-catalog': {'nsd': ['fake_nsd']}} + with mock.patch.object(self.s, '_get_topology', + return_value=fake_topology) as mock_get_topology: + self.s._render_topology() + mock_get_topology.assert_called_once() + + mock_generate.assert_called_once_with( + fake_topology, + {'extra_args': {'arg1': 'value1', 'arg2': 'value2'}} + ) + self.assertEqual(self.s.topology, 'fake_nsd') def test_teardown(self): vnf = mock.Mock(autospec=GenericVNF) @@ -720,7 +753,7 @@ class TestNetworkServiceTestCase(unittest.TestCase): /sys/devices/pci0000:00/0000:00:19.0/net/lan/driver:e1000e /sys/devices/pci0000:00/0000:00:19.0/net/lan/pci_bus_id:0000:00:19.0 """ - res = NetworkServiceTestCase.parse_netdev_info(output) + res = vnf_generic.NetworkServiceTestCase.parse_netdev_info(output) assert res == self.SAMPLE_NETDEVS def test_parse_netdev_info_virtio(self): @@ -732,67 +765,63 @@ class TestNetworkServiceTestCase(unittest.TestCase): /sys/devices/pci0000:00/0000:00:04.0/virtio1/net/eth1/device/device:0x0001 /sys/devices/pci0000:00/0000:00:04.0/virtio1/net/eth1/driver:virtio_net """ - res = NetworkServiceTestCase.parse_netdev_info(output) + res = vnf_generic.NetworkServiceTestCase.parse_netdev_info(output) assert res == self.SAMPLE_VM_NETDEVS def test_probe_missing_values(self): netdevs = self.SAMPLE_NETDEVS.copy() network = {'local_mac': '0a:de:ad:be:ef:f5'} - NetworkServiceTestCase._probe_missing_values(netdevs, network) + vnf_generic.NetworkServiceTestCase._probe_missing_values(netdevs, + network) assert network['vpci'] == '0000:0b:00.0' network = {'local_mac': '0a:de:ad:be:ef:f4'} - NetworkServiceTestCase._probe_missing_values(netdevs, network) + vnf_generic.NetworkServiceTestCase._probe_missing_values(netdevs, + network) assert network['vpci'] == '0000:00:19.0' - # TODO: Split this into several tests, for different IOError sub-types - def test_open_relative_path(self): - mock_open = mock.mock_open() + @mock.patch.object(six.moves.builtins, 'open') + def test_open_relative_path(self, mock_open): + # NOTE(ralonsoh): the mocked function is not properly used and tested. mock_open_result = mock_open() mock_open_call_count = 1 # initial call to get result - - module_name = \ - 'yardstick.benchmark.scenarios.networking.vnf_generic.open' - - # test - with mock.patch(module_name, mock_open, create=True): - self.assertEqual(open_relative_file( - 'foo', 'bar'), mock_open_result) - - mock_open_call_count += 1 # one more call expected - self.assertEqual(mock_open.call_count, mock_open_call_count) - self.assertIn('foo', mock_open.call_args_list[-1][0][0]) - self.assertNotIn('bar', mock_open.call_args_list[-1][0][0]) - - def open_effect(*args, **kwargs): - if kwargs.get('name', args[0]) == os.path.join('bar', 'foo'): - return mock_open_result - raise IOError(errno.ENOENT, 'not found') - - mock_open.side_effect = open_effect - self.assertEqual(open_relative_file( - 'foo', 'bar'), mock_open_result) - - mock_open_call_count += 2 # two more calls expected - self.assertEqual(mock_open.call_count, mock_open_call_count) - self.assertIn('foo', mock_open.call_args_list[-1][0][0]) - self.assertIn('bar', mock_open.call_args_list[-1][0][0]) - - # test an IOError of type ENOENT - mock_open.side_effect = IOError(errno.ENOENT, 'not found') - with self.assertRaises(IOError): - # the second call still raises - open_relative_file('foo', 'bar') - - mock_open_call_count += 2 # two more calls expected - self.assertEqual(mock_open.call_count, mock_open_call_count) - self.assertIn('foo', mock_open.call_args_list[-1][0][0]) - self.assertIn('bar', mock_open.call_args_list[-1][0][0]) - - # test an IOError other than ENOENT - mock_open.side_effect = IOError(errno.EBUSY, 'busy') - with self.assertRaises(IOError): - open_relative_file('foo', 'bar') - - mock_open_call_count += 1 # one more call expected - self.assertEqual(mock_open.call_count, mock_open_call_count) + self.assertEqual(utils.open_relative_file('foo', 'bar'), + mock_open_result) + + mock_open_call_count += 1 # one more call expected + self.assertEqual(mock_open.call_count, mock_open_call_count) + self.assertIn('foo', mock_open.call_args_list[-1][0][0]) + self.assertNotIn('bar', mock_open.call_args_list[-1][0][0]) + + def open_effect(*args, **kwargs): + if kwargs.get('name', args[0]) == os.path.join('bar', 'foo'): + return mock_open_result + raise IOError(errno.ENOENT, 'not found') + + mock_open.side_effect = open_effect + self.assertEqual(utils.open_relative_file('foo', 'bar'), + mock_open_result) + + mock_open_call_count += 2 # two more calls expected + self.assertEqual(mock_open.call_count, mock_open_call_count) + self.assertIn('foo', mock_open.call_args_list[-1][0][0]) + self.assertIn('bar', mock_open.call_args_list[-1][0][0]) + + # test an IOError of type ENOENT + mock_open.side_effect = IOError(errno.ENOENT, 'not found') + with self.assertRaises(IOError): + # the second call still raises + utils.open_relative_file('foo', 'bar') + + mock_open_call_count += 2 # two more calls expected + self.assertEqual(mock_open.call_count, mock_open_call_count) + self.assertIn('foo', mock_open.call_args_list[-1][0][0]) + self.assertIn('bar', mock_open.call_args_list[-1][0][0]) + + # test an IOError other than ENOENT + mock_open.side_effect = IOError(errno.EBUSY, 'busy') + with self.assertRaises(IOError): + utils.open_relative_file('foo', 'bar') + + mock_open_call_count += 1 # one more call expected + self.assertEqual(mock_open.call_count, mock_open_call_count) diff --git a/yardstick/tests/unit/benchmark/scenarios/test_base.py b/yardstick/tests/unit/benchmark/scenarios/test_base.py index a95e6bc86..985338532 100644 --- a/yardstick/tests/unit/benchmark/scenarios/test_base.py +++ b/yardstick/tests/unit/benchmark/scenarios/test_base.py @@ -13,12 +13,11 @@ # License for the specific language governing permissions and limitations # under the License. -import unittest - from yardstick.benchmark.scenarios import base +from yardstick.tests.unit import base as ut_base -class ScenarioTestCase(unittest.TestCase): +class ScenarioTestCase(ut_base.BaseUnitTestCase): def test_get_scenario_type(self): scenario_type = 'dummy scenario' @@ -87,7 +86,7 @@ class ScenarioTestCase(unittest.TestCase): str(exc.exception)) -class IterScenarioClassesTestCase(unittest.TestCase): +class IterScenarioClassesTestCase(ut_base.BaseUnitTestCase): def test_no_scenario_type_defined(self): some_existing_scenario_class_names = [ diff --git a/yardstick/tests/unit/common/test_packages.py b/yardstick/tests/unit/common/test_packages.py new file mode 100644 index 000000000..ba59a3015 --- /dev/null +++ b/yardstick/tests/unit/common/test_packages.py @@ -0,0 +1,88 @@ +# Copyright (c) 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. + +import mock +from pip import exceptions as pip_exceptions +from pip.operations import freeze +import unittest + +from yardstick.common import packages + + +class PipExecuteActionTestCase(unittest.TestCase): + + def setUp(self): + self._mock_pip_main = mock.patch.object(packages, '_pip_main') + self.mock_pip_main = self._mock_pip_main.start() + self.mock_pip_main.return_value = 0 + self._mock_freeze = mock.patch.object(freeze, 'freeze') + self.mock_freeze = self._mock_freeze.start() + self.addCleanup(self._cleanup) + + def _cleanup(self): + self._mock_pip_main.stop() + self._mock_freeze.stop() + + def test_pip_execute_action(self): + self.assertEqual(0, packages._pip_execute_action('test_package')) + + def test_remove(self): + self.assertEqual(0, packages._pip_execute_action('test_package', + action='uninstall')) + + def test_install(self): + self.assertEqual(0, packages._pip_execute_action( + 'test_package', action='install', target='temp_dir')) + + def test_pip_execute_action_error(self): + self.mock_pip_main.return_value = 1 + self.assertEqual(1, packages._pip_execute_action('test_package')) + + def test_pip_execute_action_exception(self): + self.mock_pip_main.side_effect = pip_exceptions.PipError + self.assertEqual(1, packages._pip_execute_action('test_package')) + + def test_pip_list(self): + pkg_input = [ + 'XStatic-Rickshaw==1.5.0.0', + 'xvfbwrapper==0.2.9', + '-e git+https://git.opnfv.org/yardstick@50773a24afc02c9652b662ecca' + '2fc5621ea6097a#egg=yardstick', + 'zope.interface==4.4.3' + ] + pkg_dict = { + 'XStatic-Rickshaw': '1.5.0.0', + 'xvfbwrapper': '0.2.9', + 'yardstick': '50773a24afc02c9652b662ecca2fc5621ea6097a', + 'zope.interface': '4.4.3' + } + self.mock_freeze.return_value = pkg_input + + pkg_output = packages.pip_list() + for pkg_name, pkg_version in pkg_output.items(): + self.assertEqual(pkg_dict.get(pkg_name), pkg_version) + + def test_pip_list_single_package(self): + pkg_input = [ + 'XStatic-Rickshaw==1.5.0.0', + 'xvfbwrapper==0.2.9', + '-e git+https://git.opnfv.org/yardstick@50773a24afc02c9652b662ecca' + '2fc5621ea6097a#egg=yardstick', + 'zope.interface==4.4.3' + ] + self.mock_freeze.return_value = pkg_input + + pkg_output = packages.pip_list(pkg_name='xvfbwrapper') + self.assertEqual(1, len(pkg_output)) + self.assertEqual(pkg_output.get('xvfbwrapper'), '0.2.9') diff --git a/yardstick/tests/unit/common/test_utils.py b/yardstick/tests/unit/common/test_utils.py index 033bb0243..b4907addc 100644 --- a/yardstick/tests/unit/common/test_utils.py +++ b/yardstick/tests/unit/common/test_utils.py @@ -19,6 +19,7 @@ from six.moves import configparser import unittest import yardstick +from yardstick import ssh from yardstick.common import utils from yardstick.common import constants @@ -1075,8 +1076,27 @@ class SafeDecodeUtf8TestCase(unittest.TestCase): self.assertEqual('this is a byte array', out) -def main(): - unittest.main() - -if __name__ == '__main__': - main() +class ReadMeminfoTestCase(unittest.TestCase): + + MEMINFO = (b'MemTotal: 65860500 kB\n' + b'MemFree: 28690900 kB\n' + b'MemAvailable: 52873764 kB\n' + b'Active(anon): 3015676 kB\n' + b'HugePages_Total: 8\n' + b'Hugepagesize: 1048576 kB') + MEMINFO_DICT = {'MemTotal': '65860500', + 'MemFree': '28690900', + 'MemAvailable': '52873764', + 'Active(anon)': '3015676', + 'HugePages_Total': '8', + 'Hugepagesize': '1048576'} + + def test_read_meminfo(self): + ssh_client = ssh.SSH('user', 'host') + with mock.patch.object(ssh_client, 'get_file_obj') as \ + mock_get_client, \ + mock.patch.object(six, 'BytesIO', + return_value=six.BytesIO(self.MEMINFO)): + output = utils.read_meminfo(ssh_client) + mock_get_client.assert_called_once_with('/proc/meminfo', mock.ANY) + self.assertEqual(self.MEMINFO_DICT, output) |