aboutsummaryrefslogtreecommitdiffstats
path: root/yardstick
diff options
context:
space:
mode:
Diffstat (limited to 'yardstick')
-rw-r--r--yardstick/benchmark/contexts/heat.py4
-rw-r--r--yardstick/benchmark/core/report.py135
-rwxr-xr-xyardstick/benchmark/runners/base.py49
-rw-r--r--yardstick/benchmark/runners/iteration.py37
-rw-r--r--yardstick/benchmark/runners/iteration_ipc.py205
-rw-r--r--yardstick/benchmark/runners/sequence.py33
-rw-r--r--yardstick/benchmark/scenarios/availability/monitor/monitor_multi.py27
-rw-r--r--yardstick/benchmark/scenarios/availability/monitor/monitor_process.py12
-rw-r--r--yardstick/benchmark/scenarios/base.py4
-rw-r--r--yardstick/benchmark/scenarios/networking/vnf_generic.py156
-rw-r--r--yardstick/common/exceptions.py19
-rw-r--r--yardstick/common/messaging/__init__.py27
-rw-r--r--yardstick/common/nsb_report.css19
-rw-r--r--yardstick/common/nsb_report.html.j252
-rw-r--r--yardstick/common/nsb_report.js73
-rw-r--r--yardstick/common/utils.py11
-rw-r--r--yardstick/network_services/helpers/dpdkbindnic_helper.py1
-rw-r--r--yardstick/network_services/libs/ixia_libs/ixnet/ixnet_api.py148
-rw-r--r--yardstick/network_services/traffic_profile/http_ixload.py38
-rw-r--r--yardstick/network_services/traffic_profile/ixia_rfc2544.py191
-rw-r--r--yardstick/network_services/traffic_profile/rfc2544.py20
-rw-r--r--yardstick/network_services/traffic_profile/trex_traffic_profile.py7
-rw-r--r--yardstick/network_services/vnf_generic/vnf/acl_vnf.py13
-rw-r--r--yardstick/network_services/vnf_generic/vnf/agnostic_vnf.py6
-rw-r--r--yardstick/network_services/vnf_generic/vnf/base.py91
-rw-r--r--yardstick/network_services/vnf_generic/vnf/cgnapt_vnf.py14
-rw-r--r--yardstick/network_services/vnf_generic/vnf/epc_vnf.py6
-rw-r--r--yardstick/network_services/vnf_generic/vnf/prox_helpers.py4
-rw-r--r--yardstick/network_services/vnf_generic/vnf/prox_irq.py16
-rw-r--r--yardstick/network_services/vnf_generic/vnf/prox_vnf.py9
-rw-r--r--yardstick/network_services/vnf_generic/vnf/router_vnf.py8
-rw-r--r--yardstick/network_services/vnf_generic/vnf/sample_vnf.py153
-rw-r--r--yardstick/network_services/vnf_generic/vnf/tg_ixload.py14
-rw-r--r--yardstick/network_services/vnf_generic/vnf/tg_landslide.py6
-rw-r--r--yardstick/network_services/vnf_generic/vnf/tg_ping.py12
-rw-r--r--yardstick/network_services/vnf_generic/vnf/tg_pktgen.py25
-rw-r--r--yardstick/network_services/vnf_generic/vnf/tg_prox.py8
-rw-r--r--yardstick/network_services/vnf_generic/vnf/tg_rfc2544_ixia.py466
-rw-r--r--yardstick/network_services/vnf_generic/vnf/tg_rfc2544_trex.py67
-rw-r--r--yardstick/network_services/vnf_generic/vnf/tg_trex.py13
-rw-r--r--yardstick/network_services/vnf_generic/vnf/udp_replay.py11
-rw-r--r--yardstick/network_services/vnf_generic/vnf/vfw_vnf.py13
-rw-r--r--yardstick/network_services/vnf_generic/vnf/vpe_vnf.py9
-rw-r--r--yardstick/ssh.py90
-rw-r--r--yardstick/tests/functional/benchmark/core/__init__.py (renamed from yardstick/tests/functional/network_services/__init__.py)0
-rw-r--r--yardstick/tests/functional/benchmark/core/test_report.py114
-rw-r--r--yardstick/tests/functional/network_services/vnf_generic/__init__.py0
-rw-r--r--yardstick/tests/functional/network_services/vnf_generic/vnf/__init__.py0
-rw-r--r--yardstick/tests/functional/network_services/vnf_generic/vnf/test_base.py103
-rw-r--r--yardstick/tests/unit/benchmark/core/test_report.py149
-rw-r--r--yardstick/tests/unit/benchmark/runner/test_base.py79
-rw-r--r--yardstick/tests/unit/benchmark/runner/test_iteration_ipc.py136
-rw-r--r--yardstick/tests/unit/benchmark/scenarios/availability/test_monitor_multi.py17
-rw-r--r--yardstick/tests/unit/benchmark/scenarios/availability/test_monitor_process.py16
-rw-r--r--yardstick/tests/unit/benchmark/scenarios/networking/test_vnf_generic.py101
-rw-r--r--yardstick/tests/unit/common/test_utils.py9
-rw-r--r--yardstick/tests/unit/network_services/libs/ixia_libs/test_ixnet_api.py201
-rw-r--r--yardstick/tests/unit/network_services/traffic_profile/test_http_ixload.py11
-rw-r--r--yardstick/tests/unit/network_services/traffic_profile/test_ixia_rfc2544.py324
-rw-r--r--yardstick/tests/unit/network_services/traffic_profile/test_prox_irq.py6
-rw-r--r--yardstick/tests/unit/network_services/traffic_profile/test_prox_profile.py6
-rw-r--r--yardstick/tests/unit/network_services/traffic_profile/test_rfc2544.py12
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_acl_vnf.py16
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_agnostic_vnf.py6
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_base.py118
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_cgnapt_vnf.py18
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_epc_vnf.py10
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_prox_helpers.py6
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_prox_irq.py30
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_prox_vnf.py27
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_router_vnf.py12
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_sample_vnf.py238
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_ixload.py25
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_landslide.py13
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_ping.py14
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_pktgen.py29
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_prox.py18
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_rfc2544_ixia.py471
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_rfc2544_trex.py18
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_trex.py34
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_udp_replay.py25
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_vfw_vnf.py14
-rw-r--r--yardstick/tests/unit/network_services/vnf_generic/vnf/test_vpe_vnf.py24
-rw-r--r--yardstick/tests/unit/test_ssh.py42
84 files changed, 3162 insertions, 1652 deletions
diff --git a/yardstick/benchmark/contexts/heat.py b/yardstick/benchmark/contexts/heat.py
index c3c5451bd..f4c48f4a5 100644
--- a/yardstick/benchmark/contexts/heat.py
+++ b/yardstick/benchmark/contexts/heat.py
@@ -508,10 +508,12 @@ class HeatContext(Context):
pkey = pkg_resources.resource_string(
'yardstick.resources',
h_join('files/yardstick_key', self.name)).decode('utf-8')
-
+ key_filename = pkg_resources.resource_filename('yardstick.resources',
+ h_join('files/yardstick_key', self.name))
result = {
"user": server.context.user,
"pkey": pkey,
+ "key_filename": key_filename,
"private_ip": server.private_ip,
"interfaces": server.interfaces,
"routing_table": self.generate_routing_table(server),
diff --git a/yardstick/benchmark/core/report.py b/yardstick/benchmark/core/report.py
index 0bc392fe5..b7d2fd02b 100644
--- a/yardstick/benchmark/core/report.py
+++ b/yardstick/benchmark/core/report.py
@@ -1,6 +1,6 @@
##############################################################################
# Copyright (c) 2017 Rajesh Kudaka <4k.rajesh@gmail.com>
-# Copyright (c) 2018 Intel Corporation.
+# Copyright (c) 2018-2019 Intel Corporation.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
@@ -10,13 +10,12 @@
""" Handler for yardstick command 'report' """
-import ast
import re
+import six
import uuid
import jinja2
from api.utils import influx
-from oslo_utils import encodeutils
from oslo_utils import uuidutils
from yardstick.common import constants as consts
from yardstick.common.utils import cliargs
@@ -55,11 +54,9 @@ class JSTree(object):
def format_for_jstree(self, data):
"""Format the data into the required format for jsTree.
- The data format expected is a list of key-value pairs which represent
- the data and label for each metric e.g.:
+ The data format expected is a list of metric names e.g.:
- [{'data': [0, ], 'label': 'tg__0.DropPackets'},
- {'data': [548, ], 'label': 'tg__0.LatencyAvg.5'},]
+ ['tg__0.DropPackets', 'tg__0.LatencyAvg.5']
This data is converted into the format required for jsTree to group and
display the metrics in a hierarchial fashion, including creating a
@@ -76,8 +73,8 @@ class JSTree(object):
self._created_nodes = ['#']
self.jstree_data = []
- for item in data:
- self._create_node(item["label"])
+ for metric in data:
+ self._create_node(metric)
return self.jstree_data
@@ -115,15 +112,34 @@ class Report(object):
else:
raise KeyError("Test case not found.")
- def _get_tasks(self):
- task_cmd = "select * from \"%s\" where task_id= '%s'"
- task_query = task_cmd % (self.yaml_name, self.task_id)
- query_exec = influx.query(task_query)
+ def _get_metrics(self):
+ metrics_cmd = "select * from \"%s\" where task_id = '%s'"
+ metrics_query = metrics_cmd % (self.yaml_name, self.task_id)
+ query_exec = influx.query(metrics_query)
if query_exec:
return query_exec
else:
raise KeyError("Task ID or Test case not found.")
+ def _get_trimmed_timestamp(self, metric_time, resolution=4):
+ if not isinstance(metric_time, str):
+ metric_time = metric_time.encode('utf8') # PY2: unicode to str
+ metric_time = metric_time[11:] # skip date, keep time
+ head, _, tail = metric_time.partition('.') # split HH:MM:SS & nsZ
+ metric_time = head + '.' + tail[:resolution] # join HH:MM:SS & .us
+ return metric_time
+
+ def _get_timestamps(self, metrics, resolution=6):
+ # Extract the timestamps from a list of metrics
+ timestamps = []
+ for metric in metrics:
+ metric_time = self._get_trimmed_timestamp(
+ metric['time'], resolution)
+ timestamps.append(metric_time) # HH:MM:SS.micros
+ return timestamps
+
+ @cliargs("task_id", type=str, help=" task id", nargs=1)
+ @cliargs("yaml_name", type=str, help=" Yaml file Name", nargs=1)
def _generate_common(self, args):
"""Actions that are common to both report formats.
@@ -132,38 +148,64 @@ class Report(object):
"""
self._validate(args.yaml_name[0], args.task_id[0])
- self.db_fieldkeys = self._get_fieldkeys()
+ db_fieldkeys = self._get_fieldkeys()
+ # list of dicts of:
+ # - PY2: unicode key and unicode value
+ # - PY3: str key and str value
- self.db_task = self._get_tasks()
+ db_metrics = self._get_metrics()
+ # list of dicts of:
+ # - PY2: unicode key and { None | unicode | float | long | int } value
+ # - PY3: str key and { None | str | float | int } value
- field_keys = []
- datasets = []
- table_vals = {}
+ # extract fieldKey entries, and convert them to str where needed
+ field_keys = [key if isinstance(key, str) # PY3: already str
+ else key.encode('utf8') # PY2: unicode to str
+ for key in
+ [field['fieldKey']
+ for field in db_fieldkeys]]
+
+ # extract timestamps
+ self.Timestamp = self._get_timestamps(db_metrics)
- field_keys = [encodeutils.to_utf8(field['fieldKey'])
- for field in self.db_fieldkeys]
+ # prepare return values
+ datasets = []
+ table_vals = {'Timestamp': self.Timestamp}
+ # extract and convert field values
for key in field_keys:
- self.Timestamp = []
values = []
- for task in self.db_task:
- task_time = encodeutils.to_utf8(task['time'])
- if not isinstance(task_time, str):
- task_time = str(task_time, 'utf8')
- if not isinstance(key, str):
- key = str(key, 'utf8')
- task_time = task_time[11:]
- head, _, tail = task_time.partition('.')
- task_time = head + "." + tail[:6]
- self.Timestamp.append(task_time)
- if task[key] is None:
- values.append(None)
- elif isinstance(task[key], (int, float)):
- values.append(task[key])
+ for metric in db_metrics:
+ val = metric.get(key, None)
+ if val is None:
+ # keep explicit None or missing entry as is
+ pass
+ elif isinstance(val, (int, float)):
+ # keep plain int or float as is
+ pass
+ elif six.PY2 and isinstance(val,
+ long): # pylint: disable=undefined-variable
+ # PY2: long value would be rendered with trailing L,
+ # which JS does not support, so convert it to float
+ val = float(val)
+ elif isinstance(val, six.string_types):
+ s = val
+ if not isinstance(s, str):
+ s = s.encode('utf8') # PY2: unicode to str
+ try:
+ # convert until failure
+ val = s
+ val = float(s)
+ val = int(s)
+ if six.PY2 and isinstance(val,
+ long): # pylint: disable=undefined-variable
+ val = float(val) # PY2: long to float
+ except ValueError:
+ pass
else:
- values.append(ast.literal_eval(task[key]))
+ raise ValueError("Cannot convert %r" % val)
+ values.append(val)
datasets.append({'label': key, 'data': values})
- table_vals['Timestamp'] = self.Timestamp
table_vals[key] = values
return datasets, table_vals
@@ -197,8 +239,14 @@ class Report(object):
@cliargs("yaml_name", type=str, help=" Yaml file Name", nargs=1)
def generate_nsb(self, args):
"""Start NSB report generation."""
- datasets, table_vals = self._generate_common(args)
- jstree_data = JSTree().format_for_jstree(datasets)
+ _, report_data = self._generate_common(args)
+ report_time = report_data.pop('Timestamp')
+ report_keys = sorted(report_data, key=str.lower)
+ report_tree = JSTree().format_for_jstree(report_keys)
+ report_meta = {
+ "testcase": self.yaml_name,
+ "task_id": self.task_id,
+ }
template_dir = consts.YARDSTICK_ROOT_PATH + "yardstick/common"
template_environment = jinja2.Environment(
@@ -207,10 +255,11 @@ class Report(object):
lstrip_blocks=True)
context = {
- "Timestamps": self.Timestamp,
- "task_id": self.task_id,
- "table": table_vals,
- "jstree_nodes": jstree_data,
+ "report_meta": report_meta,
+ "report_data": report_data,
+ "report_time": report_time,
+ "report_keys": report_keys,
+ "report_tree": report_tree,
}
template_html = template_environment.get_template("nsb_report.html.j2")
diff --git a/yardstick/benchmark/runners/base.py b/yardstick/benchmark/runners/base.py
index af2557441..94de45d1e 100755
--- a/yardstick/benchmark/runners/base.py
+++ b/yardstick/benchmark/runners/base.py
@@ -25,9 +25,6 @@ import traceback
from six import moves
from yardstick.benchmark.scenarios import base as base_scenario
-from yardstick.common import messaging
-from yardstick.common.messaging import payloads
-from yardstick.common.messaging import producer
from yardstick.common import utils
from yardstick.dispatcher.base import Base as DispatcherBase
@@ -80,6 +77,33 @@ def _periodic_action(interval, command, queue):
queue.put({'periodic-action-data': data})
+class ScenarioOutput(dict):
+
+ QUEUE_PUT_TIMEOUT = 10
+
+ def __init__(self, queue, **kwargs):
+ super(ScenarioOutput, self).__init__()
+ self._queue = queue
+ self.result_ext = dict()
+ for key, val in kwargs.items():
+ self.result_ext[key] = val
+ setattr(self, key, val)
+
+ def push(self, data=None, add_timestamp=True):
+ if data is None:
+ data = dict(self)
+
+ if add_timestamp:
+ result = {'timestamp': time.time(), 'data': data}
+ else:
+ result = data
+
+ for key in self.result_ext.keys():
+ result[key] = getattr(self, key)
+
+ self._queue.put(result, True, self.QUEUE_PUT_TIMEOUT)
+
+
class Runner(object):
runners = []
@@ -271,22 +295,3 @@ class Runner(object):
dispatchers = DispatcherBase.get(self.config['output_config'])
dispatcher = next((d for d in dispatchers if d.__dispatcher_type__ == 'Influxdb'))
dispatcher.upload_one_record(record, self.case_name, '', task_id=self.task_id)
-
-
-class RunnerProducer(producer.MessagingProducer):
- """Class implementing the message producer for runners"""
-
- def __init__(self, _id):
- super(RunnerProducer, self).__init__(messaging.TOPIC_RUNNER, _id=_id)
-
- def start_iteration(self, version=1, data=None):
- data = {} if not data else data
- self.send_message(
- messaging.RUNNER_METHOD_START_ITERATION,
- payloads.RunnerPayload(version=version, data=data))
-
- def stop_iteration(self, version=1, data=None):
- data = {} if not data else data
- self.send_message(
- messaging.RUNNER_METHOD_STOP_ITERATION,
- payloads.RunnerPayload(version=version, data=data))
diff --git a/yardstick/benchmark/runners/iteration.py b/yardstick/benchmark/runners/iteration.py
index 58ab06a32..15dad2cd5 100644
--- a/yardstick/benchmark/runners/iteration.py
+++ b/yardstick/benchmark/runners/iteration.py
@@ -23,7 +23,6 @@ from __future__ import absolute_import
import logging
import multiprocessing
-import time
import traceback
import os
@@ -40,8 +39,6 @@ QUEUE_PUT_TIMEOUT = 10
def _worker_process(queue, cls, method_name, scenario_cfg,
context_cfg, aborted, output_queue):
- sequence = 1
-
runner_cfg = scenario_cfg['runner']
interval = runner_cfg.get("interval", 1)
@@ -53,6 +50,7 @@ def _worker_process(queue, cls, method_name, scenario_cfg,
runner_cfg['runner_id'] = os.getpid()
+ scenario_output = base.ScenarioOutput(queue, sequence=1, errors="")
benchmark = cls(scenario_cfg, context_cfg)
if "setup" in run_step:
benchmark.setup()
@@ -67,22 +65,21 @@ def _worker_process(queue, cls, method_name, scenario_cfg,
LOG.debug("runner=%(runner)s seq=%(sequence)s START",
{"runner": runner_cfg["runner_id"],
- "sequence": sequence})
-
- data = {}
- errors = ""
+ "sequence": scenario_output.sequence})
+ scenario_output.clear()
+ scenario_output.errors = ""
benchmark.pre_run_wait_time(interval)
try:
- result = method(data)
+ result = method(scenario_output)
except y_exc.SLAValidationError as error:
# SLA validation failed in scenario, determine what to do now
if sla_action == "assert":
raise
elif sla_action == "monitor":
LOG.warning("SLA validation failed: %s", error.args)
- errors = error.args
+ scenario_output.errors = error.args
elif sla_action == "rate-control":
try:
scenario_cfg['options']['rate']
@@ -91,10 +88,10 @@ def _worker_process(queue, cls, method_name, scenario_cfg,
scenario_cfg['options']['rate'] = 100
scenario_cfg['options']['rate'] -= delta
- sequence = 1
+ scenario_output.sequence = 1
continue
except Exception: # pylint: disable=broad-except
- errors = traceback.format_exc()
+ scenario_output.errors = traceback.format_exc()
LOG.exception("")
raise
else:
@@ -105,23 +102,17 @@ def _worker_process(queue, cls, method_name, scenario_cfg,
benchmark.post_run_wait_time(interval)
- benchmark_output = {
- 'timestamp': time.time(),
- 'sequence': sequence,
- 'data': data,
- 'errors': errors
- }
-
- queue.put(benchmark_output, True, QUEUE_PUT_TIMEOUT)
+ if scenario_output:
+ scenario_output.push()
LOG.debug("runner=%(runner)s seq=%(sequence)s END",
{"runner": runner_cfg["runner_id"],
- "sequence": sequence})
+ "sequence": scenario_output.sequence})
- sequence += 1
+ scenario_output.sequence += 1
- if (errors and sla_action is None) or \
- (sequence > iterations or aborted.is_set()):
+ if (scenario_output.errors and sla_action is None) or \
+ (scenario_output.sequence > iterations or aborted.is_set()):
LOG.info("worker END")
break
if "teardown" in run_step:
diff --git a/yardstick/benchmark/runners/iteration_ipc.py b/yardstick/benchmark/runners/iteration_ipc.py
deleted file mode 100644
index a0335fdc7..000000000
--- a/yardstick/benchmark/runners/iteration_ipc.py
+++ /dev/null
@@ -1,205 +0,0 @@
-# Copyright 2018: Intel Corporation
-# All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License"); you may
-# not use this file except in compliance with the License. You may obtain
-# a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-# License for the specific language governing permissions and limitations
-# under the License.
-
-"""A runner that runs a configurable number of times before it returns. Each
- iteration has a configurable timeout. The loop control depends on the
- feedback received from the running VNFs. The context PIDs from the VNFs
- to listen the messages from are given in the scenario "setup" method.
-"""
-
-import logging
-import multiprocessing
-import time
-import traceback
-
-import os
-
-from yardstick.benchmark.runners import base as base_runner
-from yardstick.common import exceptions
-from yardstick.common import messaging
-from yardstick.common import utils
-from yardstick.common.messaging import consumer
-from yardstick.common.messaging import payloads
-
-
-LOG = logging.getLogger(__name__)
-
-QUEUE_PUT_TIMEOUT = 10
-ITERATION_TIMEOUT = 180
-
-
-class RunnerIterationIPCEndpoint(consumer.NotificationHandler):
- """Endpoint class for ``RunnerIterationIPCConsumer``"""
-
- def tg_method_started(self, ctxt, **kwargs):
- if ctxt['id'] in self._ctx_ids:
- self._queue.put(
- {'id': ctxt['id'],
- 'action': messaging.TG_METHOD_STARTED,
- 'payload': payloads.TrafficGeneratorPayload.dict_to_obj(
- kwargs)},
- QUEUE_PUT_TIMEOUT)
-
- def tg_method_finished(self, ctxt, **kwargs):
- if ctxt['id'] in self._ctx_ids:
- self._queue.put(
- {'id': ctxt['id'],
- 'action': messaging.TG_METHOD_FINISHED,
- 'payload': payloads.TrafficGeneratorPayload.dict_to_obj(
- kwargs)})
-
- def tg_method_iteration(self, ctxt, **kwargs):
- if ctxt['id'] in self._ctx_ids:
- self._queue.put(
- {'id': ctxt['id'],
- 'action': messaging.TG_METHOD_ITERATION,
- 'payload': payloads.TrafficGeneratorPayload.dict_to_obj(
- kwargs)})
-
-
-class RunnerIterationIPCConsumer(consumer.MessagingConsumer):
- """MQ consumer for "IterationIPC" runner"""
-
- def __init__(self, _id, ctx_ids):
- self._id = _id
- self._queue = multiprocessing.Queue()
- endpoints = [RunnerIterationIPCEndpoint(_id, ctx_ids, self._queue)]
- super(RunnerIterationIPCConsumer, self).__init__(
- messaging.TOPIC_TG, ctx_ids, endpoints)
- self._kpi_per_id = {ctx: [] for ctx in ctx_ids}
- self.iteration_index = None
-
- def is_all_kpis_received_in_iteration(self):
- """Check if all producers registered have sent the ITERATION msg
-
- During the present iteration, all producers (traffic generators) must
- start and finish the traffic injection, and at the end of the traffic
- injection a TG_METHOD_ITERATION must be sent. This function will check
- all KPIs in the present iteration are received. E.g.:
- self.iteration_index = 2
-
- self._kpi_per_id = {
- 'ctx1': [kpi0, kpi1, kpi2],
- 'ctx2': [kpi0, kpi1]} --> return False
-
- self._kpi_per_id = {
- 'ctx1': [kpi0, kpi1, kpi2],
- 'ctx2': [kpi0, kpi1, kpi2]} --> return True
- """
- while not self._queue.empty():
- msg = self._queue.get(True, 1)
- if msg['action'] == messaging.TG_METHOD_ITERATION:
- id_iter_list = self._kpi_per_id[msg['id']]
- id_iter_list.append(msg['payload'].kpi)
-
- return all(len(id_iter_list) == self.iteration_index
- for id_iter_list in self._kpi_per_id.values())
-
-
-def _worker_process(queue, cls, method_name, scenario_cfg,
- context_cfg, aborted, output_queue): # pragma: no cover
- runner_cfg = scenario_cfg['runner']
-
- timeout = runner_cfg.get('timeout', ITERATION_TIMEOUT)
- iterations = runner_cfg.get('iterations', 1)
- run_step = runner_cfg.get('run_step', 'setup,run,teardown')
- LOG.info('Worker START. Iterations %d times, class %s', iterations, cls)
-
- runner_cfg['runner_id'] = os.getpid()
-
- benchmark = cls(scenario_cfg, context_cfg)
- method = getattr(benchmark, method_name)
-
- if 'setup' not in run_step:
- raise exceptions.RunnerIterationIPCSetupActionNeeded()
- benchmark.setup()
- producer_ctxs = benchmark.get_mq_ids()
- if not producer_ctxs:
- raise exceptions.RunnerIterationIPCNoCtxs()
-
- mq_consumer = RunnerIterationIPCConsumer(os.getpid(), producer_ctxs)
- mq_consumer.start_rpc_server()
- mq_producer = base_runner.RunnerProducer(scenario_cfg['task_id'])
-
- iteration_index = 1
- while 'run' in run_step:
- LOG.debug('runner=%(runner)s seq=%(sequence)s START',
- {'runner': runner_cfg['runner_id'],
- 'sequence': iteration_index})
- data = {}
- result = None
- errors = ''
- mq_consumer.iteration_index = iteration_index
- mq_producer.start_iteration()
-
- try:
- utils.wait_until_true(
- mq_consumer.is_all_kpis_received_in_iteration,
- timeout=timeout, sleep=2)
- result = method(data)
- except Exception: # pylint: disable=broad-except
- errors = traceback.format_exc()
- LOG.exception(errors)
-
- mq_producer.stop_iteration()
-
- if result:
- output_queue.put(result, True, QUEUE_PUT_TIMEOUT)
- benchmark_output = {'timestamp': time.time(),
- 'sequence': iteration_index,
- 'data': data,
- 'errors': errors}
- queue.put(benchmark_output, True, QUEUE_PUT_TIMEOUT)
-
- LOG.debug('runner=%(runner)s seq=%(sequence)s END',
- {'runner': runner_cfg['runner_id'],
- 'sequence': iteration_index})
-
- iteration_index += 1
- if iteration_index > iterations or aborted.is_set():
- LOG.info('"IterationIPC" worker END')
- break
-
- if 'teardown' in run_step:
- try:
- benchmark.teardown()
- except Exception:
- LOG.exception('Exception during teardown process')
- mq_consumer.stop_rpc_server()
- raise SystemExit(1)
-
- LOG.debug('Data queue size = %s', queue.qsize())
- LOG.debug('Output queue size = %s', output_queue.qsize())
- mq_consumer.stop_rpc_server()
-
-
-class IterationIPCRunner(base_runner.Runner):
- """Run a scenario for a configurable number of times.
-
- Each iteration has a configurable timeout. The loop control depends on the
- feedback received from the running VNFs. The context PIDs from the VNFs to
- listen the messages from are given in the scenario "setup" method.
- """
- __execution_type__ = 'IterationIPC'
-
- def _run_benchmark(self, cls, method, scenario_cfg, context_cfg):
- name = '{}-{}-{}'.format(
- self.__execution_type__, scenario_cfg.get('type'), os.getpid())
- self.process = multiprocessing.Process(
- name=name,
- target=_worker_process,
- args=(self.result_queue, cls, method, scenario_cfg,
- context_cfg, self.aborted, self.output_queue))
- self.process.start()
diff --git a/yardstick/benchmark/runners/sequence.py b/yardstick/benchmark/runners/sequence.py
index 0148a45b2..58ffddd22 100644
--- a/yardstick/benchmark/runners/sequence.py
+++ b/yardstick/benchmark/runners/sequence.py
@@ -38,8 +38,6 @@ LOG = logging.getLogger(__name__)
def _worker_process(queue, cls, method_name, scenario_cfg,
context_cfg, aborted, output_queue):
- sequence = 1
-
runner_cfg = scenario_cfg['runner']
interval = runner_cfg.get("interval", 1)
@@ -56,6 +54,7 @@ def _worker_process(queue, cls, method_name, scenario_cfg,
LOG.info("worker START, sequence_values(%s, %s), class %s",
arg_name, sequence_values, cls)
+ scenario_output = base.ScenarioOutput(queue, sequence=1, errors="")
benchmark = cls(scenario_cfg, context_cfg)
benchmark.setup()
method = getattr(benchmark, method_name)
@@ -68,22 +67,23 @@ def _worker_process(queue, cls, method_name, scenario_cfg,
options[arg_name] = value
LOG.debug("runner=%(runner)s seq=%(sequence)s START",
- {"runner": runner_cfg["runner_id"], "sequence": sequence})
+ {"runner": runner_cfg["runner_id"],
+ "sequence": scenario_output.sequence})
- data = {}
- errors = ""
+ scenario_output.clear()
+ scenario_output.errors = ""
try:
- result = method(data)
+ result = method(scenario_output)
except y_exc.SLAValidationError as error:
# SLA validation failed in scenario, determine what to do now
if sla_action == "assert":
raise
elif sla_action == "monitor":
LOG.warning("SLA validation failed: %s", error.args)
- errors = error.args
+ scenario_output.errors = error.args
except Exception as e: # pylint: disable=broad-except
- errors = traceback.format_exc()
+ scenario_output.errors = traceback.format_exc()
LOG.exception(e)
else:
if result:
@@ -91,21 +91,16 @@ def _worker_process(queue, cls, method_name, scenario_cfg,
time.sleep(interval)
- benchmark_output = {
- 'timestamp': time.time(),
- 'sequence': sequence,
- 'data': data,
- 'errors': errors
- }
-
- queue.put(benchmark_output)
+ if scenario_output:
+ scenario_output.push()
LOG.debug("runner=%(runner)s seq=%(sequence)s END",
- {"runner": runner_cfg["runner_id"], "sequence": sequence})
+ {"runner": runner_cfg["runner_id"],
+ "sequence": scenario_output.sequence})
- sequence += 1
+ scenario_output.sequence += 1
- if (errors and sla_action is None) or aborted.is_set():
+ if (scenario_output.errors and sla_action is None) or aborted.is_set():
break
try:
diff --git a/yardstick/benchmark/scenarios/availability/monitor/monitor_multi.py b/yardstick/benchmark/scenarios/availability/monitor/monitor_multi.py
index 971bae1e9..8f1f53cde 100644
--- a/yardstick/benchmark/scenarios/availability/monitor/monitor_multi.py
+++ b/yardstick/benchmark/scenarios/availability/monitor/monitor_multi.py
@@ -62,20 +62,19 @@ class MultiMonitor(basemonitor.BaseMonitor):
outage_time = (
last_outage - first_outage if last_outage > first_outage else 0
)
+ self._result = {"outage_time": outage_time}
LOG.debug("outage_time is: %f", outage_time)
max_outage_time = 0
- if "max_outage_time" in self._config["sla"]:
- max_outage_time = self._config["sla"]["max_outage_time"]
- elif "max_recover_time" in self._config["sla"]:
- max_outage_time = self._config["sla"]["max_recover_time"]
- else:
- raise RuntimeError("'max_outage_time' or 'max_recover_time' "
- "config is not found")
- self._result = {"outage_time": outage_time}
-
- if outage_time > max_outage_time:
- LOG.error("SLA failure: %f > %f", outage_time, max_outage_time)
- return False
- else:
- return True
+ if self._config.get("sla"):
+ if "max_outage_time" in self._config["sla"]:
+ max_outage_time = self._config["sla"]["max_outage_time"]
+ elif "max_recover_time" in self._config["sla"]:
+ max_outage_time = self._config["sla"]["max_recover_time"]
+ else:
+ raise RuntimeError("'max_outage_time' or 'max_recover_time' "
+ "config is not found")
+ if outage_time > max_outage_time:
+ LOG.error("SLA failure: %f > %f", outage_time, max_outage_time)
+ return False
+ return True
diff --git a/yardstick/benchmark/scenarios/availability/monitor/monitor_process.py b/yardstick/benchmark/scenarios/availability/monitor/monitor_process.py
index 8d2f2633c..280e5811d 100644
--- a/yardstick/benchmark/scenarios/availability/monitor/monitor_process.py
+++ b/yardstick/benchmark/scenarios/availability/monitor/monitor_process.py
@@ -46,12 +46,12 @@ class MonitorProcess(basemonitor.BaseMonitor):
def verify_SLA(self):
outage_time = self._result.get('outage_time', None)
- max_outage_time = self._config["sla"]["max_recover_time"]
- if outage_time > max_outage_time:
- LOG.info("SLA failure: %f > %f", outage_time, max_outage_time)
- return False
- else:
- return True
+ if self._config.get("sla"):
+ max_outage_time = self._config["sla"]["max_recover_time"]
+ if outage_time > max_outage_time:
+ LOG.info("SLA failure: %f > %f", outage_time, max_outage_time)
+ return False
+ return True
def _test(): # pragma: no cover
diff --git a/yardstick/benchmark/scenarios/base.py b/yardstick/benchmark/scenarios/base.py
index 1737bb942..ae8bfad71 100644
--- a/yardstick/benchmark/scenarios/base.py
+++ b/yardstick/benchmark/scenarios/base.py
@@ -122,7 +122,3 @@ class Scenario(object):
except TypeError:
dic[k] = v
return dic
-
- def get_mq_ids(self): # pragma: no cover
- """Return stored MQ producer IDs, if defined"""
- pass
diff --git a/yardstick/benchmark/scenarios/networking/vnf_generic.py b/yardstick/benchmark/scenarios/networking/vnf_generic.py
index 5ac51cdfc..c88ea51c3 100644
--- a/yardstick/benchmark/scenarios/networking/vnf_generic.py
+++ b/yardstick/benchmark/scenarios/networking/vnf_generic.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -44,14 +44,13 @@ traffic_profile.register_modules()
LOG = logging.getLogger(__name__)
-class NetworkServiceTestCase(scenario_base.Scenario):
- """Class handles Generic framework to do pre-deployment VNF &
- Network service testing """
+class NetworkServiceBase(scenario_base.Scenario):
+ """Base class for Network service testing scenarios"""
- __scenario_type__ = "NSPerf"
+ __scenario_type__ = ""
def __init__(self, scenario_cfg, context_cfg): # pragma: no cover
- super(NetworkServiceTestCase, self).__init__()
+ super(NetworkServiceBase, self).__init__()
self.scenario_cfg = scenario_cfg
self.context_cfg = context_cfg
@@ -61,7 +60,32 @@ class NetworkServiceTestCase(scenario_base.Scenario):
self.traffic_profile = None
self.node_netdevs = {}
self.bin_path = get_nsb_option('bin_path', '')
- self._mq_ids = []
+
+ def run(self, *args):
+ pass
+
+ def teardown(self):
+ """ Stop the collector and terminate VNF & TG instance
+
+ :return
+ """
+
+ try:
+ try:
+ self.collector.stop()
+ for vnf in self.vnfs:
+ LOG.info("Stopping %s", vnf.name)
+ vnf.terminate()
+ LOG.debug("all VNFs terminated: %s", ", ".join(vnf.name for vnf in self.vnfs))
+ finally:
+ terminate_children()
+ except Exception:
+ # catch any exception in teardown and convert to simple exception
+ # never pass exceptions back to multiprocessing, because some exceptions can
+ # be unpicklable
+ # https://bugs.python.org/issue9400
+ LOG.exception("")
+ raise RuntimeError("Error in teardown")
def is_ended(self):
return self.traffic_profile is not None and self.traffic_profile.is_ended()
@@ -140,6 +164,13 @@ class NetworkServiceTestCase(scenario_base.Scenario):
imix = {}
return imix
+ def _get_ip_priority(self):
+ try:
+ priority = self.scenario_cfg['options']['priority']
+ except KeyError:
+ priority = {}
+ return priority
+
def _get_traffic_profile(self):
profile = self.scenario_cfg["traffic_profile"]
path = self.scenario_cfg["task_path"]
@@ -177,6 +208,7 @@ class NetworkServiceTestCase(scenario_base.Scenario):
tprofile_data = {
'flow': self._get_traffic_flow(),
'imix': self._get_traffic_imix(),
+ 'priority': self._get_ip_priority(),
tprofile_base.TrafficProfile.UPLINK: {},
tprofile_base.TrafficProfile.DOWNLINK: {},
'extra_args': extra_args,
@@ -446,12 +478,30 @@ class NetworkServiceTestCase(scenario_base.Scenario):
pass
self.create_interfaces_from_node(vnfd, node)
vnf_impl = self.get_vnf_impl(vnfd['id'])
- vnf_instance = vnf_impl(node_name, vnfd, scenario_cfg['task_id'])
+ vnf_instance = vnf_impl(node_name, vnfd)
vnfs.append(vnf_instance)
self.vnfs = vnfs
return vnfs
+ def pre_run_wait_time(self, time_seconds): # pragma: no cover
+ """Time waited before executing the run method"""
+ time.sleep(time_seconds)
+
+ def post_run_wait_time(self, time_seconds): # pragma: no cover
+ """Time waited after executing the run method"""
+ pass
+
+
+class NetworkServiceTestCase(NetworkServiceBase):
+ """Class handles Generic framework to do pre-deployment VNF &
+ Network service testing """
+
+ __scenario_type__ = "NSPerf"
+
+ def __init__(self, scenario_cfg, context_cfg): # pragma: no cover
+ super(NetworkServiceTestCase, self).__init__(scenario_cfg, context_cfg)
+
def setup(self):
"""Setup infrastructure, provission VNFs & start traffic"""
# 1. Verify if infrastructure mapping can meet topology
@@ -495,11 +545,6 @@ class NetworkServiceTestCase(scenario_base.Scenario):
for traffic_gen in traffic_runners:
LOG.info("Starting traffic on %s", traffic_gen.name)
traffic_gen.run_traffic(self.traffic_profile)
- self._mq_ids.append(traffic_gen.get_mq_producer_id())
-
- def get_mq_ids(self): # pragma: no cover
- """Return stored MQ producer IDs"""
- return self._mq_ids
def run(self, result): # yardstick API
""" Yardstick calls run() at intervals defined in the yaml and
@@ -515,33 +560,70 @@ class NetworkServiceTestCase(scenario_base.Scenario):
result.update(self.collector.get_kpi())
- def teardown(self):
- """ Stop the collector and terminate VNF & TG instance
- :return
- """
+class NetworkServiceRFC2544(NetworkServiceBase):
+ """Class handles RFC2544 Network service testing"""
+ __scenario_type__ = "NSPerf-RFC2544"
+
+ def __init__(self, scenario_cfg, context_cfg): # pragma: no cover
+ super(NetworkServiceRFC2544, self).__init__(scenario_cfg, context_cfg)
+
+ def setup(self):
+ """Setup infrastructure, provision VNFs"""
+ self.map_topology_to_infrastructure()
+ self.load_vnf_models()
+
+ traffic_runners = [vnf for vnf in self.vnfs if vnf.runs_traffic]
+ non_traffic_runners = [vnf for vnf in self.vnfs if not vnf.runs_traffic]
try:
- try:
- self.collector.stop()
- for vnf in self.vnfs:
- LOG.info("Stopping %s", vnf.name)
- vnf.terminate()
- LOG.debug("all VNFs terminated: %s", ", ".join(vnf.name for vnf in self.vnfs))
- finally:
- terminate_children()
- except Exception:
- # catch any exception in teardown and convert to simple exception
- # never pass exceptions back to multiprocessing, because some exceptions can
- # be unpicklable
- # https://bugs.python.org/issue9400
+ for vnf in chain(traffic_runners, non_traffic_runners):
+ LOG.info("Instantiating %s", vnf.name)
+ vnf.instantiate(self.scenario_cfg, self.context_cfg)
+ LOG.info("Waiting for %s to instantiate", vnf.name)
+ vnf.wait_for_instantiate()
+ except:
LOG.exception("")
- raise RuntimeError("Error in teardown")
+ for vnf in self.vnfs:
+ vnf.terminate()
+ raise
- def pre_run_wait_time(self, time_seconds): # pragma: no cover
- """Time waited before executing the run method"""
- time.sleep(time_seconds)
+ self._generate_pod_yaml()
- def post_run_wait_time(self, time_seconds): # pragma: no cover
- """Time waited after executing the run method"""
- pass
+ def run(self, output):
+ """ Run experiment
+
+ :param output: scenario output to push results
+ :return: None
+ """
+
+ self._fill_traffic_profile()
+
+ traffic_runners = [vnf for vnf in self.vnfs if vnf.runs_traffic]
+
+ for traffic_gen in traffic_runners:
+ traffic_gen.listen_traffic(self.traffic_profile)
+
+ self.collector = Collector(self.vnfs,
+ context_base.Context.get_physical_nodes())
+ self.collector.start()
+
+ test_completed = False
+ while not test_completed:
+ for traffic_gen in traffic_runners:
+ LOG.info("Run traffic on %s", traffic_gen.name)
+ traffic_gen.run_traffic_once(self.traffic_profile)
+
+ test_completed = True
+ for traffic_gen in traffic_runners:
+ # wait for all tg to complete running traffic
+ status = traffic_gen.wait_on_traffic()
+ LOG.info("Run traffic on %s complete status=%s",
+ traffic_gen.name, status)
+ if status == 'CONTINUE':
+ # continue running if at least one tg is running
+ test_completed = False
+
+ output.push(self.collector.get_kpi())
+
+ self.collector.stop()
diff --git a/yardstick/common/exceptions.py b/yardstick/common/exceptions.py
index 5e0df973a..010ec6a51 100644
--- a/yardstick/common/exceptions.py
+++ b/yardstick/common/exceptions.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2017 Intel Corporation
+# Copyright (c) 2017-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -83,10 +83,6 @@ class InvalidType(YardstickException):
message = 'Type "%(type_to_convert)s" is not valid'
-class InvalidRxfFile(YardstickException):
- message = 'Loaded rxf file has unexpected format'
-
-
class InfluxDBConfigurationMissing(YardstickException):
message = ('InfluxDB configuration is not available. Add "influxdb" as '
'a dispatcher and the configuration section')
@@ -207,15 +203,6 @@ class TaskRenderError(YardstickException):
message = 'Failed to render template:\n%(input_task)s'
-class RunnerIterationIPCSetupActionNeeded(YardstickException):
- message = ('IterationIPC needs the "setup" action to retrieve the VNF '
- 'handling processes PIDs to receive the messages sent')
-
-
-class RunnerIterationIPCNoCtxs(YardstickException):
- message = 'Benchmark "setup" action did not return any VNF process PID'
-
-
class TimerTimeout(YardstickException):
message = 'Timer timeout expired, %(timeout)s seconds'
@@ -405,6 +392,10 @@ class IxNetworkFieldNotPresentInStackItem(YardstickException):
message = 'Field "%(field_name)s" not present in stack item %(stack_item)s'
+class IncorrectFlowOption(YardstickException):
+ message = 'Flow option {option} for {link} is incorrect'
+
+
class SLAValidationError(YardstickException):
message = '%(case_name)s SLA validation failed. Error: %(error_msg)s'
diff --git a/yardstick/common/messaging/__init__.py b/yardstick/common/messaging/__init__.py
index bd700d9b1..089c99c9f 100644
--- a/yardstick/common/messaging/__init__.py
+++ b/yardstick/common/messaging/__init__.py
@@ -1,3 +1,14 @@
+# Copyright (c) 2018-2019 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.
@@ -15,19 +26,3 @@ TRANSPORT_URL = (MQ_SERVICE + '://' + MQ_USER + ':' + MQ_PASS + '@' + SERVER +
# RPC server.
RPC_SERVER_EXECUTOR = 'threading'
-
-# Topics.
-TOPIC_TG = 'topic_traffic_generator'
-TOPIC_RUNNER = 'topic_runner'
-
-# Methods.
-# Traffic generator consumers methods. Names must match the methods implemented
-# in the consumer endpoint class.
-TG_METHOD_STARTED = 'tg_method_started'
-TG_METHOD_FINISHED = 'tg_method_finished'
-TG_METHOD_ITERATION = 'tg_method_iteration'
-
-# Runner consumers methods. Names must match the methods implemented in the
-# consumer endpoint class.
-RUNNER_METHOD_START_ITERATION = "runner_method_start_iteration"
-RUNNER_METHOD_STOP_ITERATION = "runner_method_stop_iteration"
diff --git a/yardstick/common/nsb_report.css b/yardstick/common/nsb_report.css
index 2beb91c53..667f865a5 100644
--- a/yardstick/common/nsb_report.css
+++ b/yardstick/common/nsb_report.css
@@ -9,21 +9,26 @@
******************************************************************************/
body {
- font-size: 16pt;
+ font-family: Frutiger, "Helvetica Neue", Helvetica, Arial, sans-serif;
+}
+
+header {
+ padding-top: 5px;
+ text-align: center;
+ font-weight: bold;
}
-table {
+#tblMetrics {
overflow-y: scroll;
height: 360px;
display: block;
}
-header {
- font-family: Frutiger, "Helvetica Neue", Helvetica, Arial, sans-serif;
- clear: left;
- text-align: center;
+#cnvGraph {
+ width: 100%;
+ height: 500px;
}
-.control-pane {
+#divTree {
font-size: 10pt;
}
diff --git a/yardstick/common/nsb_report.html.j2 b/yardstick/common/nsb_report.html.j2
index a3087d746..aa90253f8 100644
--- a/yardstick/common/nsb_report.html.j2
+++ b/yardstick/common/nsb_report.html.j2
@@ -29,53 +29,45 @@
</head>
<body>
- <div class="container" style="width:80%">
+ <div class="container-fluid">
<div class="row">
- <header class="jumbotron">
- <h1>Yardstick User Interface</h1>
- <h4>Report of {{task_id}} Generated</h4>
+ <header>
+ Testcase: {{report_meta.testcase}}<br>
+ Task-ID: {{report_meta.task_id}}<br>
</header>
</div>
<div class="row">
- <div class="col-md-2 control-pane">
- <div id="data_selector"></div>
+ <div class="col-md-2">
+ <div id="divTree"></div>
</div>
- <div class="col-md-10 data-pane">
- <canvas id="cnvGraph" style="width: 100%; height: 500px"></canvas>
+ <div class="col-md-10">
+ <canvas id="cnvGraph"></canvas>
</div>
</div>
<div class="row">
<div class="col-md-12 table-responsive">
- <table class="table table-hover"></table>
+ <table id="tblMetrics" class="table table-condensed table-hover"></table>
</div>
</div>
</div>
<script>
- var arr, jstree_data, timestamps;
- arr = {{table|safe}};
- timestamps = {{Timestamps|safe}};
- jstree_data = {{jstree_nodes|safe}};
+ // Injected metrics, timestamps, keys and hierarchy
+ var report_data = {{report_data|safe}};
+ var report_time = {{report_time|safe}};
+ var report_keys = {{report_keys|safe}};
+ var report_tree = {{report_tree|safe}};
+ // Wait for DOM to be loaded
$(function() {
- create_table(arr);
- create_tree(jstree_data);
- var objGraph = create_graph($('#cnvGraph'), timestamps);
+ var tblMetrics = $('#tblMetrics');
+ var cnvGraph = $('#cnvGraph');
+ var divTree = $('#divTree');
- $('#data_selector').on('check_node.jstree uncheck_node.jstree', function(e, data) {
- var selected_datasets = [];
- for (var i = 0; i < data.selected.length; i++) {
- var node = data.instance.get_node(data.selected[i]);
- if (node.children.length == 0) {
- var dataset = {
- label: node.id,
- data: arr[node.id],
- };
- selected_datasets.push(dataset);
- }
- }
- update_graph(objGraph, selected_datasets);
- });
+ create_table(tblMetrics, report_data, report_time, report_keys);
+ var objGraph = create_graph(cnvGraph, report_time);
+ create_tree(divTree, report_tree);
+ handle_tree(divTree, tblMetrics, objGraph, report_data, report_time);
});
</script>
</body>
diff --git a/yardstick/common/nsb_report.js b/yardstick/common/nsb_report.js
index cc5e14ee7..4de1c8e78 100644
--- a/yardstick/common/nsb_report.js
+++ b/yardstick/common/nsb_report.js
@@ -10,9 +10,9 @@
var None = null;
-function create_tree(jstree_data)
+function create_tree(divTree, jstree_data)
{
- $('#data_selector').jstree({
+ divTree.jstree({
plugins: ['checkbox'],
checkbox: {
three_state: false,
@@ -29,34 +29,33 @@ function create_tree(jstree_data)
});
}
-// may need to pass timestamps too...
-function create_table(table_data)
+function create_table(tblMetrics, table_data, timestamps, table_keys)
{
- var tab, tr, td, tn, tbody, keys, key, curr_data, val;
- // create table
- tab = document.getElementsByTagName('table')[0];
- tbody = document.createElement('tbody');
+ var tbody = $('<tbody></tbody>');
+ var tr0 = $('<tr></tr>');
+ var th0 = $('<th></th>');
+ var td0 = $('<td></td>');
+ var tr;
+
+ // create table headings using timestamps
+ tr = tr0.clone().append(th0.clone().text('Timestamp'));
+ timestamps.forEach(function(t) {
+ tr.append(th0.clone().text(t));
+ });
+ tbody.append(tr);
+
// for each metric
- keys = Object.keys(table_data);
- for (var i = 0; i < keys.length; i++) {
- key = keys[i];
- tr = document.createElement('tr');
- td = document.createElement('td');
- tn = document.createTextNode(key);
- td.appendChild(tn);
- tr.appendChild(td);
+ table_keys.forEach(function(key) {
+ tr = tr0.clone().append(td0.clone().text(key));
// add each piece of data as its own column
- curr_data = table_data[key];
- for (var j = 0; j < curr_data.length; j++) {
- val = curr_data[j];
- td = document.createElement('td');
- tn = document.createTextNode(val === None ? '' : val);
- td.appendChild(tn);
- tr.appendChild(td);
- }
- tbody.appendChild(tr);
- }
- tab.appendChild(tbody);
+ table_data[key].forEach(function(val) {
+ tr.append(td0.clone().text(val === None ? '' : val));
+ });
+ tbody.append(tr);
+ });
+
+ // re-create table
+ tblMetrics.empty().append(tbody);
}
function create_graph(cnvGraph, timestamps)
@@ -144,3 +143,23 @@ function update_graph(objGraph, datasets)
objGraph.data.datasets = datasets;
objGraph.update();
}
+
+function handle_tree(divTree, tblMetrics, objGraph, table_data, timestamps)
+{
+ divTree.on('check_node.jstree uncheck_node.jstree', function(e, data) {
+ var selected_keys = [];
+ var selected_datasets = [];
+ data.selected.forEach(function(sel) {
+ var node = data.instance.get_node(sel);
+ if (node.children.length == 0) {
+ selected_keys.push(node.id);
+ selected_datasets.push({
+ label: node.id,
+ data: table_data[node.id],
+ });
+ }
+ });
+ create_table(tblMetrics, table_data, timestamps, selected_keys);
+ update_graph(objGraph, selected_datasets);
+ });
+}
diff --git a/yardstick/common/utils.py b/yardstick/common/utils.py
index 51313ef47..9eba896e2 100644
--- a/yardstick/common/utils.py
+++ b/yardstick/common/utils.py
@@ -293,6 +293,17 @@ def make_ipv4_address(ip_addr):
return ipaddress.IPv4Address(six.text_type(ip_addr))
+def get_ip_range_count(iprange):
+ start_range, end_range = iprange.split("-")
+ start = int(make_ipv4_address(start_range))
+ end = int(make_ipv4_address(end_range))
+ return end - start
+
+
+def get_ip_range_start(iprange):
+ return str(make_ipv4_address(iprange.split("-")[0]))
+
+
def safe_ip_address(ip_addr):
""" get ip address version v6 or v4 """
try:
diff --git a/yardstick/network_services/helpers/dpdkbindnic_helper.py b/yardstick/network_services/helpers/dpdkbindnic_helper.py
index 1c74355ef..0fc63f88d 100644
--- a/yardstick/network_services/helpers/dpdkbindnic_helper.py
+++ b/yardstick/network_services/helpers/dpdkbindnic_helper.py
@@ -284,6 +284,7 @@ printf "%s/driver:" $1 ; basename $(readlink -s $1/device/driver); } \
res = self.ssh_helper.execute(*args, **kwargs)
if res[0] != 0:
template = '{} command failed with rc={}'
+ LOG.critical("DPDK_DEVBIND Failure %s", res[1])
raise DpdkBindHelperException(template.format(self.dpdk_devbind, res[0]))
return res
diff --git a/yardstick/network_services/libs/ixia_libs/ixnet/ixnet_api.py b/yardstick/network_services/libs/ixia_libs/ixnet/ixnet_api.py
index 6645d45fe..cb8ba1771 100644
--- a/yardstick/network_services/libs/ixia_libs/ixnet/ixnet_api.py
+++ b/yardstick/network_services/libs/ixia_libs/ixnet/ixnet_api.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2018 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -14,6 +14,8 @@
import ipaddress
import logging
+import re
+import collections
import IxNetwork
@@ -62,6 +64,13 @@ SUPPORTED_TOS_FIELDS = [
'reliability'
]
+IP_PRIORITY_PATTERN = r'[^\w+]*.+(Raw priority|' \
+ 'Precedence|' \
+ 'Default PHB|' \
+ 'Class selector PHB|' \
+ 'Assured forwarding selector PHB|' \
+ 'Expedited forwarding PHB)'
+
class Vlan(object):
def __init__(self,
@@ -91,6 +100,8 @@ class IxNextgen(object): # pragma: no cover
"Rx_Rate_Kbps": 'Rx. Rate (Kbps)',
"Tx_Rate_Mbps": 'Tx. Rate (Mbps)',
"Rx_Rate_Mbps": 'Rx. Rate (Mbps)',
+ "Bytes_Tx": 'Bytes Tx.',
+ "Bytes_Rx": 'Bytes Rx.'
}
LATENCY_NAME_MAP = {
@@ -99,6 +110,18 @@ class IxNextgen(object): # pragma: no cover
"Store-Forward_Max_latency_ns": 'Store-Forward Max Latency (ns)',
}
+ FLOWS_STATS_NAME_MAP = {
+ "Tx_Port": 'Tx Port',
+ "VLAN-ID": 'VLAN:VLAN-ID',
+ "IP_Priority": re.compile(IP_PRIORITY_PATTERN),
+ "Flow_Group": 'Flow Group',
+ "Tx_Frames": 'Tx Frames',
+ "Rx_Frames": 'Rx Frames',
+ "Store-Forward_Avg_latency_ns": 'Store-Forward Avg Latency (ns)',
+ "Store-Forward_Min_latency_ns": 'Store-Forward Min Latency (ns)',
+ "Store-Forward_Max_latency_ns": 'Store-Forward Max Latency (ns)'
+ }
+
PPPOX_CLIENT_PER_PORT_NAME_MAP = {
'subs_port': 'Port',
'Sessions_Up': 'Sessions Up',
@@ -111,6 +134,18 @@ class IxNextgen(object): # pragma: no cover
FLOW_STATISTICS = '::ixNet::OBJ-/statistics/view:"Flow Statistics"'
PPPOX_CLIENT_PER_PORT = '::ixNet::OBJ-/statistics/view:"PPPoX Client Per Port"'
+ PPPOE_SCENARIO_STATS = {
+ 'port_statistics': PORT_STATISTICS,
+ 'flow_statistic': FLOW_STATISTICS,
+ 'pppox_client_per_port': PPPOX_CLIENT_PER_PORT
+ }
+
+ PPPOE_SCENARIO_STATS_MAP = {
+ 'port_statistics': PORT_STATS_NAME_MAP,
+ 'flow_statistic': FLOWS_STATS_NAME_MAP,
+ 'pppox_client_per_port': PPPOX_CLIENT_PER_PORT_NAME_MAP
+ }
+
@staticmethod
def get_config(tg_cfg):
card = []
@@ -152,6 +187,9 @@ class IxNextgen(object): # pragma: no cover
vports = self.ixnet.getList(self.ixnet.getRoot(), 'vport')
return vports
+ def get_static_interface(self, vport):
+ return self.ixnet.getList(vport, 'interface')
+
def _get_config_element_by_flow_group_name(self, flow_group_name):
"""Get a config element using the flow group name
@@ -369,7 +407,25 @@ class IxNextgen(object): # pragma: no cover
'/traffic/protocolTemplate:"{}"'.format(protocol_name))
self.ixnet.execute('append', previous_element, protocol)
- def _setup_config_elements(self, add_default_proto=True):
+ def is_qinq(self, flow_data):
+ for traffic_type in flow_data:
+ if flow_data[traffic_type]['outer_l2'].get('QinQ'):
+ return True
+ return False
+
+ def _flows_settings(self, cfg):
+ flows_data = []
+ res = [key for key in cfg.keys() if key.split('_')[0] in ['uplink', 'downlink']]
+ for i in range(len(res)):
+ uplink = 'uplink_{}'.format(i)
+ downlink = 'downlink_{}'.format(i)
+ if uplink in res:
+ flows_data.append(cfg[uplink])
+ if downlink in res:
+ flows_data.append(cfg[downlink])
+ return flows_data
+
+ def _setup_config_elements(self, traffic_profile, add_default_proto=True):
"""Setup the config elements
The traffic item is configured to allow individual configurations per
@@ -385,7 +441,9 @@ class IxNextgen(object): # pragma: no cover
'trafficItem')[0]
log.info('Split the frame rate distribution per config element')
config_elements = self.ixnet.getList(traffic_item_id, 'configElement')
- for config_element in config_elements:
+ flows = self._flows_settings(traffic_profile.params)
+ # TODO: check length of both lists, it should be equal!!!
+ for config_element, flow_data in zip(config_elements, flows):
self.ixnet.setAttribute(config_element + '/frameRateDistribution',
'-portDistribution', 'splitRateEvenly')
self.ixnet.setAttribute(config_element + '/frameRateDistribution',
@@ -396,8 +454,13 @@ class IxNextgen(object): # pragma: no cover
PROTO_UDP, config_element + '/stack:"ethernet-1"')
self._append_procotol_to_stack(
PROTO_IPV4, config_element + '/stack:"ethernet-1"')
+ if self.is_qinq(flow_data):
+ self._append_procotol_to_stack(
+ PROTO_VLAN, config_element + '/stack:"ethernet-1"')
+ self._append_procotol_to_stack(
+ PROTO_VLAN, config_element + '/stack:"ethernet-1"')
- def create_traffic_model(self, uplink_ports, downlink_ports):
+ def create_traffic_model(self, uplink_ports, downlink_ports, traffic_profile):
"""Create a traffic item and the needed flow groups
Each flow group inside the traffic item (only one is present)
@@ -412,7 +475,7 @@ class IxNextgen(object): # pragma: no cover
uplink_endpoints = [port + '/protocols' for port in uplink_ports]
downlink_endpoints = [port + '/protocols' for port in downlink_ports]
self._create_flow_groups(uplink_endpoints, downlink_endpoints)
- self._setup_config_elements()
+ self._setup_config_elements(traffic_profile=traffic_profile)
def create_ipv4_traffic_model(self, uplink_endpoints, downlink_endpoints):
"""Create a traffic item and the needed flow groups
@@ -494,11 +557,6 @@ class IxNextgen(object): # pragma: no cover
'-fieldValue', ETHER_TYPE_802_1ad,
'-valueType', SINGLE_VALUE)
- self._append_procotol_to_stack(
- PROTO_VLAN, config_element + '/stack:"ethernet-1"')
- self._append_procotol_to_stack(
- PROTO_VLAN, config_element + '/stack:"ethernet-1"')
-
self._update_vlan_tag(fg_id, s_vlan, S_VLAN)
self._update_vlan_tag(fg_id, c_vlan, C_VLAN)
@@ -728,6 +786,19 @@ class IxNextgen(object): # pragma: no cover
'getColumnValues', view_obj, data_ixia)
for data_yardstick, data_ixia in name_map.items()}
+ def _get_view_page_stats(self, view_obj):
+ """Get full view page stats
+
+ :param view_obj: view object, e.g.
+ '::ixNet::OBJ-/statistics/view:"Port Statistics"'
+ :return: (list) List of dicts. Each dict represents view page row
+ """
+ view = view_obj + '/page'
+ column_headers = self.ixnet.getAttribute(view, '-columnCaptions')
+ view_rows = self.ixnet.getAttribute(view, '-rowValues')
+ view_page = [dict(zip(column_headers, row[0])) for row in view_rows]
+ return view_page
+
def _set_egress_flow_tracking(self, encapsulation, offset):
"""Set egress flow tracking options
@@ -750,7 +821,7 @@ class IxNextgen(object): # pragma: no cover
self.ixnet.setAttribute(enc_obj, '-offset', offset)
self.ixnet.commit()
- def _set_flow_tracking(self, track_by):
+ def set_flow_tracking(self, track_by):
"""Set flow tracking options
:param track_by: list of tracking fields
@@ -777,24 +848,39 @@ class IxNextgen(object): # pragma: no cover
return stats
def get_pppoe_scenario_statistics(self):
- """Retrieve port, flow and PPPoE subscribers statistics
-
- "Port Statistics" parameters are stored in self.PORT_STATS_NAME_MAP.
- "Flow Statistics" parameters are stored in self.LATENCY_NAME_MAP.
- "PPPoX Client Per Port" parameters are stored in
- self.PPPOE_CLIENT_PER_PORT_NAME_MAP
-
- :return: dictionary with the statistics; the keys of this dictionary
- are PORT_STATS_NAME_MAP, LATENCY_NAME_MAP and
- PPPOE_CLIENT_PER_PORT_NAME_MAP keys.
- """
- stats = self._build_stats_map(self.PORT_STATISTICS,
- self.PORT_STATS_NAME_MAP)
- stats.update(self._build_stats_map(self.FLOW_STATISTICS,
- self.LATENCY_NAME_MAP))
- stats.update(self._build_stats_map(self.PPPOX_CLIENT_PER_PORT,
- self.PPPOX_CLIENT_PER_PORT_NAME_MAP))
- return stats
+ """Retrieve port, flow and PPPoE subscribers statistics"""
+ stats = collections.defaultdict(list)
+ result = collections.defaultdict(list)
+ for stat, view in self.PPPOE_SCENARIO_STATS.items():
+ # Get view total pages number
+ total_pages = self.ixnet.getAttribute(
+ view + '/page', '-totalPages')
+ # Collect stats from all view pages
+ for page in range(1, int(total_pages) + 1):
+ current_page = int(self.ixnet.getAttribute(
+ view + '/page', '-currentPage'))
+ if page != int(current_page):
+ self.ixnet.setAttribute(view + '/page', '-currentPage',
+ str(page))
+ self.ixnet.commit()
+ page_data = self._get_view_page_stats(view)
+ stats[stat].extend(page_data)
+ # Filter collected views stats
+ for stat in stats:
+ for view_row in stats[stat]:
+ filtered_row = {}
+ for key, value in self.PPPOE_SCENARIO_STATS_MAP[stat].items():
+ if isinstance(value, str):
+ filtered_row.update({key: view_row[value]})
+ # Handle keys which values are represented by regex
+ else:
+ for k in view_row.keys():
+ if value.match(k):
+ value = value.match(k).group()
+ filtered_row.update({key: view_row[value]})
+ break
+ result[stat].append(filtered_row)
+ return result
def start_protocols(self):
self.ixnet.execute('startAllProtocols')
@@ -1038,7 +1124,7 @@ class IxNextgen(object): # pragma: no cover
return obj
- def add_static_ipv4(self, iface, vport, start_ip, count):
+ def add_static_ipv4(self, iface, vport, start_ip, count, mask='24'):
"""Add static IP range to the interface"""
log.debug("add_static_ipv4: start_ip:'%s', count:'%s'",
start_ip, count)
@@ -1046,5 +1132,5 @@ class IxNextgen(object): # pragma: no cover
self.ixnet.setMultiAttribute(obj, '-protocolInterface', iface,
'-ipStart', start_ip, '-count', count,
- '-enabled', 'true')
+ '-mask', mask, '-enabled', 'true')
self.ixnet.commit()
diff --git a/yardstick/network_services/traffic_profile/http_ixload.py b/yardstick/network_services/traffic_profile/http_ixload.py
index b88aadff7..ec0762500 100644
--- a/yardstick/network_services/traffic_profile/http_ixload.py
+++ b/yardstick/network_services/traffic_profile/http_ixload.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -16,14 +16,6 @@ import sys
import os
import logging
import collections
-import subprocess
-try:
- libs = subprocess.check_output(
- 'python -c "import site; print(site.getsitepackages())"', shell=True)
-
- sys.path.extend(libs[1:-1].replace("'", "").split(','))
-except subprocess.CalledProcessError:
- pass
# ixload uses its own py2. So importing jsonutils fails. So adding below
# workaround to support call from yardstick
@@ -32,14 +24,26 @@ try:
except ImportError:
import json as jsonutils
-from yardstick.common import exceptions #pylint: disable=wrong-import-position
+
+class ErrorClass(object):
+
+ def __init__(self, *args, **kwargs):
+ if 'test' not in kwargs:
+ raise RuntimeError
+
+ def __getattr__(self, item):
+ raise AttributeError
+
+
+class InvalidRxfFile(Exception):
+ message = 'Loaded rxf file has unexpected format'
+
try:
from IxLoad import IxLoad, StatCollectorUtils
except ImportError:
- IxLoad = exceptions.ErrorClass
- StatCollectorUtils = exceptions.ErrorClass
-
+ IxLoad = ErrorClass
+ StatCollectorUtils = ErrorClass
LOG = logging.getLogger(__name__)
CSV_FILEPATH_NAME = 'IxL_statResults.csv'
@@ -205,7 +209,7 @@ class IXLOADHttpTest(object):
ipAddress=address,
gatewayAddress=gateway)
except Exception:
- raise exceptions.InvalidRxfFile
+ raise InvalidRxfFile
def update_network_mac_address(self, net_traffic, mac):
"""Update MACaddress for net_traffic object
@@ -233,7 +237,7 @@ class IXLOADHttpTest(object):
"MacRange")
mac_range.config(mac=mac)
except Exception:
- raise exceptions.InvalidRxfFile
+ raise InvalidRxfFile
def update_network_param(self, net_traffic, param):
"""Update net_traffic by parameters specified in param"""
@@ -301,7 +305,7 @@ class IXLOADHttpTest(object):
ix_http_command = activity.agent.actionList[0]
ix_http_command.config(pageObject=page_object)
except Exception:
- raise exceptions.InvalidRxfFile
+ raise InvalidRxfFile
def update_user_count(self, net_traffic, user_count):
"""Update userObjectiveValue field in activity object in net_traffic
@@ -318,7 +322,7 @@ class IXLOADHttpTest(object):
activity = net_traffic.activityList[0]
activity.config(userObjectiveValue=user_count)
except Exception:
- raise exceptions.InvalidRxfFile
+ raise InvalidRxfFile
def start_http_test(self):
self.ix_load = IxLoad()
diff --git a/yardstick/network_services/traffic_profile/ixia_rfc2544.py b/yardstick/network_services/traffic_profile/ixia_rfc2544.py
index 35038891b..aded2d347 100644
--- a/yardstick/network_services/traffic_profile/ixia_rfc2544.py
+++ b/yardstick/network_services/traffic_profile/ixia_rfc2544.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -28,7 +28,6 @@ class IXIARFC2544Profile(trex_traffic_profile.TrexProfile):
UPLINK = 'uplink'
DOWNLINK = 'downlink'
DROP_PERCENT_ROUND = 6
- RATE_ROUND = 5
STATUS_SUCCESS = "Success"
STATUS_FAIL = "Failure"
@@ -146,12 +145,16 @@ class IXIARFC2544Profile(trex_traffic_profile.TrexProfile):
return result
- def _ixia_traffic_generate(self, traffic, ixia_obj):
+ def _ixia_traffic_generate(self, traffic, ixia_obj, traffic_gen):
ixia_obj.update_frame(traffic, self.config.duration)
ixia_obj.update_ip_packet(traffic)
ixia_obj.update_l4(traffic)
+ self._update_traffic_tracking_options(traffic_gen)
ixia_obj.start_traffic()
+ def _update_traffic_tracking_options(self, traffic_gen):
+ traffic_gen.update_tracking_options()
+
def update_traffic_profile(self, traffic_generator):
def port_generator():
for vld_id, intfs in sorted(traffic_generator.networks.items()):
@@ -167,6 +170,19 @@ class IXIARFC2544Profile(trex_traffic_profile.TrexProfile):
self.ports = [port for port in port_generator()]
+ def _get_framesize(self):
+ framesizes = []
+ traffic = self._get_ixia_traffic_profile(self.full_profile)
+ for v in traffic.values():
+ framesize = v['outer_l2']['framesize']
+ for size in (s for s, w in framesize.items() if int(w) != 0):
+ framesizes.append(size)
+ if len(set(framesizes)) == 0:
+ return ''
+ elif len(set(framesizes)) == 1:
+ return framesizes[0]
+ return 'IMIX'
+
def execute_traffic(self, traffic_generator, ixia_obj=None, mac=None):
mac = {} if mac is None else mac
first_run = self.first_run
@@ -176,25 +192,33 @@ class IXIARFC2544Profile(trex_traffic_profile.TrexProfile):
self.max_rate = self.rate
self.min_rate = 0.0
else:
- self.rate = round(float(self.max_rate + self.min_rate) / 2.0,
- self.RATE_ROUND)
+ self.rate = self._get_next_rate()
traffic = self._get_ixia_traffic_profile(self.full_profile, mac)
- self._ixia_traffic_generate(traffic, ixia_obj)
+ self._ixia_traffic_generate(traffic, ixia_obj, traffic_generator)
return first_run
+ # pylint: disable=unused-argument
def get_drop_percentage(self, samples, tol_min, tolerance, precision,
- first_run=False):
+ resolution, first_run=False, tc_rfc2544_opts=None):
completed = False
- drop_percent = 100
+ drop_percent = 100.0
num_ifaces = len(samples)
duration = self.config.duration
in_packets_sum = sum(
[samples[iface]['in_packets'] for iface in samples])
out_packets_sum = sum(
[samples[iface]['out_packets'] for iface in samples])
+ in_bytes_sum = sum(
+ [samples[iface]['in_bytes'] for iface in samples])
+ out_bytes_sum = sum(
+ [samples[iface]['out_bytes'] for iface in samples])
rx_throughput = round(float(in_packets_sum) / duration, 3)
tx_throughput = round(float(out_packets_sum) / duration, 3)
+ # Rx throughput in Bps
+ rx_throughput_bps = round(float(in_bytes_sum) / duration, 3)
+ # Tx throughput in Bps
+ tx_throughput_bps = round(float(out_bytes_sum) / duration, 3)
packet_drop = abs(out_packets_sum - in_packets_sum)
try:
@@ -217,6 +241,15 @@ class IXIARFC2544Profile(trex_traffic_profile.TrexProfile):
else:
completed = True
+ last_rate = self.rate
+ next_rate = self._get_next_rate()
+ if abs(next_rate - self.rate) < resolution:
+ LOG.debug("rate=%s, next_rate=%s, resolution=%s", self.rate,
+ next_rate, resolution)
+ # stop test if the difference between the rate transmission
+ # in two iterations is smaller than the value of the resolution
+ completed = True
+
LOG.debug("tolerance=%s, tolerance_precision=%s drop_percent=%s "
"completed=%s", tolerance, precision, drop_percent,
completed)
@@ -237,10 +270,14 @@ class IXIARFC2544Profile(trex_traffic_profile.TrexProfile):
samples['TxThroughput'] = tx_throughput
samples['RxThroughput'] = rx_throughput
+ samples['TxThroughputBps'] = tx_throughput_bps
+ samples['RxThroughputBps'] = rx_throughput_bps
samples['DropPercentage'] = drop_percent
samples['latency_ns_avg'] = latency_ns_avg
samples['latency_ns_min'] = latency_ns_min
samples['latency_ns_max'] = latency_ns_max
+ samples['Rate'] = last_rate
+ samples['PktSize'] = self._get_framesize()
return completed, samples
@@ -264,12 +301,144 @@ class IXIARFC2544PppoeScenarioProfile(IXIARFC2544Profile):
self.full_profile.update({downlink: self.params[downlink]})
def update_traffic_profile(self, traffic_generator):
+
+ networks = collections.OrderedDict()
+
+ # Sort network interfaces pairs
+ for i in range(len(traffic_generator.networks)):
+ uplink = '_'.join([self.UPLINK, str(i)])
+ downlink = '_'.join([self.DOWNLINK, str(i)])
+ if uplink in traffic_generator.networks:
+ networks[uplink] = traffic_generator.networks[uplink]
+ if downlink in traffic_generator.networks:
+ networks[downlink] = traffic_generator.networks[downlink]
+
def port_generator():
- for vld_id, intfs in sorted(traffic_generator.networks.items()):
- if not vld_id.startswith((self.UPLINK, self.DOWNLINK)):
- continue
+ for intfs in networks.values():
for intf in intfs:
yield traffic_generator.vnfd_helper.port_num(intf)
self._get_flow_groups_params()
self.ports = [port for port in port_generator()]
+
+ def _get_prio_flows_drop_percentage(self, stats):
+ drop_percent = 100
+ for prio_id in stats:
+ prio_flow = stats[prio_id]
+ sum_packet_drop = abs(prio_flow['out_packets'] - prio_flow['in_packets'])
+ try:
+ drop_percent = round(
+ (sum_packet_drop / float(prio_flow['out_packets'])) * 100,
+ self.DROP_PERCENT_ROUND)
+ except ZeroDivisionError:
+ LOG.info('No traffic is flowing')
+ prio_flow['DropPercentage'] = drop_percent
+ return stats
+
+ def _get_summary_pppoe_subs_counters(self, samples):
+ result = {}
+ keys = ['sessions_up',
+ 'sessions_down',
+ 'sessions_not_started',
+ 'sessions_total']
+ for key in keys:
+ result[key] = \
+ sum([samples[port][key] for port in samples
+ if key in samples[port]])
+ return result
+
+ def get_drop_percentage(self, samples, tol_min, tolerance, precision,
+ resolution, first_run=False, tc_rfc2544_opts=None):
+ completed = False
+ sum_drop_percent = 100
+ num_ifaces = len(samples)
+ duration = self.config.duration
+ last_rate = self.rate
+ priority_stats = samples.pop('priority_stats')
+ priority_stats = self._get_prio_flows_drop_percentage(priority_stats)
+ summary_subs_stats = self._get_summary_pppoe_subs_counters(samples)
+ in_packets_sum = sum(
+ [samples[iface]['in_packets'] for iface in samples])
+ out_packets_sum = sum(
+ [samples[iface]['out_packets'] for iface in samples])
+ in_bytes_sum = sum(
+ [samples[iface]['in_bytes'] for iface in samples])
+ out_bytes_sum = sum(
+ [samples[iface]['out_bytes'] for iface in samples])
+ rx_throughput = round(float(in_packets_sum) / duration, 3)
+ tx_throughput = round(float(out_packets_sum) / duration, 3)
+ # Rx throughput in Bps
+ rx_throughput_bps = round(float(in_bytes_sum) / duration, 3)
+ # Tx throughput in Bps
+ tx_throughput_bps = round(float(out_bytes_sum) / duration, 3)
+ sum_packet_drop = abs(out_packets_sum - in_packets_sum)
+
+ try:
+ sum_drop_percent = round(
+ (sum_packet_drop / float(out_packets_sum)) * 100,
+ self.DROP_PERCENT_ROUND)
+ except ZeroDivisionError:
+ LOG.info('No traffic is flowing')
+
+ latency_ns_avg = float(
+ sum([samples[iface]['Store-Forward_Avg_latency_ns']
+ for iface in samples])) / num_ifaces
+ latency_ns_min = float(
+ sum([samples[iface]['Store-Forward_Min_latency_ns']
+ for iface in samples])) / num_ifaces
+ latency_ns_max = float(
+ sum([samples[iface]['Store-Forward_Max_latency_ns']
+ for iface in samples])) / num_ifaces
+
+ samples['TxThroughput'] = tx_throughput
+ samples['RxThroughput'] = rx_throughput
+ samples['TxThroughputBps'] = tx_throughput_bps
+ samples['RxThroughputBps'] = rx_throughput_bps
+ samples['DropPercentage'] = sum_drop_percent
+ samples['latency_ns_avg'] = latency_ns_avg
+ samples['latency_ns_min'] = latency_ns_min
+ samples['latency_ns_max'] = latency_ns_max
+ samples['priority'] = priority_stats
+ samples['Rate'] = last_rate
+ samples['PktSize'] = self._get_framesize()
+ samples.update(summary_subs_stats)
+
+ if tc_rfc2544_opts:
+ priority = tc_rfc2544_opts.get('priority')
+ if priority:
+ drop_percent = samples['priority'][priority]['DropPercentage']
+ else:
+ drop_percent = sum_drop_percent
+ else:
+ drop_percent = sum_drop_percent
+
+ if first_run:
+ completed = True if drop_percent <= tolerance else False
+ if (first_run and
+ self.rate_unit == tp_base.TrafficProfileConfig.RATE_FPS):
+ self.rate = float(out_packets_sum) / duration / num_ifaces
+
+ if drop_percent > tolerance:
+ self.max_rate = self.rate
+ elif drop_percent < tol_min:
+ self.min_rate = self.rate
+ else:
+ completed = True
+
+ next_rate = self._get_next_rate()
+ if abs(next_rate - self.rate) < resolution:
+ LOG.debug("rate=%s, next_rate=%s, resolution=%s", self.rate,
+ next_rate, resolution)
+ # stop test if the difference between the rate transmission
+ # in two iterations is smaller than the value of the resolution
+ completed = True
+
+ LOG.debug("tolerance=%s, tolerance_precision=%s drop_percent=%s "
+ "completed=%s", tolerance, precision, drop_percent,
+ completed)
+
+ samples['Status'] = self.STATUS_FAIL
+ if round(drop_percent, precision) <= tolerance:
+ samples['Status'] = self.STATUS_SUCCESS
+
+ return completed, samples
diff --git a/yardstick/network_services/traffic_profile/rfc2544.py b/yardstick/network_services/traffic_profile/rfc2544.py
index e33c437c9..b838bf814 100644
--- a/yardstick/network_services/traffic_profile/rfc2544.py
+++ b/yardstick/network_services/traffic_profile/rfc2544.py
@@ -23,7 +23,7 @@ from yardstick.common import constants
from yardstick.network_services.traffic_profile import trex_traffic_profile
-LOGGING = logging.getLogger(__name__)
+LOG = logging.getLogger(__name__)
SRC_PORT = 'sport'
DST_PORT = 'dport'
@@ -271,17 +271,23 @@ class RFC2544Profile(trex_traffic_profile.TrexProfile):
return streams
def get_drop_percentage(self, samples, tol_low, tol_high,
- correlated_traffic):
+ correlated_traffic, resolution):
"""Calculate the drop percentage and run the traffic"""
completed = False
out_pkt_end = sum(port['out_packets'] for port in samples[-1].values())
in_pkt_end = sum(port['in_packets'] for port in samples[-1].values())
out_pkt_ini = sum(port['out_packets'] for port in samples[0].values())
in_pkt_ini = sum(port['in_packets'] for port in samples[0].values())
+ in_bytes_ini = sum(port['in_bytes'] for port in samples[0].values())
+ out_bytes_ini = sum(port['out_bytes'] for port in samples[0].values())
+ in_bytes_end = sum(port['in_bytes'] for port in samples[-1].values())
+ out_bytes_end = sum(port['out_bytes'] for port in samples[-1].values())
time_diff = (list(samples[-1].values())[0]['timestamp'] -
list(samples[0].values())[0]['timestamp']).total_seconds()
out_packets = out_pkt_end - out_pkt_ini
in_packets = in_pkt_end - in_pkt_ini
+ out_bytes = out_bytes_end - out_bytes_ini
+ in_bytes = in_bytes_end - in_bytes_ini
tx_rate_fps = float(out_packets) / time_diff
rx_rate_fps = float(in_packets) / time_diff
drop_percent = 100.0
@@ -301,7 +307,13 @@ class RFC2544Profile(trex_traffic_profile.TrexProfile):
completed = True
last_rate = self.rate
- self.rate = round(float(self.max_rate + self.min_rate) / 2.0, 5)
+ self.rate = self._get_next_rate()
+ if abs(last_rate - self.rate) < resolution:
+ # stop test if the difference between the rate transmission
+ # in two iterations is smaller than the value of the resolution
+ completed = True
+ LOG.debug("rate=%s, next_rate=%s, resolution=%s, completed=%s",
+ last_rate, self.rate, resolution, completed)
throughput = rx_rate_fps * 2 if correlated_traffic else rx_rate_fps
@@ -314,6 +326,8 @@ class RFC2544Profile(trex_traffic_profile.TrexProfile):
output = {
'TxThroughput': tx_rate_fps,
'RxThroughput': rx_rate_fps,
+ 'RxThroughputBps': round(float(in_bytes) / time_diff, 3),
+ 'TxThroughputBps': round(float(out_bytes) / time_diff, 3),
'CurrentDropPercentage': drop_percent,
'Throughput': throughput,
'DropPercentage': self.drop_percent_max,
diff --git a/yardstick/network_services/traffic_profile/trex_traffic_profile.py b/yardstick/network_services/traffic_profile/trex_traffic_profile.py
index ed0355fa5..2d2c2d8b6 100644
--- a/yardstick/network_services/traffic_profile/trex_traffic_profile.py
+++ b/yardstick/network_services/traffic_profile/trex_traffic_profile.py
@@ -52,6 +52,7 @@ class TrexProfile(base.TrafficProfile):
IPv6: ('ip6_packet', Pkt.IPv6),
UDP: ('udp_packet', Pkt.UDP),
}
+ RATE_ROUND = 5
def _general_single_action_partial(self, protocol):
def f(field):
@@ -186,6 +187,8 @@ class TrexProfile(base.TrafficProfile):
self.qinq = False
self.vm_flow_vars = []
self.packets = []
+ self.max_rate = 0
+ self.min_rate = 0
self._map_proto_actions = {
# the tuple is (single value function, range value function, if the values should be
@@ -337,6 +340,10 @@ class TrexProfile(base.TrafficProfile):
if 'dstport' in outer_l4:
self._set_proto_addr(UDP, DST_PORT, outer_l4['dstport'], outer_l4['count'])
+ def _get_next_rate(self):
+ rate = round(float(self.max_rate + self.min_rate)/2.0, self.RATE_ROUND)
+ return rate
+
@classmethod
def _count_ip(cls, start_ip, end_ip):
start = ipaddress.ip_address(six.u(start_ip))
diff --git a/yardstick/network_services/vnf_generic/vnf/acl_vnf.py b/yardstick/network_services/vnf_generic/vnf/acl_vnf.py
index 11a602472..69d29bf76 100644
--- a/yardstick/network_services/vnf_generic/vnf/acl_vnf.py
+++ b/yardstick/network_services/vnf_generic/vnf/acl_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -246,9 +246,12 @@ class AclApproxVnf(SampleVNF):
'packets_dropped': 2,
}
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
- resource_helper_type=None):
+ def __init__(self, name, vnfd, setup_env_helper_type=None, resource_helper_type=None):
if setup_env_helper_type is None:
setup_env_helper_type = AclApproxSetupEnvSetupEnvHelper
- super(AclApproxVnf, self).__init__(
- name, vnfd, task_id, setup_env_helper_type, resource_helper_type)
+
+ super(AclApproxVnf, self).__init__(name, vnfd, setup_env_helper_type, resource_helper_type)
+
+ def wait_for_instantiate(self):
+ """Wait for VNF to initialize"""
+ self.wait_for_initialize()
diff --git a/yardstick/network_services/vnf_generic/vnf/agnostic_vnf.py b/yardstick/network_services/vnf_generic/vnf/agnostic_vnf.py
index 115fddcf0..d1d9667db 100644
--- a/yardstick/network_services/vnf_generic/vnf/agnostic_vnf.py
+++ b/yardstick/network_services/vnf_generic/vnf/agnostic_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2018 Intel Corporation
+# Copyright (c) 2018-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -21,8 +21,8 @@ LOG = logging.getLogger(__name__)
class AgnosticVnf(base.GenericVNF):
""" AgnosticVnf implementation. """
- def __init__(self, name, vnfd, task_id):
- super(AgnosticVnf, self).__init__(name, vnfd, task_id)
+ def __init__(self, name, vnfd):
+ super(AgnosticVnf, self).__init__(name, vnfd)
def instantiate(self, scenario_cfg, context_cfg):
pass
diff --git a/yardstick/network_services/vnf_generic/vnf/base.py b/yardstick/network_services/vnf_generic/vnf/base.py
index 0fb310075..8064ae927 100644
--- a/yardstick/network_services/vnf_generic/vnf/base.py
+++ b/yardstick/network_services/vnf_generic/vnf/base.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -17,10 +17,6 @@ import abc
import logging
import six
-from yardstick.common import messaging
-from yardstick.common.messaging import consumer
-from yardstick.common.messaging import payloads
-from yardstick.common.messaging import producer
from yardstick.network_services.helpers.samplevnf_helper import PortPairs
@@ -141,70 +137,6 @@ class VnfdHelper(dict):
yield port_name, port_num
-class TrafficGeneratorProducer(producer.MessagingProducer):
- """Class implementing the message producer for traffic generators
-
- This message producer must be instantiated in the process created
- "run_traffic" process.
- """
- def __init__(self, _id):
- super(TrafficGeneratorProducer, self).__init__(messaging.TOPIC_TG,
- _id=_id)
-
- def tg_method_started(self, version=1):
- """Send a message to inform the traffic generation has started"""
- self.send_message(
- messaging.TG_METHOD_STARTED,
- payloads.TrafficGeneratorPayload(version=version, iteration=0,
- kpi={}))
-
- def tg_method_finished(self, version=1):
- """Send a message to inform the traffic generation has finished"""
- self.send_message(
- messaging.TG_METHOD_FINISHED,
- payloads.TrafficGeneratorPayload(version=version, iteration=0,
- kpi={}))
-
- def tg_method_iteration(self, iteration, version=1, kpi=None):
- """Send a message, with KPI, once an iteration has finished"""
- kpi = {} if kpi is None else kpi
- self.send_message(
- messaging.TG_METHOD_ITERATION,
- payloads.TrafficGeneratorPayload(version=version,
- iteration=iteration, kpi=kpi))
-
-
-@six.add_metaclass(abc.ABCMeta)
-class GenericVNFEndpoint(consumer.NotificationHandler):
- """Endpoint class for ``GenericVNFConsumer``"""
-
- @abc.abstractmethod
- def runner_method_start_iteration(self, ctxt, **kwargs):
- """Endpoint when RUNNER_METHOD_START_ITERATION is received
-
- :param ctxt: (dict) {'id': <Producer ID>}
- :param kwargs: (dict) ``payloads.RunnerPayload`` context
- """
-
- @abc.abstractmethod
- def runner_method_stop_iteration(self, ctxt, **kwargs):
- """Endpoint when RUNNER_METHOD_STOP_ITERATION is received
-
- :param ctxt: (dict) {'id': <Producer ID>}
- :param kwargs: (dict) ``payloads.RunnerPayload`` context
- """
-
-
-class GenericVNFConsumer(consumer.MessagingConsumer):
- """MQ consumer for ``GenericVNF`` derived classes"""
-
- def __init__(self, ctx_ids, endpoints):
- if not isinstance(endpoints, list):
- endpoints = [endpoints]
- super(GenericVNFConsumer, self).__init__(messaging.TOPIC_RUNNER,
- ctx_ids, endpoints)
-
-
@six.add_metaclass(abc.ABCMeta)
class GenericVNF(object):
"""Class providing file-like API for generic VNF implementation
@@ -217,9 +149,8 @@ class GenericVNF(object):
UPLINK = PortPairs.UPLINK
DOWNLINK = PortPairs.DOWNLINK
- def __init__(self, name, vnfd, task_id):
+ def __init__(self, name, vnfd):
self.name = name
- self._task_id = task_id
self.vnfd_helper = VnfdHelper(vnfd)
# List of statistics we can obtain from this VNF
# - ETSI MANO 6.3.1.1 monitoring_parameter
@@ -280,11 +211,10 @@ class GenericVNF(object):
class GenericTrafficGen(GenericVNF):
"""Class providing file-like API for generic traffic generator"""
- def __init__(self, name, vnfd, task_id):
- super(GenericTrafficGen, self).__init__(name, vnfd, task_id)
+ def __init__(self, name, vnfd):
+ super(GenericTrafficGen, self).__init__(name, vnfd)
self.runs_traffic = True
self.traffic_finished = False
- self._mq_producer = None
@abc.abstractmethod
def run_traffic(self, traffic_profile):
@@ -355,16 +285,3 @@ class GenericTrafficGen(GenericVNF):
:return: True/False
"""
pass
-
- @staticmethod
- def _setup_mq_producer(id):
- """Setup the TG MQ producer to send messages between processes
-
- :return: (derived class from ``MessagingProducer``) MQ producer object
- """
- return TrafficGeneratorProducer(id)
-
- def get_mq_producer_id(self):
- """Return the MQ producer ID if initialized"""
- if self._mq_producer:
- return self._mq_producer.id
diff --git a/yardstick/network_services/vnf_generic/vnf/cgnapt_vnf.py b/yardstick/network_services/vnf_generic/vnf/cgnapt_vnf.py
index 14f1e2e97..ee4a581b1 100644
--- a/yardstick/network_services/vnf_generic/vnf/cgnapt_vnf.py
+++ b/yardstick/network_services/vnf_generic/vnf/cgnapt_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -85,12 +85,12 @@ class CgnaptApproxVnf(SampleVNF):
"packets_dropped": 4,
}
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
- resource_helper_type=None):
+ def __init__(self, name, vnfd, setup_env_helper_type=None, resource_helper_type=None):
if setup_env_helper_type is None:
setup_env_helper_type = CgnaptApproxSetupEnvHelper
- super(CgnaptApproxVnf, self).__init__(
- name, vnfd, task_id, setup_env_helper_type, resource_helper_type)
+
+ super(CgnaptApproxVnf, self).__init__(name, vnfd, setup_env_helper_type,
+ resource_helper_type)
def _vnf_up_post(self):
super(CgnaptApproxVnf, self)._vnf_up_post()
@@ -120,3 +120,7 @@ class CgnaptApproxVnf(SampleVNF):
self.vnf_execute(cmd)
time.sleep(WAIT_FOR_STATIC_NAPT)
+
+ def wait_for_instantiate(self):
+ """Wait for VNF to initialize"""
+ self.wait_for_initialize()
diff --git a/yardstick/network_services/vnf_generic/vnf/epc_vnf.py b/yardstick/network_services/vnf_generic/vnf/epc_vnf.py
index 66d16d07f..8112963e9 100644
--- a/yardstick/network_services/vnf_generic/vnf/epc_vnf.py
+++ b/yardstick/network_services/vnf_generic/vnf/epc_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2018 Intel Corporation
+# Copyright (c) 2018-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -21,8 +21,8 @@ LOG = logging.getLogger(__name__)
class EPCVnf(base.GenericVNF):
- def __init__(self, name, vnfd, task_id):
- super(EPCVnf, self).__init__(name, vnfd, task_id)
+ def __init__(self, name, vnfd):
+ super(EPCVnf, self).__init__(name, vnfd)
def instantiate(self, scenario_cfg, context_cfg):
"""Prepare VNF for operation and start the VNF process/VM
diff --git a/yardstick/network_services/vnf_generic/vnf/prox_helpers.py b/yardstick/network_services/vnf_generic/vnf/prox_helpers.py
index cd3035ef8..a3d0c19cd 100644
--- a/yardstick/network_services/vnf_generic/vnf/prox_helpers.py
+++ b/yardstick/network_services/vnf_generic/vnf/prox_helpers.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2018 Intel Corporation
+# Copyright (c) 2018-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -1146,7 +1146,7 @@ class ProxResourceHelper(ClientResourceHelper):
self._test_type = self.setup_helper.find_in_section('global', 'name', None)
return self._test_type
- def run_traffic(self, traffic_profile, *args):
+ def run_traffic(self, traffic_profile):
self._queue.cancel_join_thread()
self.lower = 0.0
self.upper = 100.0
diff --git a/yardstick/network_services/vnf_generic/vnf/prox_irq.py b/yardstick/network_services/vnf_generic/vnf/prox_irq.py
index dda26b0fe..614066e46 100644
--- a/yardstick/network_services/vnf_generic/vnf/prox_irq.py
+++ b/yardstick/network_services/vnf_generic/vnf/prox_irq.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2018 Intel Corporation
+# Copyright (c) 2018-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -28,13 +28,13 @@ LOG = logging.getLogger(__name__)
class ProxIrq(SampleVNFTrafficGen):
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
+ def __init__(self, name, vnfd, setup_env_helper_type=None,
resource_helper_type=None):
vnfd_cpy = copy.deepcopy(vnfd)
- super(ProxIrq, self).__init__(name, vnfd_cpy, task_id)
+ super(ProxIrq, self).__init__(name, vnfd_cpy)
self._vnf_wrapper = ProxApproxVnf(
- name, vnfd, task_id, setup_env_helper_type, resource_helper_type)
+ name, vnfd, setup_env_helper_type, resource_helper_type)
self.bin_path = get_nsb_option('bin_path', '')
self.name = self._vnf_wrapper.name
self.ssh_helper = self._vnf_wrapper.ssh_helper
@@ -83,9 +83,9 @@ class ProxIrqVNF(ProxIrq, SampleVNFTrafficGen):
APP_NAME = 'ProxIrqVNF'
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
+ def __init__(self, name, vnfd, setup_env_helper_type=None,
resource_helper_type=None):
- ProxIrq.__init__(self, name, vnfd, task_id, setup_env_helper_type,
+ ProxIrq.__init__(self, name, vnfd, setup_env_helper_type,
resource_helper_type)
self.start_test_time = None
@@ -150,9 +150,9 @@ class ProxIrqGen(ProxIrq, SampleVNFTrafficGen):
APP_NAME = 'ProxIrqGen'
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
+ def __init__(self, name, vnfd, setup_env_helper_type=None,
resource_helper_type=None):
- ProxIrq.__init__(self, name, vnfd, task_id, setup_env_helper_type,
+ ProxIrq.__init__(self, name, vnfd, setup_env_helper_type,
resource_helper_type)
self.start_test_time = None
self.end_test_time = None
diff --git a/yardstick/network_services/vnf_generic/vnf/prox_vnf.py b/yardstick/network_services/vnf_generic/vnf/prox_vnf.py
index c3b50369b..c9abc757e 100644
--- a/yardstick/network_services/vnf_generic/vnf/prox_vnf.py
+++ b/yardstick/network_services/vnf_generic/vnf/prox_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2018 Intel Corporation
+# Copyright (c) 2018-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,8 +35,7 @@ class ProxApproxVnf(SampleVNF):
VNF_PROMPT = "PROX started"
LUA_PARAMETER_NAME = "sut"
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
- resource_helper_type=None):
+ def __init__(self, name, vnfd, setup_env_helper_type=None, resource_helper_type=None):
if setup_env_helper_type is None:
setup_env_helper_type = ProxDpdkVnfSetupEnvHelper
@@ -47,8 +46,8 @@ class ProxApproxVnf(SampleVNF):
self.prev_packets_sent = 0
self.prev_tsc = 0
self.tsc_hz = 0
- super(ProxApproxVnf, self).__init__(
- name, vnfd, task_id, setup_env_helper_type, resource_helper_type)
+ super(ProxApproxVnf, self).__init__(name, vnfd, setup_env_helper_type,
+ resource_helper_type)
def _vnf_up_post(self):
self.resource_helper.up_post()
diff --git a/yardstick/network_services/vnf_generic/vnf/router_vnf.py b/yardstick/network_services/vnf_generic/vnf/router_vnf.py
index e99de9cb3..f1486bdb4 100644
--- a/yardstick/network_services/vnf_generic/vnf/router_vnf.py
+++ b/yardstick/network_services/vnf_generic/vnf/router_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -34,8 +34,7 @@ class RouterVNF(SampleVNF):
WAIT_TIME = 1
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
- resource_helper_type=None):
+ def __init__(self, name, vnfd, setup_env_helper_type=None, resource_helper_type=None):
if setup_env_helper_type is None:
setup_env_helper_type = DpdkVnfSetupEnvHelper
@@ -43,8 +42,7 @@ class RouterVNF(SampleVNF):
vnfd['mgmt-interface'].pop("pkey", "")
vnfd['mgmt-interface']['password'] = 'password'
- super(RouterVNF, self).__init__(
- name, vnfd, task_id, setup_env_helper_type, resource_helper_type)
+ super(RouterVNF, self).__init__(name, vnfd, setup_env_helper_type, resource_helper_type)
def instantiate(self, scenario_cfg, context_cfg):
self.scenario_helper.scenario_cfg = scenario_cfg
diff --git a/yardstick/network_services/vnf_generic/vnf/sample_vnf.py b/yardstick/network_services/vnf_generic/vnf/sample_vnf.py
index 8833b88f2..2a477bb8d 100644
--- a/yardstick/network_services/vnf_generic/vnf/sample_vnf.py
+++ b/yardstick/network_services/vnf_generic/vnf/sample_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2018 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -14,11 +14,10 @@
import logging
import decimal
-from multiprocessing import Queue, Value, Process
+from multiprocessing import Queue, Value, Process, JoinableQueue
import os
import posixpath
import re
-import uuid
import subprocess
import time
@@ -232,6 +231,9 @@ class DpdkVnfSetupEnvHelper(SetupEnvHelper):
exit_status = self.dpdk_bind_helper.check_dpdk_driver()
if exit_status == 0:
return
+ else:
+ LOG.critical("DPDK Driver not installed")
+ return
def _setup_resources(self):
# what is this magic? how do we know which socket is for which port?
@@ -397,26 +399,26 @@ class ClientResourceHelper(ResourceHelper):
time.sleep(self.QUEUE_WAIT_TIME)
self._queue.put(samples)
- def run_traffic(self, traffic_profile, mq_producer):
+ def run_traffic(self, traffic_profile):
# if we don't do this we can hang waiting for the queue to drain
# have to do this in the subprocess
self._queue.cancel_join_thread()
# fixme: fix passing correct trex config file,
# instead of searching the default path
- mq_producer.tg_method_started()
try:
self._build_ports()
self.client = self._connect()
+ if self.client is None:
+ LOG.critical("Failure to Connect ... unable to continue")
+ return
+
self.client.reset(ports=self.all_ports)
self.client.remove_all_streams(self.all_ports) # remove all streams
traffic_profile.register_generator(self)
- iteration_index = 0
while self._terminated.value == 0:
- iteration_index += 1
if self._run_traffic_once(traffic_profile):
self._terminated.value = 1
- mq_producer.tg_method_iteration(iteration_index)
self.client.stop(self.all_ports)
self.client.disconnect()
@@ -427,8 +429,6 @@ class ClientResourceHelper(ResourceHelper):
return # return if trex/tg server is stopped.
raise
- mq_producer.tg_method_finished()
-
def terminate(self):
self._terminated.value = 1 # stop client
@@ -461,22 +461,35 @@ class ClientResourceHelper(ResourceHelper):
server=self.vnfd_helper.mgmt_interface["ip"],
verbose_level=LoggerApi.VERBOSE_QUIET)
- # try to connect with 5s intervals, 30s max
+ # try to connect with 5s intervals
for idx in range(6):
try:
client.connect()
- break
+ for idx2 in range(6):
+ if client.is_connected():
+ return client
+ LOG.info("Waiting to confirm connection %s .. Attempt %s",
+ idx, idx2)
+ time.sleep(1)
+ client.disconnect(stop_traffic=True, release_ports=True)
except STLError:
LOG.info("Unable to connect to Trex Server.. Attempt %s", idx)
time.sleep(5)
- return client
+ if client.is_connected():
+ return client
+ else:
+ LOG.critical("Connection failure ..TRex username: %s server: %s",
+ self.vnfd_helper.mgmt_interface["user"],
+ self.vnfd_helper.mgmt_interface["ip"])
+ return None
class Rfc2544ResourceHelper(object):
DEFAULT_CORRELATED_TRAFFIC = False
DEFAULT_LATENCY = False
DEFAULT_TOLERANCE = '0.0001 - 0.0001'
+ DEFAULT_RESOLUTION = '0.1'
def __init__(self, scenario_helper):
super(Rfc2544ResourceHelper, self).__init__()
@@ -488,6 +501,7 @@ class Rfc2544ResourceHelper(object):
self._tolerance_low = None
self._tolerance_high = None
self._tolerance_precision = None
+ self._resolution = None
@property
def rfc2544(self):
@@ -527,6 +541,13 @@ class Rfc2544ResourceHelper(object):
self._latency = self.get_rfc2544('latency', self.DEFAULT_LATENCY)
return self._latency
+ @property
+ def resolution(self):
+ if self._resolution is None:
+ self._resolution = float(self.get_rfc2544('resolution',
+ self.DEFAULT_RESOLUTION))
+ return self._resolution
+
def get_rfc2544(self, name, default=None):
return self.rfc2544.get(name, default)
@@ -619,7 +640,6 @@ class ScenarioHelper(object):
test_timeout = self.options.get('timeout', constants.DEFAULT_VNF_TIMEOUT)
return test_duration if test_duration > test_timeout else test_timeout
-
class SampleVNF(GenericVNF):
""" Class providing file-like API for generic VNF implementation """
@@ -629,9 +649,8 @@ class SampleVNF(GenericVNF):
APP_NAME = "SampleVNF"
# we run the VNF interactively, so the ssh command will timeout after this long
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
- resource_helper_type=None):
- super(SampleVNF, self).__init__(name, vnfd, task_id)
+ def __init__(self, name, vnfd, setup_env_helper_type=None, resource_helper_type=None):
+ super(SampleVNF, self).__init__(name, vnfd)
self.bin_path = get_nsb_option('bin_path', '')
self.scenario_helper = ScenarioHelper(self.name)
@@ -764,6 +783,53 @@ class SampleVNF(GenericVNF):
# by other VNF output
self.q_in.put('\r\n')
+ def wait_for_initialize(self):
+ buf = []
+ vnf_prompt_found = False
+ prompt_command = '\r\n'
+ script_name = 'non_existent_script_name'
+ done_string = 'Cannot open file "{}"'.format(script_name)
+ time.sleep(self.WAIT_TIME) # Give some time for config to load
+ while True:
+ if not self._vnf_process.is_alive():
+ raise RuntimeError("%s VNF process died." % self.APP_NAME)
+ while self.q_out.qsize() > 0:
+ buf.append(self.q_out.get())
+ message = ''.join(buf)
+
+ if self.VNF_PROMPT in message and not vnf_prompt_found:
+ # Once we got VNF promt, it doesn't mean that the VNF is
+ # up and running/initialized completely. But we can run
+ # addition (any) VNF command and wait for it to complete
+ # as it will be finished ONLY at the end of the VNF
+ # initialization. So, this approach can be used to
+ # indentify that VNF is completely initialized.
+ LOG.info("Got %s VNF prompt.", self.APP_NAME)
+ prompt_command = "run {}\r\n".format(script_name)
+ self.q_in.put(prompt_command)
+ # Cut the buffer since we are not interesting to find
+ # the VNF prompt anymore
+ prompt_pos = message.find(self.VNF_PROMPT)
+ buf = [message[prompt_pos + len(self.VNF_PROMPT):]]
+ vnf_prompt_found = True
+ continue
+
+ if done_string in message:
+ LOG.info("%s VNF is up and running.", self.APP_NAME)
+ self._vnf_up_post()
+ self.queue_wrapper.clear()
+ return self._vnf_process.exitcode
+
+ if "PANIC" in message:
+ raise RuntimeError("Error starting %s VNF." %
+ self.APP_NAME)
+
+ LOG.info("Waiting for %s VNF to start.. ", self.APP_NAME)
+ time.sleep(self.WAIT_TIME_FOR_SCRIPT)
+ # Send command again to display the expected prompt in case the
+ # expected text was corrupted by other VNF output
+ self.q_in.put(prompt_command)
+
def start_collect(self):
self.resource_helper.start_collect()
@@ -862,9 +928,8 @@ class SampleVNFTrafficGen(GenericTrafficGen):
APP_NAME = 'Sample'
RUN_WAIT = 1
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
- resource_helper_type=None):
- super(SampleVNFTrafficGen, self).__init__(name, vnfd, task_id)
+ def __init__(self, name, vnfd, setup_env_helper_type=None, resource_helper_type=None):
+ super(SampleVNFTrafficGen, self).__init__(name, vnfd)
self.bin_path = get_nsb_option('bin_path', '')
self.scenario_helper = ScenarioHelper(self.name)
@@ -886,6 +951,39 @@ class SampleVNFTrafficGen(GenericTrafficGen):
self.traffic_finished = False
self._tg_process = None
self._traffic_process = None
+ self._tasks_queue = JoinableQueue()
+ self._result_queue = Queue()
+
+ def _test_runner(self, traffic_profile, tasks, results):
+ self.resource_helper.run_test(traffic_profile, tasks, results)
+
+ def _init_traffic_process(self, traffic_profile):
+ name = '{}-{}-{}-{}'.format(self.name, self.APP_NAME,
+ traffic_profile.__class__.__name__,
+ os.getpid())
+ self._traffic_process = Process(name=name, target=self._test_runner,
+ args=(
+ traffic_profile, self._tasks_queue,
+ self._result_queue))
+
+ self._traffic_process.start()
+ while self.resource_helper.client_started.value == 0:
+ time.sleep(1)
+ if not self._traffic_process.is_alive():
+ break
+
+ def run_traffic_once(self, traffic_profile):
+ if self.resource_helper.client_started.value == 0:
+ self._init_traffic_process(traffic_profile)
+
+ # continue test - run next iteration
+ LOG.info("Run next iteration ...")
+ self._tasks_queue.put('RUN_TRAFFIC')
+
+ def wait_on_traffic(self):
+ self._tasks_queue.join()
+ result = self._result_queue.get()
+ return result
def _start_server(self):
# we can't share ssh paramiko objects to force new connection
@@ -923,13 +1021,12 @@ class SampleVNFTrafficGen(GenericTrafficGen):
LOG.info("%s TG Server is up and running.", self.APP_NAME)
return self._tg_process.exitcode
- def _traffic_runner(self, traffic_profile, mq_id):
+ def _traffic_runner(self, traffic_profile):
# always drop connections first thing in new processes
# so we don't get paramiko errors
self.ssh_helper.drop_connection()
LOG.info("Starting %s client...", self.APP_NAME)
- self._mq_producer = self._setup_mq_producer(mq_id)
- self.resource_helper.run_traffic(traffic_profile, self._mq_producer)
+ self.resource_helper.run_traffic(traffic_profile)
def run_traffic(self, traffic_profile):
""" Generate traffic on the wire according to the given params.
@@ -939,12 +1036,10 @@ class SampleVNFTrafficGen(GenericTrafficGen):
:param traffic_profile:
:return: True/False
"""
- name = '{}-{}-{}-{}'.format(self.name, self.APP_NAME,
- traffic_profile.__class__.__name__,
+ name = "{}-{}-{}-{}".format(self.name, self.APP_NAME, traffic_profile.__class__.__name__,
os.getpid())
- self._traffic_process = Process(
- name=name, target=self._traffic_runner,
- args=(traffic_profile, uuid.uuid1().int))
+ self._traffic_process = Process(name=name, target=self._traffic_runner,
+ args=(traffic_profile,))
self._traffic_process.start()
# Wait for traffic process to start
while self.resource_helper.client_started.value == 0:
@@ -953,6 +1048,8 @@ class SampleVNFTrafficGen(GenericTrafficGen):
if not self._traffic_process.is_alive():
break
+ return self._traffic_process.is_alive()
+
def collect_kpi(self):
# check if the tg processes have exited
physical_node = Context.get_physical_node_from_server(
diff --git a/yardstick/network_services/vnf_generic/vnf/tg_ixload.py b/yardstick/network_services/vnf_generic/vnf/tg_ixload.py
index d25402740..38b00a4b2 100644
--- a/yardstick/network_services/vnf_generic/vnf/tg_ixload.py
+++ b/yardstick/network_services/vnf_generic/vnf/tg_ixload.py
@@ -126,13 +126,12 @@ class IxLoadResourceHelper(sample_vnf.ClientResourceHelper):
class IxLoadTrafficGen(sample_vnf.SampleVNFTrafficGen):
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
- resource_helper_type=None):
+ def __init__(self, name, vnfd, setup_env_helper_type=None, resource_helper_type=None):
if resource_helper_type is None:
resource_helper_type = IxLoadResourceHelper
- super(IxLoadTrafficGen, self).__init__(
- name, vnfd, task_id, setup_env_helper_type, resource_helper_type)
+ super(IxLoadTrafficGen, self).__init__(name, vnfd, setup_env_helper_type,
+ resource_helper_type)
self._result = {}
def update_gateways(self, links):
@@ -143,7 +142,12 @@ class IxLoadTrafficGen(sample_vnf.SampleVNFTrafficGen):
"external-interface"] if
intf["virtual-interface"]["vld_id"] == name)
- links[name]["ip"]["gateway"] = gateway
+ try:
+ links[name]["ip"]["gateway"] = gateway
+ except KeyError:
+ LOG.error("Invalid traffic profile: No IP section defined for %s", name)
+ raise
+
except StopIteration:
LOG.debug("Cant find gateway for link %s", name)
links[name]["ip"]["gateway"] = "0.0.0.0"
diff --git a/yardstick/network_services/vnf_generic/vnf/tg_landslide.py b/yardstick/network_services/vnf_generic/vnf/tg_landslide.py
index 2fba89b22..285374a92 100644
--- a/yardstick/network_services/vnf_generic/vnf/tg_landslide.py
+++ b/yardstick/network_services/vnf_generic/vnf/tg_landslide.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2018 Intel Corporation
+# Copyright (c) 2018-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,11 +35,11 @@ LOG = logging.getLogger(__name__)
class LandslideTrafficGen(sample_vnf.SampleVNFTrafficGen):
APP_NAME = 'LandslideTG'
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
+ def __init__(self, name, vnfd, setup_env_helper_type=None,
resource_helper_type=None):
if resource_helper_type is None:
resource_helper_type = LandslideResourceHelper
- super(LandslideTrafficGen, self).__init__(name, vnfd, task_id,
+ super(LandslideTrafficGen, self).__init__(name, vnfd,
setup_env_helper_type,
resource_helper_type)
diff --git a/yardstick/network_services/vnf_generic/vnf/tg_ping.py b/yardstick/network_services/vnf_generic/vnf/tg_ping.py
index a3b5afa39..5c8819119 100644
--- a/yardstick/network_services/vnf_generic/vnf/tg_ping.py
+++ b/yardstick/network_services/vnf_generic/vnf/tg_ping.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -71,7 +71,7 @@ class PingResourceHelper(ClientResourceHelper):
self._queue = Queue()
self._parser = PingParser(self._queue)
- def run_traffic(self, traffic_profile, *args):
+ def run_traffic(self, traffic_profile):
# drop the connection in order to force a new one
self.ssh_helper.drop_connection()
@@ -103,14 +103,14 @@ class PingTrafficGen(SampleVNFTrafficGen):
APP_NAME = 'Ping'
RUN_WAIT = 4
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
- resource_helper_type=None):
+ def __init__(self, name, vnfd, setup_env_helper_type=None, resource_helper_type=None):
if setup_env_helper_type is None:
setup_env_helper_type = PingSetupEnvHelper
if resource_helper_type is None:
resource_helper_type = PingResourceHelper
- super(PingTrafficGen, self).__init__(
- name, vnfd, task_id, setup_env_helper_type, resource_helper_type)
+
+ super(PingTrafficGen, self).__init__(name, vnfd, setup_env_helper_type,
+ resource_helper_type)
self._result = {}
def _check_status(self):
diff --git a/yardstick/network_services/vnf_generic/vnf/tg_pktgen.py b/yardstick/network_services/vnf_generic/vnf/tg_pktgen.py
index 9d452213f..5da2178af 100644
--- a/yardstick/network_services/vnf_generic/vnf/tg_pktgen.py
+++ b/yardstick/network_services/vnf_generic/vnf/tg_pktgen.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2018 Intel Corporation
+# Copyright (c) 2018-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -13,9 +13,7 @@
# limitations under the License.
import logging
-import multiprocessing
import time
-import uuid
from yardstick.common import constants
from yardstick.common import exceptions
@@ -26,8 +24,7 @@ from yardstick.network_services.vnf_generic.vnf import base as vnf_base
LOG = logging.getLogger(__name__)
-class PktgenTrafficGen(vnf_base.GenericTrafficGen,
- vnf_base.GenericVNFEndpoint):
+class PktgenTrafficGen(vnf_base.GenericTrafficGen):
"""DPDK Pktgen traffic generator
Website: http://pktgen-dpdk.readthedocs.io/en/latest/index.html
@@ -35,15 +32,8 @@ class PktgenTrafficGen(vnf_base.GenericTrafficGen,
TIMEOUT = 30
- def __init__(self, name, vnfd, task_id):
- vnf_base.GenericTrafficGen.__init__(self, name, vnfd, task_id)
- self.queue = multiprocessing.Queue()
- self._id = uuid.uuid1().int
- self._mq_producer = self._setup_mq_producer(self._id)
- vnf_base.GenericVNFEndpoint.__init__(self, self._id, [task_id],
- self.queue)
- self._consumer = vnf_base.GenericVNFConsumer([task_id], self)
- self._consumer.start_rpc_server()
+ def __init__(self, name, vnfd):
+ vnf_base.GenericTrafficGen.__init__(self, name, vnfd)
self._traffic_profile = None
self._node_ip = vnfd['mgmt-interface'].get('ip')
self._lua_node_port = self._get_lua_node_port(
@@ -71,7 +61,7 @@ class PktgenTrafficGen(vnf_base.GenericTrafficGen,
def wait_for_instantiate(self): # pragma: no cover
pass
- def runner_method_start_iteration(self, ctxt, **kwargs):
+ def runner_method_start_iteration(self):
# pragma: no cover
LOG.debug('Start method')
# NOTE(ralonsoh): 'rate' should be modified between iterations. The
@@ -81,11 +71,6 @@ class PktgenTrafficGen(vnf_base.GenericTrafficGen,
self._traffic_profile.rate(self._rate)
time.sleep(4)
self._traffic_profile.stop()
- self._mq_producer.tg_method_iteration(1, 1, {})
-
- def runner_method_stop_iteration(self, ctxt, **kwargs): # pragma: no cover
- # pragma: no cover
- LOG.debug('Stop method')
@staticmethod
def _get_lua_node_port(service_ports):
diff --git a/yardstick/network_services/vnf_generic/vnf/tg_prox.py b/yardstick/network_services/vnf_generic/vnf/tg_prox.py
index d12c42ec8..65b7bac10 100644
--- a/yardstick/network_services/vnf_generic/vnf/tg_prox.py
+++ b/yardstick/network_services/vnf_generic/vnf/tg_prox.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2017 Intel Corporation
+# Copyright (c) 2017-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -29,13 +29,13 @@ class ProxTrafficGen(SampleVNFTrafficGen):
LUA_PARAMETER_NAME = "gen"
WAIT_TIME = 1
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
+ def __init__(self, name, vnfd, setup_env_helper_type=None,
resource_helper_type=None):
vnfd_cpy = copy.deepcopy(vnfd)
- super(ProxTrafficGen, self).__init__(name, vnfd_cpy, task_id)
+ super(ProxTrafficGen, self).__init__(name, vnfd_cpy)
self._vnf_wrapper = ProxApproxVnf(
- name, vnfd, task_id, setup_env_helper_type, resource_helper_type)
+ name, vnfd, setup_env_helper_type, resource_helper_type)
self.bin_path = get_nsb_option('bin_path', '')
self.name = self._vnf_wrapper.name
self.ssh_helper = self._vnf_wrapper.ssh_helper
diff --git a/yardstick/network_services/vnf_generic/vnf/tg_rfc2544_ixia.py b/yardstick/network_services/vnf_generic/vnf/tg_rfc2544_ixia.py
index 1d37f8f6f..5d69fc8c8 100644
--- a/yardstick/network_services/vnf_generic/vnf/tg_rfc2544_ixia.py
+++ b/yardstick/network_services/vnf_generic/vnf/tg_rfc2544_ixia.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -15,8 +15,11 @@
import ipaddress
import logging
import six
+import collections
+from six import moves
from yardstick.common import utils
+from yardstick.common import exceptions
from yardstick.network_services.libs.ixia_libs.ixnet import ixnet_api
from yardstick.network_services.vnf_generic.vnf.sample_vnf import SampleVNFTrafficGen
from yardstick.network_services.vnf_generic.vnf.sample_vnf import ClientResourceHelper
@@ -27,10 +30,12 @@ LOG = logging.getLogger(__name__)
WAIT_AFTER_CFG_LOAD = 10
WAIT_FOR_TRAFFIC = 30
-WAIT_PROTOCOLS_STARTED = 360
+WAIT_PROTOCOLS_STARTED = 420
class IxiaBasicScenario(object):
+ """Ixia Basic scenario for flow from port to port"""
+
def __init__(self, client, context_cfg, ixia_cfg):
self.client = client
@@ -43,21 +48,142 @@ class IxiaBasicScenario(object):
def apply_config(self):
pass
+ def run_protocols(self):
+ pass
+
+ def stop_protocols(self):
+ pass
+
def create_traffic_model(self, traffic_profile=None):
# pylint: disable=unused-argument
vports = self.client.get_vports()
self._uplink_vports = vports[::2]
self._downlink_vports = vports[1::2]
self.client.create_traffic_model(self._uplink_vports,
- self._downlink_vports)
+ self._downlink_vports, traffic_profile)
- def run_protocols(self):
+ def _get_stats(self):
+ return self.client.get_statistics()
+
+ def generate_samples(self, resource_helper, ports, duration):
+ stats = self._get_stats()
+
+ samples = {}
+ # this is not DPDK port num, but this is whatever number we gave
+ # when we selected ports and programmed the profile
+ for port_num in ports:
+ try:
+ # reverse lookup port name from port_num so the stats dict is descriptive
+ intf = resource_helper.vnfd_helper.find_interface_by_port(port_num)
+ port_name = intf['name']
+ avg_latency = stats['Store-Forward_Avg_latency_ns'][port_num]
+ min_latency = stats['Store-Forward_Min_latency_ns'][port_num]
+ max_latency = stats['Store-Forward_Max_latency_ns'][port_num]
+ samples[port_name] = {
+ 'rx_throughput_kps': float(stats['Rx_Rate_Kbps'][port_num]),
+ 'tx_throughput_kps': float(stats['Tx_Rate_Kbps'][port_num]),
+ 'rx_throughput_mbps': float(stats['Rx_Rate_Mbps'][port_num]),
+ 'tx_throughput_mbps': float(stats['Tx_Rate_Mbps'][port_num]),
+ 'RxThroughputBps': float(stats['Bytes_Rx'][port_num]) / duration,
+ 'TxThroughputBps': float(stats['Bytes_Tx'][port_num]) / duration,
+ 'in_packets': int(stats['Valid_Frames_Rx'][port_num]),
+ 'out_packets': int(stats['Frames_Tx'][port_num]),
+ 'in_bytes': int(stats['Bytes_Rx'][port_num]),
+ 'out_bytes': int(stats['Bytes_Tx'][port_num]),
+ 'RxThroughput': float(stats['Valid_Frames_Rx'][port_num]) / duration,
+ 'TxThroughput': float(stats['Frames_Tx'][port_num]) / duration,
+ 'Store-Forward_Avg_latency_ns': utils.safe_cast(avg_latency, int, 0),
+ 'Store-Forward_Min_latency_ns': utils.safe_cast(min_latency, int, 0),
+ 'Store-Forward_Max_latency_ns': utils.safe_cast(max_latency, int, 0)
+ }
+ except IndexError:
+ pass
+
+ return samples
+
+ def update_tracking_options(self):
pass
- def stop_protocols(self):
+ def get_tc_rfc2544_options(self):
pass
+class IxiaL3Scenario(IxiaBasicScenario):
+ """Ixia scenario for L3 flow between static ip's"""
+
+ def _add_static_ips(self):
+ vports = self.client.get_vports()
+ uplink_intf_vport = [(self.client.get_static_interface(vport), vport)
+ for vport in vports[::2]]
+ downlink_intf_vport = [(self.client.get_static_interface(vport), vport)
+ for vport in vports[1::2]]
+
+ for index in range(len(uplink_intf_vport)):
+ intf, vport = uplink_intf_vport[index]
+ try:
+ iprange = self.ixia_cfg['flow'].get('src_ip')[index]
+ start_ip = utils.get_ip_range_start(iprange)
+ count = utils.get_ip_range_count(iprange)
+ self.client.add_static_ipv4(intf, vport, start_ip, count, '32')
+ except IndexError:
+ raise exceptions.IncorrectFlowOption(
+ option="src_ip", link="uplink_{}".format(index))
+
+ intf, vport = downlink_intf_vport[index]
+ try:
+ iprange = self.ixia_cfg['flow'].get('dst_ip')[index]
+ start_ip = utils.get_ip_range_start(iprange)
+ count = utils.get_ip_range_count(iprange)
+ self.client.add_static_ipv4(intf, vport, start_ip, count, '32')
+ except IndexError:
+ raise exceptions.IncorrectFlowOption(
+ option="dst_ip", link="downlink_{}".format(index))
+
+ def _add_interfaces(self):
+ vports = self.client.get_vports()
+ uplink_vports = (vport for vport in vports[::2])
+ downlink_vports = (vport for vport in vports[1::2])
+
+ ix_node = next(node for _, node in self.context_cfg['nodes'].items()
+ if node['role'] == 'IxNet')
+
+ for intf in ix_node['interfaces'].values():
+ ip = intf.get('local_ip')
+ mac = intf.get('local_mac')
+ gateway = None
+ try:
+ gateway = next(route.get('gateway')
+ for route in ix_node.get('routing_table')
+ if route.get('if') == intf.get('ifname'))
+ except StopIteration:
+ LOG.debug("Gateway not provided")
+
+ if 'uplink' in intf.get('vld_id'):
+ self.client.add_interface(next(uplink_vports),
+ ip, mac, gateway)
+ else:
+ self.client.add_interface(next(downlink_vports),
+ ip, mac, gateway)
+
+ def apply_config(self):
+ self._add_interfaces()
+ self._add_static_ips()
+
+ def create_traffic_model(self, traffic_profile=None):
+ # pylint: disable=unused-argument
+ vports = self.client.get_vports()
+ self._uplink_vports = vports[::2]
+ self._downlink_vports = vports[1::2]
+
+ uplink_endpoints = [port + '/protocols/static'
+ for port in self._uplink_vports]
+ downlink_endpoints = [port + '/protocols/static'
+ for port in self._downlink_vports]
+
+ self.client.create_ipv4_traffic_model(uplink_endpoints,
+ downlink_endpoints)
+
+
class IxiaPppoeClientScenario(object):
def __init__(self, client, context_cfg, ixia_cfg):
@@ -87,8 +213,12 @@ class IxiaPppoeClientScenario(object):
traffic_profile.full_profile)
endpoints_obj_pairs = \
self._get_endpoints_src_dst_obj_pairs(endpoints_id_pairs)
- uplink_endpoints = endpoints_obj_pairs[::2]
- downlink_endpoints = endpoints_obj_pairs[1::2]
+ if endpoints_obj_pairs:
+ uplink_endpoints = endpoints_obj_pairs[::2]
+ downlink_endpoints = endpoints_obj_pairs[1::2]
+ else:
+ uplink_endpoints = self._access_topologies
+ downlink_endpoints = self._core_topologies
self.client.create_ipv4_traffic_model(uplink_endpoints,
downlink_endpoints)
@@ -181,18 +311,14 @@ class IxiaPppoeClientScenario(object):
device groups pairs between which flow groups will be created:
1. In case uplink/downlink flows in traffic profile doesn't have
- specified 'port' key, flows will be created between each device
- group on access port and device group on corresponding core port.
+ specified 'port' key, flows will be created between topologies
+ on corresponding access and core port.
E.g.:
- Device groups created on access port xe0: dg1, dg2, dg3
- Device groups created on core port xe1: dg4
+ Access topology on xe0: topology1
+ Core topology on xe1: topology2
Flows will be created between:
- dg1 -> dg4
- dg4 -> dg1
- dg2 -> dg4
- dg4 -> dg2
- dg3 -> dg4
- dg4 -> dg3
+ topology1 -> topology2
+ topology2 -> topology1
2. In case uplink/downlink flows in traffic profile have specified
'port' key, flows will be created between device groups on this
@@ -253,13 +379,6 @@ class IxiaPppoeClientScenario(object):
[endpoint_obj_pairs.extend([up, down])
for up, down in zip(uplink_dev_groups, downlink_dev_groups)]
- if not endpoint_obj_pairs:
- for up, down in zip(uplink_ports, downlink_ports):
- uplink_dev_groups = port_to_dev_group_mapping[up]
- downlink_dev_groups = \
- port_to_dev_group_mapping[down] * len(uplink_dev_groups)
- [endpoint_obj_pairs.extend(list(i))
- for i in zip(uplink_dev_groups, downlink_dev_groups)]
return endpoint_obj_pairs
def _fill_ixia_config(self):
@@ -353,6 +472,172 @@ class IxiaPppoeClientScenario(object):
bgp_type=ipv4["bgp"].get("bgp_type"))
self.protocols.append(bgp_peer_obj)
+ def update_tracking_options(self):
+ priority_map = {
+ 'raw': 'ipv4Raw0',
+ 'tos': {'precedence': 'ipv4Precedence0'},
+ 'dscp': {'defaultPHB': 'ipv4DefaultPhb0',
+ 'selectorPHB': 'ipv4ClassSelectorPhb0',
+ 'assuredPHB': 'ipv4AssuredForwardingPhb0',
+ 'expeditedPHB': 'ipv4ExpeditedForwardingPhb0'}
+ }
+
+ prio_trackby_key = 'ipv4Precedence0'
+
+ try:
+ priority = list(self._ixia_cfg['priority'])[0]
+ if priority == 'raw':
+ prio_trackby_key = priority_map[priority]
+ elif priority in ['tos', 'dscp']:
+ priority_type = list(self._ixia_cfg['priority'][priority])[0]
+ prio_trackby_key = priority_map[priority][priority_type]
+ except KeyError:
+ pass
+
+ tracking_options = ['flowGroup0', 'vlanVlanId0', prio_trackby_key]
+ self.client.set_flow_tracking(tracking_options)
+
+ def get_tc_rfc2544_options(self):
+ return self._ixia_cfg.get('rfc2544')
+
+ def _get_stats(self):
+ return self.client.get_pppoe_scenario_statistics()
+
+ @staticmethod
+ def get_flow_id_data(stats, flow_id, key):
+ result = [float(flow.get(key)) for flow in stats if flow['id'] == flow_id]
+ return sum(result) / len(result)
+
+ def get_priority_flows_stats(self, samples, duration):
+ results = {}
+ priorities = set([flow['IP_Priority'] for flow in samples])
+ for priority in priorities:
+ tx_frames = sum(
+ [int(flow['Tx_Frames']) for flow in samples
+ if flow['IP_Priority'] == priority])
+ rx_frames = sum(
+ [int(flow['Rx_Frames']) for flow in samples
+ if flow['IP_Priority'] == priority])
+ prio_flows_num = len([flow for flow in samples
+ if flow['IP_Priority'] == priority])
+ avg_latency_ns = sum(
+ [int(flow['Store-Forward_Avg_latency_ns']) for flow in samples
+ if flow['IP_Priority'] == priority]) / prio_flows_num
+ min_latency_ns = sum(
+ [int(flow['Store-Forward_Min_latency_ns']) for flow in samples
+ if flow['IP_Priority'] == priority]) / prio_flows_num
+ max_latency_ns = sum(
+ [int(flow['Store-Forward_Max_latency_ns']) for flow in samples
+ if flow['IP_Priority'] == priority]) / prio_flows_num
+ tx_throughput = float(tx_frames) / duration
+ rx_throughput = float(rx_frames) / duration
+ results[priority] = {
+ 'in_packets': rx_frames,
+ 'out_packets': tx_frames,
+ 'RxThroughput': round(rx_throughput, 3),
+ 'TxThroughput': round(tx_throughput, 3),
+ 'avg_latency_ns': utils.safe_cast(avg_latency_ns, int, 0),
+ 'min_latency_ns': utils.safe_cast(min_latency_ns, int, 0),
+ 'max_latency_ns': utils.safe_cast(max_latency_ns, int, 0)
+ }
+ return results
+
+ def generate_samples(self, resource_helper, ports, duration):
+
+ stats = self._get_stats()
+ samples = {}
+ ports_stats = stats['port_statistics']
+ flows_stats = stats['flow_statistic']
+ pppoe_subs_per_port = stats['pppox_client_per_port']
+
+ # Get sorted list of ixia ports names
+ ixia_port_names = sorted([data['port_name'] for data in ports_stats])
+
+ # Set 'port_id' key for ports stats items
+ for item in ports_stats:
+ port_id = item.pop('port_name').split('-')[-1].strip()
+ item['port_id'] = int(port_id)
+
+ # Set 'id' key for flows stats items
+ for item in flows_stats:
+ flow_id = item.pop('Flow_Group').split('-')[1].strip()
+ item['id'] = int(flow_id)
+
+ # Set 'port_id' key for pppoe subs per port stats
+ for item in pppoe_subs_per_port:
+ port_id = item.pop('subs_port').split('-')[-1].strip()
+ item['port_id'] = int(port_id)
+
+ # Map traffic flows to ports
+ port_flow_map = collections.defaultdict(set)
+ for item in flows_stats:
+ tx_port = item.pop('Tx_Port')
+ tx_port_index = ixia_port_names.index(tx_port)
+ port_flow_map[tx_port_index].update([item['id']])
+
+ # Sort ports stats
+ ports_stats = sorted(ports_stats, key=lambda k: k['port_id'])
+
+ # Get priority flows stats
+ prio_flows_stats = self.get_priority_flows_stats(flows_stats, duration)
+ samples['priority_stats'] = prio_flows_stats
+
+ # this is not DPDK port num, but this is whatever number we gave
+ # when we selected ports and programmed the profile
+ for port_num in ports:
+ try:
+ # reverse lookup port name from port_num so the stats dict is descriptive
+ intf = resource_helper.vnfd_helper.find_interface_by_port(port_num)
+ port_name = intf['name']
+ port_id = ports_stats[port_num]['port_id']
+ port_subs_stats = \
+ [port_data for port_data in pppoe_subs_per_port
+ if port_data.get('port_id') == port_id]
+
+ avg_latency = \
+ sum([float(self.get_flow_id_data(
+ flows_stats, flow, 'Store-Forward_Avg_latency_ns'))
+ for flow in port_flow_map[port_num]]) / len(port_flow_map[port_num])
+ min_latency = \
+ sum([float(self.get_flow_id_data(
+ flows_stats, flow, 'Store-Forward_Min_latency_ns'))
+ for flow in port_flow_map[port_num]]) / len(port_flow_map[port_num])
+ max_latency = \
+ sum([float(self.get_flow_id_data(
+ flows_stats, flow, 'Store-Forward_Max_latency_ns'))
+ for flow in port_flow_map[port_num]]) / len(port_flow_map[port_num])
+
+ samples[port_name] = {
+ 'rx_throughput_kps': float(ports_stats[port_num]['Rx_Rate_Kbps']),
+ 'tx_throughput_kps': float(ports_stats[port_num]['Tx_Rate_Kbps']),
+ 'rx_throughput_mbps': float(ports_stats[port_num]['Rx_Rate_Mbps']),
+ 'tx_throughput_mbps': float(ports_stats[port_num]['Tx_Rate_Mbps']),
+ 'RxThroughputBps': float(ports_stats[port_num]['Bytes_Rx']) / duration,
+ 'TxThroughputBps': float(ports_stats[port_num]['Bytes_Tx']) / duration,
+ 'in_packets': int(ports_stats[port_num]['Valid_Frames_Rx']),
+ 'out_packets': int(ports_stats[port_num]['Frames_Tx']),
+ 'in_bytes': int(ports_stats[port_num]['Bytes_Rx']),
+ 'out_bytes': int(ports_stats[port_num]['Bytes_Tx']),
+ 'RxThroughput': float(ports_stats[port_num]['Valid_Frames_Rx']) / duration,
+ 'TxThroughput': float(ports_stats[port_num]['Frames_Tx']) / duration,
+ 'Store-Forward_Avg_latency_ns': utils.safe_cast(avg_latency, int, 0),
+ 'Store-Forward_Min_latency_ns': utils.safe_cast(min_latency, int, 0),
+ 'Store-Forward_Max_latency_ns': utils.safe_cast(max_latency, int, 0)
+ }
+
+ if port_subs_stats:
+ samples[port_name].update(
+ {'sessions_up': int(port_subs_stats[0]['Sessions_Up']),
+ 'sessions_down': int(port_subs_stats[0]['Sessions_Down']),
+ 'sessions_not_started': int(port_subs_stats[0]['Sessions_Not_Started']),
+ 'sessions_total': int(port_subs_stats[0]['Sessions_Total'])}
+ )
+
+ except IndexError:
+ pass
+
+ return samples
+
class IxiaRfc2544Helper(Rfc2544ResourceHelper):
@@ -370,6 +655,7 @@ class IxiaResourceHelper(ClientResourceHelper):
self._ixia_scenarios = {
"IxiaBasic": IxiaBasicScenario,
+ "IxiaL3": IxiaL3Scenario,
"IxiaPppoeClient": IxiaPppoeClientScenario,
}
@@ -388,9 +674,6 @@ class IxiaResourceHelper(ClientResourceHelper):
def _connect(self, client=None):
self.client.connect(self.vnfd_helper)
- def get_stats(self, *args, **kwargs):
- return self.client.get_statistics()
-
def setup(self):
super(IxiaResourceHelper, self).setup()
self._init_ix_scenario()
@@ -400,36 +683,7 @@ class IxiaResourceHelper(ClientResourceHelper):
self._terminated.value = 1
def generate_samples(self, ports, duration):
- stats = self.get_stats()
-
- samples = {}
- # this is not DPDK port num, but this is whatever number we gave
- # when we selected ports and programmed the profile
- for port_num in ports:
- try:
- # reverse lookup port name from port_num so the stats dict is descriptive
- intf = self.vnfd_helper.find_interface_by_port(port_num)
- port_name = intf['name']
- avg_latency = stats['Store-Forward_Avg_latency_ns'][port_num]
- min_latency = stats['Store-Forward_Min_latency_ns'][port_num]
- max_latency = stats['Store-Forward_Max_latency_ns'][port_num]
- samples[port_name] = {
- 'rx_throughput_kps': float(stats['Rx_Rate_Kbps'][port_num]),
- 'tx_throughput_kps': float(stats['Tx_Rate_Kbps'][port_num]),
- 'rx_throughput_mbps': float(stats['Rx_Rate_Mbps'][port_num]),
- 'tx_throughput_mbps': float(stats['Tx_Rate_Mbps'][port_num]),
- 'in_packets': int(stats['Valid_Frames_Rx'][port_num]),
- 'out_packets': int(stats['Frames_Tx'][port_num]),
- 'RxThroughput': float(stats['Valid_Frames_Rx'][port_num]) / duration,
- 'TxThroughput': float(stats['Frames_Tx'][port_num]) / duration,
- 'Store-Forward_Avg_latency_ns': utils.safe_cast(avg_latency, int, 0),
- 'Store-Forward_Min_latency_ns': utils.safe_cast(min_latency, int, 0),
- 'Store-Forward_Max_latency_ns': utils.safe_cast(max_latency, int, 0)
- }
- except IndexError:
- pass
-
- return samples
+ return self._ix_scenario.generate_samples(self, ports, duration)
def _init_ix_scenario(self):
ixia_config = self.scenario_helper.scenario_cfg.get('ixia_config', 'IxiaBasic')
@@ -450,13 +704,17 @@ class IxiaResourceHelper(ClientResourceHelper):
self._ix_scenario.apply_config()
self._ix_scenario.create_traffic_model(traffic_profile)
- def run_traffic(self, traffic_profile, *args):
+ def update_tracking_options(self):
+ self._ix_scenario.update_tracking_options()
+
+ def run_traffic(self, traffic_profile):
if self._terminated.value:
return
min_tol = self.rfc_helper.tolerance_low
max_tol = self.rfc_helper.tolerance_high
precision = self.rfc_helper.tolerance_precision
+ resolution = self.rfc_helper.resolution
default = "00:00:00:00:00:00"
self._build_ports()
@@ -477,17 +735,19 @@ class IxiaResourceHelper(ClientResourceHelper):
try:
while not self._terminated.value:
- first_run = traffic_profile.execute_traffic(
- self, self.client, mac)
+ first_run = traffic_profile.execute_traffic(self, self.client,
+ mac)
self.client_started.value = 1
# pylint: disable=unnecessary-lambda
utils.wait_until_true(lambda: self.client.is_traffic_stopped(),
timeout=traffic_profile.config.duration * 2)
+ rfc2544_opts = self._ix_scenario.get_tc_rfc2544_options()
samples = self.generate_samples(traffic_profile.ports,
traffic_profile.config.duration)
completed, samples = traffic_profile.get_drop_percentage(
- samples, min_tol, max_tol, precision, first_run=first_run)
+ samples, min_tol, max_tol, precision, resolution,
+ first_run=first_run, tc_rfc2544_opts=rfc2544_opts)
self._queue.put(samples)
if completed:
@@ -497,23 +757,93 @@ class IxiaResourceHelper(ClientResourceHelper):
LOG.exception('Run Traffic terminated')
self._ix_scenario.stop_protocols()
+ self.client_started.value = 0
self._terminated.value = 1
- def collect_kpi(self):
- self.rfc_helper.iteration.value += 1
- return super(IxiaResourceHelper, self).collect_kpi()
+ def run_test(self, traffic_profile, tasks_queue, results_queue, *args): # pragma: no cover
+ LOG.info("Ixia resource_helper run_test")
+ if self._terminated.value:
+ return
+
+ min_tol = self.rfc_helper.tolerance_low
+ max_tol = self.rfc_helper.tolerance_high
+ precision = self.rfc_helper.tolerance_precision
+ resolution = self.rfc_helper.resolution
+ default = "00:00:00:00:00:00"
+
+ self._build_ports()
+ traffic_profile.update_traffic_profile(self)
+ self._initialize_client(traffic_profile)
+
+ mac = {}
+ for port_name in self.vnfd_helper.port_pairs.all_ports:
+ intf = self.vnfd_helper.find_interface(name=port_name)
+ virt_intf = intf["virtual-interface"]
+ # we only know static traffic id by reading the json
+ # this is used by _get_ixia_trafficrofile
+ port_num = self.vnfd_helper.port_num(intf)
+ mac["src_mac_{}".format(port_num)] = virt_intf.get("local_mac", default)
+ mac["dst_mac_{}".format(port_num)] = virt_intf.get("dst_mac", default)
+
+ self._ix_scenario.run_protocols()
+
+ try:
+ completed = False
+ self.rfc_helper.iteration.value = 0
+ self.client_started.value = 1
+ while completed is False and not self._terminated.value:
+ LOG.info("Wait for task ...")
+
+ try:
+ task = tasks_queue.get(True, 5)
+ except moves.queue.Empty:
+ continue
+ else:
+ if task != 'RUN_TRAFFIC':
+ continue
+
+ self.rfc_helper.iteration.value += 1
+ LOG.info("Got %s task, start iteration %d", task,
+ self.rfc_helper.iteration.value)
+ first_run = traffic_profile.execute_traffic(self, self.client,
+ mac)
+ # pylint: disable=unnecessary-lambda
+ utils.wait_until_true(lambda: self.client.is_traffic_stopped(),
+ timeout=traffic_profile.config.duration * 2)
+ samples = self.generate_samples(traffic_profile.ports,
+ traffic_profile.config.duration)
+
+ completed, samples = traffic_profile.get_drop_percentage(
+ samples, min_tol, max_tol, precision, resolution,
+ first_run=first_run)
+ samples['Iteration'] = self.rfc_helper.iteration.value
+ self._queue.put(samples)
+
+ if completed:
+ LOG.debug("IxiaResourceHelper::run_test - test completed")
+ results_queue.put('COMPLETE')
+ else:
+ results_queue.put('CONTINUE')
+ tasks_queue.task_done()
+
+ except Exception: # pylint: disable=broad-except
+ LOG.exception('Run Traffic terminated')
+
+ self._ix_scenario.stop_protocols()
+ self.client_started.value = 0
+ LOG.debug("IxiaResourceHelper::run_test done")
class IxiaTrafficGen(SampleVNFTrafficGen):
APP_NAME = 'Ixia'
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
- resource_helper_type=None):
+ def __init__(self, name, vnfd, setup_env_helper_type=None, resource_helper_type=None):
if resource_helper_type is None:
resource_helper_type = IxiaResourceHelper
- super(IxiaTrafficGen, self).__init__(
- name, vnfd, task_id, setup_env_helper_type, resource_helper_type)
+
+ super(IxiaTrafficGen, self).__init__(name, vnfd, setup_env_helper_type,
+ resource_helper_type)
self._ixia_traffic_gen = None
self.ixia_file_name = ''
self.vnf_port_pairs = []
diff --git a/yardstick/network_services/vnf_generic/vnf/tg_rfc2544_trex.py b/yardstick/network_services/vnf_generic/vnf/tg_rfc2544_trex.py
index 7ecb12478..a9c0222ac 100644
--- a/yardstick/network_services/vnf_generic/vnf/tg_rfc2544_trex.py
+++ b/yardstick/network_services/vnf_generic/vnf/tg_rfc2544_trex.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -15,12 +15,14 @@
import logging
import time
+from six import moves
from yardstick.common import utils
from yardstick.network_services.vnf_generic.vnf import sample_vnf
from yardstick.network_services.vnf_generic.vnf import tg_trex
+from trex_stl_lib.trex_stl_exceptions import STLError
-LOGGING = logging.getLogger(__name__)
+LOG = logging.getLogger(__name__)
class TrexRfcResourceHelper(tg_trex.TrexResourceHelper):
@@ -48,7 +50,8 @@ class TrexRfcResourceHelper(tg_trex.TrexResourceHelper):
completed, output = traffic_profile.get_drop_percentage(
samples, self.rfc2544_helper.tolerance_low,
self.rfc2544_helper.tolerance_high,
- self.rfc2544_helper.correlated_traffic)
+ self.rfc2544_helper.correlated_traffic,
+ self.rfc2544_helper.resolution)
self._queue.put(output)
return completed
@@ -58,6 +61,56 @@ class TrexRfcResourceHelper(tg_trex.TrexResourceHelper):
def clear_client_stats(self, ports):
self.client.clear_stats(ports=ports)
+ def run_test(self, traffic_profile, tasks_queue, results_queue, *args): # pragma: no cover
+ LOG.debug("Trex resource_helper run_test")
+ if self._terminated.value:
+ return
+ # if we don't do this we can hang waiting for the queue to drain
+ # have to do this in the subprocess
+ self._queue.cancel_join_thread()
+ try:
+ self._build_ports()
+ self.client = self._connect()
+ self.client.reset(ports=self.all_ports)
+ self.client.remove_all_streams(self.all_ports) # remove all streams
+ traffic_profile.register_generator(self)
+
+ completed = False
+ self.rfc2544_helper.iteration.value = 0
+ self.client_started.value = 1
+ while completed is False and not self._terminated.value:
+ LOG.debug("Wait for task ...")
+ try:
+ task = tasks_queue.get(True, 5)
+ except moves.queue.Empty:
+ LOG.debug("Wait for task timeout, continue waiting...")
+ continue
+ else:
+ if task != 'RUN_TRAFFIC':
+ continue
+ self.rfc2544_helper.iteration.value += 1
+ LOG.info("Got %s task, start iteration %d", task,
+ self.rfc2544_helper.iteration.value)
+ completed = self._run_traffic_once(traffic_profile)
+ if completed:
+ LOG.debug("%s::run_test - test completed",
+ self.__class__.__name__)
+ results_queue.put('COMPLETE')
+ else:
+ results_queue.put('CONTINUE')
+ tasks_queue.task_done()
+
+ self.client.stop(self.all_ports)
+ self.client.disconnect()
+ self._terminated.value = 0
+ except STLError:
+ if self._terminated.value:
+ LOG.debug("traffic generator is stopped")
+ return # return if trex/tg server is stopped.
+ raise
+
+ self.client_started.value = 0
+ LOG.debug("%s::run_test done", self.__class__.__name__)
class TrexTrafficGenRFC(tg_trex.TrexTrafficGen):
"""
@@ -65,9 +118,9 @@ class TrexTrafficGenRFC(tg_trex.TrexTrafficGen):
traffic for rfc2544 testcase.
"""
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
- resource_helper_type=None):
+ def __init__(self, name, vnfd, setup_env_helper_type=None, resource_helper_type=None):
if resource_helper_type is None:
resource_helper_type = TrexRfcResourceHelper
- super(TrexTrafficGenRFC, self).__init__(
- name, vnfd, task_id, setup_env_helper_type, resource_helper_type)
+
+ super(TrexTrafficGenRFC, self).__init__(name, vnfd, setup_env_helper_type,
+ resource_helper_type)
diff --git a/yardstick/network_services/vnf_generic/vnf/tg_trex.py b/yardstick/network_services/vnf_generic/vnf/tg_trex.py
index 4296da84c..0cb66a714 100644
--- a/yardstick/network_services/vnf_generic/vnf/tg_trex.py
+++ b/yardstick/network_services/vnf_generic/vnf/tg_trex.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -179,6 +179,8 @@ class TrexResourceHelper(ClientResourceHelper):
'tx_throughput_bps': float(port_stats.get('tx_bps', 0.0)),
'in_packets': int(port_stats.get('ipackets', 0)),
'out_packets': int(port_stats.get('opackets', 0)),
+ 'in_bytes': int(port_stats.get('ibytes', 0)),
+ 'out_bytes': int(port_stats.get('obytes', 0)),
'timestamp': timestamp
}
@@ -200,14 +202,15 @@ class TrexTrafficGen(SampleVNFTrafficGen):
APP_NAME = 'TRex'
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
- resource_helper_type=None):
+ def __init__(self, name, vnfd, setup_env_helper_type=None, resource_helper_type=None):
if resource_helper_type is None:
resource_helper_type = TrexResourceHelper
+
if setup_env_helper_type is None:
setup_env_helper_type = TrexDpdkVnfSetupEnvHelper
- super(TrexTrafficGen, self).__init__(
- name, vnfd, task_id, setup_env_helper_type, resource_helper_type)
+
+ super(TrexTrafficGen, self).__init__(name, vnfd, setup_env_helper_type,
+ resource_helper_type)
def _check_status(self):
return self.resource_helper.check_status()
diff --git a/yardstick/network_services/vnf_generic/vnf/udp_replay.py b/yardstick/network_services/vnf_generic/vnf/udp_replay.py
index e3fde1a79..3f9994486 100644
--- a/yardstick/network_services/vnf_generic/vnf/udp_replay.py
+++ b/yardstick/network_services/vnf_generic/vnf/udp_replay.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -60,14 +60,15 @@ class UdpReplayApproxVnf(SampleVNF):
PIPELINE_COMMAND = REPLAY_PIPELINE_COMMAND
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
- resource_helper_type=None):
+ def __init__(self, name, vnfd, setup_env_helper_type=None, resource_helper_type=None):
if resource_helper_type is None:
resource_helper_type = UdpReplayResourceHelper
+
if setup_env_helper_type is None:
setup_env_helper_type = UdpReplaySetupEnvHelper
- super(UdpReplayApproxVnf, self).__init__(
- name, vnfd, task_id, setup_env_helper_type, resource_helper_type)
+
+ super(UdpReplayApproxVnf, self).__init__(name, vnfd, setup_env_helper_type,
+ resource_helper_type)
def _build_pipeline_kwargs(self):
ports = self.vnfd_helper.port_pairs.all_ports
diff --git a/yardstick/network_services/vnf_generic/vnf/vfw_vnf.py b/yardstick/network_services/vnf_generic/vnf/vfw_vnf.py
index a1523dee3..743f2d4bb 100644
--- a/yardstick/network_services/vnf_generic/vnf/vfw_vnf.py
+++ b/yardstick/network_services/vnf_generic/vnf/vfw_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -52,9 +52,12 @@ class FWApproxVnf(SampleVNF):
'packets_dropped': 3,
}
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
- resource_helper_type=None):
+ def __init__(self, name, vnfd, setup_env_helper_type=None, resource_helper_type=None):
if setup_env_helper_type is None:
setup_env_helper_type = FWApproxSetupEnvHelper
- super(FWApproxVnf, self).__init__(
- name, vnfd, task_id, setup_env_helper_type, resource_helper_type)
+
+ super(FWApproxVnf, self).__init__(name, vnfd, setup_env_helper_type, resource_helper_type)
+
+ def wait_for_instantiate(self):
+ """Wait for VNF to initialize"""
+ self.wait_for_initialize()
diff --git a/yardstick/network_services/vnf_generic/vnf/vpe_vnf.py b/yardstick/network_services/vnf_generic/vnf/vpe_vnf.py
index dd3221386..322ecd016 100644
--- a/yardstick/network_services/vnf_generic/vnf/vpe_vnf.py
+++ b/yardstick/network_services/vnf_generic/vnf/vpe_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -158,12 +158,11 @@ class VpeApproxVnf(SampleVNF):
COLLECT_KPI = VPE_COLLECT_KPI
WAIT_TIME = 20
- def __init__(self, name, vnfd, task_id, setup_env_helper_type=None,
- resource_helper_type=None):
+ def __init__(self, name, vnfd, setup_env_helper_type=None, resource_helper_type=None):
if setup_env_helper_type is None:
setup_env_helper_type = VpeApproxSetupEnvHelper
- super(VpeApproxVnf, self).__init__(
- name, vnfd, task_id, setup_env_helper_type, resource_helper_type)
+
+ super(VpeApproxVnf, self).__init__(name, vnfd, setup_env_helper_type, resource_helper_type)
def get_stats(self, *args, **kwargs):
raise NotImplementedError
diff --git a/yardstick/ssh.py b/yardstick/ssh.py
index 8bdc32c7c..6bc6010f7 100644
--- a/yardstick/ssh.py
+++ b/yardstick/ssh.py
@@ -80,6 +80,7 @@ from yardstick.common import exceptions
from yardstick.common.utils import try_int, NON_NONE_DEFAULT, make_dict_from_map
from yardstick.network_services.utils import provision_tool
+LOG = logging.getLogger(__name__)
def convert_key_to_str(key):
if not isinstance(key, (paramiko.RSAKey, paramiko.DSSKey)):
@@ -89,14 +90,6 @@ def convert_key_to_str(key):
return k.getvalue()
-# class SSHError(Exception):
-# pass
-#
-#
-# class SSHTimeout(SSHError):
-# pass
-
-
class SSH(object):
"""Represent ssh connection."""
@@ -345,6 +338,7 @@ class SSH(object):
details = fmt % {"cmd": cmd, "status": exit_status}
if stderr_data:
details += " Last stderr data: '%s'." % stderr_data
+ LOG.critical("PROX ERROR: %s", details)
raise exceptions.SSHError(error_msg=details)
return exit_status
@@ -456,6 +450,86 @@ class SSH(object):
with client.open_sftp() as sftp:
sftp.getfo(remotepath, file_obj)
+ def interactive_terminal_open(self, time_out=45):
+ """Open interactive terminal on a SSH channel.
+
+ :param time_out: Timeout in seconds.
+ :returns: SSH channel with opened terminal.
+
+ .. warning:: Interruptingcow is used here, and it uses
+ signal(SIGALRM) to let the operating system interrupt program
+ execution. This has the following limitations: Python signal
+ handlers only apply to the main thread, so you cannot use this
+ from other threads. You must not use this in a program that
+ uses SIGALRM itself (this includes certain profilers)
+ """
+ chan = self._get_client().get_transport().open_session()
+ chan.get_pty()
+ chan.invoke_shell()
+ chan.settimeout(int(time_out))
+ chan.set_combine_stderr(True)
+
+ buf = ''
+ while not buf.endswith((":~# ", ":~$ ", "~]$ ", "~]# ")):
+ try:
+ chunk = chan.recv(10 * 1024 * 1024)
+ if not chunk:
+ break
+ buf += chunk
+ if chan.exit_status_ready():
+ self.log.error('Channel exit status ready')
+ break
+ except socket.timeout:
+ raise exceptions.SSHTimeout(error_msg='Socket timeout: %s' % buf)
+ return chan
+
+ def interactive_terminal_exec_command(self, chan, cmd, prompt):
+ """Execute command on interactive terminal.
+
+ interactive_terminal_open() method has to be called first!
+
+ :param chan: SSH channel with opened terminal.
+ :param cmd: Command to be executed.
+ :param prompt: Command prompt, sequence of characters used to
+ indicate readiness to accept commands.
+ :returns: Command output.
+
+ .. warning:: Interruptingcow is used here, and it uses
+ signal(SIGALRM) to let the operating system interrupt program
+ execution. This has the following limitations: Python signal
+ handlers only apply to the main thread, so you cannot use this
+ from other threads. You must not use this in a program that
+ uses SIGALRM itself (this includes certain profilers)
+ """
+ chan.sendall('{c}\n'.format(c=cmd))
+ buf = ''
+ while not buf.endswith(prompt):
+ try:
+ chunk = chan.recv(10 * 1024 * 1024)
+ if not chunk:
+ break
+ buf += chunk
+ if chan.exit_status_ready():
+ self.log.error('Channel exit status ready')
+ break
+ except socket.timeout:
+ message = ("Socket timeout during execution of command: "
+ "%(cmd)s\nBuffer content:\n%(buf)s" % {"cmd": cmd,
+ "buf": buf})
+ raise exceptions.SSHTimeout(error_msg=message)
+ tmp = buf.replace(cmd.replace('\n', ''), '')
+ for item in prompt:
+ tmp.replace(item, '')
+ return tmp
+
+ @staticmethod
+ def interactive_terminal_close(chan):
+ """Close interactive terminal SSH channel.
+
+ :param: chan: SSH channel to be closed.
+ """
+ chan.close()
+
class AutoConnectSSH(SSH):
diff --git a/yardstick/tests/functional/network_services/__init__.py b/yardstick/tests/functional/benchmark/core/__init__.py
index e69de29bb..e69de29bb 100644
--- a/yardstick/tests/functional/network_services/__init__.py
+++ b/yardstick/tests/functional/benchmark/core/__init__.py
diff --git a/yardstick/tests/functional/benchmark/core/test_report.py b/yardstick/tests/functional/benchmark/core/test_report.py
new file mode 100644
index 000000000..5f060dd1e
--- /dev/null
+++ b/yardstick/tests/functional/benchmark/core/test_report.py
@@ -0,0 +1,114 @@
+##############################################################################
+# Copyright (c) 2018 Intel Corporation.
+#
+# 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
+##############################################################################
+
+import ast
+import tempfile
+import unittest
+
+import mock
+from six.moves import configparser
+
+from yardstick.benchmark import core
+from yardstick.benchmark.core import report
+from yardstick.cmd.commands import change_osloobj_to_paras
+
+
+GOOD_YAML_NAME = 'fake_name'
+GOOD_TASK_ID = "9cbe74b6-df09-4535-8bdc-dc3a43b8a4e2"
+GOOD_DB_FIELDKEYS = [
+ {u'fieldKey': u'metric1', u'fieldType': u'integer'},
+ {u'fieldKey': u'metric4', u'fieldType': u'integer'},
+ {u'fieldKey': u'metric2', u'fieldType': u'integer'},
+ {u'fieldKey': u'metric3', u'fieldType': u'integer'},
+]
+GOOD_DB_METRICS = [
+ {u'time': u'2018-08-20T16:49:26.372662016Z',
+ u'metric1': 1, u'metric2': 0, u'metric3': 8, u'metric4': 5},
+ {u'time': u'2018-08-20T16:49:27.374208000Z',
+ u'metric1': 1, u'metric2': 1, u'metric3': 5, u'metric4': 4},
+ {u'time': u'2018-08-20T16:49:28.375742976Z',
+ u'metric1': 2, u'metric2': 2, u'metric3': 3, u'metric4': 3},
+ {u'time': u'2018-08-20T16:49:29.377299968Z',
+ u'metric1': 3, u'metric2': 3, u'metric3': 2, u'metric4': 2},
+ {u'time': u'2018-08-20T16:49:30.378252032Z',
+ u'metric1': 5, u'metric2': 4, u'metric3': 1, u'metric4': 1},
+ {u'time': u'2018-08-20T16:49:30.379359421Z',
+ u'metric1': 8, u'metric2': 5, u'metric3': 1, u'metric4': 0},
+]
+
+yardstick_config = """
+[DEFAULT]
+dispatcher = influxdb
+"""
+
+
+def my_query(query_sql):
+ get_fieldkeys_cmd = 'show field keys'
+ get_metrics_cmd = 'select * from'
+
+ if get_fieldkeys_cmd in query_sql:
+ return GOOD_DB_FIELDKEYS
+ elif get_metrics_cmd in query_sql:
+ return GOOD_DB_METRICS
+ return []
+
+
+class ReportTestCase(unittest.TestCase):
+
+ @mock.patch.object(report.influx, 'query', new=my_query)
+ @mock.patch.object(configparser.ConfigParser,
+ 'read', side_effect=mock.mock_open(read_data=yardstick_config))
+ def test_report_generate_nsb_simple(self, *args):
+ tmpfile = tempfile.NamedTemporaryFile(delete=True)
+
+ args = core.Param({"task_id": [GOOD_TASK_ID], "yaml_name": [GOOD_YAML_NAME]})
+ params = change_osloobj_to_paras(args)
+
+ with mock.patch.object(report.consts, 'DEFAULT_HTML_FILE', tmpfile.name):
+ report.Report().generate_nsb(params)
+
+ data_act = None
+ time_act = None
+ keys_act = None
+ tree_act = None
+ with open(tmpfile.name) as f:
+ for l in f.readlines():
+ if "var report_data = {" in l:
+ data_act = ast.literal_eval(l.strip()[18:-1])
+ elif "var report_time = [" in l:
+ time_act = ast.literal_eval(l.strip()[18:-1])
+ elif "var report_keys = [" in l:
+ keys_act = ast.literal_eval(l.strip()[18:-1])
+ elif "var report_tree = [" in l:
+ tree_act = ast.literal_eval(l.strip()[18:-1])
+
+ data_exp = {
+ 'metric1': [1, 1, 2, 3, 5, 8],
+ 'metric2': [0, 1, 2, 3, 4, 5],
+ 'metric3': [8, 5, 3, 2, 1, 1],
+ 'metric4': [5, 4, 3, 2, 1, 0],
+ }
+ time_exp = [
+ '16:49:26.372662', '16:49:27.374208', '16:49:28.375742',
+ '16:49:29.377299', '16:49:30.378252', '16:49:30.379359',
+ ]
+ keys_exp = [
+ 'metric1', 'metric2', 'metric3', 'metric4',
+ ]
+ tree_exp = [
+ {'parent': '#', 'text': 'metric1', 'id': 'metric1'},
+ {'parent': '#', 'text': 'metric2', 'id': 'metric2'},
+ {'parent': '#', 'text': 'metric3', 'id': 'metric3'},
+ {'parent': '#', 'text': 'metric4', 'id': 'metric4'},
+ ]
+
+ self.assertEqual(data_exp, data_act)
+ self.assertEqual(time_exp, time_act)
+ self.assertEqual(keys_exp, keys_act)
+ self.assertEqual(tree_exp, tree_act)
diff --git a/yardstick/tests/functional/network_services/vnf_generic/__init__.py b/yardstick/tests/functional/network_services/vnf_generic/__init__.py
deleted file mode 100644
index e69de29bb..000000000
--- a/yardstick/tests/functional/network_services/vnf_generic/__init__.py
+++ /dev/null
diff --git a/yardstick/tests/functional/network_services/vnf_generic/vnf/__init__.py b/yardstick/tests/functional/network_services/vnf_generic/vnf/__init__.py
deleted file mode 100644
index e69de29bb..000000000
--- a/yardstick/tests/functional/network_services/vnf_generic/vnf/__init__.py
+++ /dev/null
diff --git a/yardstick/tests/functional/network_services/vnf_generic/vnf/test_base.py b/yardstick/tests/functional/network_services/vnf_generic/vnf/test_base.py
deleted file mode 100644
index e57f8f51c..000000000
--- a/yardstick/tests/functional/network_services/vnf_generic/vnf/test_base.py
+++ /dev/null
@@ -1,103 +0,0 @@
-# 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 multiprocessing
-import time
-import uuid
-
-import mock
-
-from yardstick.common import messaging
-from yardstick.common.messaging import payloads
-from yardstick.common.messaging import producer
-from yardstick.network_services.vnf_generic.vnf import base as vnf_base
-from yardstick.tests.functional import base as ft_base
-
-
-class _TrafficGenMQConsumer(vnf_base.GenericTrafficGen,
- vnf_base.GenericVNFEndpoint):
-
- def __init__(self, name, vnfd, task_id):
- vnf_base.GenericTrafficGen.__init__(self, name, vnfd, task_id)
- self.queue = multiprocessing.Queue()
- self._id = uuid.uuid1().int
- vnf_base.GenericVNFEndpoint.__init__(self, self._id, [task_id],
- self.queue)
- self._consumer = vnf_base.GenericVNFConsumer([task_id], self)
- self._consumer.start_rpc_server()
-
- def run_traffic(self, *args):
- pass
-
- def terminate(self):
- pass
-
- def collect_kpi(self):
- pass
-
- def instantiate(self, *args):
- pass
-
- def scale(self, flavor=''):
- pass
-
- def runner_method_start_iteration(self, ctxt, **kwargs):
- if ctxt['id'] in self._ctx_ids:
- self._queue.put(
- {'action': messaging.RUNNER_METHOD_START_ITERATION,
- 'payload': payloads.RunnerPayload.dict_to_obj(kwargs)})
-
- def runner_method_stop_iteration(self, ctxt, **kwargs):
- if ctxt['id'] in self._ctx_ids:
- self._queue.put(
- {'action': messaging.RUNNER_METHOD_STOP_ITERATION,
- 'payload': payloads.RunnerPayload.dict_to_obj(kwargs)})
-
-
-class _DummyProducer(producer.MessagingProducer):
- pass
-
-
-class GenericVNFMQConsumerTestCase(ft_base.BaseFunctionalTestCase):
-
- def test_fistro(self):
- vnfd = {'benchmark': {'kpi': mock.ANY},
- 'vdu': [{'external-interface': 'ext_int'}]
- }
- task_id = uuid.uuid1().int
- tg_obj = _TrafficGenMQConsumer('name_tg', vnfd, task_id)
- producer = _DummyProducer(messaging.TOPIC_RUNNER, task_id)
-
- num_messages = 10
- for i in range(num_messages):
- pload = payloads.RunnerPayload(version=10, data=i)
- for method in (messaging.RUNNER_METHOD_START_ITERATION,
- messaging.RUNNER_METHOD_STOP_ITERATION):
- producer.send_message(method, pload)
-
- time.sleep(0.5) # Let consumers attend the calls
- output = []
- while not tg_obj.queue.empty():
- data = tg_obj.queue.get(True, 1)
- data_dict = {'action': data['action'],
- 'payload': data['payload'].obj_to_dict()}
- output.append(data_dict)
-
- self.assertEqual(num_messages * 2, len(output))
- for i in range(num_messages):
- pload = payloads.RunnerPayload(version=10, data=i).obj_to_dict()
- for method in (messaging.RUNNER_METHOD_START_ITERATION,
- messaging.RUNNER_METHOD_STOP_ITERATION):
- reg = {'action': method, 'payload': pload}
- self.assertIn(reg, output)
diff --git a/yardstick/tests/unit/benchmark/core/test_report.py b/yardstick/tests/unit/benchmark/core/test_report.py
index 11d017ff0..b498299a9 100644
--- a/yardstick/tests/unit/benchmark/core/test_report.py
+++ b/yardstick/tests/unit/benchmark/core/test_report.py
@@ -1,6 +1,6 @@
##############################################################################
# Copyright (c) 2017 Rajesh Kudaka.
-# Copyright (c) 2018 Intel Corporation.
+# Copyright (c) 2018-2019 Intel Corporation.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
@@ -9,6 +9,7 @@
##############################################################################
import mock
+import six
import unittest
import uuid
@@ -19,13 +20,82 @@ from yardstick.cmd.commands import change_osloobj_to_paras
GOOD_YAML_NAME = 'fake_name'
GOOD_TASK_ID = str(uuid.uuid4())
GOOD_DB_FIELDKEYS = [{'fieldKey': 'fake_key'}]
-GOOD_DB_TASK = [{
+GOOD_DB_METRICS = [{
'fake_key': 1.234,
'time': '0000-00-00T12:34:56.789012Z',
}]
GOOD_TIMESTAMP = ['12:34:56.789012']
BAD_YAML_NAME = 'F@KE_NAME'
BAD_TASK_ID = 'aaaaaa-aaaaaaaa-aaaaaaaaaa-aaaaaa'
+MORE_DB_FIELDKEYS = [
+ {'fieldKey': 'fake_key'},
+ {'fieldKey': 'str_str'},
+ {'fieldKey': u'str_unicode'},
+ {u'fieldKey': 'unicode_str'},
+ {u'fieldKey': u'unicode_unicode'},
+ ]
+MORE_DB_METRICS = [{
+ 'fake_key': None,
+ 'time': '0000-00-00T00:00:00.000000Z',
+ }, {
+ 'fake_key': 123,
+ 'time': '0000-00-00T00:00:01.000000Z',
+ }, {
+ 'fake_key': 4.56,
+ 'time': '0000-00-00T00:00:02.000000Z',
+ }, {
+ 'fake_key': 9876543210987654321,
+ 'time': '0000-00-00T00:00:03.000000Z',
+ }, {
+ 'fake_key': 'str_str value',
+ 'time': '0000-00-00T00:00:04.000000Z',
+ }, {
+ 'fake_key': u'str_unicode value',
+ 'time': '0000-00-00T00:00:05.000000Z',
+ }, {
+ u'fake_key': 'unicode_str value',
+ 'time': '0000-00-00T00:00:06.000000Z',
+ }, {
+ u'fake_key': u'unicode_unicode value',
+ 'time': '0000-00-00T00:00:07.000000Z',
+ }, {
+ 'fake_key': '7.89',
+ 'time': '0000-00-00T00:00:08.000000Z',
+ }, {
+ 'fake_key': '1011',
+ 'time': '0000-00-00T00:00:09.000000Z',
+ }, {
+ 'fake_key': '9876543210123456789',
+ 'time': '0000-00-00T00:00:10.000000Z',
+ }]
+MORE_TIMESTAMP = ['00:00:%02d.000000' % n for n in range(len(MORE_DB_METRICS))]
+MORE_EMPTY_DATA = [None] * len(MORE_DB_METRICS)
+MORE_EXPECTED_TABLE_VALS = {
+ 'Timestamp': MORE_TIMESTAMP,
+ 'fake_key': [
+ None,
+ 123,
+ 4.56,
+ 9876543210987654321 if six.PY3 else 9.876543210987655e+18,
+ 'str_str value',
+ 'str_unicode value',
+ 'unicode_str value',
+ 'unicode_unicode value',
+ 7.89,
+ 1011,
+ 9876543210123456789 if six.PY3 else 9.876543210123457e+18,
+ ],
+ 'str_str': MORE_EMPTY_DATA,
+ 'str_unicode': MORE_EMPTY_DATA,
+ 'unicode_str': MORE_EMPTY_DATA,
+ 'unicode_unicode': MORE_EMPTY_DATA,
+ }
+MORE_EXPECTED_DATASETS = [{
+ 'label': key,
+ 'data': MORE_EXPECTED_TABLE_VALS[key],
+ }
+ for key in map(str, [field['fieldKey'] for field in MORE_DB_FIELDKEYS])
+ ]
class JSTreeTestCase(unittest.TestCase):
@@ -47,23 +117,15 @@ class JSTreeTestCase(unittest.TestCase):
def test_format_for_jstree(self):
data = [
- {'data': [0, ], 'label': 'tg__0.DropPackets'},
- {'data': [548, ], 'label': 'tg__0.LatencyAvg.5'},
- {'data': [1172, ], 'label': 'tg__0.LatencyAvg.6'},
- {'data': [1001, ], 'label': 'tg__0.LatencyMax.5'},
- {'data': [1468, ], 'label': 'tg__0.LatencyMax.6'},
- {'data': [18.11, ], 'label': 'tg__0.RxThroughput'},
- {'data': [18.11, ], 'label': 'tg__0.TxThroughput'},
- {'data': [0, ], 'label': 'tg__1.DropPackets'},
- {'data': [548, ], 'label': 'tg__1.LatencyAvg.5'},
- {'data': [1172, ], 'label': 'tg__1.LatencyAvg.6'},
- {'data': [1001, ], 'label': 'tg__1.LatencyMax.5'},
- {'data': [1468, ], 'label': 'tg__1.LatencyMax.6'},
- {'data': [18.1132084505, ], 'label': 'tg__1.RxThroughput'},
- {'data': [18.1157260383, ], 'label': 'tg__1.TxThroughput'},
- {'data': [9057888, ], 'label': 'vnf__0.curr_packets_in'},
- {'data': [0, ], 'label': 'vnf__0.packets_dropped'},
- {'data': [617825443, ], 'label': 'vnf__0.packets_fwd'},
+ 'tg__0.DropPackets',
+ 'tg__0.LatencyAvg.5', 'tg__0.LatencyAvg.6',
+ 'tg__0.LatencyMax.5', 'tg__0.LatencyMax.6',
+ 'tg__0.RxThroughput', 'tg__0.TxThroughput',
+ 'tg__1.DropPackets',
+ 'tg__1.LatencyAvg.5', 'tg__1.LatencyAvg.6',
+ 'tg__1.LatencyMax.5', 'tg__1.LatencyMax.6',
+ 'tg__1.RxThroughput', 'tg__1.TxThroughput',
+ 'vnf__0.curr_packets_in', 'vnf__0.packets_dropped', 'vnf__0.packets_fwd',
]
expected_output = [
@@ -117,11 +179,11 @@ class ReportTestCase(unittest.TestCase):
self.assertEqual(GOOD_TASK_ID, str(self.rep.task_id))
def test__validate_invalid_yaml_name(self):
- with self.assertRaisesRegexp(ValueError, "yaml*"):
+ with six.assertRaisesRegex(self, ValueError, "yaml*"):
self.rep._validate(BAD_YAML_NAME, GOOD_TASK_ID)
def test__validate_invalid_task_id(self):
- with self.assertRaisesRegexp(ValueError, "task*"):
+ with six.assertRaisesRegex(self, ValueError, "task*"):
self.rep._validate(GOOD_YAML_NAME, BAD_TASK_ID)
@mock.patch.object(influx, 'query')
@@ -141,42 +203,59 @@ class ReportTestCase(unittest.TestCase):
mock_query.return_value = []
self.rep.yaml_name = GOOD_YAML_NAME
self.rep.task_id = GOOD_TASK_ID
- self.assertRaisesRegexp(KeyError, "Test case", self.rep._get_fieldkeys)
+ six.assertRaisesRegex(self, KeyError, "Test case", self.rep._get_fieldkeys)
@mock.patch.object(influx, 'query')
- def test__get_tasks(self, mock_query):
- mock_query.return_value = GOOD_DB_TASK
+ def test__get_metrics(self, mock_query):
+ mock_query.return_value = GOOD_DB_METRICS
self.rep.yaml_name = GOOD_YAML_NAME
self.rep.task_id = GOOD_TASK_ID
- self.assertEqual(GOOD_DB_TASK, self.rep._get_tasks())
+ self.assertEqual(GOOD_DB_METRICS, self.rep._get_metrics())
@mock.patch.object(influx, 'query')
- def test__get_tasks_task_not_found(self, mock_query):
+ def test__get_metrics_task_not_found(self, mock_query):
mock_query.return_value = []
self.rep.yaml_name = GOOD_YAML_NAME
self.rep.task_id = GOOD_TASK_ID
- self.assertRaisesRegexp(KeyError, "Task ID", self.rep._get_tasks)
+ six.assertRaisesRegex(self, KeyError, "Task ID", self.rep._get_metrics)
+
+ def test__get_timestamps(self):
+
+ metrics = MORE_DB_METRICS
+ self.assertEqual(
+ MORE_TIMESTAMP,
+ self.rep._get_timestamps(metrics)
+ )
+
+ @mock.patch.object(report.Report, '_get_metrics')
+ @mock.patch.object(report.Report, '_get_fieldkeys')
+ def test__generate_common(self, mock_keys, mock_metrics):
+ mock_metrics.return_value = MORE_DB_METRICS
+ mock_keys.return_value = MORE_DB_FIELDKEYS
+ datasets, table_vals = self.rep._generate_common(self.param)
+ self.assertEqual(MORE_EXPECTED_DATASETS, datasets)
+ self.assertEqual(MORE_EXPECTED_TABLE_VALS, table_vals)
- @mock.patch.object(report.Report, '_get_tasks')
+ @mock.patch.object(report.Report, '_get_metrics')
@mock.patch.object(report.Report, '_get_fieldkeys')
@mock.patch.object(report.Report, '_validate')
- def test_generate(self, mock_valid, mock_keys, mock_tasks):
- mock_tasks.return_value = GOOD_DB_TASK
+ def test_generate(self, mock_valid, mock_keys, mock_metrics):
+ mock_metrics.return_value = GOOD_DB_METRICS
mock_keys.return_value = GOOD_DB_FIELDKEYS
self.rep.generate(self.param)
mock_valid.assert_called_once_with(GOOD_YAML_NAME, GOOD_TASK_ID)
- mock_tasks.assert_called_once_with()
+ mock_metrics.assert_called_once_with()
mock_keys.assert_called_once_with()
self.assertEqual(GOOD_TIMESTAMP, self.rep.Timestamp)
- @mock.patch.object(report.Report, '_get_tasks')
+ @mock.patch.object(report.Report, '_get_metrics')
@mock.patch.object(report.Report, '_get_fieldkeys')
@mock.patch.object(report.Report, '_validate')
- def test_generate_nsb(self, mock_valid, mock_keys, mock_tasks):
- mock_tasks.return_value = GOOD_DB_TASK
+ def test_generate_nsb(self, mock_valid, mock_keys, mock_metrics):
+ mock_metrics.return_value = GOOD_DB_METRICS
mock_keys.return_value = GOOD_DB_FIELDKEYS
self.rep.generate_nsb(self.param)
mock_valid.assert_called_once_with(GOOD_YAML_NAME, GOOD_TASK_ID)
- mock_tasks.assert_called_once_with()
+ mock_metrics.assert_called_once_with()
mock_keys.assert_called_once_with()
self.assertEqual(GOOD_TIMESTAMP, self.rep.Timestamp)
diff --git a/yardstick/tests/unit/benchmark/runner/test_base.py b/yardstick/tests/unit/benchmark/runner/test_base.py
index 49ba1efe4..07d6f1843 100644
--- a/yardstick/tests/unit/benchmark/runner/test_base.py
+++ b/yardstick/tests/unit/benchmark/runner/test_base.py
@@ -8,17 +8,12 @@
##############################################################################
import time
-import uuid
import mock
-from oslo_config import cfg
-import oslo_messaging
import subprocess
from yardstick.benchmark.runners import base as runner_base
from yardstick.benchmark.runners import iteration
-from yardstick.common import messaging
-from yardstick.common.messaging import payloads
from yardstick.tests.unit import base as ut_base
@@ -48,6 +43,29 @@ class ActionTestCase(ut_base.BaseUnitTestCase):
runner_base._periodic_action(0, 'echo', mock.Mock())
+class ScenarioOutputTestCase(ut_base.BaseUnitTestCase):
+
+ def setUp(self):
+ self.output_queue = mock.Mock()
+ self.scenario_output = runner_base.ScenarioOutput(self.output_queue,
+ sequence=1)
+
+ @mock.patch.object(time, 'time')
+ def test_push(self, mock_time):
+ mock_time.return_value = 2
+ data = {"value1": 1}
+ self.scenario_output.push(data)
+ self.output_queue.put.assert_called_once_with({'timestamp': 2,
+ 'sequence': 1,
+ 'data': data}, True, 10)
+
+ def test_push_no_timestamp(self):
+ self.scenario_output["value1"] = 1
+ self.scenario_output.push(None, False)
+ self.output_queue.put.assert_called_once_with({'sequence': 1,
+ 'value1': 1}, True, 10)
+
+
class RunnerTestCase(ut_base.BaseUnitTestCase):
def setUp(self):
@@ -99,54 +117,3 @@ class RunnerTestCase(ut_base.BaseUnitTestCase):
with self.assertRaises(NotImplementedError):
runner._run_benchmark(mock.Mock(), mock.Mock(), mock.Mock(), mock.Mock())
-
-
-class RunnerProducerTestCase(ut_base.BaseUnitTestCase):
-
- @mock.patch.object(oslo_messaging, 'Target', return_value='rpc_target')
- @mock.patch.object(oslo_messaging, 'RPCClient')
- @mock.patch.object(oslo_messaging, 'get_rpc_transport',
- return_value='rpc_transport')
- @mock.patch.object(cfg, 'CONF')
- def test__init(self, mock_config, mock_transport, mock_rpcclient,
- mock_target):
- _id = uuid.uuid1().int
- runner_producer = runner_base.RunnerProducer(_id)
- mock_transport.assert_called_once_with(
- mock_config, url='rabbit://yardstick:yardstick@localhost:5672/')
- mock_target.assert_called_once_with(topic=messaging.TOPIC_RUNNER,
- fanout=True,
- server=messaging.SERVER)
- mock_rpcclient.assert_called_once_with('rpc_transport', 'rpc_target')
- self.assertEqual(_id, runner_producer._id)
- self.assertEqual(messaging.TOPIC_RUNNER, runner_producer._topic)
-
- @mock.patch.object(oslo_messaging, 'Target', return_value='rpc_target')
- @mock.patch.object(oslo_messaging, 'RPCClient')
- @mock.patch.object(oslo_messaging, 'get_rpc_transport',
- return_value='rpc_transport')
- @mock.patch.object(payloads, 'RunnerPayload', return_value='runner_pload')
- def test_start_iteration(self, mock_runner_payload, *args):
- runner_producer = runner_base.RunnerProducer(uuid.uuid1().int)
- with mock.patch.object(runner_producer,
- 'send_message') as mock_message:
- runner_producer.start_iteration(version=10)
-
- mock_message.assert_called_once_with(
- messaging.RUNNER_METHOD_START_ITERATION, 'runner_pload')
- mock_runner_payload.assert_called_once_with(version=10, data={})
-
- @mock.patch.object(oslo_messaging, 'Target', return_value='rpc_target')
- @mock.patch.object(oslo_messaging, 'RPCClient')
- @mock.patch.object(oslo_messaging, 'get_rpc_transport',
- return_value='rpc_transport')
- @mock.patch.object(payloads, 'RunnerPayload', return_value='runner_pload')
- def test_stop_iteration(self, mock_runner_payload, *args):
- runner_producer = runner_base.RunnerProducer(uuid.uuid1().int)
- with mock.patch.object(runner_producer,
- 'send_message') as mock_message:
- runner_producer.stop_iteration(version=15)
-
- mock_message.assert_called_once_with(
- messaging.RUNNER_METHOD_STOP_ITERATION, 'runner_pload')
- mock_runner_payload.assert_called_once_with(version=15, data={})
diff --git a/yardstick/tests/unit/benchmark/runner/test_iteration_ipc.py b/yardstick/tests/unit/benchmark/runner/test_iteration_ipc.py
deleted file mode 100644
index 10d14a8a0..000000000
--- a/yardstick/tests/unit/benchmark/runner/test_iteration_ipc.py
+++ /dev/null
@@ -1,136 +0,0 @@
-# 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 multiprocessing
-import time
-import os
-import uuid
-
-import mock
-
-from yardstick.benchmark.runners import iteration_ipc
-from yardstick.common import messaging
-from yardstick.common.messaging import payloads
-from yardstick.tests.unit import base as ut_base
-
-
-class RunnerIterationIPCEndpointTestCase(ut_base.BaseUnitTestCase):
-
- def setUp(self):
- self._id = uuid.uuid1().int
- self._ctx_ids = [uuid.uuid1().int, uuid.uuid1().int]
- self._queue = multiprocessing.Queue()
- self.runner = iteration_ipc.RunnerIterationIPCEndpoint(
- self._id, self._ctx_ids, self._queue)
- self._kwargs = {'version': 1, 'iteration': 10, 'kpi': {}}
- self._pload_dict = payloads.TrafficGeneratorPayload.dict_to_obj(
- self._kwargs).obj_to_dict()
-
- def test_tg_method_started(self):
- self._queue.empty()
- ctxt = {'id': self._ctx_ids[0]}
- self.runner.tg_method_started(ctxt, **self._kwargs)
- time.sleep(0.2)
-
- output = []
- while not self._queue.empty():
- output.append(self._queue.get(True, 1))
-
- self.assertEqual(1, len(output))
- self.assertEqual(self._ctx_ids[0], output[0]['id'])
- self.assertEqual(messaging.TG_METHOD_STARTED, output[0]['action'])
- self.assertEqual(self._pload_dict, output[0]['payload'].obj_to_dict())
-
- def test_tg_method_finished(self):
- self._queue.empty()
- ctxt = {'id': self._ctx_ids[0]}
- self.runner.tg_method_finished(ctxt, **self._kwargs)
- time.sleep(0.2)
-
- output = []
- while not self._queue.empty():
- output.append(self._queue.get(True, 1))
-
- self.assertEqual(1, len(output))
- self.assertEqual(self._ctx_ids[0], output[0]['id'])
- self.assertEqual(messaging.TG_METHOD_FINISHED, output[0]['action'])
- self.assertEqual(self._pload_dict, output[0]['payload'].obj_to_dict())
-
- def test_tg_method_iteration(self):
- self._queue.empty()
- ctxt = {'id': self._ctx_ids[0]}
- self.runner.tg_method_iteration(ctxt, **self._kwargs)
- time.sleep(0.2)
-
- output = []
- while not self._queue.empty():
- output.append(self._queue.get(True, 1))
-
- self.assertEqual(1, len(output))
- self.assertEqual(self._ctx_ids[0], output[0]['id'])
- self.assertEqual(messaging.TG_METHOD_ITERATION, output[0]['action'])
- self.assertEqual(self._pload_dict, output[0]['payload'].obj_to_dict())
-
-
-class RunnerIterationIPCConsumerTestCase(ut_base.BaseUnitTestCase):
-
- def setUp(self):
- self._id = uuid.uuid1().int
- self._ctx_ids = [uuid.uuid1().int, uuid.uuid1().int]
- self.consumer = iteration_ipc.RunnerIterationIPCConsumer(
- self._id, self._ctx_ids)
- self.consumer._queue = mock.Mock()
-
- def test__init(self):
- self.assertEqual({self._ctx_ids[0]: [], self._ctx_ids[1]: []},
- self.consumer._kpi_per_id)
-
- def test_is_all_kpis_received_in_iteration(self):
- payload = payloads.TrafficGeneratorPayload(
- version=1, iteration=1, kpi={})
- msg1 = {'action': messaging.TG_METHOD_ITERATION,
- 'id': self._ctx_ids[0], 'payload': payload}
- msg2 = {'action': messaging.TG_METHOD_ITERATION,
- 'id': self._ctx_ids[1], 'payload': payload}
- self.consumer.iteration_index = 1
-
- self.consumer._queue.empty.side_effect = [False, True]
- self.consumer._queue.get.return_value = msg1
- self.assertFalse(self.consumer.is_all_kpis_received_in_iteration())
-
- self.consumer._queue.empty.side_effect = [False, True]
- self.consumer._queue.get.return_value = msg2
- self.assertTrue(self.consumer.is_all_kpis_received_in_iteration())
-
-
-class IterationIPCRunnerTestCase(ut_base.BaseUnitTestCase):
-
- @mock.patch.object(iteration_ipc, '_worker_process')
- @mock.patch.object(os, 'getpid', return_value=12345678)
- @mock.patch.object(multiprocessing, 'Process', return_value=mock.Mock())
- def test__run_benchmark(self, mock_process, mock_getpid, mock_worker):
- method = 'method'
- scenario_cfg = {'type': 'scenario_type'}
- context_cfg = 'context_cfg'
- name = '%s-%s-%s' % ('IterationIPC', 'scenario_type', 12345678)
- runner = iteration_ipc.IterationIPCRunner(mock.ANY)
- mock_getpid.reset_mock()
-
- runner._run_benchmark('class', method, scenario_cfg, context_cfg)
- mock_process.assert_called_once_with(
- name=name,
- target=mock_worker,
- args=(runner.result_queue, 'class', method, scenario_cfg,
- context_cfg, runner.aborted, runner.output_queue))
- mock_getpid.assert_called_once()
diff --git a/yardstick/tests/unit/benchmark/scenarios/availability/test_monitor_multi.py b/yardstick/tests/unit/benchmark/scenarios/availability/test_monitor_multi.py
index e9c680257..dc3a4b99a 100644
--- a/yardstick/tests/unit/benchmark/scenarios/availability/test_monitor_multi.py
+++ b/yardstick/tests/unit/benchmark/scenarios/availability/test_monitor_multi.py
@@ -63,3 +63,20 @@ class MultiMonitorServiceTestCase(unittest.TestCase):
ins.start_monitor()
ins.wait_monitor()
ins.verify_SLA()
+
+ def test__monitor_multi_no_sla(self, mock_open, mock_ssh):
+ monitor_cfg = {
+ 'monitor_type': 'general-monitor',
+ 'monitor_number': 3,
+ 'key': 'service-status',
+ 'monitor_key': 'service-status',
+ 'host': 'node1',
+ 'monitor_time': 0.1,
+ 'parameter': {'serviceName': 'haproxy'}
+ }
+ ins = monitor_multi.MultiMonitor(
+ monitor_cfg, self.context, {"nova-api": 10})
+ mock_ssh.SSH.from_node().execute.return_value = (0, "running", '')
+ ins.start_monitor()
+ ins.wait_monitor()
+ self.assertTrue(ins.verify_SLA())
diff --git a/yardstick/tests/unit/benchmark/scenarios/availability/test_monitor_process.py b/yardstick/tests/unit/benchmark/scenarios/availability/test_monitor_process.py
index a6d2ca398..8c73bf221 100644
--- a/yardstick/tests/unit/benchmark/scenarios/availability/test_monitor_process.py
+++ b/yardstick/tests/unit/benchmark/scenarios/availability/test_monitor_process.py
@@ -55,3 +55,19 @@ class MonitorProcessTestCase(unittest.TestCase):
ins.monitor_func()
ins._result = {"outage_time": 10}
ins.verify_SLA()
+
+ def test__monitor_process_no_sla(self, mock_ssh):
+
+ monitor_cfg = {
+ 'monitor_type': 'process',
+ 'process_name': 'nova-api',
+ 'host': "node1",
+ 'monitor_time': 1,
+ }
+ ins = monitor_process.MonitorProcess(monitor_cfg, self.context, {"nova-api": 10})
+
+ mock_ssh.SSH.from_node().execute.return_value = (0, "0", '')
+ ins.setup()
+ ins.monitor_func()
+ ins._result = {"outage_time": 10}
+ self.assertTrue(ins.verify_SLA())
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 8214782b2..ff8ce5796 100644
--- a/yardstick/tests/unit/benchmark/scenarios/networking/test_vnf_generic.py
+++ b/yardstick/tests/unit/benchmark/scenarios/networking/test_vnf_generic.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -450,7 +450,6 @@ class TestNetworkServiceTestCase(unittest.TestCase):
self._get_file_abspath("tg_trex_tpl.yaml")
self.context_cfg["nodes"]['vnf__1']['VNF model'] = \
self._get_file_abspath("tg_trex_tpl.yaml")
- self.context_cfg['task_id'] = 'fake_task_id'
vnf = mock.Mock(autospec=GenericVNF)
self.s.get_vnf_impl = mock.Mock(return_value=vnf)
@@ -568,7 +567,6 @@ class TestNetworkServiceTestCase(unittest.TestCase):
tgen.verify_traffic = lambda x: verified_dict
tgen.terminate = mock.Mock(return_value=True)
tgen.name = "tgen__1"
- tgen.run_traffic.return_value = 'tg_id'
vnf = mock.Mock(autospec=GenericVNF)
vnf.runs_traffic = False
vnf.terminate = mock.Mock(return_value=True)
@@ -581,6 +579,7 @@ class TestNetworkServiceTestCase(unittest.TestCase):
self.s.load_vnf_models = mock.Mock(return_value=self.s.vnfs)
self.s._fill_traffic_profile = \
mock.Mock(return_value=TRAFFIC_PROFILE)
+ self.assertIsNone(self.s.setup())
def test_setup_exception(self):
with mock.patch("yardstick.ssh.SSH") as ssh:
@@ -641,6 +640,14 @@ class TestNetworkServiceTestCase(unittest.TestCase):
self.assertEqual({'imix': {'64B': 100}},
self.s._get_traffic_imix())
+ def test__get_ip_priority(self):
+ with mock.patch.dict(self.scenario_cfg["options"],
+ {'priority': {'raw': '0x01'}}):
+ self.assertEqual({'raw': '0x01'}, self.s._get_ip_priority())
+
+ def test__get_ip_priority_exception(self):
+ self.assertEqual({}, self.s._get_ip_priority())
+
@mock.patch.object(base.TrafficProfile, 'get')
@mock.patch.object(vnfdgen, 'generate_vnfd')
def test__fill_traffic_profile(self, mock_generate, mock_tprofile_get):
@@ -657,6 +664,7 @@ class TestNetworkServiceTestCase(unittest.TestCase):
'extra_args': {'arg1': 'value1', 'arg2': 'value2'},
'flow': {'flow': {}},
'imix': {'imix': {'64B': 100}},
+ 'priority': {},
'uplink': {},
'duration': 30,
'simulated_users': {
@@ -705,9 +713,6 @@ class TestNetworkServiceTestCase(unittest.TestCase):
)
self.assertEqual(self.s.topology, 'fake_nsd')
- def test_get_mq_ids(self):
- self.assertEqual(self.s._mq_ids, self.s.get_mq_ids())
-
def test_teardown(self):
vnf = mock.Mock(autospec=GenericVNF)
vnf.terminate = mock.Mock(return_value=True)
@@ -731,3 +736,87 @@ class TestNetworkServiceTestCase(unittest.TestCase):
mock.Mock(return_value=True)
with self.assertRaises(RuntimeError):
self.s.teardown()
+
+
+class TestNetworkServiceRFC2544TestCase(TestNetworkServiceTestCase):
+
+ def setUp(self):
+ super(TestNetworkServiceRFC2544TestCase, self).setUp()
+ self.s = vnf_generic.NetworkServiceRFC2544(self.scenario_cfg,
+ self.context_cfg)
+
+ def test_run(self):
+ tgen = mock.Mock(autospec=GenericTrafficGen)
+ tgen.traffic_finished = True
+ verified_dict = {"verified": True}
+ tgen.verify_traffic = lambda x: verified_dict
+ tgen.name = "tgen__1"
+ tgen.wait_on_trafic.return_value = 'COMPLETE'
+ vnf = mock.Mock(autospec=GenericVNF)
+ vnf.runs_traffic = False
+ self.s.vnfs = [tgen, vnf]
+ self.s.traffic_profile = mock.Mock()
+ self.s._fill_traffic_profile = mock.Mock()
+ self.s.collector = mock.Mock(autospec=Collector)
+ self.s.collector.get_kpi = mock.Mock(
+ return_value={tgen.name: verified_dict})
+ result = mock.Mock()
+ self.s.run(result)
+ self.s._fill_traffic_profile.assert_called_once()
+ result.push.assert_called_once()
+
+ def test_setup(self):
+ with mock.patch("yardstick.ssh.SSH") as ssh:
+ ssh_mock = mock.Mock(autospec=ssh.SSH)
+ ssh_mock.execute = \
+ mock.Mock(return_value=(0, SYS_CLASS_NET + IP_ADDR_SHOW, ""))
+ ssh.from_node.return_value = ssh_mock
+
+ tgen = mock.Mock(autospec=GenericTrafficGen)
+ tgen.traffic_finished = True
+ verified_dict = {"verified": True}
+ tgen.verify_traffic = lambda x: verified_dict
+ tgen.terminate = mock.Mock(return_value=True)
+ tgen.name = "tgen__1"
+ tgen.run_traffic.return_value = 'tg_id'
+ vnf = mock.Mock(autospec=GenericVNF)
+ vnf.runs_traffic = False
+ vnf.terminate = mock.Mock(return_value=True)
+ self.s.vnfs = [tgen, vnf]
+ self.s.traffic_profile = mock.Mock()
+ self.s.collector = mock.Mock(autospec=Collector)
+ self.s.collector.get_kpi = \
+ mock.Mock(return_value={tgen.name: verified_dict})
+ self.s.map_topology_to_infrastructure = mock.Mock(return_value=0)
+ self.s.load_vnf_models = mock.Mock(return_value=self.s.vnfs)
+ self.s.setup()
+
+ def test_setup_exception(self):
+ with mock.patch("yardstick.ssh.SSH") as ssh:
+ ssh_mock = mock.Mock(autospec=ssh.SSH)
+ ssh_mock.execute = \
+ mock.Mock(return_value=(0, SYS_CLASS_NET + IP_ADDR_SHOW, ""))
+ ssh.from_node.return_value = ssh_mock
+
+ tgen = mock.Mock(autospec=GenericTrafficGen)
+ tgen.traffic_finished = True
+ verified_dict = {"verified": True}
+ tgen.verify_traffic = lambda x: verified_dict
+ tgen.terminate = mock.Mock(return_value=True)
+ tgen.name = "tgen__1"
+ vnf = mock.Mock(autospec=GenericVNF)
+ vnf.runs_traffic = False
+ vnf.instantiate.side_effect = RuntimeError(
+ "error during instantiate")
+ vnf.terminate = mock.Mock(return_value=True)
+ self.s.vnfs = [tgen, vnf]
+ self.s.traffic_profile = mock.Mock()
+ self.s.collector = mock.Mock(autospec=Collector)
+ self.s.collector.get_kpi = \
+ mock.Mock(return_value={tgen.name: verified_dict})
+ self.s.map_topology_to_infrastructure = mock.Mock(return_value=0)
+ self.s.load_vnf_models = mock.Mock(return_value=self.s.vnfs)
+ self.s._fill_traffic_profile = \
+ mock.Mock(return_value=TRAFFIC_PROFILE)
+ with self.assertRaises(RuntimeError):
+ self.s.setup()
diff --git a/yardstick/tests/unit/common/test_utils.py b/yardstick/tests/unit/common/test_utils.py
index c0c928916..6b8d81907 100644
--- a/yardstick/tests/unit/common/test_utils.py
+++ b/yardstick/tests/unit/common/test_utils.py
@@ -1135,6 +1135,15 @@ class TestUtilsIpAddrMethods(ut_base.BaseUnitTestCase):
for addr in addr_list:
self.assertRaises(Exception, utils.make_ipv4_address, addr)
+ def test_get_ip_range_count(self):
+ iprange = "192.168.0.1-192.168.0.25"
+ count = utils.get_ip_range_count(iprange)
+ self.assertEqual(count, 24)
+
+ def test_get_ip_range_start(self):
+ iprange = "192.168.0.1-192.168.0.25"
+ start = utils.get_ip_range_start(iprange)
+ self.assertEqual(start, "192.168.0.1")
def test_safe_ip_address(self):
addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
diff --git a/yardstick/tests/unit/network_services/libs/ixia_libs/test_ixnet_api.py b/yardstick/tests/unit/network_services/libs/ixia_libs/test_ixnet_api.py
index c1d902061..270d342fd 100644
--- a/yardstick/tests/unit/network_services/libs/ixia_libs/test_ixnet_api.py
+++ b/yardstick/tests/unit/network_services/libs/ixia_libs/test_ixnet_api.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2018 Intel Corporation
+# Copyright (c) 2018-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -15,16 +15,54 @@
import mock
import IxNetwork
import unittest
+import re
from copy import deepcopy
+from collections import OrderedDict
from yardstick.common import exceptions
from yardstick.network_services.libs.ixia_libs.ixnet import ixnet_api
+from yardstick.network_services.traffic_profile import ixia_rfc2544
UPLINK = 'uplink'
DOWNLINK = 'downlink'
+TRAFFIC_PROFILE = {
+ 'uplink_0': {
+ 'ipv4': {
+ 'outer_l2': {
+ 'framesize': {
+ '128B': '0',
+ '1518B': '0',
+ '64B': '0',
+ '373b': '0',
+ '256B': '0',
+ '1400B': '0',
+ '570B': '0'}},
+ 'id': 1}},
+ 'description': 'Traffic profile to run RFC2544 latency',
+ 'name': 'rfc2544',
+ 'schema': 'isb:traffic_profile:0.1',
+ 'traffic_profile': {
+ 'injection_time': None,
+ 'enable_latency': True,
+ 'frame_rate': '100%',
+ 'traffic_type': 'IXIARFC2544Profile'},
+ 'downlink_0': {
+ 'ipv4': {
+ 'outer_l2': {
+ 'framesize': {
+ '128B': '0',
+ '1518B': '0',
+ '64B': '0',
+ '373b': '0',
+ '256B': '0',
+ '1400B': '0',
+ '570B': '0'}},
+ 'id': 2}}}
+
+
TRAFFIC_PARAMETERS = {
UPLINK: {
'id': 1,
@@ -103,6 +141,12 @@ class TestIxNextgen(unittest.TestCase):
self.ixnet.getRoot.return_value = 'my_root'
self.ixnet_gen = ixnet_api.IxNextgen()
self.ixnet_gen._ixnet = self.ixnet
+ self._mock_log = mock.patch.object(ixnet_api.log, 'info')
+ self.mock_log = self._mock_log.start()
+ self.addCleanup(self._stop_mocks)
+
+ def _stop_mocks(self):
+ self.mock_log.stop()
def test_get_config(self):
tg_cfg = {
@@ -373,13 +417,15 @@ class TestIxNextgen(unittest.TestCase):
self.ixnet_gen.add_static_ipv4(iface='iface',
vport='vport',
start_ip='10.0.0.0',
- count='100')
+ count='100',
+ mask='32')
self.ixnet_gen.ixnet.add.assert_called_once_with(
'vport/protocols/static', 'ip')
self.ixnet_gen.ixnet.setMultiAttribute.assert_any_call(
'obj', '-protocolInterface', 'iface',
'-ipStart', '10.0.0.0',
'-count', '100',
+ '-mask', '32',
'-enabled', 'true')
@mock.patch.object(IxNetwork, 'IxNet')
@@ -496,12 +542,17 @@ class TestIxNextgen(unittest.TestCase):
'my_root/traffic/protocolTemplate:"my_protocol"')
def test__setup_config_elements(self):
+ # the config parsed from some_file
+ yaml_data = {'traffic_profile': {}
+ }
+ traffic_profile = ixia_rfc2544.IXIARFC2544Profile(yaml_data)
+ traffic_profile.params = TRAFFIC_PROFILE
self.ixnet_gen.ixnet.getList.side_effect = [['traffic_item'],
['cfg_element']]
with mock.patch.object(self.ixnet_gen, '_append_procotol_to_stack') as \
mock_append_proto:
- self.ixnet_gen._setup_config_elements()
- mock_append_proto.assert_has_calls([
+ self.ixnet_gen._setup_config_elements(traffic_profile=traffic_profile)
+ mock_append_proto.assert_has_calls([
mock.call(ixnet_api.PROTO_UDP, 'cfg_element/stack:"ethernet-1"'),
mock.call(ixnet_api.PROTO_IPV4, 'cfg_element/stack:"ethernet-1"')])
self.ixnet_gen.ixnet.setAttribute.assert_has_calls([
@@ -516,11 +567,15 @@ class TestIxNextgen(unittest.TestCase):
def test_create_traffic_model(self, mock__setup_config_elements,
mock__create_flow_groups,
mock__create_traffic_item):
+ # the config parsed from some_file
+ yaml_data = {'traffic_profile': {}}
+ traffic_profile = ixia_rfc2544.IXIARFC2544Profile(yaml_data)
uplink_ports = ['port1', 'port3']
downlink_ports = ['port2', 'port4']
uplink_endpoints = ['port1/protocols', 'port3/protocols']
downlink_endpoints = ['port2/protocols', 'port4/protocols']
- self.ixnet_gen.create_traffic_model(uplink_ports, downlink_ports)
+ self.ixnet_gen.create_traffic_model(uplink_ports, downlink_ports,
+ traffic_profile=traffic_profile)
mock__create_traffic_item.assert_called_once_with('raw')
mock__create_flow_groups.assert_called_once_with(uplink_endpoints,
downlink_endpoints)
@@ -541,6 +596,56 @@ class TestIxNextgen(unittest.TestCase):
downlink_topologies)
mock__setup_config_elements.assert_called_once_with(False)
+ def test_flows_settings(self):
+ cfg = {'uplink_0': {
+ 'ipv4': {
+ 'outer_l2': {
+ 'framesize': {
+ '128B': '0',
+ '1518B': '0',
+ '64B': '0',
+ '373b': '0',
+ '256B': '0',
+ '1400B': '0',
+ '570B': '0'}},
+ 'id': 1}}}
+
+ expected = [
+ {'ipv4': {
+ 'id': 1,
+ 'outer_l2': {
+ 'framesize': {
+ '1518B': '0',
+ '1400B': '0',
+ '128B': '0',
+ '64B': '0',
+ '256B': '0',
+ '373b': '0',
+ '570B': '0'}}}}]
+
+ self.assertEqual(expected, self.ixnet_gen._flows_settings(cfg=cfg))
+
+ def test_is_qinq(self):
+ flow_data = {'ipv4': {
+ 'outer_l2': {},
+ 'id': 1}}
+ self.assertEqual(False, self.ixnet_gen.is_qinq(flow_data=flow_data))
+
+ flow_data = {'ipv4': {
+ 'outer_l2': {
+ 'QinQ': {
+ 'C-VLAN': {
+ 'priority': 0,
+ 'cfi': 0,
+ 'id': 512},
+ 'S-VLAN': {
+ 'priority': 0,
+ 'cfi': 0,
+ 'id': 128}},
+ },
+ 'id': 1}}
+ self.assertEqual(True, self.ixnet_gen.is_qinq(flow_data=flow_data))
+
def test__update_frame_mac(self):
with mock.patch.object(self.ixnet_gen, '_get_field_in_stack_item') as \
mock_get_field:
@@ -625,9 +730,9 @@ class TestIxNextgen(unittest.TestCase):
mock.call(self.ixnet_gen.FLOW_STATISTICS,
self.ixnet_gen.LATENCY_NAME_MAP)])
- def test__set_flow_tracking(self):
+ def test_set_flow_tracking(self):
self.ixnet_gen._ixnet.getList.return_value = ['traffic_item']
- self.ixnet_gen._set_flow_tracking(track_by=['vlanVlanId0'])
+ self.ixnet_gen.set_flow_tracking(track_by=['vlanVlanId0'])
self.ixnet_gen.ixnet.setAttribute.assert_called_once_with(
'traffic_item/tracking', '-trackBy', ['vlanVlanId0'])
self.assertEqual(self.ixnet.commit.call_count, 1)
@@ -645,17 +750,77 @@ class TestIxNextgen(unittest.TestCase):
'encapsulation', '-offset', 'IPv4 TOS Precedence')
self.assertEqual(self.ixnet.commit.call_count, 2)
- def test_get_pppoe_scenario_statistics(self):
- with mock.patch.object(self.ixnet_gen, '_build_stats_map') as \
- mock_build_stats:
- self.ixnet_gen.get_pppoe_scenario_statistics()
-
- mock_build_stats.assert_any_call(self.ixnet_gen.PORT_STATISTICS,
- self.ixnet_gen.PORT_STATS_NAME_MAP)
- mock_build_stats.assert_any_call(self.ixnet_gen.FLOW_STATISTICS,
- self.ixnet_gen.LATENCY_NAME_MAP)
- mock_build_stats.assert_any_call(self.ixnet_gen.PPPOX_CLIENT_PER_PORT,
- self.ixnet_gen.PPPOX_CLIENT_PER_PORT_NAME_MAP)
+ def test__get_view_page_stats(self):
+ expected_stats = [
+ {'header1': 'row1_1', 'header2': 'row1_2'},
+ {'header1': 'row2_1', 'header2': 'row2_2'}
+ ]
+ self.ixnet_gen._ixnet.getAttribute.side_effect = [
+ ['header1', 'header2'],
+ [
+ [['row1_1', 'row1_2']],
+ [['row2_1', 'row2_2']]
+ ]
+ ]
+ stats = self.ixnet_gen._get_view_page_stats('view_obj')
+ self.assertListEqual(stats, expected_stats)
+
+ @mock.patch.object(ixnet_api.IxNextgen, '_get_view_page_stats')
+ def test_get_pppoe_scenario_statistics(self, mock_get_view):
+
+ pattern = re.compile('Flow 2')
+
+ expected_stats = {
+ 'port_statistics': [{
+ 'port_1': 'port_stat1',
+ 'port_2': 'port_stat2'
+ }],
+ 'flow_statistic': [{
+ 'flow_1': 'flow_stat1',
+ 'flow_2': 'flow_stat2'
+ }],
+ 'pppox_client_per_port': [{
+ 'sub_1': 'sub_stat1',
+ 'sub_2': 'sub_stat2'
+ }]
+ }
+
+ pppoe_scenario_stats = OrderedDict([
+ ('port_statistics', 'view_obj'),
+ ('flow_statistic', 'view_obj'),
+ ('pppox_client_per_port', 'view_obj')
+ ])
+
+ pppoe_scenario_stats_map = {
+ 'port_statistics': {'port_1': 'Port 1',
+ 'port_2': 'Port 2'},
+ 'flow_statistic': {'flow_1': 'Flow 1',
+ 'flow_2': pattern},
+ 'pppox_client_per_port': {'sub_1': 'Sub 1',
+ 'sub_2': 'Sub 2'}
+ }
+
+ # All stats keys
+ port_stats = [{'Port 1': 'port_stat1',
+ 'Port 2': 'port_stat2',
+ 'Port 3': 'port_stat3'}]
+ flows_stats = [{'Flow 1': 'flow_stat1',
+ 'Flow 2': 'flow_stat2',
+ 'Flow 3': 'flow_stat3'}]
+ pppoe_sub_stats = [{'Sub 1': 'sub_stat1',
+ 'Sub 2': 'sub_stat2',
+ 'Sub 3': 'sub_stat3'}]
+
+ mock_get_view.side_effect = [port_stats, flows_stats, pppoe_sub_stats]
+ self.ixnet_gen._ixnet.getAttribute.return_value = '1'
+
+ with mock.patch.multiple(ixnet_api.IxNextgen,
+ PPPOE_SCENARIO_STATS=pppoe_scenario_stats,
+ PPPOE_SCENARIO_STATS_MAP=pppoe_scenario_stats_map):
+ stats = self.ixnet_gen.get_pppoe_scenario_statistics()
+ self.assertDictEqual(stats, expected_stats)
+ self.assertEqual(self.ixnet_gen.ixnet.getAttribute.call_count, 6)
+ self.ixnet_gen.ixnet.setAttribute.assert_not_called()
def test__update_ipv4_address(self):
with mock.patch.object(self.ixnet_gen, '_get_field_in_stack_item',
diff --git a/yardstick/tests/unit/network_services/traffic_profile/test_http_ixload.py b/yardstick/tests/unit/network_services/traffic_profile/test_http_ixload.py
index c9be200b2..996360c2e 100644
--- a/yardstick/tests/unit/network_services/traffic_profile/test_http_ixload.py
+++ b/yardstick/tests/unit/network_services/traffic_profile/test_http_ixload.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2017 Intel Corporation
+# Copyright (c) 2017-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -17,7 +17,6 @@ import mock
from oslo_serialization import jsonutils
-from yardstick.common import exceptions
from yardstick.network_services.traffic_profile import http_ixload
from yardstick.network_services.traffic_profile.http_ixload import \
join_non_strings, validate_non_string_sequence
@@ -288,7 +287,7 @@ class TestIxLoadTrafficGen(unittest.TestCase):
net_traffic.network.getL1Plugin.return_value = Exception
- with self.assertRaises(exceptions.InvalidRxfFile):
+ with self.assertRaises(http_ixload.InvalidRxfFile):
ixload.update_network_mac_address(net_traffic, "auto")
def test_update_network_address(self):
@@ -312,7 +311,7 @@ class TestIxLoadTrafficGen(unittest.TestCase):
net_traffic.network.getL1Plugin.return_value = Exception
- with self.assertRaises(exceptions.InvalidRxfFile):
+ with self.assertRaises(http_ixload.InvalidRxfFile):
ixload.update_network_address(net_traffic, "address", "gateway",
"prefix")
@@ -375,7 +374,7 @@ class TestIxLoadTrafficGen(unittest.TestCase):
pageObject="page_object")
net_traffic.activityList = []
- with self.assertRaises(exceptions.InvalidRxfFile):
+ with self.assertRaises(http_ixload.InvalidRxfFile):
ixload.update_page_size(net_traffic, "page_object")
def test_update_user_count(self):
@@ -390,7 +389,7 @@ class TestIxLoadTrafficGen(unittest.TestCase):
activity.config.assert_called_once_with(userObjectiveValue=123)
net_traffic.activityList = []
- with self.assertRaises(exceptions.InvalidRxfFile):
+ with self.assertRaises(http_ixload.InvalidRxfFile):
ixload.update_user_count(net_traffic, 123)
@mock.patch('yardstick.network_services.traffic_profile.http_ixload.IxLoad')
diff --git a/yardstick/tests/unit/network_services/traffic_profile/test_ixia_rfc2544.py b/yardstick/tests/unit/network_services/traffic_profile/test_ixia_rfc2544.py
index ef16676c7..7b5165c39 100644
--- a/yardstick/tests/unit/network_services/traffic_profile/test_ixia_rfc2544.py
+++ b/yardstick/tests/unit/network_services/traffic_profile/test_ixia_rfc2544.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -487,7 +487,9 @@ class TestIXIARFC2544Profile(unittest.TestCase):
result = r_f_c2544_profile._get_ixia_traffic_profile({})
self.assertDictEqual(result, expected)
- def test__ixia_traffic_generate(self):
+ @mock.patch.object(ixia_rfc2544.IXIARFC2544Profile,
+ '_update_traffic_tracking_options')
+ def test__ixia_traffic_generate(self, mock_upd_tracking_opts):
traffic_generator = mock.Mock(
autospec=trex_traffic_profile.TrexProfile)
traffic_generator.networks = {
@@ -502,8 +504,62 @@ class TestIXIARFC2544Profile(unittest.TestCase):
r_f_c2544_profile = ixia_rfc2544.IXIARFC2544Profile(
self.TRAFFIC_PROFILE)
r_f_c2544_profile.rate = 100
- result = r_f_c2544_profile._ixia_traffic_generate(traffic, ixia_obj)
+ result = r_f_c2544_profile._ixia_traffic_generate(traffic, ixia_obj,
+ traffic_generator)
self.assertIsNone(result)
+ mock_upd_tracking_opts.assert_called_once_with(traffic_generator)
+
+ def test__update_traffic_tracking_options(self):
+ mock_traffic_gen = mock.Mock()
+ rfc2544_profile = ixia_rfc2544.IXIARFC2544Profile(self.TRAFFIC_PROFILE)
+ rfc2544_profile._update_traffic_tracking_options(mock_traffic_gen)
+ mock_traffic_gen.update_tracking_options.assert_called_once()
+
+ def test__get_framesize(self):
+ traffic_profile = {
+ 'uplink_0': {'outer_l2': {'framesize': {'64B': 100}}},
+ 'downlink_0': {'outer_l2': {'framesize': {'64B': 100}}},
+ 'uplink_1': {'outer_l2': {'framesize': {'64B': 100}}},
+ 'downlink_1': {'outer_l2': {'framesize': {'64B': 100}}}
+ }
+ rfc2544_profile = ixia_rfc2544.IXIARFC2544Profile(self.TRAFFIC_PROFILE)
+ with mock.patch.object(rfc2544_profile, '_get_ixia_traffic_profile') \
+ as mock_get_tp:
+ mock_get_tp.return_value = traffic_profile
+ result = rfc2544_profile._get_framesize()
+ self.assertEqual(result, '64B')
+
+ def test__get_framesize_IMIX_traffic(self):
+ traffic_profile = {
+ 'uplink_0': {'outer_l2': {'framesize': {'64B': 50,
+ '128B': 50}}},
+ 'downlink_0': {'outer_l2': {'framesize': {'64B': 50,
+ '128B': 50}}},
+ 'uplink_1': {'outer_l2': {'framesize': {'64B': 50,
+ '128B': 50}}},
+ 'downlink_1': {'outer_l2': {'framesize': {'64B': 50,
+ '128B': 50}}}
+ }
+ rfc2544_profile = ixia_rfc2544.IXIARFC2544Profile(self.TRAFFIC_PROFILE)
+ with mock.patch.object(rfc2544_profile, '_get_ixia_traffic_profile') \
+ as mock_get_tp:
+ mock_get_tp.return_value = traffic_profile
+ result = rfc2544_profile._get_framesize()
+ self.assertEqual(result, 'IMIX')
+
+ def test__get_framesize_zero_pkt_size_weight(self):
+ traffic_profile = {
+ 'uplink_0': {'outer_l2': {'framesize': {'64B': 0}}},
+ 'downlink_0': {'outer_l2': {'framesize': {'64B': 0}}},
+ 'uplink_1': {'outer_l2': {'framesize': {'64B': 0}}},
+ 'downlink_1': {'outer_l2': {'framesize': {'64B': 0}}}
+ }
+ rfc2544_profile = ixia_rfc2544.IXIARFC2544Profile(self.TRAFFIC_PROFILE)
+ with mock.patch.object(rfc2544_profile, '_get_ixia_traffic_profile') \
+ as mock_get_tp:
+ mock_get_tp.return_value = traffic_profile
+ result = rfc2544_profile._get_framesize()
+ self.assertEqual(result, '')
def test_execute_traffic_first_run(self):
rfc2544_profile = ixia_rfc2544.IXIARFC2544Profile(self.TRAFFIC_PROFILE)
@@ -574,18 +630,23 @@ class TestIXIARFC2544Profile(unittest.TestCase):
def test_get_drop_percentage_completed(self):
samples = {'iface_name_1':
{'in_packets': 1000, 'out_packets': 1000,
+ 'in_bytes': 64000, 'out_bytes': 64000,
'Store-Forward_Avg_latency_ns': 20,
'Store-Forward_Min_latency_ns': 15,
'Store-Forward_Max_latency_ns': 25},
'iface_name_2':
{'in_packets': 1005, 'out_packets': 1007,
+ 'in_bytes': 64320, 'out_bytes': 64448,
'Store-Forward_Avg_latency_ns': 23,
'Store-Forward_Min_latency_ns': 13,
'Store-Forward_Max_latency_ns': 28}
}
rfc2544_profile = ixia_rfc2544.IXIARFC2544Profile(self.TRAFFIC_PROFILE)
+ rfc2544_profile.rate = 100.0
+ rfc2544_profile._get_next_rate = mock.Mock(return_value=100.0)
+ rfc2544_profile._get_framesize = mock.Mock(return_value='64B')
completed, samples = rfc2544_profile.get_drop_percentage(
- samples, 0, 1, 4)
+ samples, 0, 1, 4, 0.1)
self.assertTrue(completed)
self.assertEqual(66.9, samples['TxThroughput'])
self.assertEqual(66.833, samples['RxThroughput'])
@@ -593,23 +654,28 @@ class TestIXIARFC2544Profile(unittest.TestCase):
self.assertEqual(21.5, samples['latency_ns_avg'])
self.assertEqual(14.0, samples['latency_ns_min'])
self.assertEqual(26.5, samples['latency_ns_max'])
+ self.assertEqual(100.0, samples['Rate'])
+ self.assertEqual('64B', samples['PktSize'])
def test_get_drop_percentage_over_drop_percentage(self):
samples = {'iface_name_1':
{'in_packets': 1000, 'out_packets': 1000,
+ 'in_bytes': 64000, 'out_bytes': 64000,
'Store-Forward_Avg_latency_ns': 20,
'Store-Forward_Min_latency_ns': 15,
'Store-Forward_Max_latency_ns': 25},
'iface_name_2':
{'in_packets': 1005, 'out_packets': 1007,
+ 'in_bytes': 64320, 'out_bytes': 64448,
'Store-Forward_Avg_latency_ns': 20,
'Store-Forward_Min_latency_ns': 15,
'Store-Forward_Max_latency_ns': 25}
}
rfc2544_profile = ixia_rfc2544.IXIARFC2544Profile(self.TRAFFIC_PROFILE)
rfc2544_profile.rate = 1000
+ rfc2544_profile._get_next_rate = mock.Mock(return_value=50.0)
completed, samples = rfc2544_profile.get_drop_percentage(
- samples, 0, 0.05, 4)
+ samples, 0, 0.05, 4, 0.1)
self.assertFalse(completed)
self.assertEqual(66.9, samples['TxThroughput'])
self.assertEqual(66.833, samples['RxThroughput'])
@@ -619,19 +685,22 @@ class TestIXIARFC2544Profile(unittest.TestCase):
def test_get_drop_percentage_under_drop_percentage(self):
samples = {'iface_name_1':
{'in_packets': 1000, 'out_packets': 1000,
+ 'in_bytes': 64000, 'out_bytes': 64000,
'Store-Forward_Avg_latency_ns': 20,
'Store-Forward_Min_latency_ns': 15,
'Store-Forward_Max_latency_ns': 25},
'iface_name_2':
{'in_packets': 1005, 'out_packets': 1007,
+ 'in_bytes': 64320, 'out_bytes': 64448,
'Store-Forward_Avg_latency_ns': 20,
'Store-Forward_Min_latency_ns': 15,
'Store-Forward_Max_latency_ns': 25}
}
rfc2544_profile = ixia_rfc2544.IXIARFC2544Profile(self.TRAFFIC_PROFILE)
rfc2544_profile.rate = 1000
+ rfc2544_profile._get_next_rate = mock.Mock(return_value=50.0)
completed, samples = rfc2544_profile.get_drop_percentage(
- samples, 0.2, 1, 4)
+ samples, 0.2, 1, 4, 0.1)
self.assertFalse(completed)
self.assertEqual(66.9, samples['TxThroughput'])
self.assertEqual(66.833, samples['RxThroughput'])
@@ -642,19 +711,22 @@ class TestIXIARFC2544Profile(unittest.TestCase):
def test_get_drop_percentage_not_flow(self, *args):
samples = {'iface_name_1':
{'in_packets': 1000, 'out_packets': 0,
+ 'in_bytes': 64000, 'out_bytes': 0,
'Store-Forward_Avg_latency_ns': 20,
'Store-Forward_Min_latency_ns': 15,
'Store-Forward_Max_latency_ns': 25},
'iface_name_2':
{'in_packets': 1005, 'out_packets': 0,
+ 'in_bytes': 64320, 'out_bytes': 0,
'Store-Forward_Avg_latency_ns': 20,
'Store-Forward_Min_latency_ns': 15,
'Store-Forward_Max_latency_ns': 25}
}
rfc2544_profile = ixia_rfc2544.IXIARFC2544Profile(self.TRAFFIC_PROFILE)
rfc2544_profile.rate = 1000
+ rfc2544_profile._get_next_rate = mock.Mock(return_value=50.0)
completed, samples = rfc2544_profile.get_drop_percentage(
- samples, 0.2, 1, 4)
+ samples, 0.2, 1, 4, 0.1)
self.assertFalse(completed)
self.assertEqual(0.0, samples['TxThroughput'])
self.assertEqual(66.833, samples['RxThroughput'])
@@ -664,24 +736,66 @@ class TestIXIARFC2544Profile(unittest.TestCase):
def test_get_drop_percentage_first_run(self):
samples = {'iface_name_1':
{'in_packets': 1000, 'out_packets': 1000,
+ 'in_bytes': 64000, 'out_bytes': 64000,
'Store-Forward_Avg_latency_ns': 20,
'Store-Forward_Min_latency_ns': 15,
'Store-Forward_Max_latency_ns': 25},
'iface_name_2':
{'in_packets': 1005, 'out_packets': 1007,
+ 'in_bytes': 64320, 'out_bytes': 64448,
'Store-Forward_Avg_latency_ns': 20,
'Store-Forward_Min_latency_ns': 15,
'Store-Forward_Max_latency_ns': 25}
}
rfc2544_profile = ixia_rfc2544.IXIARFC2544Profile(self.TRAFFIC_PROFILE)
+ rfc2544_profile._get_next_rate = mock.Mock(return_value=50.0)
completed, samples = rfc2544_profile.get_drop_percentage(
- samples, 0, 1, 4, first_run=True)
+ samples, 0, 1, 4, 0.1, first_run=True)
self.assertTrue(completed)
self.assertEqual(66.9, samples['TxThroughput'])
self.assertEqual(66.833, samples['RxThroughput'])
self.assertEqual(0.099651, samples['DropPercentage'])
self.assertEqual(33.45, rfc2544_profile.rate)
+ def test_get_drop_percentage_resolution(self):
+ rfc2544_profile = ixia_rfc2544.IXIARFC2544Profile(self.TRAFFIC_PROFILE)
+ rfc2544_profile._get_next_rate = mock.Mock(return_value=0.1)
+ samples = {'iface_name_1':
+ {'in_packets': 1000, 'out_packets': 1000,
+ 'in_bytes': 64000, 'out_bytes': 64000,
+ 'Store-Forward_Avg_latency_ns': 20,
+ 'Store-Forward_Min_latency_ns': 15,
+ 'Store-Forward_Max_latency_ns': 25},
+ 'iface_name_2':
+ {'in_packets': 1005, 'out_packets': 1007,
+ 'in_bytes': 64320, 'out_bytes': 64448,
+ 'Store-Forward_Avg_latency_ns': 20,
+ 'Store-Forward_Min_latency_ns': 15,
+ 'Store-Forward_Max_latency_ns': 25}
+ }
+ rfc2544_profile.rate = 0.19
+ completed, _ = rfc2544_profile.get_drop_percentage(
+ samples, 0, 0.05, 4, 0.1)
+ self.assertTrue(completed)
+
+ samples = {'iface_name_1':
+ {'in_packets': 1000, 'out_packets': 1000,
+ 'in_bytes': 64000, 'out_bytes': 64000,
+ 'Store-Forward_Avg_latency_ns': 20,
+ 'Store-Forward_Min_latency_ns': 15,
+ 'Store-Forward_Max_latency_ns': 25},
+ 'iface_name_2':
+ {'in_packets': 1005, 'out_packets': 1007,
+ 'in_bytes': 64320, 'out_bytes': 64448,
+ 'Store-Forward_Avg_latency_ns': 20,
+ 'Store-Forward_Min_latency_ns': 15,
+ 'Store-Forward_Max_latency_ns': 25}
+ }
+ rfc2544_profile.rate = 0.5
+ completed, _ = rfc2544_profile.get_drop_percentage(
+ samples, 0, 0.05, 4, 0.1)
+ self.assertFalse(completed)
+
class TestIXIARFC2544PppoeScenarioProfile(unittest.TestCase):
@@ -701,6 +815,8 @@ class TestIXIARFC2544PppoeScenarioProfile(unittest.TestCase):
def setUp(self):
self.ixia_tp = ixia_rfc2544.IXIARFC2544PppoeScenarioProfile(
self.TRAFFIC_PROFILE)
+ self.ixia_tp.rate = 100.0
+ self.ixia_tp._get_next_rate = mock.Mock(return_value=50.0)
def test___init__(self):
self.assertIsInstance(self.ixia_tp.full_profile,
@@ -715,3 +831,195 @@ class TestIXIARFC2544PppoeScenarioProfile(unittest.TestCase):
self.ixia_tp._get_flow_groups_params()
self.assertDictEqual(self.ixia_tp.full_profile, expected_tp)
+
+ @mock.patch.object(ixia_rfc2544.IXIARFC2544PppoeScenarioProfile,
+ '_get_flow_groups_params')
+ def test_update_traffic_profile(self, mock_get_flow_groups_params):
+ networks = {
+ 'uplink_0': 'data1',
+ 'downlink_0': 'data2',
+ 'uplink_1': 'data3',
+ 'downlink_1': 'data4'
+ }
+ ports = ['xe0', 'xe1', 'xe2', 'xe3']
+ mock_traffic_gen = mock.Mock()
+ mock_traffic_gen.networks = networks
+ mock_traffic_gen.vnfd_helper.port_num.side_effect = ports
+ self.ixia_tp.update_traffic_profile(mock_traffic_gen)
+ mock_get_flow_groups_params.assert_called_once()
+ self.assertEqual(self.ixia_tp.ports, ports)
+
+ def test__get_prio_flows_drop_percentage(self):
+
+ input_stats = {
+ '0': {
+ 'in_packets': 50,
+ 'out_packets': 100,
+ 'Store-Forward_Avg_latency_ns': 10,
+ 'Store-Forward_Min_latency_ns': 10,
+ 'Store-Forward_Max_latency_ns': 10}}
+
+ result = self.ixia_tp._get_prio_flows_drop_percentage(input_stats)
+ self.assertIsNotNone(result['0'].get('DropPercentage'))
+ self.assertEqual(result['0'].get('DropPercentage'), 50.0)
+
+ def test__get_prio_flows_drop_percentage_traffic_not_flowing(self):
+ input_stats = {
+ '0': {
+ 'in_packets': 0,
+ 'out_packets': 0,
+ 'Store-Forward_Avg_latency_ns': 0,
+ 'Store-Forward_Min_latency_ns': 0,
+ 'Store-Forward_Max_latency_ns': 0}}
+
+ result = self.ixia_tp._get_prio_flows_drop_percentage(input_stats)
+ self.assertIsNotNone(result['0'].get('DropPercentage'))
+ self.assertEqual(result['0'].get('DropPercentage'), 100)
+
+ def test__get_summary_pppoe_subs_counters(self):
+ input_stats = {
+ 'xe0': {
+ 'out_packets': 100,
+ 'sessions_up': 4,
+ 'sessions_down': 0,
+ 'sessions_not_started': 0,
+ 'sessions_total': 4},
+ 'xe1': {
+ 'out_packets': 100,
+ 'sessions_up': 4,
+ 'sessions_down': 0,
+ 'sessions_not_started': 0,
+ 'sessions_total': 4}
+ }
+
+ expected_stats = {
+ 'sessions_up': 8,
+ 'sessions_down': 0,
+ 'sessions_not_started': 0,
+ 'sessions_total': 8
+ }
+
+ res = self.ixia_tp._get_summary_pppoe_subs_counters(input_stats)
+ self.assertDictEqual(res, expected_stats)
+
+ @mock.patch.object(ixia_rfc2544.IXIARFC2544PppoeScenarioProfile,
+ '_get_prio_flows_drop_percentage')
+ @mock.patch.object(ixia_rfc2544.IXIARFC2544PppoeScenarioProfile,
+ '_get_summary_pppoe_subs_counters')
+ def test_get_drop_percentage(self, mock_get_pppoe_subs,
+ mock_sum_prio_drop_rate):
+ samples = {
+ 'priority_stats': {
+ '0': {
+ 'in_packets': 100,
+ 'out_packets': 100,
+ 'in_bytes': 6400,
+ 'out_bytes': 6400,
+ 'Store-Forward_Avg_latency_ns': 10,
+ 'Store-Forward_Min_latency_ns': 10,
+ 'Store-Forward_Max_latency_ns': 10}},
+ 'xe0': {
+ 'in_packets': 100,
+ 'out_packets': 100,
+ 'in_bytes': 6400,
+ 'out_bytes': 6400,
+ 'Store-Forward_Avg_latency_ns': 10,
+ 'Store-Forward_Min_latency_ns': 10,
+ 'Store-Forward_Max_latency_ns': 10}}
+
+ mock_get_pppoe_subs.return_value = {'sessions_up': 1}
+ mock_sum_prio_drop_rate.return_value = {'0': {'DropPercentage': 0.0}}
+
+ self.ixia_tp._get_framesize = mock.Mock(return_value='64B')
+ status, res = self.ixia_tp.get_drop_percentage(
+ samples, tol_min=0.0, tolerance=0.0001, precision=0,
+ resolution=0.1, first_run=True)
+ self.assertIsNotNone(res.get('DropPercentage'))
+ self.assertIsNotNone(res.get('priority'))
+ self.assertIsNotNone(res.get('sessions_up'))
+ self.assertEqual(res['DropPercentage'], 0.0)
+ self.assertEqual(res['Rate'], 100.0)
+ self.assertEqual(res['PktSize'], '64B')
+ self.assertTrue(status)
+ mock_sum_prio_drop_rate.assert_called_once()
+ mock_get_pppoe_subs.assert_called_once()
+
+ @mock.patch.object(ixia_rfc2544.IXIARFC2544PppoeScenarioProfile,
+ '_get_prio_flows_drop_percentage')
+ @mock.patch.object(ixia_rfc2544.IXIARFC2544PppoeScenarioProfile,
+ '_get_summary_pppoe_subs_counters')
+ def test_get_drop_percentage_failed_status(self, mock_get_pppoe_subs,
+ mock_sum_prio_drop_rate):
+ samples = {
+ 'priority_stats': {
+ '0': {
+ 'in_packets': 90,
+ 'out_packets': 100,
+ 'in_bytes': 5760,
+ 'out_bytes': 6400,
+ 'Store-Forward_Avg_latency_ns': 10,
+ 'Store-Forward_Min_latency_ns': 10,
+ 'Store-Forward_Max_latency_ns': 10}},
+ 'xe0': {
+ 'in_packets': 90,
+ 'out_packets': 100,
+ 'in_bytes': 5760,
+ 'out_bytes': 6400,
+ 'Store-Forward_Avg_latency_ns': 10,
+ 'Store-Forward_Min_latency_ns': 10,
+ 'Store-Forward_Max_latency_ns': 10}}
+
+ mock_get_pppoe_subs.return_value = {'sessions_up': 1}
+ mock_sum_prio_drop_rate.return_value = {'0': {'DropPercentage': 0.0}}
+
+ status, res = self.ixia_tp.get_drop_percentage(
+ samples, tol_min=0.0, tolerance=0.0001, precision=0,
+ resolution=0.1, first_run=True)
+ self.assertIsNotNone(res.get('DropPercentage'))
+ self.assertIsNotNone(res.get('priority'))
+ self.assertIsNotNone(res.get('sessions_up'))
+ self.assertEqual(res['DropPercentage'], 10.0)
+ self.assertFalse(status)
+ mock_sum_prio_drop_rate.assert_called_once()
+ mock_get_pppoe_subs.assert_called_once()
+
+ @mock.patch.object(ixia_rfc2544.IXIARFC2544PppoeScenarioProfile,
+ '_get_prio_flows_drop_percentage')
+ @mock.patch.object(ixia_rfc2544.IXIARFC2544PppoeScenarioProfile,
+ '_get_summary_pppoe_subs_counters')
+ def test_get_drop_percentage_priority_flow_check(self, mock_get_pppoe_subs,
+ mock_sum_prio_drop_rate):
+ samples = {
+ 'priority_stats': {
+ '0': {
+ 'in_packets': 100,
+ 'out_packets': 100,
+ 'in_bytes': 6400,
+ 'out_bytes': 6400,
+ 'Store-Forward_Avg_latency_ns': 10,
+ 'Store-Forward_Min_latency_ns': 10,
+ 'Store-Forward_Max_latency_ns': 10}},
+ 'xe0': {
+ 'in_packets': 90,
+ 'out_packets': 100,
+ 'in_bytes': 5760,
+ 'out_bytes': 6400,
+ 'Store-Forward_Avg_latency_ns': 10,
+ 'Store-Forward_Min_latency_ns': 10,
+ 'Store-Forward_Max_latency_ns': 10
+ }}
+
+ mock_get_pppoe_subs.return_value = {'sessions_up': 1}
+ mock_sum_prio_drop_rate.return_value = {'0': {'DropPercentage': 0.0}}
+
+ tc_rfc2544_opts = {'priority': '0',
+ 'allowed_drop_rate': '0.0001 - 0.0001'}
+ status, res = self.ixia_tp.get_drop_percentage(
+ samples, tol_min=15.0000, tolerance=15.0001, precision=0,
+ resolution=0.1, first_run=True, tc_rfc2544_opts=tc_rfc2544_opts)
+ self.assertIsNotNone(res.get('DropPercentage'))
+ self.assertIsNotNone(res.get('priority'))
+ self.assertIsNotNone(res.get('sessions_up'))
+ self.assertTrue(status)
+ mock_sum_prio_drop_rate.assert_called_once()
+ mock_get_pppoe_subs.assert_called_once()
diff --git a/yardstick/tests/unit/network_services/traffic_profile/test_prox_irq.py b/yardstick/tests/unit/network_services/traffic_profile/test_prox_irq.py
index 59f37befa..1d9eb0887 100644
--- a/yardstick/tests/unit/network_services/traffic_profile/test_prox_irq.py
+++ b/yardstick/tests/unit/network_services/traffic_profile/test_prox_irq.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2018 Intel Corporation
+# Copyright (c) 2018-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -11,6 +11,7 @@
# 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 time
import unittest
import mock
@@ -28,7 +29,8 @@ class TestProxIrqProfile(unittest.TestCase):
def _stop_mocks(self):
self._mock_log_info.stop()
- def test_execute_1(self):
+ @mock.patch.object(time, 'sleep')
+ def test_execute_1(self, *args):
tp_config = {
'traffic_profile': {
},
diff --git a/yardstick/tests/unit/network_services/traffic_profile/test_prox_profile.py b/yardstick/tests/unit/network_services/traffic_profile/test_prox_profile.py
index 11bee03a4..1593a0835 100644
--- a/yardstick/tests/unit/network_services/traffic_profile/test_prox_profile.py
+++ b/yardstick/tests/unit/network_services/traffic_profile/test_prox_profile.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2017 Intel Corporation
+# Copyright (c) 2017-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
+import time
import unittest
import mock
@@ -78,7 +79,8 @@ class TestProxProfile(unittest.TestCase):
profile.init(queue)
self.assertIs(profile.queue, queue)
- def test_execute_traffic(self):
+ @mock.patch.object(time, 'sleep')
+ def test_execute_traffic(self, *args):
packet_sizes = [
10,
100,
diff --git a/yardstick/tests/unit/network_services/traffic_profile/test_rfc2544.py b/yardstick/tests/unit/network_services/traffic_profile/test_rfc2544.py
index b8fbc6344..c72a72d3d 100644
--- a/yardstick/tests/unit/network_services/traffic_profile/test_rfc2544.py
+++ b/yardstick/tests/unit/network_services/traffic_profile/test_rfc2544.py
@@ -255,31 +255,41 @@ class TestRFC2544Profile(base.BaseUnitTestCase):
'rx_throughput_fps': 101,
'out_packets': 2100,
'in_packets': 2010,
+ 'out_bytes': 134400,
+ 'in_bytes': 128640,
'timestamp': datetime.datetime(2000, 1, 1, 1, 1, 1, 1)},
'xe2': {'tx_throughput_fps': 210,
'rx_throughput_fps': 201,
'out_packets': 4100,
'in_packets': 4010,
+ 'out_bytes': 262400,
+ 'in_bytes': 256640,
'timestamp': datetime.datetime(2000, 1, 1, 1, 1, 1, 1)}},
{'xe1': {'tx_throughput_fps': 156,
'rx_throughput_fps': 108,
'out_packets': 2110,
'in_packets': 2040,
+ 'out_bytes': 135040,
+ 'in_bytes': 130560,
'latency': 'Latency1',
'timestamp': datetime.datetime(2000, 1, 1, 1, 1, 1, 31)},
'xe2': {'tx_throughput_fps': 253,
'rx_throughput_fps': 215,
'out_packets': 4150,
'in_packets': 4010,
+ 'out_bytes': 265600,
+ 'in_bytes': 256640,
'latency': 'Latency2',
'timestamp': datetime.datetime(2000, 1, 1, 1, 1, 1, 31)}}
]
completed, output = rfc2544_profile.get_drop_percentage(
- samples, 0, 0, False)
+ samples, 0, 0, False, 0.1)
expected = {'DropPercentage': 50.0,
'Latency': {'xe1': 'Latency1', 'xe2': 'Latency2'},
'RxThroughput': 1000000.0,
'TxThroughput': 2000000.0,
+ 'RxThroughputBps': 64000000.0,
+ 'TxThroughputBps': 128000000.0,
'CurrentDropPercentage': 50.0,
'Rate': 100.0,
'Throughput': 1000000.0}
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_acl_vnf.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_acl_vnf.py
index 69a5fb484..12bb42f20 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_acl_vnf.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_acl_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -237,7 +237,7 @@ class TestAclApproxVnf(unittest.TestCase):
def test___init__(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- acl_approx_vnf = acl_vnf.AclApproxVnf(name, vnfd, 'task_id')
+ acl_approx_vnf = acl_vnf.AclApproxVnf(name, vnfd)
self.assertIsNone(acl_approx_vnf._vnf_process)
@mock.patch("yardstick.network_services.vnf_generic.vnf.sample_vnf.time")
@@ -247,7 +247,7 @@ class TestAclApproxVnf(unittest.TestCase):
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- acl_approx_vnf = acl_vnf.AclApproxVnf(name, vnfd, 'task_id')
+ acl_approx_vnf = acl_vnf.AclApproxVnf(name, vnfd)
acl_approx_vnf.scenario_helper.scenario_cfg = {
'nodes': {acl_approx_vnf.name: "mock"}
}
@@ -270,7 +270,7 @@ class TestAclApproxVnf(unittest.TestCase):
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- acl_approx_vnf = acl_vnf.AclApproxVnf(name, vnfd, 'task_id')
+ acl_approx_vnf = acl_vnf.AclApproxVnf(name, vnfd)
acl_approx_vnf.q_in = mock.MagicMock()
acl_approx_vnf.q_out = mock.MagicMock()
acl_approx_vnf.q_out.qsize = mock.Mock(return_value=0)
@@ -282,7 +282,7 @@ class TestAclApproxVnf(unittest.TestCase):
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- acl_approx_vnf = acl_vnf.AclApproxVnf(name, vnfd, 'task_id')
+ acl_approx_vnf = acl_vnf.AclApproxVnf(name, vnfd)
acl_approx_vnf.q_in = mock.MagicMock()
acl_approx_vnf.q_out = mock.MagicMock()
acl_approx_vnf.q_out.qsize = mock.Mock(return_value=0)
@@ -303,7 +303,7 @@ class TestAclApproxVnf(unittest.TestCase):
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- acl_approx_vnf = acl_vnf.AclApproxVnf(name, vnfd, 'task_id')
+ acl_approx_vnf = acl_vnf.AclApproxVnf(name, vnfd)
acl_approx_vnf._build_config = mock.MagicMock()
acl_approx_vnf.queue_wrapper = mock.MagicMock()
acl_approx_vnf.scenario_helper.scenario_cfg = self.scenario_cfg
@@ -323,7 +323,7 @@ class TestAclApproxVnf(unittest.TestCase):
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- acl_approx_vnf = acl_vnf.AclApproxVnf(name, vnfd, 'task_id')
+ acl_approx_vnf = acl_vnf.AclApproxVnf(name, vnfd)
acl_approx_vnf.deploy_helper = mock.MagicMock()
acl_approx_vnf.resource_helper = mock.MagicMock()
acl_approx_vnf._build_config = mock.MagicMock()
@@ -341,7 +341,7 @@ class TestAclApproxVnf(unittest.TestCase):
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- acl_approx_vnf = acl_vnf.AclApproxVnf(name, vnfd, 'task_id')
+ acl_approx_vnf = acl_vnf.AclApproxVnf(name, vnfd)
acl_approx_vnf._vnf_process = mock.MagicMock()
acl_approx_vnf._vnf_process.terminate = mock.Mock()
acl_approx_vnf.used_drivers = {"01:01.0": "i40e",
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_agnostic_vnf.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_agnostic_vnf.py
index 3374cbe76..7c7fe5955 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_agnostic_vnf.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_agnostic_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2018 Intel Corporation
+# Copyright (c) 2018-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -13,7 +13,6 @@
# limitations under the License.
import unittest
-import uuid
from yardstick.network_services.vnf_generic.vnf import agnostic_vnf
@@ -44,9 +43,8 @@ VNFD = {
class TestAgnosticVnf(unittest.TestCase):
def setUp(self):
- self._id = uuid.uuid1().int
self.vnfd = VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- self.agnostic_vnf = agnostic_vnf.AgnosticVnf(NAME, self.vnfd, self._id)
+ self.agnostic_vnf = agnostic_vnf.AgnosticVnf(NAME, self.vnfd)
def test_instantiate(self):
self.assertIsNone(self.agnostic_vnf.instantiate({}, {}))
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_base.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_base.py
index 2ea13a5e0..1a72e042b 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_base.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_base.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -14,15 +14,10 @@
import multiprocessing
import os
-import uuid
import mock
-from oslo_config import cfg
-import oslo_messaging
import unittest
-from yardstick.common import messaging
-from yardstick.common.messaging import payloads
from yardstick.network_services.vnf_generic.vnf import base
from yardstick.ssh import SSH
from yardstick.tests.unit import base as ut_base
@@ -145,24 +140,6 @@ VNFD = {
}
-class _DummyGenericTrafficGen(base.GenericTrafficGen): # pragma: no cover
-
- def run_traffic(self, *args):
- pass
-
- def terminate(self):
- pass
-
- def collect_kpi(self):
- pass
-
- def instantiate(self, *args):
- pass
-
- def scale(self, flavor=''):
- pass
-
-
class FileAbsPath(object):
def __init__(self, module_file):
super(FileAbsPath, self).__init__()
@@ -235,8 +212,7 @@ class TestGenericVNF(ut_base.BaseUnitTestCase):
"""Make sure that the abstract class cannot be instantiated"""
with self.assertRaises(TypeError) as exc:
# pylint: disable=abstract-class-instantiated
- base.GenericVNF('vnf1', VNFD['vnfd:vnfd-catalog']['vnfd'][0],
- 'task_id')
+ base.GenericVNF('vnf1', VNFD['vnfd:vnfd-catalog']['vnfd'][0])
msg = ("Can't instantiate abstract class GenericVNF with abstract "
"methods collect_kpi, instantiate, scale, start_collect, "
@@ -253,96 +229,8 @@ class GenericTrafficGenTestCase(ut_base.BaseUnitTestCase):
name = 'vnf1'
with self.assertRaises(TypeError) as exc:
# pylint: disable=abstract-class-instantiated
- base.GenericTrafficGen(name, vnfd, 'task_id')
+ base.GenericTrafficGen(name, vnfd)
msg = ("Can't instantiate abstract class GenericTrafficGen with "
"abstract methods collect_kpi, instantiate, run_traffic, "
"scale, terminate")
self.assertEqual(msg, str(exc.exception))
-
- def test_get_mq_producer_id(self):
- vnfd = {'benchmark': {'kpi': mock.ANY},
- 'vdu': [{'external-interface': 'ext_int'}]
- }
- tg = _DummyGenericTrafficGen('name', vnfd, 'task_id')
- tg._mq_producer = mock.Mock()
- tg._mq_producer.id = 'fake_id'
- self.assertEqual('fake_id', tg.get_mq_producer_id())
-
-
-class TrafficGeneratorProducerTestCase(ut_base.BaseUnitTestCase):
-
- @mock.patch.object(oslo_messaging, 'Target', return_value='rpc_target')
- @mock.patch.object(oslo_messaging, 'RPCClient')
- @mock.patch.object(oslo_messaging, 'get_rpc_transport',
- return_value='rpc_transport')
- @mock.patch.object(cfg, 'CONF')
- def test__init(self, mock_config, mock_transport, mock_rpcclient,
- mock_target):
- _id = uuid.uuid1().int
- tg_producer = base.TrafficGeneratorProducer(_id)
- mock_transport.assert_called_once_with(
- mock_config, url='rabbit://yardstick:yardstick@localhost:5672/')
- mock_target.assert_called_once_with(topic=messaging.TOPIC_TG,
- fanout=True,
- server=messaging.SERVER)
- mock_rpcclient.assert_called_once_with('rpc_transport', 'rpc_target')
- self.assertEqual(_id, tg_producer._id)
- self.assertEqual(messaging.TOPIC_TG, tg_producer._topic)
-
- @mock.patch.object(oslo_messaging, 'Target', return_value='rpc_target')
- @mock.patch.object(oslo_messaging, 'RPCClient')
- @mock.patch.object(oslo_messaging, 'get_rpc_transport',
- return_value='rpc_transport')
- @mock.patch.object(payloads, 'TrafficGeneratorPayload',
- return_value='tg_pload')
- def test_tg_method_started(self, mock_tg_payload, *args):
- tg_producer = base.TrafficGeneratorProducer(uuid.uuid1().int)
- with mock.patch.object(tg_producer, 'send_message') as mock_message:
- tg_producer.tg_method_started(version=10)
-
- mock_message.assert_called_once_with(messaging.TG_METHOD_STARTED,
- 'tg_pload')
- mock_tg_payload.assert_called_once_with(version=10, iteration=0,
- kpi={})
-
- @mock.patch.object(oslo_messaging, 'Target', return_value='rpc_target')
- @mock.patch.object(oslo_messaging, 'RPCClient')
- @mock.patch.object(oslo_messaging, 'get_rpc_transport',
- return_value='rpc_transport')
- @mock.patch.object(payloads, 'TrafficGeneratorPayload',
- return_value='tg_pload')
- def test_tg_method_finished(self, mock_tg_payload, *args):
- tg_producer = base.TrafficGeneratorProducer(uuid.uuid1().int)
- with mock.patch.object(tg_producer, 'send_message') as mock_message:
- tg_producer.tg_method_finished(version=20)
-
- mock_message.assert_called_once_with(messaging.TG_METHOD_FINISHED,
- 'tg_pload')
- mock_tg_payload.assert_called_once_with(version=20, iteration=0,
- kpi={})
-
- @mock.patch.object(oslo_messaging, 'Target', return_value='rpc_target')
- @mock.patch.object(oslo_messaging, 'RPCClient')
- @mock.patch.object(oslo_messaging, 'get_rpc_transport',
- return_value='rpc_transport')
- @mock.patch.object(payloads, 'TrafficGeneratorPayload',
- return_value='tg_pload')
- def test_tg_method_iteration(self, mock_tg_payload, *args):
- tg_producer = base.TrafficGeneratorProducer(uuid.uuid1().int)
- with mock.patch.object(tg_producer, 'send_message') as mock_message:
- tg_producer.tg_method_iteration(100, version=30, kpi={'k': 'v'})
-
- mock_message.assert_called_once_with(messaging.TG_METHOD_ITERATION,
- 'tg_pload')
- mock_tg_payload.assert_called_once_with(version=30, iteration=100,
- kpi={'k': 'v'})
-
-
-class GenericVNFConsumerTestCase(ut_base.BaseUnitTestCase):
-
- def test__init(self):
- endpoints = 'endpoint_1'
- _ids = [uuid.uuid1().int]
- gvnf_consumer = base.GenericVNFConsumer(_ids, endpoints)
- self.assertEqual(_ids, gvnf_consumer._ids)
- self.assertEqual([endpoints], gvnf_consumer._endpoints)
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_cgnapt_vnf.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_cgnapt_vnf.py
index 32f5b758d..d0672dcfd 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_cgnapt_vnf.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_cgnapt_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -318,14 +318,14 @@ class TestCgnaptApproxVnf(unittest.TestCase):
def test___init__(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- cgnapt_approx_vnf = cgnapt_vnf.CgnaptApproxVnf(name, vnfd, 'task_id')
+ cgnapt_approx_vnf = cgnapt_vnf.CgnaptApproxVnf(name, vnfd)
self.assertIsNone(cgnapt_approx_vnf._vnf_process)
@mock.patch.object(process, 'check_if_process_failed')
@mock.patch.object(ctx_base.Context, 'get_physical_node_from_server', return_value='mock_node')
def test_collect_kpi(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- cgnapt_approx_vnf = cgnapt_vnf.CgnaptApproxVnf(name, vnfd, 'task_id')
+ cgnapt_approx_vnf = cgnapt_vnf.CgnaptApproxVnf(name, vnfd)
cgnapt_approx_vnf.scenario_helper.scenario_cfg = {
'nodes': {cgnapt_approx_vnf.name: "mock"}
}
@@ -349,7 +349,7 @@ class TestCgnaptApproxVnf(unittest.TestCase):
@mock.patch.object(time, 'sleep')
def test_vnf_execute_command(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- cgnapt_approx_vnf = cgnapt_vnf.CgnaptApproxVnf(name, vnfd, 'task_id')
+ cgnapt_approx_vnf = cgnapt_vnf.CgnaptApproxVnf(name, vnfd)
cgnapt_approx_vnf.q_in = mock.Mock()
cgnapt_approx_vnf.q_out = mock.Mock()
cgnapt_approx_vnf.q_out.qsize = mock.Mock(return_value=0)
@@ -357,7 +357,7 @@ class TestCgnaptApproxVnf(unittest.TestCase):
def test_get_stats(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- cgnapt_approx_vnf = cgnapt_vnf.CgnaptApproxVnf(name, vnfd, 'task_id')
+ cgnapt_approx_vnf = cgnapt_vnf.CgnaptApproxVnf(name, vnfd)
with mock.patch.object(cgnapt_approx_vnf, 'vnf_execute') as mock_exec:
mock_exec.return_value = 'output'
self.assertEqual('output', cgnapt_approx_vnf.get_stats())
@@ -366,7 +366,7 @@ class TestCgnaptApproxVnf(unittest.TestCase):
def test_run_vcgnapt(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- cgnapt_approx_vnf = cgnapt_vnf.CgnaptApproxVnf(name, vnfd, 'task_id')
+ cgnapt_approx_vnf = cgnapt_vnf.CgnaptApproxVnf(name, vnfd)
cgnapt_approx_vnf.ssh_helper = mock.Mock()
cgnapt_approx_vnf.setup_helper = mock.Mock()
with mock.patch.object(cgnapt_approx_vnf, '_build_config'), \
@@ -379,7 +379,7 @@ class TestCgnaptApproxVnf(unittest.TestCase):
@mock.patch.object(ctx_base.Context, 'get_context_from_server')
def test_instantiate(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- cgnapt_approx_vnf = cgnapt_vnf.CgnaptApproxVnf(name, vnfd, 'task_id')
+ cgnapt_approx_vnf = cgnapt_vnf.CgnaptApproxVnf(name, vnfd)
cgnapt_approx_vnf.deploy_helper = mock.MagicMock()
cgnapt_approx_vnf.resource_helper = mock.MagicMock()
cgnapt_approx_vnf._build_config = mock.MagicMock()
@@ -396,7 +396,7 @@ class TestCgnaptApproxVnf(unittest.TestCase):
def test__vnf_up_post(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
self.scenario_cfg['options'][name]['napt'] = 'static'
- cgnapt_approx_vnf = cgnapt_vnf.CgnaptApproxVnf(name, vnfd, 'task_id')
+ cgnapt_approx_vnf = cgnapt_vnf.CgnaptApproxVnf(name, vnfd)
cgnapt_approx_vnf.vnf_execute = mock.Mock()
cgnapt_approx_vnf.scenario_helper.scenario_cfg = self.scenario_cfg
with mock.patch.object(cgnapt_approx_vnf, 'setup_helper') as \
@@ -407,6 +407,6 @@ class TestCgnaptApproxVnf(unittest.TestCase):
def test__vnf_up_post_short(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- cgnapt_approx_vnf = cgnapt_vnf.CgnaptApproxVnf(name, vnfd, 'task_id')
+ cgnapt_approx_vnf = cgnapt_vnf.CgnaptApproxVnf(name, vnfd)
cgnapt_approx_vnf.scenario_helper.scenario_cfg = self.scenario_cfg
cgnapt_approx_vnf._vnf_up_post()
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_epc_vnf.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_epc_vnf.py
index 6d14ddb54..b1bef2e39 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_epc_vnf.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_epc_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2018 Intel Corporation
+# Copyright (c) 2018-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -14,7 +14,6 @@
import copy
import unittest
-import uuid
from yardstick.network_services.vnf_generic.vnf import epc_vnf
@@ -45,12 +44,11 @@ VNFD = {
class TestEPCVnf(unittest.TestCase):
def setUp(self):
- self._id = uuid.uuid1().int
self.vnfd = VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- self.epc_vnf = epc_vnf.EPCVnf(NAME, self.vnfd, self._id)
+ self.epc_vnf = epc_vnf.EPCVnf(NAME, self.vnfd)
def test___init__(self, *args):
- _epc_vnf = epc_vnf.EPCVnf(NAME, self.vnfd, self._id)
+ _epc_vnf = epc_vnf.EPCVnf(NAME, self.vnfd)
for x in {'user', 'password', 'ip'}:
self.assertEqual(self.vnfd['mgmt-interface'][x],
_epc_vnf.vnfd_helper.mgmt_interface[x])
@@ -62,7 +60,7 @@ class TestEPCVnf(unittest.TestCase):
def test___init__missing_ip(self, *args):
_vnfd = copy.deepcopy(self.vnfd)
_vnfd['mgmt-interface'].pop('ip')
- _epc_vnf = epc_vnf.EPCVnf(NAME, _vnfd, self._id)
+ _epc_vnf = epc_vnf.EPCVnf(NAME, _vnfd)
for x in {'user', 'password'}:
self.assertEqual(_vnfd['mgmt-interface'][x],
_epc_vnf.vnfd_helper.mgmt_interface[x])
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_prox_helpers.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_prox_helpers.py
index 9a30fb9e9..32f384027 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_prox_helpers.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_prox_helpers.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2018 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -2400,6 +2400,7 @@ class TestProxProfileHelper(unittest.TestCase):
with helper.traffic_context(64, 1):
pass
+ @mock.patch.object(time, 'sleep')
def test_run_test(self, *args):
resource_helper = mock.MagicMock()
resource_helper.step_delta = 0.4
@@ -2549,6 +2550,7 @@ class TestProxBngProfileHelper(unittest.TestCase):
self.assertEqual(helper.arp_task_cores, expected_arp_task)
self.assertEqual(helper._cores_tuple, expected_combined)
+ @mock.patch.object(time, 'sleep')
def test_run_test(self, *args):
resource_helper = mock.MagicMock()
resource_helper.step_delta = 0.4
@@ -2675,6 +2677,7 @@ class TestProxVpeProfileHelper(unittest.TestCase):
self.assertEqual(helper.inet_ports, expected_inet)
self.assertEqual(helper._ports_tuple, expected_combined)
+ @mock.patch.object(time, 'sleep')
def test_run_test(self, *args):
resource_helper = mock.MagicMock()
resource_helper.step_delta = 0.4
@@ -2792,6 +2795,7 @@ class TestProxlwAFTRProfileHelper(unittest.TestCase):
self.assertEqual(helper.inet_ports, expected_inet)
self.assertEqual(helper._ports_tuple, expected_combined)
+ @mock.patch.object(time, 'sleep')
def test_run_test(self, *args):
resource_helper = mock.MagicMock()
resource_helper.step_delta = 0.4
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_prox_irq.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_prox_irq.py
index 4eaa38c27..94197c3be 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_prox_irq.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_prox_irq.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2018 Intel Corporation
+# Copyright (c) 2017-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -312,7 +312,7 @@ class TestProxIrqVNF(unittest.TestCase):
}
def test___init__(self):
- prox_irq_vnf = ProxIrqVNF('vnf1', self.VNFD_0, 'task_id')
+ prox_irq_vnf = ProxIrqVNF('vnf1', self.VNFD_0)
self.assertEqual(prox_irq_vnf.name, 'vnf1')
self.assertDictEqual(prox_irq_vnf.vnfd_helper, self.VNFD_0)
@@ -342,7 +342,7 @@ class TestProxIrqVNF(unittest.TestCase):
build_config_file = mock.MagicMock()
build_config_file.return_value = None
- prox_irq_vnf = ProxIrqVNF(VNF_NAME, vnfd, 'task_id')
+ prox_irq_vnf = ProxIrqVNF(VNF_NAME, vnfd)
startup = ["global", [["eal", "-4"]]]
master_0 = ["core 0", [["mode", "master"]]]
@@ -371,7 +371,7 @@ class TestProxIrqVNF(unittest.TestCase):
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- prox_irq_vnf = ProxIrqVNF(VNF_NAME, vnfd, 'task_id')
+ prox_irq_vnf = ProxIrqVNF(VNF_NAME, vnfd)
prox_irq_vnf.resource_helper = resource_helper = mock.Mock()
resource_helper.execute.side_effect = OSError(errno.EPIPE, "")
@@ -391,7 +391,7 @@ class TestProxIrqVNF(unittest.TestCase):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
mock_ssh(ssh, exec_result=(1, "", ""))
- prox_irq_vnf = ProxIrqVNF(VNF_NAME, vnfd, 'task_id')
+ prox_irq_vnf = ProxIrqVNF(VNF_NAME, vnfd)
prox_irq_vnf._terminated = mock.MagicMock()
prox_irq_vnf._traffic_process = mock.MagicMock()
@@ -414,7 +414,7 @@ class TestProxIrqVNF(unittest.TestCase):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
mock_ssh(ssh, exec_result=(1, "", ""))
- prox_irq_vnf = ProxIrqVNF(VNF_NAME, vnfd, 'task_id')
+ prox_irq_vnf = ProxIrqVNF(VNF_NAME, vnfd)
prox_irq_vnf._terminated = mock.MagicMock()
prox_irq_vnf._traffic_process = mock.MagicMock()
@@ -714,18 +714,18 @@ class TestProxIrqGen(unittest.TestCase):
def test__check_status(self):
- prox_irq_gen = ProxIrqGen('tg1', self.VNFD_0, 'task_id')
+ prox_irq_gen = ProxIrqGen('tg1', self.VNFD_0)
with self.assertRaises(NotImplementedError):
prox_irq_gen._check_status()
def test_listen_traffic(self):
- prox_irq_gen = ProxIrqGen('tg1', self.VNFD_0, 'task_id')
+ prox_irq_gen = ProxIrqGen('tg1', self.VNFD_0)
prox_irq_gen.listen_traffic(mock.Mock())
def test_verify_traffic(self):
- prox_irq_gen = ProxIrqGen('tg1', self.VNFD_0, 'task_id')
+ prox_irq_gen = ProxIrqGen('tg1', self.VNFD_0)
prox_irq_gen.verify_traffic(mock.Mock())
@@ -734,7 +734,7 @@ class TestProxIrqGen(unittest.TestCase):
def test_terminate(self, ssh, *args):
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- prox_traffic_gen = ProxIrqGen(VNF_NAME, vnfd, 'task_id')
+ prox_traffic_gen = ProxIrqGen(VNF_NAME, vnfd)
prox_traffic_gen._terminated = mock.MagicMock()
prox_traffic_gen._traffic_process = mock.MagicMock()
prox_traffic_gen._traffic_process.terminate = mock.Mock()
@@ -747,7 +747,7 @@ class TestProxIrqGen(unittest.TestCase):
self.assertIsNone(prox_traffic_gen.terminate())
def test__wait_for_process(self):
- prox_irq_gen = ProxIrqGen('tg1', self.VNFD_0, 'task_id')
+ prox_irq_gen = ProxIrqGen('tg1', self.VNFD_0)
with mock.patch.object(prox_irq_gen, '_check_status',
return_value=0) as mock_status, \
mock.patch.object(prox_irq_gen, '_tg_process') as mock_proc:
@@ -758,14 +758,14 @@ class TestProxIrqGen(unittest.TestCase):
mock_status.assert_called_once()
def test__wait_for_process_not_alive(self):
- prox_irq_gen = ProxIrqGen('tg1', self.VNFD_0, 'task_id')
+ prox_irq_gen = ProxIrqGen('tg1', self.VNFD_0)
with mock.patch.object(prox_irq_gen, '_tg_process') as mock_proc:
mock_proc.is_alive.return_value = False
self.assertRaises(RuntimeError, prox_irq_gen._wait_for_process)
mock_proc.is_alive.assert_called_once()
def test__wait_for_process_delayed(self):
- prox_irq_gen = ProxIrqGen('tg1', self.VNFD_0, 'task_id')
+ prox_irq_gen = ProxIrqGen('tg1', self.VNFD_0)
with mock.patch.object(prox_irq_gen, '_check_status',
side_effect=[1, 0]) as mock_status, \
mock.patch.object(prox_irq_gen,
@@ -777,7 +777,7 @@ class TestProxIrqGen(unittest.TestCase):
mock_status.assert_has_calls([mock.call(), mock.call()])
def test_scale(self):
- prox_irq_gen = ProxIrqGen('tg1', self.VNFD_0, 'task_id')
+ prox_irq_gen = ProxIrqGen('tg1', self.VNFD_0)
self.assertRaises(y_exceptions.FunctionNotImplemented,
prox_irq_gen.scale)
@@ -804,7 +804,7 @@ class TestProxIrqGen(unittest.TestCase):
build_config_file = mock.MagicMock()
build_config_file.return_value = None
- prox_irq_gen = ProxIrqGen(VNF_NAME, vnfd, 'task_id')
+ prox_irq_gen = ProxIrqGen(VNF_NAME, vnfd)
startup = ["global", [["eal", "-4"]]]
master_0 = ["core 0", [["mode", "master"]]]
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_prox_vnf.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_prox_vnf.py
index 62cbea0bb..76fd74dfe 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_prox_vnf.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_prox_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -317,7 +317,7 @@ class TestProxApproxVnf(unittest.TestCase):
@mock.patch(SSH_HELPER)
def test___init__(self, ssh, *args):
mock_ssh(ssh)
- prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0, 'task_id')
+ prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0)
self.assertIsNone(prox_approx_vnf._vnf_process)
@mock.patch.object(ctx_base.Context, 'get_physical_node_from_server', return_value='mock_node')
@@ -325,7 +325,7 @@ class TestProxApproxVnf(unittest.TestCase):
def test_collect_kpi_no_client(self, ssh, *args):
mock_ssh(ssh)
- prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0, 'task_id')
+ prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0)
prox_approx_vnf.scenario_helper.scenario_cfg = {
'nodes': {prox_approx_vnf.name: "mock"}
}
@@ -352,7 +352,7 @@ class TestProxApproxVnf(unittest.TestCase):
[[0, 1, 2, 3, 4, 5], [1, 1, 2, 3, 4, 5]])
resource_helper.collect_collectd_kpi.return_value = {'core': {'result': 234}}
- prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0, 'task_id')
+ prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0)
prox_approx_vnf.scenario_helper.scenario_cfg = {
'nodes': {prox_approx_vnf.name: "mock"}
}
@@ -385,7 +385,7 @@ class TestProxApproxVnf(unittest.TestCase):
[[0, 'A', 'B', 'C', 'D', 'E'],
['F', 1, 2, 3, 4, 5]])
- prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0, 'task_id')
+ prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0)
prox_approx_vnf.scenario_helper.scenario_cfg = {
'nodes': {prox_approx_vnf.name: "mock"}
}
@@ -404,7 +404,7 @@ class TestProxApproxVnf(unittest.TestCase):
[[0, 'A', 'B', 'C', 'D', 'E'],
['F', 1, 2, 3, 4, 5]])
- prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0, 'task_id')
+ prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0)
prox_approx_vnf.scenario_helper.scenario_cfg = {
'nodes': {prox_approx_vnf.name: "mock"}
}
@@ -419,8 +419,7 @@ class TestProxApproxVnf(unittest.TestCase):
mock_ssh(ssh)
resource_helper = mock.MagicMock()
- prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, deepcopy(self.VNFD0),
- 'task_id')
+ prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, deepcopy(self.VNFD0))
prox_approx_vnf.scenario_helper.scenario_cfg = {
'nodes': {prox_approx_vnf.name: "mock"}
}
@@ -443,7 +442,7 @@ class TestProxApproxVnf(unittest.TestCase):
def test_run_prox(self, ssh, *_):
mock_ssh(ssh)
- prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0, 'task_id')
+ prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0)
prox_approx_vnf.scenario_helper.scenario_cfg = self.SCENARIO_CFG
prox_approx_vnf.ssh_helper.join_bin_path.return_value = '/tool_path12/tool_file34'
prox_approx_vnf.setup_helper.remote_path = 'configs/file56.cfg'
@@ -457,7 +456,7 @@ class TestProxApproxVnf(unittest.TestCase):
@mock.patch(SSH_HELPER)
def bad_test_instantiate(self, *args):
- prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0, 'task_id')
+ prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0)
prox_approx_vnf.scenario_helper = mock.MagicMock()
prox_approx_vnf.setup_helper = mock.MagicMock()
# we can't mock super
@@ -467,7 +466,7 @@ class TestProxApproxVnf(unittest.TestCase):
@mock.patch(SSH_HELPER)
def test_wait_for_instantiate_panic(self, ssh, *args):
mock_ssh(ssh, exec_result=(1, "", ""))
- prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0, 'task_id')
+ prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0)
prox_approx_vnf._vnf_process = mock.MagicMock(**{"is_alive.return_value": True})
prox_approx_vnf._run_prox = mock.Mock(return_value=0)
prox_approx_vnf.WAIT_TIME = 0
@@ -479,7 +478,7 @@ class TestProxApproxVnf(unittest.TestCase):
@mock.patch(SSH_HELPER)
def test_terminate(self, ssh, *args):
mock_ssh(ssh)
- prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0, 'task_id')
+ prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0)
prox_approx_vnf._vnf_process = mock.MagicMock()
prox_approx_vnf._vnf_process.terminate = mock.Mock()
prox_approx_vnf.ssh_helper = mock.MagicMock()
@@ -491,7 +490,7 @@ class TestProxApproxVnf(unittest.TestCase):
@mock.patch(SSH_HELPER)
def test__vnf_up_post(self, ssh, *args):
mock_ssh(ssh)
- prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0, 'task_id')
+ prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0)
prox_approx_vnf.resource_helper = resource_helper = mock.Mock()
prox_approx_vnf._vnf_up_post()
@@ -500,7 +499,7 @@ class TestProxApproxVnf(unittest.TestCase):
@mock.patch(SSH_HELPER)
def test_vnf_execute_oserror(self, ssh, *args):
mock_ssh(ssh)
- prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0, 'task_id')
+ prox_approx_vnf = prox_vnf.ProxApproxVnf(NAME, self.VNFD0)
prox_approx_vnf.resource_helper = resource_helper = mock.Mock()
resource_helper.execute.side_effect = OSError(errno.EPIPE, "")
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_router_vnf.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_router_vnf.py
index ad74145b4..b8f3fcaca 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_router_vnf.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_router_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -199,7 +199,7 @@ class TestRouterVNF(unittest.TestCase):
def test___init__(self):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- router_vnf = RouterVNF(name, vnfd, 'task_id')
+ router_vnf = RouterVNF(name, vnfd)
self.assertIsNone(router_vnf._vnf_process)
def test_get_stats(self):
@@ -213,7 +213,7 @@ class TestRouterVNF(unittest.TestCase):
m = mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- router_vnf = RouterVNF(name, vnfd, 'task_id')
+ router_vnf = RouterVNF(name, vnfd)
router_vnf.scenario_helper.scenario_cfg = {
'nodes': {router_vnf.name: "mock"}
}
@@ -232,7 +232,7 @@ class TestRouterVNF(unittest.TestCase):
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- router_vnf = RouterVNF(name, vnfd, 'task_id')
+ 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()
@@ -243,7 +243,7 @@ class TestRouterVNF(unittest.TestCase):
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- router_vnf = RouterVNF(name, vnfd, 'task_id')
+ router_vnf = RouterVNF(name, vnfd)
router_vnf.WAIT_TIME = 0
router_vnf.INTERFACE_WAIT = 0
self.scenario_cfg.update({"nodes": {"vnf__1": ""}})
@@ -256,7 +256,7 @@ class TestRouterVNF(unittest.TestCase):
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- router_vnf = RouterVNF(name, vnfd, 'task_id')
+ router_vnf = RouterVNF(name, vnfd)
router_vnf._vnf_process = mock.MagicMock()
router_vnf._vnf_process.terminate = mock.Mock()
self.assertIsNone(router_vnf.terminate())
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_sample_vnf.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_sample_vnf.py
index 43682dd07..bc914bf87 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_sample_vnf.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_sample_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2018 Intel Corporation
+# Copyright (c) 2017-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -16,13 +16,16 @@ from copy import deepcopy
import unittest
import mock
+import time
+
+import paramiko
from yardstick.common import exceptions as y_exceptions
from yardstick.common import utils
from yardstick.network_services.nfvi.resource import ResourceProfile
from yardstick.network_services.vnf_generic.vnf.base import VnfdHelper
from yardstick.network_services.vnf_generic.vnf import sample_vnf
-from yardstick.network_services.vnf_generic.vnf.vnf_ssh_helper import VnfSshHelper
+from yardstick.network_services.vnf_generic.vnf import vnf_ssh_helper
from yardstick.network_services.vnf_generic.vnf.sample_vnf import SampleVNFDeployHelper
from yardstick.network_services.vnf_generic.vnf.sample_vnf import ScenarioHelper
from yardstick.network_services.vnf_generic.vnf.sample_vnf import ResourceHelper
@@ -34,6 +37,7 @@ from yardstick.network_services.vnf_generic.vnf.sample_vnf import SampleVNFTraff
from yardstick.network_services.vnf_generic.vnf.sample_vnf import DpdkVnfSetupEnvHelper
from yardstick.tests.unit.network_services.vnf_generic.vnf import test_base
from yardstick.benchmark.contexts import base as ctx_base
+from yardstick import ssh
class MockError(Exception):
@@ -82,10 +86,11 @@ class TestVnfSshHelper(unittest.TestCase):
'virtual-interface': {
'dst_mac': '00:00:00:00:00:03',
'vpci': '0000:05:00.0',
+ 'dpdk_port_num': 0,
+ 'driver': 'i40e',
'local_ip': '152.16.100.19',
'type': 'PCI-PASSTHROUGH',
'netmask': '255.255.255.0',
- 'dpdk_port_num': 0,
'bandwidth': '10 Gbps',
'dst_ip': '152.16.100.20',
'local_mac': '00:00:00:00:00:01',
@@ -99,10 +104,11 @@ class TestVnfSshHelper(unittest.TestCase):
'virtual-interface': {
'dst_mac': '00:00:00:00:00:04',
'vpci': '0000:05:00.1',
+ 'dpdk_port_num': 1,
+ 'driver': 'ixgbe',
'local_ip': '152.16.40.19',
'type': 'PCI-PASSTHROUGH',
'netmask': '255.255.255.0',
- 'dpdk_port_num': 1,
'bandwidth': '10 Gbps',
'dst_ip': '152.16.40.20',
'local_mac': '00:00:00:00:00:02',
@@ -151,90 +157,88 @@ class TestVnfSshHelper(unittest.TestCase):
}
}
+ def setUp(self):
+ self.ssh_helper = vnf_ssh_helper.VnfSshHelper(
+ self.VNFD_0['mgmt-interface'], 'my/bin/path')
+ self.ssh_helper._run = mock.Mock()
+
def assertAll(self, iterable, message=None):
self.assertTrue(all(iterable), message)
def test_get_class(self):
- self.assertIs(VnfSshHelper.get_class(), VnfSshHelper)
+ self.assertIs(vnf_ssh_helper.VnfSshHelper.get_class(),
+ vnf_ssh_helper.VnfSshHelper)
- @mock.patch('yardstick.ssh.paramiko')
+ @mock.patch.object(ssh, 'paramiko')
def test_copy(self, _):
- ssh_helper = VnfSshHelper(self.VNFD_0['mgmt-interface'], 'my/bin/path')
- ssh_helper._run = mock.Mock()
-
- ssh_helper.execute('ls')
- self.assertTrue(ssh_helper.is_connected)
- result = ssh_helper.copy()
- self.assertIsInstance(result, VnfSshHelper)
+ self.ssh_helper.execute('ls')
+ self.assertTrue(self.ssh_helper.is_connected)
+ result = self.ssh_helper.copy()
+ self.assertIsInstance(result, vnf_ssh_helper.VnfSshHelper)
self.assertFalse(result.is_connected)
- self.assertEqual(result.bin_path, ssh_helper.bin_path)
- self.assertEqual(result.host, ssh_helper.host)
- self.assertEqual(result.port, ssh_helper.port)
- self.assertEqual(result.user, ssh_helper.user)
- self.assertEqual(result.password, ssh_helper.password)
- self.assertEqual(result.key_filename, ssh_helper.key_filename)
-
- @mock.patch('yardstick.ssh.paramiko')
+ self.assertEqual(result.bin_path, self.ssh_helper.bin_path)
+ self.assertEqual(result.host, self.ssh_helper.host)
+ self.assertEqual(result.port, self.ssh_helper.port)
+ self.assertEqual(result.user, self.ssh_helper.user)
+ self.assertEqual(result.password, self.ssh_helper.password)
+ self.assertEqual(result.key_filename, self.ssh_helper.key_filename)
+
+ @mock.patch.object(paramiko, 'SSHClient')
def test_upload_config_file(self, mock_paramiko):
- ssh_helper = VnfSshHelper(self.VNFD_0['mgmt-interface'], 'my/bin/path')
- ssh_helper._run = mock.MagicMock()
+ self.assertFalse(self.ssh_helper.is_connected)
+ cfg_file = self.ssh_helper.upload_config_file('/my/prefix', 'my content')
+ self.assertTrue(self.ssh_helper.is_connected)
+ mock_paramiko.assert_called_once()
+ self.assertEqual(cfg_file, '/my/prefix')
- self.assertFalse(ssh_helper.is_connected)
- cfg_file = ssh_helper.upload_config_file('my/prefix', 'my content')
- self.assertTrue(ssh_helper.is_connected)
- mock_paramiko.SSHClient.assert_called_once()
+ @mock.patch.object(paramiko, 'SSHClient')
+ def test_upload_config_file_path_does_not_exist(self, mock_paramiko):
+ self.assertFalse(self.ssh_helper.is_connected)
+ cfg_file = self.ssh_helper.upload_config_file('my/prefix', 'my content')
+ self.assertTrue(self.ssh_helper.is_connected)
+ mock_paramiko.assert_called_once()
self.assertTrue(cfg_file.startswith('/tmp'))
- cfg_file = ssh_helper.upload_config_file('/my/prefix', 'my content')
- self.assertTrue(ssh_helper.is_connected)
- mock_paramiko.SSHClient.assert_called_once()
- self.assertEqual(cfg_file, '/my/prefix')
-
def test_join_bin_path(self):
- ssh_helper = VnfSshHelper(self.VNFD_0['mgmt-interface'], 'my/bin/path')
-
expected_start = 'my'
expected_middle_list = ['bin']
expected_end = 'path'
- result = ssh_helper.join_bin_path()
+ result = self.ssh_helper.join_bin_path()
self.assertTrue(result.startswith(expected_start))
self.assertAll(middle in result for middle in expected_middle_list)
self.assertTrue(result.endswith(expected_end))
expected_middle_list.append(expected_end)
expected_end = 'some_file.sh'
- result = ssh_helper.join_bin_path('some_file.sh')
+ result = self.ssh_helper.join_bin_path('some_file.sh')
self.assertTrue(result.startswith(expected_start))
self.assertAll(middle in result for middle in expected_middle_list)
self.assertTrue(result.endswith(expected_end))
expected_middle_list.append('some_dir')
expected_end = 'some_file.sh'
- result = ssh_helper.join_bin_path('some_dir', 'some_file.sh')
+ result = self.ssh_helper.join_bin_path('some_dir', 'some_file.sh')
self.assertTrue(result.startswith(expected_start))
self.assertAll(middle in result for middle in expected_middle_list)
self.assertTrue(result.endswith(expected_end))
- @mock.patch('yardstick.ssh.paramiko')
- @mock.patch('yardstick.ssh.provision_tool')
+ @mock.patch.object(paramiko, 'SSHClient')
+ @mock.patch.object(ssh, 'provision_tool')
def test_provision_tool(self, mock_provision_tool, mock_paramiko):
- ssh_helper = VnfSshHelper(self.VNFD_0['mgmt-interface'], 'my/bin/path')
- ssh_helper._run = mock.MagicMock()
-
- self.assertFalse(ssh_helper.is_connected)
- ssh_helper.provision_tool()
- self.assertTrue(ssh_helper.is_connected)
- mock_paramiko.SSHClient.assert_called_once()
+ self.assertFalse(self.ssh_helper.is_connected)
+ self.ssh_helper.provision_tool()
+ self.assertTrue(self.ssh_helper.is_connected)
+ mock_paramiko.assert_called_once()
mock_provision_tool.assert_called_once()
- ssh_helper.provision_tool(tool_file='my_tool.sh')
- self.assertTrue(ssh_helper.is_connected)
- mock_paramiko.SSHClient.assert_called_once()
+ self.ssh_helper.provision_tool(tool_file='my_tool.sh')
+ self.assertTrue(self.ssh_helper.is_connected)
+ mock_paramiko.assert_called_once()
self.assertEqual(mock_provision_tool.call_count, 2)
- ssh_helper.provision_tool('tool_path', 'my_tool.sh')
- self.assertTrue(ssh_helper.is_connected)
- mock_paramiko.SSHClient.assert_called_once()
+ self.ssh_helper.provision_tool('tool_path', 'my_tool.sh')
+ self.assertTrue(self.ssh_helper.is_connected)
+ mock_paramiko.assert_called_once()
self.assertEqual(mock_provision_tool.call_count, 3)
@@ -1059,58 +1063,6 @@ class TestClientResourceHelper(unittest.TestCase):
self.assertIs(client_resource_helper._connect(client), client)
- @mock.patch.object(ClientResourceHelper, '_build_ports')
- @mock.patch.object(ClientResourceHelper, '_run_traffic_once',
- return_value=(True, mock.ANY))
- def test_run_traffic(self, mock_run_traffic_once, mock_build_ports):
- client_resource_helper = ClientResourceHelper(mock.Mock())
- client = mock.Mock()
- traffic_profile = mock.Mock()
- mq_producer = mock.Mock()
- with mock.patch.object(client_resource_helper, '_connect') \
- as mock_connect, \
- mock.patch.object(client_resource_helper, '_terminated') \
- as mock_terminated:
- mock_connect.return_value = client
- type(mock_terminated).value = mock.PropertyMock(
- side_effect=[0, 1, 1, lambda x: x])
- client_resource_helper.run_traffic(traffic_profile, mq_producer)
-
- mock_build_ports.assert_called_once()
- traffic_profile.register_generator.assert_called_once()
- mq_producer.tg_method_started.assert_called_once()
- mq_producer.tg_method_finished.assert_called_once()
- mq_producer.tg_method_iteration.assert_called_once_with(1)
- mock_run_traffic_once.assert_called_once_with(traffic_profile)
-
- @mock.patch.object(ClientResourceHelper, '_build_ports')
- @mock.patch.object(ClientResourceHelper, '_run_traffic_once',
- side_effect=Exception)
- def test_run_traffic_exception(self, mock_run_traffic_once,
- mock_build_ports):
- client_resource_helper = ClientResourceHelper(mock.Mock())
- client = mock.Mock()
- traffic_profile = mock.Mock()
- mq_producer = mock.Mock()
- with mock.patch.object(client_resource_helper, '_connect') \
- as mock_connect, \
- mock.patch.object(client_resource_helper, '_terminated') \
- as mock_terminated:
- mock_connect.return_value = client
- type(mock_terminated).value = mock.PropertyMock(return_value=0)
- mq_producer.reset_mock()
- # NOTE(ralonsoh): "trex_stl_exceptions.STLError" is mocked
- with self.assertRaises(Exception):
- client_resource_helper.run_traffic(traffic_profile,
- mq_producer)
-
- mock_build_ports.assert_called_once()
- traffic_profile.register_generator.assert_called_once()
- mock_run_traffic_once.assert_called_once_with(traffic_profile)
- mq_producer.tg_method_started.assert_called_once()
- mq_producer.tg_method_finished.assert_not_called()
- mq_producer.tg_method_iteration.assert_not_called()
-
class TestRfc2544ResourceHelper(unittest.TestCase):
@@ -1515,7 +1467,7 @@ class TestSampleVnf(unittest.TestCase):
}
def test___init__(self):
- sample_vnf = SampleVNF('vnf1', self.VNFD_0, 'task_id')
+ sample_vnf = SampleVNF('vnf1', self.VNFD_0)
self.assertEqual(sample_vnf.name, 'vnf1')
self.assertDictEqual(sample_vnf.vnfd_helper, self.VNFD_0)
@@ -1533,8 +1485,7 @@ class TestSampleVnf(unittest.TestCase):
class MyResourceHelper(ResourceHelper):
pass
- sample_vnf = SampleVNF('vnf1', self.VNFD_0, 'task_id',
- MySetupEnvHelper, MyResourceHelper)
+ sample_vnf = SampleVNF('vnf1', self.VNFD_0, MySetupEnvHelper, MyResourceHelper)
self.assertEqual(sample_vnf.name, 'vnf1')
self.assertDictEqual(sample_vnf.vnfd_helper, self.VNFD_0)
@@ -1548,7 +1499,7 @@ class TestSampleVnf(unittest.TestCase):
@mock.patch('yardstick.network_services.vnf_generic.vnf.sample_vnf.Process')
def test__start_vnf(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- sample_vnf = SampleVNF('vnf1', vnfd, 'task_id')
+ sample_vnf = SampleVNF('vnf1', vnfd)
sample_vnf._run = mock.Mock()
self.assertIsNone(sample_vnf.queue_wrapper)
@@ -1567,7 +1518,7 @@ class TestSampleVnf(unittest.TestCase):
}
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- sample_vnf = SampleVNF('vnf1', vnfd, 'task_id')
+ sample_vnf = SampleVNF('vnf1', vnfd)
sample_vnf.scenario_helper.scenario_cfg = {
'nodes': {sample_vnf.name: 'mock'}
}
@@ -1611,7 +1562,7 @@ class TestSampleVnf(unittest.TestCase):
'plugin1': {'param': 1}}}
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- sample_vnf = SampleVNF('vnf__0', vnfd, 'task_id')
+ sample_vnf = SampleVNF('vnf__0', vnfd)
sample_vnf._update_collectd_options(scenario_cfg, context_cfg)
self.assertEqual(sample_vnf.setup_helper.collectd_options, expected)
@@ -1638,7 +1589,7 @@ class TestSampleVnf(unittest.TestCase):
'plugin1': {'param': 1}}}
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- sample_vnf = SampleVNF('vnf1', vnfd, 'task_id')
+ sample_vnf = SampleVNF('vnf1', vnfd)
sample_vnf._update_options(options2, options1)
self.assertEqual(options2, expected)
@@ -1660,7 +1611,7 @@ class TestSampleVnf(unittest.TestCase):
]
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- sample_vnf = SampleVNF('vnf1', vnfd, 'task_id')
+ sample_vnf = SampleVNF('vnf1', vnfd)
sample_vnf.APP_NAME = 'sample1'
sample_vnf.WAIT_TIME_FOR_SCRIPT = 0
sample_vnf._start_server = mock.Mock(return_value=0)
@@ -1677,6 +1628,39 @@ class TestSampleVnf(unittest.TestCase):
self.assertEqual(sample_vnf.wait_for_instantiate(), 0)
+ @mock.patch.object(time, 'sleep')
+ @mock.patch.object(ssh, 'SSH')
+ def test_wait_for_initialize(self, ssh, *args):
+ test_base.mock_ssh(ssh, exec_result=(1, "", ""))
+ queue_get_list = [
+ 'some output',
+ 'pipeline> ',
+ 'run non_existent_script_name',
+ 'Cannot open file "non_existent_script_name"'
+ ]
+ queue_size_list = [
+ 0,
+ len(queue_get_list[0]),
+ 0,
+ len(queue_get_list[1]),
+ len(queue_get_list[2]),
+ 0,
+ len(queue_get_list[3])
+ ]
+ vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
+ sample_vnf = SampleVNF('vnf1', vnfd)
+ sample_vnf.APP_NAME = 'sample1'
+ sample_vnf.WAIT_TIME_FOR_SCRIPT = 0
+ sample_vnf._vnf_process = mock.Mock()
+ sample_vnf._vnf_process.exitcode = 0
+ sample_vnf._vnf_process._is_alive.return_value = 1
+ sample_vnf.queue_wrapper = mock.Mock()
+ sample_vnf.q_in = mock.Mock()
+ sample_vnf.q_out = mock.Mock()
+ sample_vnf.q_out.qsize.side_effect = iter(queue_size_list)
+ sample_vnf.q_out.get.side_effect = iter(queue_get_list)
+ sample_vnf.wait_for_initialize()
+
@mock.patch("yardstick.network_services.vnf_generic.vnf.sample_vnf.time")
def test_vnf_execute_with_queue_data(self, *args):
queue_size_list = [
@@ -1691,7 +1675,7 @@ class TestSampleVnf(unittest.TestCase):
]
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- sample_vnf = SampleVNF('vnf1', vnfd, 'task_id')
+ sample_vnf = SampleVNF('vnf1', vnfd)
sample_vnf.APP_NAME = 'sample1'
sample_vnf.q_out = mock.Mock()
sample_vnf.q_out.qsize.side_effect = iter(queue_size_list)
@@ -1701,7 +1685,7 @@ class TestSampleVnf(unittest.TestCase):
def test_terminate_without_vnf_process(self):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- sample_vnf = SampleVNF('vnf1', vnfd, 'task_id')
+ sample_vnf = SampleVNF('vnf1', vnfd)
sample_vnf.APP_NAME = 'sample1'
sample_vnf.vnf_execute = mock.Mock()
sample_vnf.ssh_helper = mock.Mock()
@@ -1712,7 +1696,7 @@ class TestSampleVnf(unittest.TestCase):
def test_get_stats(self):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- sample_vnf = SampleVNF('vnf1', vnfd, 'task_id')
+ sample_vnf = SampleVNF('vnf1', vnfd)
sample_vnf.APP_NAME = 'sample1'
sample_vnf.APP_WORD = 'sample1'
sample_vnf.vnf_execute = mock.Mock(return_value='the stats')
@@ -1722,7 +1706,7 @@ class TestSampleVnf(unittest.TestCase):
@mock.patch.object(ctx_base.Context, 'get_physical_node_from_server', return_value='mock_node')
def test_collect_kpi(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- sample_vnf = SampleVNF('vnf1', vnfd, 'task_id')
+ sample_vnf = SampleVNF('vnf1', vnfd)
sample_vnf.scenario_helper.scenario_cfg = {
'nodes': {sample_vnf.name: "mock"}
}
@@ -1750,7 +1734,7 @@ class TestSampleVnf(unittest.TestCase):
@mock.patch.object(ctx_base.Context, 'get_physical_node_from_server', return_value='mock_node')
def test_collect_kpi_default(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- sample_vnf = SampleVNF('vnf1', vnfd, 'task_id')
+ sample_vnf = SampleVNF('vnf1', vnfd)
sample_vnf.scenario_helper.scenario_cfg = {
'nodes': {sample_vnf.name: "mock"}
}
@@ -1769,7 +1753,7 @@ class TestSampleVnf(unittest.TestCase):
def test_scale(self):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- sample_vnf = SampleVNF('vnf1', vnfd, 'task_id')
+ sample_vnf = SampleVNF('vnf1', vnfd)
self.assertRaises(y_exceptions.FunctionNotImplemented,
sample_vnf.scale)
@@ -1777,7 +1761,7 @@ class TestSampleVnf(unittest.TestCase):
test_cmd = 'test cmd'
run_kwargs = {'arg1': 'val1', 'arg2': 'val2'}
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- sample_vnf = SampleVNF('vnf1', vnfd, 'task_id')
+ sample_vnf = SampleVNF('vnf1', vnfd)
sample_vnf.ssh_helper = mock.Mock()
sample_vnf.setup_helper = mock.Mock()
with mock.patch.object(sample_vnf, '_build_config',
@@ -1913,30 +1897,30 @@ class TestSampleVNFTrafficGen(unittest.TestCase):
}
def test__check_status(self):
- sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0, 'task_id')
+ sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0)
with self.assertRaises(NotImplementedError):
sample_vnf_tg._check_status()
def test_listen_traffic(self):
- sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0, 'task_id')
+ sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0)
sample_vnf_tg.listen_traffic(mock.Mock())
def test_verify_traffic(self):
- sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0, 'task_id')
+ sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0)
sample_vnf_tg.verify_traffic(mock.Mock())
def test_terminate(self):
- sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0, 'task_id')
+ sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0)
sample_vnf_tg._traffic_process = mock.Mock()
sample_vnf_tg._tg_process = mock.Mock()
sample_vnf_tg.terminate()
def test__wait_for_process(self):
- sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0, 'task_id')
+ sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0)
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:
@@ -1947,14 +1931,14 @@ class TestSampleVNFTrafficGen(unittest.TestCase):
mock_status.assert_called_once()
def test__wait_for_process_not_alive(self):
- sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0, 'task_id')
+ sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0)
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, 'task_id')
+ sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0)
with mock.patch.object(sample_vnf_tg, '_check_status',
side_effect=[1, 0]) as mock_status, \
mock.patch.object(sample_vnf_tg,
@@ -1966,6 +1950,6 @@ class TestSampleVNFTrafficGen(unittest.TestCase):
mock_status.assert_has_calls([mock.call(), mock.call()])
def test_scale(self):
- sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0, 'task_id')
+ sample_vnf_tg = SampleVNFTrafficGen('tg1', self.VNFD_0)
self.assertRaises(y_exceptions.FunctionNotImplemented,
sample_vnf_tg.scale)
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_ixload.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_ixload.py
index e7f6206eb..dd1c277c3 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_ixload.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_ixload.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -128,12 +128,12 @@ class TestIxLoadTrafficGen(ut_base.BaseUnitTestCase):
def test___init__(self):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd, 'task_id')
+ ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd)
self.assertIsNone(ixload_traffic_gen.resource_helper.data)
def test_update_gateways(self):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd, 'task_id')
+ ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd)
links = {'uplink_0': {'ip': {}},
'downlink_1': {'ip': {}}}
@@ -146,7 +146,7 @@ class TestIxLoadTrafficGen(ut_base.BaseUnitTestCase):
return_value='mock_node')
def test_collect_kpi(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd, 'task_id')
+ ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd)
ixload_traffic_gen.scenario_helper.scenario_cfg = {
'nodes': {ixload_traffic_gen.name: "mock"}
}
@@ -160,7 +160,7 @@ class TestIxLoadTrafficGen(ut_base.BaseUnitTestCase):
def test_listen_traffic(self):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd, 'task_id')
+ ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd)
self.assertIsNone(ixload_traffic_gen.listen_traffic({}))
@mock.patch.object(utils, 'find_relative_file')
@@ -169,7 +169,7 @@ class TestIxLoadTrafficGen(ut_base.BaseUnitTestCase):
@mock.patch.object(tg_ixload, 'shutil')
def test_instantiate(self, mock_shutil, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd, 'task_id')
+ ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd)
scenario_cfg = {'tc': "nsb_test_case",
'ixia_profile': "ixload.cfg",
'task_path': "/path/to/task"}
@@ -209,7 +209,7 @@ class TestIxLoadTrafficGen(ut_base.BaseUnitTestCase):
vnfd['mgmt-interface'].update({'tg-config': {}})
vnfd['mgmt-interface']['tg-config'].update({'ixchassis': '1.1.1.1'})
vnfd['mgmt-interface']['tg-config'].update({'py_bin_path': '/root'})
- sut = tg_ixload.IxLoadTrafficGen(NAME, vnfd, 'task_id')
+ sut = tg_ixload.IxLoadTrafficGen(NAME, vnfd)
sut.connection = mock.Mock()
sut._traffic_runner = mock.Mock(return_value=0)
result = sut.run_traffic(mock_traffic_profile)
@@ -230,7 +230,7 @@ class TestIxLoadTrafficGen(ut_base.BaseUnitTestCase):
vnfd['mgmt-interface'].update({'tg-config': {}})
vnfd['mgmt-interface']['tg-config'].update({'ixchassis': '1.1.1.1'})
vnfd['mgmt-interface']['tg-config'].update({'py_bin_path': '/root'})
- sut = tg_ixload.IxLoadTrafficGen(NAME, vnfd, 'task_id')
+ sut = tg_ixload.IxLoadTrafficGen(NAME, vnfd)
sut.connection = mock.Mock()
sut._traffic_runner = mock.Mock(return_value=0)
subprocess.call(['touch', '/tmp/1.csv'])
@@ -240,7 +240,7 @@ class TestIxLoadTrafficGen(ut_base.BaseUnitTestCase):
def test_terminate(self):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd, 'task_id')
+ ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd)
self.assertIsNone(ixload_traffic_gen.terminate())
def test_parse_csv_read(self):
@@ -253,7 +253,7 @@ class TestIxLoadTrafficGen(ut_base.BaseUnitTestCase):
'HTTP Transaction Rate': True,
}
http_reader = [kpi_data]
- ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd, 'task_id')
+ ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd)
result = ixload_traffic_gen.resource_helper.result
ixload_traffic_gen.resource_helper.parse_csv_read(http_reader)
for k_left, k_right in tg_ixload.IxLoadResourceHelper.KPI_LIST.items():
@@ -268,7 +268,7 @@ class TestIxLoadTrafficGen(ut_base.BaseUnitTestCase):
'HTTP Connection Rate': 4,
'HTTP Transaction Rate': 5,
}]
- ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd, 'task_id')
+ ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd)
init_value = ixload_traffic_gen.resource_helper.result
ixload_traffic_gen.resource_helper.parse_csv_read(http_reader)
self.assertDictEqual(ixload_traffic_gen.resource_helper.result,
@@ -282,7 +282,6 @@ class TestIxLoadTrafficGen(ut_base.BaseUnitTestCase):
'HTTP Concurrent Connections': 3,
'HTTP Transaction Rate': 5,
}]
- ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd, 'task_id')
-
+ ixload_traffic_gen = tg_ixload.IxLoadTrafficGen(NAME, vnfd)
with self.assertRaises(KeyError):
ixload_traffic_gen.resource_helper.parse_csv_read(http_reader)
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_landslide.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_landslide.py
index 1736d0f17..2d8c01bec 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_landslide.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_landslide.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2018 Intel Corporation
+# Copyright (c) 2018-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -17,7 +17,6 @@ import mock
import requests
import time
import unittest
-import uuid
from yardstick.benchmark.contexts import base as ctx_base
from yardstick.common import exceptions
@@ -399,8 +398,6 @@ class TestLandslideTrafficGen(unittest.TestCase):
TEST_USER_ID = 11
def setUp(self):
- self._id = uuid.uuid1().int
-
self.mock_lsapi = mock.patch.object(tg_landslide, 'LsApi')
self.mock_lsapi.start()
@@ -408,7 +405,7 @@ class TestLandslideTrafficGen(unittest.TestCase):
self.mock_ssh_helper.start()
self.vnfd = VNFD['vnfd:vnfd-catalog']['vnfd'][0]
self.ls_tg = tg_landslide.LandslideTrafficGen(
- NAME, self.vnfd, self._id)
+ NAME, self.vnfd)
self.session_profile = copy.deepcopy(SESSION_PROFILE)
self.ls_tg.session_profile = self.session_profile
@@ -422,7 +419,7 @@ class TestLandslideTrafficGen(unittest.TestCase):
def test___init__(self, mock_get_nsb_option, *args):
_path_to_nsb = 'path/to/nsb'
mock_get_nsb_option.return_value = _path_to_nsb
- ls_tg = tg_landslide.LandslideTrafficGen(NAME, self.vnfd, self._id)
+ ls_tg = tg_landslide.LandslideTrafficGen(NAME, self.vnfd)
self.assertIsInstance(ls_tg.resource_helper,
tg_landslide.LandslideResourceHelper)
mock_get_nsb_option.assert_called_once_with('bin_path')
@@ -655,7 +652,7 @@ class TestLandslideTrafficGen(unittest.TestCase):
def test__load_session_profile_unequal_num_of_cfg_blocks(
self, mock_yaml_load, *args):
vnfd = copy.deepcopy(VNFD['vnfd:vnfd-catalog']['vnfd'][0])
- ls_traffic_gen = tg_landslide.LandslideTrafficGen(NAME, vnfd, self._id)
+ ls_traffic_gen = tg_landslide.LandslideTrafficGen(NAME, vnfd)
ls_traffic_gen.scenario_helper.scenario_cfg = self.SCENARIO_CFG
mock_yaml_load.return_value = copy.deepcopy(SESSION_PROFILE)
# Delete test_servers item from pod file to make it not valid
@@ -670,7 +667,7 @@ class TestLandslideTrafficGen(unittest.TestCase):
vnfd = copy.deepcopy(VNFD['vnfd:vnfd-catalog']['vnfd'][0])
# Swap test servers data in pod file
vnfd['config'] = list(reversed(vnfd['config']))
- ls_tg = tg_landslide.LandslideTrafficGen(NAME, vnfd, self._id)
+ ls_tg = tg_landslide.LandslideTrafficGen(NAME, vnfd)
ls_tg.scenario_helper.scenario_cfg = self.SCENARIO_CFG
mock_yaml_load.return_value = SESSION_PROFILE
with self.assertRaises(RuntimeError):
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_ping.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_ping.py
index 434a7b770..a3e4384cf 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_ping.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_ping.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -226,7 +226,7 @@ class TestPingTrafficGen(unittest.TestCase):
@mock.patch("yardstick.ssh.SSH")
def test___init__(self, ssh):
ssh.from_node.return_value.execute.return_value = 0, "success", ""
- ping_traffic_gen = PingTrafficGen('vnf1', self.VNFD_0, 'task_id')
+ ping_traffic_gen = PingTrafficGen('vnf1', self.VNFD_0)
self.assertIsInstance(ping_traffic_gen.setup_helper, PingSetupEnvHelper)
self.assertIsInstance(ping_traffic_gen.resource_helper, PingResourceHelper)
@@ -243,7 +243,7 @@ class TestPingTrafficGen(unittest.TestCase):
(0, 'if_name_2', ''),
]
ssh.from_node.return_value.execute.side_effect = iter(execute_result_data)
- ping_traffic_gen = PingTrafficGen('vnf1', self.VNFD_0, 'task_id')
+ ping_traffic_gen = PingTrafficGen('vnf1', self.VNFD_0)
ext_ifs = ping_traffic_gen.vnfd_helper.interfaces
self.assertNotEqual(ext_ifs[0]['virtual-interface']['local_iface_name'], 'if_name_1')
self.assertNotEqual(ext_ifs[1]['virtual-interface']['local_iface_name'], 'if_name_2')
@@ -253,7 +253,7 @@ class TestPingTrafficGen(unittest.TestCase):
def test_collect_kpi(self, ssh, *args):
mock_ssh(ssh, exec_result=(0, "success", ""))
- ping_traffic_gen = PingTrafficGen('vnf1', self.VNFD_0, 'task_id')
+ ping_traffic_gen = PingTrafficGen('vnf1', self.VNFD_0)
ping_traffic_gen.scenario_helper.scenario_cfg = {
'nodes': {ping_traffic_gen.name: "mock"}
}
@@ -271,7 +271,7 @@ class TestPingTrafficGen(unittest.TestCase):
@mock.patch(SSH_HELPER)
def test_instantiate(self, ssh):
mock_ssh(ssh, spec=VnfSshHelper, exec_result=(0, "success", ""))
- ping_traffic_gen = PingTrafficGen('vnf1', self.VNFD_0, 'task_id')
+ ping_traffic_gen = PingTrafficGen('vnf1', self.VNFD_0)
ping_traffic_gen.setup_helper.ssh_helper = mock.MagicMock(
**{"execute.return_value": (0, "xe0_fake", "")})
self.assertIsInstance(ping_traffic_gen.ssh_helper, mock.Mock)
@@ -286,7 +286,7 @@ class TestPingTrafficGen(unittest.TestCase):
self.assertIsNotNone(ping_traffic_gen._result)
def test_listen_traffic(self):
- ping_traffic_gen = PingTrafficGen('vnf1', self.VNFD_0, 'task_id')
+ ping_traffic_gen = PingTrafficGen('vnf1', self.VNFD_0)
self.assertIsNone(ping_traffic_gen.listen_traffic({}))
@mock.patch("yardstick.ssh.SSH")
@@ -294,5 +294,5 @@ class TestPingTrafficGen(unittest.TestCase):
ssh.from_node.return_value.execute.return_value = 0, "success", ""
ssh.from_node.return_value.run.return_value = 0, "success", ""
- ping_traffic_gen = PingTrafficGen('vnf1', self.VNFD_0, 'task_id')
+ ping_traffic_gen = PingTrafficGen('vnf1', self.VNFD_0)
self.assertIsNone(ping_traffic_gen.terminate())
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_pktgen.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_pktgen.py
index d341b970b..1ecb6ffc9 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_pktgen.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_pktgen.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2018 Intel Corporation
+# Copyright (c) 2018-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -12,8 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-import uuid
-
import mock
from yardstick.common import constants
@@ -33,23 +31,12 @@ class PktgenTrafficGenTestCase(ut_base.BaseUnitTestCase):
'benchmark': {'kpi': 'fake_kpi'}
}
- def setUp(self):
- self._id = uuid.uuid1().int
- self._mock_vnf_consumer = mock.patch.object(vnf_base,
- 'GenericVNFConsumer')
- self.mock_vnf_consumer = self._mock_vnf_consumer.start()
- self.addCleanup(self._stop_mock)
-
- def _stop_mock(self):
- self._mock_vnf_consumer.stop()
-
def test__init(self):
- tg = tg_pktgen.PktgenTrafficGen('name1', self.VNFD, self._id)
- self.assertTrue(isinstance(tg, (vnf_base.GenericTrafficGen,
- vnf_base.GenericVNFEndpoint)))
+ tg = tg_pktgen.PktgenTrafficGen('name1', self.VNFD)
+ self.assertTrue(isinstance(tg, vnf_base.GenericTrafficGen))
def test_run_traffic(self):
- tg = tg_pktgen.PktgenTrafficGen('name1', self.VNFD, self._id)
+ tg = tg_pktgen.PktgenTrafficGen('name1', self.VNFD)
mock_tp = mock.Mock()
with mock.patch.object(tg, '_is_running', return_value=True):
tg.run_traffic(mock_tp)
@@ -57,23 +44,23 @@ class PktgenTrafficGenTestCase(ut_base.BaseUnitTestCase):
mock_tp.init.assert_called_once_with(tg._node_ip, tg._lua_node_port)
def test__get_lua_node_port(self):
- tg = tg_pktgen.PktgenTrafficGen('name1', self.VNFD, self._id)
+ tg = tg_pktgen.PktgenTrafficGen('name1', self.VNFD)
service_ports = [{'port': constants.LUA_PORT,
'node_port': '12345'}]
self.assertEqual(12345, tg._get_lua_node_port(service_ports))
def test__get_lua_node_port_no_lua_port(self):
- tg = tg_pktgen.PktgenTrafficGen('name1', self.VNFD, self._id)
+ tg = tg_pktgen.PktgenTrafficGen('name1', self.VNFD)
service_ports = [{'port': '333'}]
self.assertIsNone(tg._get_lua_node_port(service_ports))
def test__is_running(self):
- tg = tg_pktgen.PktgenTrafficGen('name1', self.VNFD, self._id)
+ tg = tg_pktgen.PktgenTrafficGen('name1', self.VNFD)
with mock.patch.object(tg, '_traffic_profile'):
self.assertTrue(tg._is_running())
def test__is_running_exception(self):
- tg = tg_pktgen.PktgenTrafficGen('name1', self.VNFD, self._id)
+ tg = tg_pktgen.PktgenTrafficGen('name1', self.VNFD)
with mock.patch.object(tg, '_traffic_profile') as mock_tp:
mock_tp.help.side_effect = exceptions.PktgenActionError()
self.assertFalse(tg._is_running())
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_prox.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_prox.py
index 935d3fa30..0aaf17790 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_prox.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_prox.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2017 Intel Corporation
+# Copyright (c) 2017-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -314,16 +314,15 @@ class TestProxTrafficGen(unittest.TestCase):
@mock.patch(SSH_HELPER)
def test___init__(self, ssh, *args):
mock_ssh(ssh)
- prox_traffic_gen = ProxTrafficGen(NAME, self.VNFD0, 'task_id')
+ prox_traffic_gen = ProxTrafficGen(NAME, self.VNFD0)
self.assertIsNone(prox_traffic_gen._tg_process)
self.assertIsNone(prox_traffic_gen._traffic_process)
- self.assertIsNone(prox_traffic_gen._mq_producer)
@mock.patch.object(ctx_base.Context, 'get_physical_node_from_server', return_value='mock_node')
@mock.patch(SSH_HELPER)
def test_collect_kpi(self, ssh, *args):
mock_ssh(ssh)
- prox_traffic_gen = ProxTrafficGen(NAME, self.VNFD0, 'task_id')
+ prox_traffic_gen = ProxTrafficGen(NAME, self.VNFD0)
prox_traffic_gen.scenario_helper.scenario_cfg = {
'nodes': {prox_traffic_gen.name: "mock"}
}
@@ -365,7 +364,7 @@ class TestProxTrafficGen(unittest.TestCase):
mock_traffic_profile.params = self.TRAFFIC_PROFILE
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- prox_traffic_gen = ProxTrafficGen(NAME, vnfd, 'task_id')
+ prox_traffic_gen = ProxTrafficGen(NAME, vnfd)
ssh_helper = mock.MagicMock(
**{"execute.return_value": (0, "", ""), "bin_path": ""})
prox_traffic_gen.ssh_helper = ssh_helper
@@ -407,22 +406,21 @@ class TestProxTrafficGen(unittest.TestCase):
mock_traffic_profile.params = self.TRAFFIC_PROFILE
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- sut = ProxTrafficGen(NAME, vnfd, 'task_id')
+ sut = ProxTrafficGen(NAME, vnfd)
sut._get_socket = mock.MagicMock()
sut.ssh_helper = mock.Mock()
sut.ssh_helper.run = mock.Mock()
sut.setup_helper.prox_config_dict = {}
sut._connect_client = mock.Mock(autospec=mock.Mock())
sut._connect_client.get_stats = mock.Mock(return_value="0")
- sut._setup_mq_producer = mock.Mock(return_value='mq_producer')
- sut._traffic_runner(mock_traffic_profile, mock.ANY)
+ sut._traffic_runner(mock_traffic_profile)
@mock.patch('yardstick.network_services.vnf_generic.vnf.prox_helpers.socket')
@mock.patch(SSH_HELPER)
def test_listen_traffic(self, ssh, *args):
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- prox_traffic_gen = ProxTrafficGen(NAME, vnfd, 'task_id')
+ prox_traffic_gen = ProxTrafficGen(NAME, vnfd)
self.assertIsNone(prox_traffic_gen.listen_traffic(mock.Mock()))
@mock.patch('yardstick.network_services.vnf_generic.vnf.prox_helpers.socket')
@@ -430,7 +428,7 @@ class TestProxTrafficGen(unittest.TestCase):
def test_terminate(self, ssh, *args):
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- prox_traffic_gen = ProxTrafficGen(NAME, vnfd, 'task_id')
+ prox_traffic_gen = ProxTrafficGen(NAME, vnfd)
prox_traffic_gen._terminated = mock.MagicMock()
prox_traffic_gen._traffic_process = mock.MagicMock()
prox_traffic_gen._traffic_process.terminate = mock.Mock()
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_rfc2544_ixia.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_rfc2544_ixia.py
index 65bf56f1e..d84fda789 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_rfc2544_ixia.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_rfc2544_ixia.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ import mock
import six
import unittest
import ipaddress
+import time
from collections import OrderedDict
from yardstick.common import utils
@@ -27,6 +28,7 @@ from yardstick.benchmark.contexts import base as ctx_base
from yardstick.network_services.libs.ixia_libs.ixnet import ixnet_api
from yardstick.network_services.traffic_profile import base as tp_base
from yardstick.network_services.vnf_generic.vnf import tg_rfc2544_ixia
+from yardstick.network_services.traffic_profile import ixia_rfc2544
TEST_FILE_YAML = 'nsb_test_case.yaml'
@@ -108,6 +110,31 @@ class TestIxiaResourceHelper(unittest.TestCase):
self.assertEqual('fake_samples', ixia_rhelper._queue.get())
mock_tprofile.update_traffic_profile.assert_called_once()
+ def test_run_test(self):
+ expected_result = {'test': 'fake_samples', 'Iteration': 1}
+ mock_tprofile = mock.Mock()
+ mock_tprofile.config.duration = 10
+ mock_tprofile.get_drop_percentage.return_value = \
+ True, {'test': 'fake_samples'}
+ ixia_rhelper = tg_rfc2544_ixia.IxiaResourceHelper(mock.Mock())
+ tasks_queue = mock.Mock()
+ tasks_queue.get.return_value = 'RUN_TRAFFIC'
+ results_queue = mock.Mock()
+ ixia_rhelper.rfc_helper = mock.Mock()
+ ixia_rhelper.vnfd_helper = mock.Mock()
+ ixia_rhelper._ix_scenario = mock.Mock()
+ ixia_rhelper.vnfd_helper.port_pairs.all_ports = []
+ with mock.patch.object(ixia_rhelper, 'generate_samples'), \
+ mock.patch.object(ixia_rhelper, '_build_ports'), \
+ mock.patch.object(ixia_rhelper, '_initialize_client'), \
+ mock.patch.object(utils, 'wait_until_true'):
+ ixia_rhelper.run_test(mock_tprofile, tasks_queue, results_queue)
+
+ self.assertEqual(expected_result, ixia_rhelper._queue.get())
+ mock_tprofile.update_traffic_profile.assert_called_once()
+ tasks_queue.task_done.assert_called_once()
+ results_queue.put.assert_called_once_with('COMPLETE')
+
@mock.patch.object(tg_rfc2544_ixia, 'ixnet_api')
class TestIXIATrafficGen(unittest.TestCase):
@@ -216,7 +243,7 @@ class TestIXIATrafficGen(unittest.TestCase):
ssh.from_node.return_value = ssh_mock
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
# NOTE(ralonsoh): check the object returned.
- tg_rfc2544_ixia.IxiaTrafficGen(NAME, vnfd, 'task_id')
+ tg_rfc2544_ixia.IxiaTrafficGen(NAME, vnfd)
def test_listen_traffic(self, *args):
with mock.patch("yardstick.ssh.SSH") as ssh:
@@ -225,8 +252,7 @@ class TestIXIATrafficGen(unittest.TestCase):
mock.Mock(return_value=(0, "", ""))
ssh.from_node.return_value = ssh_mock
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- ixnet_traffic_gen = tg_rfc2544_ixia.IxiaTrafficGen(NAME, vnfd,
- 'task_id')
+ ixnet_traffic_gen = tg_rfc2544_ixia.IxiaTrafficGen(NAME, vnfd)
self.assertIsNone(ixnet_traffic_gen.listen_traffic({}))
@mock.patch.object(ctx_base.Context, 'get_context_from_server', return_value='fake_context')
@@ -239,8 +265,7 @@ class TestIXIATrafficGen(unittest.TestCase):
mock.Mock(return_value=(0, "", ""))
ssh.from_node.return_value = ssh_mock
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- ixnet_traffic_gen = tg_rfc2544_ixia.IxiaTrafficGen(NAME, vnfd,
- 'task_id')
+ ixnet_traffic_gen = tg_rfc2544_ixia.IxiaTrafficGen(NAME, vnfd)
scenario_cfg = {'tc': "nsb_test_case",
"topology": ""}
scenario_cfg.update(
@@ -277,8 +302,7 @@ class TestIXIATrafficGen(unittest.TestCase):
ssh.from_node.return_value = ssh_mock
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- ixnet_traffic_gen = tg_rfc2544_ixia.IxiaTrafficGen(NAME, vnfd,
- 'task_id')
+ ixnet_traffic_gen = tg_rfc2544_ixia.IxiaTrafficGen(NAME, vnfd)
ixnet_traffic_gen.scenario_helper.scenario_cfg = {
'nodes': {ixnet_traffic_gen.name: "mock"}
}
@@ -298,7 +322,7 @@ class TestIXIATrafficGen(unittest.TestCase):
mock.Mock(return_value=(0, "", ""))
ssh.from_node.return_value = ssh_mock
ixnet_traffic_gen = tg_rfc2544_ixia.IxiaTrafficGen(
- NAME, vnfd, 'task_id', resource_helper_type=mock.Mock())
+ NAME, vnfd, resource_helper_type=mock.Mock())
ixnet_traffic_gen._terminated = mock.MagicMock()
ixnet_traffic_gen._terminated.value = 0
ixnet_traffic_gen._ixia_traffic_gen = mock.MagicMock()
@@ -314,7 +338,7 @@ class TestIXIATrafficGen(unittest.TestCase):
def test__check_status(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- sut = tg_rfc2544_ixia.IxiaTrafficGen('vnf1', vnfd, 'task_id')
+ sut = tg_rfc2544_ixia.IxiaTrafficGen('vnf1', vnfd)
sut._check_status()
@mock.patch("yardstick.ssh.SSH")
@@ -380,7 +404,7 @@ class TestIXIATrafficGen(unittest.TestCase):
mock_traffic_profile.get_drop_percentage.return_value = [
'Completed', samples]
- sut = tg_rfc2544_ixia.IxiaTrafficGen(name, vnfd, 'task_id')
+ sut = tg_rfc2544_ixia.IxiaTrafficGen(name, vnfd)
sut.vnf_port_pairs = [[[0], [1]]]
sut.tc_file_name = self._get_file_abspath(TEST_FILE_YAML)
sut.topology = ""
@@ -424,15 +448,70 @@ class TestIXIATrafficGen(unittest.TestCase):
mock.mock_open(), create=True)
@mock.patch('yardstick.network_services.vnf_generic.vnf.tg_rfc2544_ixia.LOG.exception')
def _traffic_runner(*args):
- sut._setup_mq_producer = mock.Mock(return_value='mq_producer')
- result = sut._traffic_runner(mock_traffic_profile, mock.ANY)
+ result = sut._traffic_runner(mock_traffic_profile)
self.assertIsNone(result)
_traffic_runner()
+ def test_run_traffic_once(self, *args):
+ vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
+ sut = tg_rfc2544_ixia.IxiaTrafficGen('vnf1', vnfd)
+ sut._init_traffic_process = mock.Mock()
+ sut._tasks_queue.put = mock.Mock()
+ sut.resource_helper.client_started.value = 0
+ sut.run_traffic_once(self.TRAFFIC_PROFILE)
+ sut._tasks_queue.put.assert_called_once_with("RUN_TRAFFIC")
+ sut._init_traffic_process.assert_called_once_with(self.TRAFFIC_PROFILE)
+
+ def test__test_runner(self, *args):
+ vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
+ sut = tg_rfc2544_ixia.IxiaTrafficGen('vnf1', vnfd)
+ tasks = 'tasks'
+ results = 'results'
+ sut.resource_helper = mock.Mock()
+ sut._test_runner(self.TRAFFIC_PROFILE, tasks, results)
+ sut.resource_helper.run_test.assert_called_once_with(self.TRAFFIC_PROFILE,
+ tasks, results)
+
+ @mock.patch.object(time, 'sleep', return_value=0)
+ def test__init_traffic_process(self, *args):
+ vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
+ sut = tg_rfc2544_ixia.IxiaTrafficGen('vnf1', vnfd)
+ sut._test_runner = mock.Mock(return_value=0)
+ sut.resource_helper = mock.Mock()
+ sut.resource_helper.client_started.value = 0
+ sut._init_traffic_process(self.TRAFFIC_PROFILE)
+
+ def test_wait_on_traffic(self, *args):
+ vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
+ sut = tg_rfc2544_ixia.IxiaTrafficGen('vnf1', vnfd)
+ sut._tasks_queue.join = mock.Mock(return_value=0)
+ sut._result_queue.get = mock.Mock(return_value='COMPLETE')
+ result = sut.wait_on_traffic()
+ sut._tasks_queue.join.assert_called_once()
+ sut._result_queue.get.assert_called_once()
+ self.assertEqual(result, 'COMPLETE')
+
class TestIxiaBasicScenario(unittest.TestCase):
+ STATS = {'stat_name': ['Card01/Port01',
+ 'Card02/Port02'],
+ 'port_name': ['Ethernet - 001', 'Ethernet - 002'],
+ 'Frames_Tx': ['150', '150'],
+ 'Valid_Frames_Rx': ['150', '150'],
+ 'Frames_Tx_Rate': ['0.0', '0.0'],
+ 'Valid_Frames_Rx_Rate': ['0.0', '0.0'],
+ 'Bytes_Rx': ['9600', '9600'],
+ 'Bytes_Tx': ['9600', '9600'],
+ 'Tx_Rate_Kbps': ['0.0', '0.0'],
+ 'Rx_Rate_Mbps': ['0.0', '0.0'],
+ 'Tx_Rate_Mbps': ['0.0', '0.0'],
+ 'Rx_Rate_Kbps': ['0.0', '0.0'],
+ 'Store-Forward_Max_latency_ns': ['100', '200'],
+ 'Store-Forward_Min_latency_ns': ['100', '200'],
+ 'Store-Forward_Avg_latency_ns': ['100', '200']}
+
def setUp(self):
self._mock_IxNextgen = mock.patch.object(ixnet_api, 'IxNextgen')
self.mock_IxNextgen = self._mock_IxNextgen.start()
@@ -450,14 +529,18 @@ class TestIxiaBasicScenario(unittest.TestCase):
self.assertIsInstance(self.scenario, tg_rfc2544_ixia.IxiaBasicScenario)
self.assertEqual(self.scenario.client, self.mock_IxNextgen)
- def test_apply_config(self):
- self.assertIsNone(self.scenario.apply_config())
-
def test_create_traffic_model(self):
self.mock_IxNextgen.get_vports.return_value = [1, 2, 3, 4]
- self.scenario.create_traffic_model()
+ yaml_data = {'traffic_profile': {}
+ }
+ traffic_profile = ixia_rfc2544.IXIARFC2544Profile(yaml_data)
+ self.scenario.create_traffic_model(traffic_profile)
self.scenario.client.get_vports.assert_called_once()
- self.scenario.client.create_traffic_model.assert_called_once_with([1, 3], [2, 4])
+ self.scenario.client.create_traffic_model.assert_called_once_with(
+ [1, 3], [2, 4], traffic_profile)
+
+ def test_apply_config(self):
+ self.assertIsNone(self.scenario.apply_config())
def test_run_protocols(self):
self.assertIsNone(self.scenario.run_protocols())
@@ -465,6 +548,147 @@ class TestIxiaBasicScenario(unittest.TestCase):
def test_stop_protocols(self):
self.assertIsNone(self.scenario.stop_protocols())
+ def test__get_stats(self):
+ self.scenario._get_stats()
+ self.scenario.client.get_statistics.assert_called_once()
+
+ @mock.patch.object(tg_rfc2544_ixia.IxiaBasicScenario, '_get_stats')
+ def test_generate_samples(self, mock_get_stats):
+
+ expected_samples = {'xe0': {
+ 'in_packets': 150,
+ 'out_packets': 150,
+ 'in_bytes': 9600,
+ 'out_bytes': 9600,
+ 'rx_throughput_mbps': 0.0,
+ 'rx_throughput_kps': 0.0,
+ 'RxThroughput': 5.0,
+ 'TxThroughput': 5.0,
+ 'RxThroughputBps': 320.0,
+ 'TxThroughputBps': 320.0,
+ 'tx_throughput_mbps': 0.0,
+ 'tx_throughput_kps': 0.0,
+ 'Store-Forward_Max_latency_ns': 100,
+ 'Store-Forward_Min_latency_ns': 100,
+ 'Store-Forward_Avg_latency_ns': 100},
+ 'xe1': {
+ 'in_packets': 150,
+ 'out_packets': 150,
+ 'in_bytes': 9600,
+ 'out_bytes': 9600,
+ 'rx_throughput_mbps': 0.0,
+ 'rx_throughput_kps': 0.0,
+ 'RxThroughput': 5.0,
+ 'TxThroughput': 5.0,
+ 'RxThroughputBps': 320.0,
+ 'TxThroughputBps': 320.0,
+ 'tx_throughput_mbps': 0.0,
+ 'tx_throughput_kps': 0.0,
+ 'Store-Forward_Max_latency_ns': 200,
+ 'Store-Forward_Min_latency_ns': 200,
+ 'Store-Forward_Avg_latency_ns': 200}}
+
+ res_helper = mock.Mock()
+ res_helper.vnfd_helper.find_interface_by_port.side_effect = \
+ [{'name': 'xe0'}, {'name': 'xe1'}]
+ ports = [0, 1]
+ duration = 30
+ mock_get_stats.return_value = self.STATS
+ samples = self.scenario.generate_samples(res_helper, ports, duration)
+ mock_get_stats.assert_called_once()
+ self.assertEqual(samples, expected_samples)
+
+
+class TestIxiaL3Scenario(TestIxiaBasicScenario):
+ IXIA_CFG = {
+ 'flow': {
+ 'src_ip': ['192.168.0.1-192.168.0.50'],
+ 'dst_ip': ['192.168.1.1-192.168.1.150']
+ }
+ }
+
+ CONTEXT_CFG = {
+ 'nodes': {
+ 'tg__0': {
+ 'role': 'IxNet',
+ 'interfaces': {
+ 'xe0': {
+ 'vld_id': 'uplink_0',
+ 'local_ip': '10.1.1.1',
+ 'local_mac': 'aa:bb:cc:dd:ee:ff',
+ 'ifname': 'xe0'
+ },
+ 'xe1': {
+ 'vld_id': 'downlink_0',
+ 'local_ip': '20.2.2.2',
+ 'local_mac': 'bb:bb:cc:dd:ee:ee',
+ 'ifname': 'xe1'
+ }
+ },
+ 'routing_table': [{
+ 'network': "152.16.100.20",
+ 'netmask': '255.255.0.0',
+ 'gateway': '152.16.100.21',
+ 'if': 'xe0'
+ }]
+ }
+ }
+ }
+
+ def setUp(self):
+ super(TestIxiaL3Scenario, self).setUp()
+ self.ixia_cfg = self.IXIA_CFG
+ self.context_cfg = self.CONTEXT_CFG
+ self.scenario = tg_rfc2544_ixia.IxiaL3Scenario(self.mock_IxNextgen,
+ self.context_cfg,
+ self.ixia_cfg)
+
+ def test___init___(self):
+ self.assertIsInstance(self.scenario, tg_rfc2544_ixia.IxiaL3Scenario)
+ self.assertEqual(self.scenario.client, self.mock_IxNextgen)
+
+ def test_create_traffic_model(self):
+ self.mock_IxNextgen.get_vports.return_value = ['1', '2']
+ self.scenario.create_traffic_model()
+ self.scenario.client.get_vports.assert_called_once()
+ self.scenario.client.create_ipv4_traffic_model.\
+ assert_called_once_with(['1/protocols/static'],
+ ['2/protocols/static'])
+
+ def test_apply_config(self):
+ self.scenario._add_interfaces = mock.Mock()
+ self.scenario._add_static_ips = mock.Mock()
+ self.assertIsNone(self.scenario.apply_config())
+
+ def test__add_static(self):
+ self.mock_IxNextgen.get_vports.return_value = ['1', '2']
+ self.mock_IxNextgen.get_static_interface.side_effect = ['intf1',
+ 'intf2']
+
+ self.scenario._add_static_ips()
+
+ self.mock_IxNextgen.get_static_interface.assert_any_call('1')
+ self.mock_IxNextgen.get_static_interface.assert_any_call('2')
+
+ self.scenario.client.add_static_ipv4.assert_any_call(
+ 'intf1', '1', '192.168.0.1', 49, '32')
+ self.scenario.client.add_static_ipv4.assert_any_call(
+ 'intf2', '2', '192.168.1.1', 149, '32')
+
+ def test__add_interfaces(self):
+ self.mock_IxNextgen.get_vports.return_value = ['1', '2']
+
+ self.scenario._add_interfaces()
+
+ self.mock_IxNextgen.add_interface.assert_any_call('1',
+ '10.1.1.1',
+ 'aa:bb:cc:dd:ee:ff',
+ '152.16.100.21')
+ self.mock_IxNextgen.add_interface.assert_any_call('2',
+ '20.2.2.2',
+ 'bb:bb:cc:dd:ee:ee',
+ None)
+
class TestIxiaPppoeClientScenario(unittest.TestCase):
@@ -483,6 +707,9 @@ class TestIxiaPppoeClientScenario(unittest.TestCase):
'gateway_ip': ['10.1.1.1', '10.2.2.1'],
'ip': ['10.1.1.1', '10.2.2.1'],
'prefix': ['24', '24']
+ },
+ 'priority': {
+ 'tos': {'precedence': [0, 4]}
}
}
@@ -547,6 +774,30 @@ class TestIxiaPppoeClientScenario(unittest.TestCase):
self.scenario.client.create_ipv4_traffic_model.assert_called_once_with(
uplink_endpoints, downlink_endpoints)
+ @mock.patch.object(tg_rfc2544_ixia.IxiaPppoeClientScenario,
+ '_get_endpoints_src_dst_id_pairs')
+ @mock.patch.object(tg_rfc2544_ixia.IxiaPppoeClientScenario,
+ '_get_endpoints_src_dst_obj_pairs')
+ def test_create_traffic_model_topology_based_flows(self, mock_obj_pairs,
+ mock_id_pairs):
+ uplink_topologies = ['topology1', 'topology3']
+ downlink_topologies = ['topology2', 'topology4']
+ mock_id_pairs.return_value = []
+ mock_obj_pairs.return_value = []
+ mock_tp = mock.Mock()
+ mock_tp.full_profile = {'uplink_0': 'data',
+ 'downlink_0': 'data',
+ 'uplink_1': 'data',
+ 'downlink_1': 'data'
+ }
+ self.scenario._access_topologies = ['topology1', 'topology3']
+ self.scenario._core_topologies = ['topology2', 'topology4']
+ self.scenario.create_traffic_model(mock_tp)
+ mock_id_pairs.assert_called_once_with(mock_tp.full_profile)
+ mock_obj_pairs.assert_called_once_with([])
+ self.scenario.client.create_ipv4_traffic_model.assert_called_once_with(
+ uplink_topologies, downlink_topologies)
+
def test__get_endpoints_src_dst_id_pairs(self):
full_tp = OrderedDict([
('uplink_0', {'ipv4': {'port': 'xe0'}}),
@@ -616,22 +867,10 @@ class TestIxiaPppoeClientScenario(unittest.TestCase):
}
}
- expected_result = ['tp1_dg1', 'tp3_dg1', 'tp1_dg2', 'tp3_dg1',
- 'tp1_dg3', 'tp3_dg1', 'tp1_dg4', 'tp3_dg1',
- 'tp2_dg1', 'tp4_dg1', 'tp2_dg2', 'tp4_dg1',
- 'tp2_dg3', 'tp4_dg1', 'tp2_dg4', 'tp4_dg1']
-
self.scenario._ixia_cfg = ixia_cfg
- self.scenario._access_topologies = ['topology1', 'topology2']
- self.scenario._core_topologies = ['topology3', 'topology4']
- self.mock_IxNextgen.get_topology_device_groups.side_effect = \
- [['tp1_dg1', 'tp1_dg2', 'tp1_dg3', 'tp1_dg4'],
- ['tp2_dg1', 'tp2_dg2', 'tp2_dg3', 'tp2_dg4'],
- ['tp3_dg1'],
- ['tp4_dg1']]
res = self.scenario._get_endpoints_src_dst_obj_pairs(
endpoints_id_pairs)
- self.assertEqual(res, expected_result)
+ self.assertEqual(res, [])
def test_run_protocols(self):
self.scenario.client.is_protocols_running.return_value = True
@@ -868,3 +1107,173 @@ class TestIxiaPppoeClientScenario(unittest.TestCase):
local_as=bgp_params["bgp"]["as_number"],
bgp_type=bgp_params["bgp"]["bgp_type"])
])
+
+ def test_update_tracking_options_raw_priority(self):
+ raw_priority = {'raw': 4}
+ self.scenario._ixia_cfg['priority'] = raw_priority
+ self.scenario.update_tracking_options()
+ self.scenario.client.set_flow_tracking.assert_called_once_with(
+ ['flowGroup0', 'vlanVlanId0', 'ipv4Raw0'])
+
+ def test_update_tracking_options_tos_priority(self):
+ tos_priority = {'tos': {'precedence': [4, 7]}}
+ self.scenario._ixia_cfg['priority'] = tos_priority
+ self.scenario.update_tracking_options()
+ self.scenario.client.set_flow_tracking.assert_called_once_with(
+ ['flowGroup0', 'vlanVlanId0', 'ipv4Precedence0'])
+
+ def test_update_tracking_options_dscp_priority(self):
+ dscp_priority = {'dscp': {'defaultPHB': [4, 7]}}
+ self.scenario._ixia_cfg['priority'] = dscp_priority
+ self.scenario.update_tracking_options()
+ self.scenario.client.set_flow_tracking.assert_called_once_with(
+ ['flowGroup0', 'vlanVlanId0', 'ipv4DefaultPhb0'])
+
+ def test_update_tracking_options_invalid_priority_data(self):
+ invalid_priority = {'tos': {'inet-precedence': [4, 7]}}
+ self.scenario._ixia_cfg['priority'] = invalid_priority
+ self.scenario.update_tracking_options()
+ self.scenario.client.set_flow_tracking.assert_called_once_with(
+ ['flowGroup0', 'vlanVlanId0', 'ipv4Precedence0'])
+
+ def test_get_tc_rfc2544_options(self):
+ rfc2544_tc_opts = {'allowed_drop_rate': '0.0001 - 0.0001'}
+ self.scenario._ixia_cfg['rfc2544'] = rfc2544_tc_opts
+ res = self.scenario.get_tc_rfc2544_options()
+ self.assertEqual(res, rfc2544_tc_opts)
+
+ def test__get_stats(self):
+ self.scenario._get_stats()
+ self.scenario.client.get_pppoe_scenario_statistics.assert_called_once()
+
+ def test_get_flow_id_data(self):
+ stats = [{'id': 1, 'in_packets': 10, 'out_packets': 20}]
+ key = "in_packets"
+ flow_id = 1
+ res = self.scenario.get_flow_id_data(stats, flow_id, key)
+ self.assertEqual(res, 10)
+
+ @mock.patch.object(tg_rfc2544_ixia.IxiaPppoeClientScenario, '_get_stats')
+ @mock.patch.object(tg_rfc2544_ixia.IxiaPppoeClientScenario,
+ 'get_priority_flows_stats')
+ def test_generate_samples(self, mock_prio_flow_statistics,
+ mock_get_stats):
+ ixia_stats = {
+ 'flow_statistic': [
+ {'Flow_Group': 'RFC2544-1 - Flow Group 0001',
+ 'Frames_Delta': '0',
+ 'IP_Priority': '0',
+ 'Rx_Frames': '3000',
+ 'Tx_Frames': '3000',
+ 'VLAN-ID': '100',
+ 'Tx_Port': 'Ethernet - 001',
+ 'Store-Forward_Avg_latency_ns': '2',
+ 'Store-Forward_Min_latency_ns': '2',
+ 'Store-Forward_Max_latency_ns': '2'},
+ {'Flow_Group': 'RFC2544-2 - Flow Group 0001',
+ 'Frames_Delta': '0',
+ 'IP_Priority': '0',
+ 'Rx_Frames': '3000',
+ 'Tx_Frames': '3000',
+ 'VLAN-ID': '101',
+ 'Tx_Port': 'Ethernet - 002',
+ 'Store-Forward_Avg_latency_ns': '2',
+ 'Store-Forward_Min_latency_ns': '2',
+ 'Store-Forward_Max_latency_ns': '2'
+ }],
+ 'port_statistics': [
+ {'Frames_Tx': '3000',
+ 'Valid_Frames_Rx': '3000',
+ 'Bytes_Rx': '192000',
+ 'Bytes_Tx': '192000',
+ 'Rx_Rate_Kbps': '0.0',
+ 'Tx_Rate_Kbps': '0.0',
+ 'Rx_Rate_Mbps': '0.0',
+ 'Tx_Rate_Mbps': '0.0',
+ 'port_name': 'Ethernet - 001'},
+ {'Frames_Tx': '3000',
+ 'Valid_Frames_Rx': '3000',
+ 'Bytes_Rx': '192000',
+ 'Bytes_Tx': '192000',
+ 'Rx_Rate_Kbps': '0.0',
+ 'Tx_Rate_Kbps': '0.0',
+ 'Rx_Rate_Mbps': '0.0',
+ 'Tx_Rate_Mbps': '0.0',
+ 'port_name': 'Ethernet - 002'}],
+ 'pppox_client_per_port': [
+ {'Sessions_Down': '0',
+ 'Sessions_Not_Started': '0',
+ 'Sessions_Total': '1',
+ 'Sessions_Up': '1',
+ 'subs_port': 'Ethernet - 001'}]}
+
+ prio_flows_stats = {
+ '0': {
+ 'in_packets': 6000,
+ 'out_packets': 6000,
+ 'RxThroughput': 200.0,
+ 'TxThroughput': 200.0,
+ 'avg_latency_ns': 2,
+ 'max_latency_ns': 2,
+ 'min_latency_ns': 2
+ }
+ }
+
+ expected_result = {'priority_stats': {
+ '0': {'RxThroughput': 200.0,
+ 'TxThroughput': 200.0,
+ 'avg_latency_ns': 2,
+ 'max_latency_ns': 2,
+ 'min_latency_ns': 2,
+ 'in_packets': 6000,
+ 'out_packets': 6000}},
+ 'xe0': {'RxThroughput': 100.0,
+ 'Store-Forward_Avg_latency_ns': 2,
+ 'Store-Forward_Max_latency_ns': 2,
+ 'Store-Forward_Min_latency_ns': 2,
+ 'TxThroughput': 100.0,
+ 'in_packets': 3000,
+ 'out_packets': 3000,
+ 'in_bytes': 192000,
+ 'out_bytes': 192000,
+ 'RxThroughputBps': 6400.0,
+ 'TxThroughputBps': 6400.0,
+ 'rx_throughput_kps': 0.0,
+ 'rx_throughput_mbps': 0.0,
+ 'sessions_down': 0,
+ 'sessions_not_started': 0,
+ 'sessions_total': 1,
+ 'sessions_up': 1,
+ 'tx_throughput_kps': 0.0,
+ 'tx_throughput_mbps': 0.0},
+ 'xe1': {'RxThroughput': 100.0,
+ 'Store-Forward_Avg_latency_ns': 2,
+ 'Store-Forward_Max_latency_ns': 2,
+ 'Store-Forward_Min_latency_ns': 2,
+ 'TxThroughput': 100.0,
+ 'in_packets': 3000,
+ 'out_packets': 3000,
+ 'in_bytes': 192000,
+ 'out_bytes': 192000,
+ 'RxThroughputBps': 6400.0,
+ 'TxThroughputBps': 6400.0,
+ 'rx_throughput_kps': 0.0,
+ 'rx_throughput_mbps': 0.0,
+ 'tx_throughput_kps': 0.0,
+ 'tx_throughput_mbps': 0.0}}
+
+ mock_get_stats.return_value = ixia_stats
+ mock_prio_flow_statistics.return_value = prio_flows_stats
+ ports = [0, 1]
+ port_names = [{'name': 'xe0'}, {'name': 'xe1'}]
+ duration = 30
+ res_helper = mock.Mock()
+ res_helper.vnfd_helper.find_interface_by_port.side_effect = \
+ port_names
+ samples = self.scenario.generate_samples(res_helper, ports, duration)
+ self.assertIsNotNone(samples)
+ self.assertIsNotNone(samples.get('xe0'))
+ self.assertIsNotNone(samples.get('xe1'))
+ self.assertEqual(samples, expected_result)
+ mock_get_stats.assert_called_once()
+ mock_prio_flow_statistics.assert_called_once()
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_rfc2544_trex.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_rfc2544_trex.py
index a5b9f258e..51b1b0d33 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_rfc2544_trex.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_rfc2544_trex.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -11,6 +11,7 @@
# 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 time
import mock
import unittest
@@ -24,7 +25,8 @@ from yardstick.network_services.vnf_generic.vnf import tg_rfc2544_trex
class TestTrexRfcResouceHelper(unittest.TestCase):
- def test__run_traffic_once(self):
+ @mock.patch.object(time, 'sleep')
+ def test__run_traffic_once(self, *args):
mock_setup_helper = mock.Mock()
mock_traffic_profile = mock.Mock()
mock_traffic_profile.config.duration = 3
@@ -224,14 +226,12 @@ class TestTrexTrafficGenRFC(unittest.TestCase):
self._mock_ssh_helper.stop()
def test___init__(self):
- trex_traffic_gen = tg_rfc2544_trex.TrexTrafficGenRFC(
- 'vnf1', self.VNFD_0, 'task_id')
+ trex_traffic_gen = tg_rfc2544_trex.TrexTrafficGenRFC('vnf1', self.VNFD_0)
self.assertIsNotNone(trex_traffic_gen.resource_helper._terminated.value)
@mock.patch.object(ctx_base.Context, 'get_physical_node_from_server', return_value='mock_node')
def test_collect_kpi(self, *args):
- trex_traffic_gen = tg_rfc2544_trex.TrexTrafficGenRFC(
- 'vnf1', self.VNFD_0, 'task_id')
+ trex_traffic_gen = tg_rfc2544_trex.TrexTrafficGenRFC('vnf1', self.VNFD_0)
trex_traffic_gen.scenario_helper.scenario_cfg = {
'nodes': {trex_traffic_gen.name: "mock"}
}
@@ -247,8 +247,7 @@ class TestTrexTrafficGenRFC(unittest.TestCase):
mock_traffic_profile.get_traffic_definition.return_value = "64"
mock_traffic_profile.params = self.TRAFFIC_PROFILE
- trex_traffic_gen = tg_rfc2544_trex.TrexTrafficGenRFC(
- 'vnf1', self.VNFD_0, 'task_id')
+ trex_traffic_gen = tg_rfc2544_trex.TrexTrafficGenRFC('vnf1', self.VNFD_0)
trex_traffic_gen._start_server = mock.Mock(return_value=0)
trex_traffic_gen.resource_helper = mock.MagicMock()
trex_traffic_gen.setup_helper.setup_vnf_environment = mock.MagicMock()
@@ -283,8 +282,7 @@ class TestTrexTrafficGenRFC(unittest.TestCase):
mock_traffic_profile.get_traffic_definition.return_value = "64"
mock_traffic_profile.params = self.TRAFFIC_PROFILE
- trex_traffic_gen = tg_rfc2544_trex.TrexTrafficGenRFC(
- 'vnf1', self.VNFD_0, 'task_id')
+ trex_traffic_gen = tg_rfc2544_trex.TrexTrafficGenRFC('vnf1', self.VNFD_0)
trex_traffic_gen.resource_helper = mock.MagicMock()
trex_traffic_gen.setup_helper.setup_vnf_environment = mock.MagicMock()
scenario_cfg = {
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_trex.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_trex.py
index 9ed2abbb9..0a441c8ce 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_trex.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_tg_trex.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -300,14 +300,14 @@ class TestTrexTrafficGen(unittest.TestCase):
def test___init__(self):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd, 'task_id')
+ trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd)
self.assertIsInstance(trex_traffic_gen.resource_helper,
tg_trex.TrexResourceHelper)
@mock.patch.object(ctx_base.Context, 'get_physical_node_from_server', return_value='mock_node')
def test_collect_kpi(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd, 'task_id')
+ trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd)
trex_traffic_gen.scenario_helper.scenario_cfg = {
'nodes': {trex_traffic_gen.name: "mock"}
}
@@ -321,13 +321,13 @@ class TestTrexTrafficGen(unittest.TestCase):
def test_listen_traffic(self):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd, 'task_id')
+ trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd)
self.assertIsNone(trex_traffic_gen.listen_traffic({}))
@mock.patch.object(ctx_base.Context, 'get_context_from_server', return_value='fake_context')
def test_instantiate(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd, 'task_id')
+ trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd)
trex_traffic_gen._start_server = mock.Mock(return_value=0)
trex_traffic_gen._tg_process = mock.MagicMock()
trex_traffic_gen._tg_process.start = mock.Mock()
@@ -342,7 +342,7 @@ class TestTrexTrafficGen(unittest.TestCase):
@mock.patch.object(ctx_base.Context, 'get_context_from_server', return_value='fake_context')
def test_instantiate_error(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd, 'task_id')
+ trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd)
trex_traffic_gen._start_server = mock.Mock(return_value=0)
trex_traffic_gen._tg_process = mock.MagicMock()
trex_traffic_gen._tg_process.start = mock.Mock()
@@ -355,7 +355,7 @@ class TestTrexTrafficGen(unittest.TestCase):
def test__start_server(self):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd, 'task_id')
+ trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd)
trex_traffic_gen.ssh_helper = mock.MagicMock()
trex_traffic_gen.resource_helper.ssh_helper = mock.MagicMock()
trex_traffic_gen.scenario_helper.scenario_cfg = {}
@@ -363,7 +363,7 @@ class TestTrexTrafficGen(unittest.TestCase):
def test__start_server_multiple_queues(self):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd, 'task_id')
+ trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd)
trex_traffic_gen.ssh_helper = mock.MagicMock()
trex_traffic_gen.resource_helper.ssh_helper = mock.MagicMock()
trex_traffic_gen.scenario_helper.scenario_cfg = {
@@ -377,7 +377,7 @@ class TestTrexTrafficGen(unittest.TestCase):
mock_traffic_profile.params = self.TRAFFIC_PROFILE
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- self.sut = tg_trex.TrexTrafficGen(NAME, vnfd, 'task_id')
+ self.sut = tg_trex.TrexTrafficGen(NAME, vnfd)
self.sut.ssh_helper = mock.Mock()
self.sut.ssh_helper.run = mock.Mock()
self.sut._connect_client = mock.Mock()
@@ -387,13 +387,12 @@ class TestTrexTrafficGen(unittest.TestCase):
# must generate cfg before we can run traffic so Trex port mapping is
# created
self.sut.resource_helper.generate_cfg()
- self.sut._setup_mq_producer = mock.Mock()
with mock.patch.object(self.sut.resource_helper, 'run_traffic'):
- self.sut._traffic_runner(mock_traffic_profile, mock.ANY)
+ self.sut._traffic_runner(mock_traffic_profile)
def test__generate_trex_cfg(self):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd, 'task_id')
+ trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd)
trex_traffic_gen.resource_helper.ssh_helper = mock.MagicMock()
self.assertIsNone(trex_traffic_gen.resource_helper.generate_cfg())
@@ -432,7 +431,7 @@ class TestTrexTrafficGen(unittest.TestCase):
'local_mac': '00:00:00:00:00:01'},
'vnfd-connection-point-ref': 'xe1',
'name': 'xe1'}]
- trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd, 'task_id')
+ trex_traffic_gen = tg_trex.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()
@@ -449,24 +448,25 @@ class TestTrexTrafficGen(unittest.TestCase):
mock_traffic_profile.params = self.TRAFFIC_PROFILE
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- self.sut = tg_trex.TrexTrafficGen(NAME, vnfd, 'task_id')
+ self.sut = tg_trex.TrexTrafficGen(NAME, vnfd)
self.sut.ssh_helper = mock.Mock()
self.sut.ssh_helper.run = mock.Mock()
self.sut._traffic_runner = mock.Mock(return_value=0)
self.sut.resource_helper.client_started.value = 1
- self.sut.run_traffic(mock_traffic_profile)
+ result = self.sut.run_traffic(mock_traffic_profile)
self.sut._traffic_process.terminate()
+ self.assertIsNotNone(result)
def test_terminate(self):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd, 'task_id')
+ trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd)
trex_traffic_gen.ssh_helper = mock.MagicMock()
trex_traffic_gen.resource_helper.ssh_helper = mock.MagicMock()
self.assertIsNone(trex_traffic_gen.terminate())
def test__connect_client(self):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd, 'task_id')
+ trex_traffic_gen = tg_trex.TrexTrafficGen(NAME, vnfd)
client = mock.Mock()
client.connect = mock.Mock(return_value=0)
self.assertIsNotNone(trex_traffic_gen.resource_helper._connect(client))
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_udp_replay.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_udp_replay.py
index 56c971da6..cbb4ee913 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_udp_replay.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_udp_replay.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -317,8 +317,7 @@ class TestUdpReplayApproxVnf(unittest.TestCase):
}
def test___init__(self, *args):
- udp_replay_approx_vnf = UdpReplayApproxVnf(NAME, self.VNFD_0,
- 'task_id')
+ udp_replay_approx_vnf = UdpReplayApproxVnf(NAME, self.VNFD_0)
self.assertIsNone(udp_replay_approx_vnf._vnf_process)
@mock.patch("yardstick.network_services.vnf_generic.vnf.sample_vnf.time")
@@ -333,7 +332,7 @@ class TestUdpReplayApproxVnf(unittest.TestCase):
"Port\t\tRx Packet\t\tTx Packet\t\tRx Pkt Drop\t\tTx Pkt Drop \r\n"\
"0\t\t7374156\t\t7374136\t\t\t0\t\t\t0\r\n" \
"1\t\t7374316\t\t7374315\t\t\t0\t\t\t0\r\n\r\nReplay>\r\r\nReplay>"
- udp_replay_approx_vnf = UdpReplayApproxVnf(NAME, vnfd, 'task_id')
+ udp_replay_approx_vnf = UdpReplayApproxVnf(NAME, vnfd)
udp_replay_approx_vnf.scenario_helper.scenario_cfg = {
'nodes': {udp_replay_approx_vnf.name: "mock"}
}
@@ -355,8 +354,7 @@ class TestUdpReplayApproxVnf(unittest.TestCase):
def test_get_stats(self, ssh, *args):
mock_ssh(ssh)
- udp_replay_approx_vnf = UdpReplayApproxVnf(NAME, self.VNFD_0,
- 'task_id')
+ udp_replay_approx_vnf = UdpReplayApproxVnf(NAME, self.VNFD_0)
udp_replay_approx_vnf.q_in = mock.MagicMock()
udp_replay_approx_vnf.q_out = mock.MagicMock()
udp_replay_approx_vnf.q_out.qsize = mock.Mock(return_value=0)
@@ -382,8 +380,7 @@ class TestUdpReplayApproxVnf(unittest.TestCase):
nfvi_context.attrs = {'nfvi_type': 'baremetal'}
mock_get_ctx.return_value = nfvi_context
- udp_replay_approx_vnf = UdpReplayApproxVnf(NAME, self.VNFD_0,
- 'task_id')
+ udp_replay_approx_vnf = UdpReplayApproxVnf(NAME, self.VNFD_0)
udp_replay_approx_vnf.queue_wrapper = mock.MagicMock()
udp_replay_approx_vnf.nfvi_context = mock_get_ctx
udp_replay_approx_vnf.nfvi_context.attrs = {'nfvi_type': 'baremetal'}
@@ -408,8 +405,7 @@ class TestUdpReplayApproxVnf(unittest.TestCase):
nfvi_context.attrs = {'nfvi_type': "baremetal"}
mock_get_ctx.return_value = nfvi_context
- udp_replay_approx_vnf = UdpReplayApproxVnf(NAME, self.VNFD_0,
- 'task_id')
+ udp_replay_approx_vnf = UdpReplayApproxVnf(NAME, self.VNFD_0)
udp_replay_approx_vnf.setup_helper.bound_pci = ['0000:00:0.1', '0000:00:0.3']
udp_replay_approx_vnf.all_ports = ["xe0", "xe1"]
udp_replay_approx_vnf.ssh_helper.provision_tool = mock.MagicMock(return_value="tool_path")
@@ -431,8 +427,7 @@ class TestUdpReplayApproxVnf(unittest.TestCase):
def test_run_udp_replay(self, ssh, *args):
mock_ssh(ssh)
- udp_replay_approx_vnf = UdpReplayApproxVnf(NAME, self.VNFD_0,
- 'task_id')
+ udp_replay_approx_vnf = UdpReplayApproxVnf(NAME, self.VNFD_0)
udp_replay_approx_vnf._build_config = mock.MagicMock()
udp_replay_approx_vnf.queue_wrapper = mock.MagicMock()
udp_replay_approx_vnf.scenario_helper = mock.MagicMock()
@@ -446,8 +441,7 @@ class TestUdpReplayApproxVnf(unittest.TestCase):
def test_instantiate(self, ssh, *args):
mock_ssh(ssh)
- udp_replay_approx_vnf = UdpReplayApproxVnf(NAME, self.VNFD_0,
- 'task_id')
+ udp_replay_approx_vnf = UdpReplayApproxVnf(NAME, self.VNFD_0)
udp_replay_approx_vnf.q_out.put("Replay>")
udp_replay_approx_vnf.WAIT_TIME = 0
udp_replay_approx_vnf.setup_helper.setup_vnf_environment = mock.Mock()
@@ -465,8 +459,7 @@ class TestUdpReplayApproxVnf(unittest.TestCase):
@mock.patch('yardstick.ssh.SSH')
@mock.patch(SSH_HELPER)
def test_instantiate_panic(self, *args):
- udp_replay_approx_vnf = UdpReplayApproxVnf(NAME, self.VNFD_0,
- 'task_id')
+ udp_replay_approx_vnf = UdpReplayApproxVnf(NAME, self.VNFD_0)
udp_replay_approx_vnf.WAIT_TIME = 0
udp_replay_approx_vnf.q_out.put("some text PANIC some text")
udp_replay_approx_vnf.setup_helper.setup_vnf_environment = mock.Mock()
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_vfw_vnf.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_vfw_vnf.py
index efbb7a856..5334ce18c 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_vfw_vnf.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_vfw_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -232,7 +232,7 @@ class TestFWApproxVnf(unittest.TestCase):
def test___init__(self, *args):
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- vfw_approx_vnf = FWApproxVnf(name, vnfd, 'task_id')
+ vfw_approx_vnf = FWApproxVnf(name, vnfd)
self.assertIsNone(vfw_approx_vnf._vnf_process)
STATS = """\
@@ -255,7 +255,7 @@ pipeline>
def test_collect_kpi(self, ssh, *args):
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- vfw_approx_vnf = FWApproxVnf(name, vnfd, 'task_id')
+ vfw_approx_vnf = FWApproxVnf(name, vnfd)
vfw_approx_vnf.scenario_helper.scenario_cfg = {
'nodes': {vfw_approx_vnf.name: "mock"}
}
@@ -281,7 +281,7 @@ pipeline>
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- vfw_approx_vnf = FWApproxVnf(name, vnfd, 'task_id')
+ vfw_approx_vnf = FWApproxVnf(name, vnfd)
vfw_approx_vnf.q_in = mock.MagicMock()
vfw_approx_vnf.q_out = mock.MagicMock()
vfw_approx_vnf.q_out.qsize = mock.Mock(return_value=0)
@@ -293,7 +293,7 @@ pipeline>
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- vfw_approx_vnf = FWApproxVnf(name, vnfd, 'task_id')
+ vfw_approx_vnf = FWApproxVnf(name, vnfd)
vfw_approx_vnf.q_in = mock.MagicMock()
vfw_approx_vnf.q_out = mock.MagicMock()
vfw_approx_vnf.q_out.qsize = mock.Mock(return_value=0)
@@ -313,7 +313,7 @@ pipeline>
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- vfw_approx_vnf = FWApproxVnf(name, vnfd, 'task_id')
+ vfw_approx_vnf = FWApproxVnf(name, vnfd)
vfw_approx_vnf._build_config = mock.MagicMock()
vfw_approx_vnf.queue_wrapper = mock.MagicMock()
vfw_approx_vnf.ssh_helper = mock.MagicMock()
@@ -335,7 +335,7 @@ pipeline>
mock_ssh(ssh)
vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]
- vfw_approx_vnf = FWApproxVnf(name, vnfd, 'task_id')
+ vfw_approx_vnf = FWApproxVnf(name, vnfd)
vfw_approx_vnf.ssh_helper = ssh
vfw_approx_vnf.deploy_helper = mock.MagicMock()
vfw_approx_vnf.resource_helper = mock.MagicMock()
diff --git a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_vpe_vnf.py b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_vpe_vnf.py
index 8d49cb3f4..8342f5faa 100644
--- a/yardstick/tests/unit/network_services/vnf_generic/vnf/test_vpe_vnf.py
+++ b/yardstick/tests/unit/network_services/vnf_generic/vnf/test_vpe_vnf.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2016-2017 Intel Corporation
+# Copyright (c) 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -476,7 +476,7 @@ class TestVpeApproxVnf(unittest.TestCase):
self._mock_time_sleep.stop()
def test___init__(self):
- vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0, 'task_id')
+ vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0)
self.assertIsNone(vpe_approx_vnf._vnf_process)
@mock.patch.object(ctx_base.Context, 'get_physical_node_from_server',
@@ -490,7 +490,7 @@ class TestVpeApproxVnf(unittest.TestCase):
resource.amqp_collect_nfvi_kpi.return_value = {'foo': 234}
resource.check_if_system_agent_running.return_value = (1, None)
- vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0, 'task_id')
+ vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0)
vpe_approx_vnf.scenario_helper.scenario_cfg = {
'nodes': {vpe_approx_vnf.name: "mock"}
}
@@ -519,7 +519,7 @@ class TestVpeApproxVnf(unittest.TestCase):
resource.check_if_system_agent_running.return_value = 0, '1234'
resource.amqp_collect_nfvi_kpi.return_value = {'foo': 234}
- vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0, 'task_id')
+ vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0)
vpe_approx_vnf.scenario_helper.scenario_cfg = {
'nodes': {vpe_approx_vnf.name: "mock"}
}
@@ -541,7 +541,7 @@ class TestVpeApproxVnf(unittest.TestCase):
@mock.patch.object(sample_vnf, 'VnfSshHelper')
def test_vnf_execute(self, ssh):
test_base.mock_ssh(ssh)
- vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0, 'task_id')
+ vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0)
vpe_approx_vnf.q_in = mock.MagicMock()
vpe_approx_vnf.q_out = mock.MagicMock()
vpe_approx_vnf.q_out.qsize = mock.Mock(return_value=0)
@@ -551,7 +551,7 @@ class TestVpeApproxVnf(unittest.TestCase):
def test_run_vpe(self, ssh):
test_base.mock_ssh(ssh)
- vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0, 'task_id')
+ vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0)
vpe_approx_vnf.tc_file_name = get_file_abspath(TEST_FILE_YAML)
vpe_approx_vnf.vnf_cfg = {
'lb_config': 'SW',
@@ -634,7 +634,7 @@ class TestVpeApproxVnf(unittest.TestCase):
mock_resource = mock.MagicMock()
- vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0, 'task_id')
+ vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0)
vpe_approx_vnf._vnf_process = mock_process
vpe_approx_vnf.q_out = mock_q_out
vpe_approx_vnf.queue_wrapper = mock.Mock(
@@ -659,7 +659,7 @@ class TestVpeApproxVnf(unittest.TestCase):
mock_resource = mock.MagicMock()
- vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0, 'task_id')
+ vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0)
vpe_approx_vnf._vnf_process = mock_process
vpe_approx_vnf.q_out = mock_q_out
vpe_approx_vnf.queue_wrapper = mock.Mock(
@@ -678,7 +678,7 @@ class TestVpeApproxVnf(unittest.TestCase):
mock_resource = mock.MagicMock()
- vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0, 'task_id')
+ vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0)
vpe_approx_vnf._vnf_process = mock_process
vpe_approx_vnf.resource_helper.resource = mock_resource
@@ -697,7 +697,7 @@ class TestVpeApproxVnf(unittest.TestCase):
mock_resource = mock.MagicMock()
- vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0, 'task_id')
+ vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0)
vpe_approx_vnf._vnf_process = mock_process
vpe_approx_vnf.resource_helper.resource = mock_resource
@@ -722,7 +722,7 @@ class TestVpeApproxVnf(unittest.TestCase):
mock_resource = mock.MagicMock()
- vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0, 'task_id')
+ vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0)
vpe_approx_vnf._vnf_process = mock_process
vpe_approx_vnf.q_out = mock_q_out
vpe_approx_vnf.resource_helper.resource = mock_resource
@@ -736,7 +736,7 @@ class TestVpeApproxVnf(unittest.TestCase):
def test_terminate(self, ssh):
test_base.mock_ssh(ssh)
- vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0, 'task_id')
+ vpe_approx_vnf = vpe_vnf.VpeApproxVnf(NAME, self.VNFD_0)
vpe_approx_vnf._vnf_process = mock.MagicMock()
vpe_approx_vnf._resource_collect_stop = mock.Mock()
vpe_approx_vnf.resource_helper = mock.MagicMock()
diff --git a/yardstick/tests/unit/test_ssh.py b/yardstick/tests/unit/test_ssh.py
index 71929f1a2..374fb6644 100644
--- a/yardstick/tests/unit/test_ssh.py
+++ b/yardstick/tests/unit/test_ssh.py
@@ -286,6 +286,48 @@ class SSHTestCase(unittest.TestCase):
mock_paramiko_exec_command.assert_called_once_with('cmd',
get_pty=True)
+ @mock.patch("yardstick.ssh.paramiko")
+ def test_interactive_terminal_open(self, mock_paramiko):
+ fake_client = mock.Mock()
+ fake_session = mock.Mock()
+ fake_session.recv.return_value = ":~# "
+ fake_transport = mock.Mock()
+ fake_transport.open_session.return_value = fake_session
+ fake_client.get_transport.return_value = fake_transport
+ mock_paramiko.SSHClient.return_value = fake_client
+
+ test_ssh = ssh.SSH("admin", "example.net", pkey="key")
+ result = test_ssh.interactive_terminal_open()
+ self.assertEqual(fake_session, result)
+
+ @mock.patch("yardstick.ssh.paramiko")
+ def test_interactive_terminal_exec_command(self, mock_paramiko):
+ fake_client = mock.Mock()
+ fake_session = mock.Mock()
+ fake_session.recv.return_value = "stdout fake data"
+ fake_transport = mock.Mock()
+ fake_transport.open_session.return_value = fake_session
+ fake_client.get_transport.return_value = fake_transport
+ mock_paramiko.SSHClient.return_value = fake_client
+
+ test_ssh = ssh.SSH("admin", "example.net", pkey="key")
+ with mock.patch.object(fake_session, "sendall") \
+ as mock_paramiko_send_command:
+ result = test_ssh.interactive_terminal_exec_command(fake_session,
+ 'cmd', "vat# ")
+ self.assertEqual("stdout fake data", result)
+ mock_paramiko_send_command.assert_called_once_with('cmd\n')
+
+ @mock.patch("yardstick.ssh.paramiko")
+ def test_interactive_terminal_close(self, _):
+ fake_session = mock.Mock()
+ paramiko_sshclient = self.test_client._get_client()
+ paramiko_sshclient.get_transport.open_session.return_value = fake_session
+ with mock.patch.object(fake_session, "close") \
+ as mock_paramiko_terminal_close:
+ self.test_client.interactive_terminal_close(fake_session)
+ mock_paramiko_terminal_close.assert_called_once_with()
+
class SSHRunTestCase(unittest.TestCase):
"""Test SSH.run method in different aspects.