From: Benjamin Diaz Date: Wed, 17 Oct 2018 17:44:36 +0000 (-0300) Subject: Adds use of CustomCollector in Prometheus exporter X-Git-Tag: v5.0.0~20 X-Git-Url: https://osm.etsi.org/gitweb/?a=commitdiff_plain;h=refs%2Fchanges%2F19%2F6719%2F11;p=osm%2FMON.git Adds use of CustomCollector in Prometheus exporter Using a CustomCollector gives more control over the collection process, which allows handling the removal of metrics when a NS is deleted. Metrics now have a lifespan of a collection cycle, so metrics of deleted vdus are now not visible in the exporter. It also adds MonCollector class, which allows to abstract collection logic and facilitates testing. Signed-off-by: Benjamin Diaz Change-Id: Idfdb86c1ee9facd07187e6582954ae4cab32a5b4 --- diff --git a/docker/scripts/runInstall.sh b/docker/scripts/runInstall.sh index ccfc2f3..29ab3c6 100755 --- a/docker/scripts/runInstall.sh +++ b/docker/scripts/runInstall.sh @@ -23,5 +23,5 @@ /bin/bash /mon/osm_mon/plugins/vRealiseOps/vROPs_Webservice/install.sh python3 /mon/osm_mon/plugins/OpenStack/Aodh/notifier.py & python3 /mon/osm_mon/core/message_bus/common_consumer.py & -osm-mon-exporter +osm-mon-prometheus-exporter diff --git a/osm_mon/cmd/exporter.py b/osm_mon/cmd/exporter.py deleted file mode 100644 index a3545a3..0000000 --- a/osm_mon/cmd/exporter.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2018 Whitestack, LLC -# ************************************************************* - -# This file is part of OSM Monitoring module -# All Rights Reserved to Whitestack, LLC - -# 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. - -# For those usages not covered by the Apache License, Version 2.0 please -# contact: bdiaz@whitestack.com or glavado@whitestack.com -## -import logging -import sys - -from osm_mon.core.settings import Config -from osm_mon.exporter.exporter import MonExporter - - -def main(): - cfg = Config.instance() - log_formatter_str = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' - logging.basicConfig(stream=sys.stdout, - format=log_formatter_str, - datefmt='%m/%d/%Y %I:%M:%S %p', - level=logging.getLevelName(cfg.OSMMON_LOG_LEVEL)) - kafka_logger = logging.getLogger('kafka') - kafka_logger.setLevel(logging.getLevelName(cfg.OSMMON_KAFKA_LOG_LEVEL)) - kafka_formatter = logging.Formatter(log_formatter_str) - kafka_handler = logging.StreamHandler(sys.stdout) - kafka_handler.setFormatter(kafka_formatter) - kafka_logger.addHandler(kafka_handler) - log = logging.getLogger(__name__) - log.info("Starting MON Exporter...") - log.info("Config: %s", vars(cfg)) - exporter = MonExporter() - exporter.run() - - -if __name__ == '__main__': - main() diff --git a/osm_mon/cmd/mon_prometheus_exporter.py b/osm_mon/cmd/mon_prometheus_exporter.py new file mode 100644 index 0000000..f018b5d --- /dev/null +++ b/osm_mon/cmd/mon_prometheus_exporter.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- + +# Copyright 2018 Whitestack, LLC +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to Whitestack, LLC + +# 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. + +# For those usages not covered by the Apache License, Version 2.0 please +# contact: bdiaz@whitestack.com or glavado@whitestack.com +## +import logging +import sys + +from osm_mon.core.settings import Config +from osm_mon.collector.prometheus_exporter import MonPrometheusExporter + + +def main(): + cfg = Config.instance() + log_formatter_str = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' + logging.basicConfig(stream=sys.stdout, + format=log_formatter_str, + datefmt='%m/%d/%Y %I:%M:%S %p', + level=logging.getLevelName(cfg.OSMMON_LOG_LEVEL)) + kafka_logger = logging.getLogger('kafka') + kafka_logger.setLevel(logging.getLevelName(cfg.OSMMON_KAFKA_LOG_LEVEL)) + kafka_formatter = logging.Formatter(log_formatter_str) + kafka_handler = logging.StreamHandler(sys.stdout) + kafka_handler.setFormatter(kafka_formatter) + kafka_logger.addHandler(kafka_handler) + log = logging.getLogger(__name__) + log.info("Starting MON Prometheus Exporter...") + log.info("Config: %s", vars(cfg)) + exporter = MonPrometheusExporter() + exporter.run() + + +if __name__ == '__main__': + main() diff --git a/osm_mon/collector/__init__.py b/osm_mon/collector/__init__.py new file mode 100644 index 0000000..8fc00af --- /dev/null +++ b/osm_mon/collector/__init__.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- + +# Copyright 2018 Whitestack, LLC +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to Whitestack, LLC + +# 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. + +# For those usages not covered by the Apache License, Version 2.0 please +# contact: bdiaz@whitestack.com or glavado@whitestack.com +## \ No newline at end of file diff --git a/osm_mon/collector/collector.py b/osm_mon/collector/collector.py new file mode 100644 index 0000000..9bf3953 --- /dev/null +++ b/osm_mon/collector/collector.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- + +# Copyright 2018 Whitestack, LLC +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to Whitestack, LLC + +# 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. +# For those usages not covered by the Apache License, Version 2.0 please +# contact: bdiaz@whitestack.com or glavado@whitestack.com +## +import json +import logging +import random +import uuid +from collections import Iterable + +from kafka import KafkaProducer, KafkaConsumer +from osm_common import dbmongo +from prometheus_client.core import GaugeMetricFamily + +from osm_mon.core.settings import Config + +log = logging.getLogger(__name__) + + +class MonCollector: + def __init__(self): + cfg = Config.instance() + self.kafka_server = cfg.BROKER_URI + self.common_db_host = cfg.MONGO_URI.split(':')[0] + self.common_db_port = cfg.MONGO_URI.split(':')[1] + self.common_db = dbmongo.DbMongo() + self.common_db.db_connect({'host': self.common_db_host, 'port': int(self.common_db_port), 'name': 'osm'}) + self.producer = KafkaProducer(bootstrap_servers=self.kafka_server, + key_serializer=str.encode, + value_serializer=str.encode) + self.consumer = KafkaConsumer(bootstrap_servers=self.kafka_server, + key_deserializer=bytes.decode, + value_deserializer=bytes.decode, + consumer_timeout_ms=10000, + group_id='mon-collector-' + str(uuid.uuid4())) + self.consumer.subscribe(['metric_response']) + + def collect_metrics(self) -> Iterable: + # TODO(diazb): Remove dependencies on prometheus_client + log.debug("collect_metrics") + metrics = {} + vnfrs = self.common_db.get_list('vnfrs') + for vnfr in vnfrs: + nsr_id = vnfr['nsr-id-ref'] + vnfd = self.common_db.get_one('vnfds', {"_id": vnfr['vnfd-id']}) + payloads = self._generate_metric_data_payloads(vnfr, vnfd) + for payload in payloads: + cor_id = payload['correlation_id'] + metric_name = payload['metric_name'] + vnf_member_index = payload['vnf_member_index'] + vdu_name = payload['vdu_name'] + self.producer.send(topic='metric_request', key='read_metric_data_request', + value=json.dumps(payload)) + self.producer.flush() + for message in self.consumer: + if message.key == 'read_metric_data_response': + content = json.loads(message.value) + if content['correlation_id'] == cor_id: + if len(content['metrics_data']['metrics_series']): + metric_reading = content['metrics_data']['metrics_series'][-1] + if metric_name not in metrics.keys(): + metrics[metric_name] = GaugeMetricFamily( + metric_name, + 'OSM metric', + labels=['ns_id', 'vnf_member_index', 'vdu_name'] + ) + metrics[metric_name].add_metric([nsr_id, vnf_member_index, vdu_name], + metric_reading) + break + return metrics.values() + + @staticmethod + def _generate_metric_data_payloads(vnfr: dict, vnfd: dict) -> list: + log.debug('_generate_metric_data_payloads') + payloads = [] + nsr_id = vnfr['nsr-id-ref'] + for vdur in vnfr['vdur']: + # This avoids errors when vdur records have not been completely filled + if 'name' not in vdur: + continue + vdu = next( + filter(lambda vdu: vdu['id'] == vdur['vdu-id-ref'], vnfd['vdu']) + ) + if 'monitoring-param' in vdu: + for param in vdu['monitoring-param']: + metric_name = param['nfvi-metric'] + vnf_member_index = vnfr['member-vnf-index-ref'] + vdu_name = vdur['name'] + cor_id = random.randint(1, 10e7) + payload = { + 'correlation_id': cor_id, + 'metric_name': metric_name, + 'ns_id': nsr_id, + 'vnf_member_index': vnf_member_index, + 'vdu_name': vdu_name, + 'collection_period': 1, + 'collection_unit': 'DAY', + } + payloads.append(payload) + return payloads diff --git a/osm_mon/collector/prometheus_exporter.py b/osm_mon/collector/prometheus_exporter.py new file mode 100644 index 0000000..d61a286 --- /dev/null +++ b/osm_mon/collector/prometheus_exporter.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- + +# Copyright 2018 Whitestack, LLC +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to Whitestack, LLC + +# 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. +# For those usages not covered by the Apache License, Version 2.0 please +# contact: bdiaz@whitestack.com or glavado@whitestack.com +## +import logging +import threading +import time +from http.server import HTTPServer + +from prometheus_client import MetricsHandler +from prometheus_client.core import REGISTRY + +from osm_mon.collector.collector import MonCollector +from osm_mon.core.settings import Config + +log = logging.getLogger(__name__) + + +class MonPrometheusExporter: + + def __init__(self): + self.mon_collector = MonCollector() + self.custom_collector = CustomCollector() + + def _run_exporter(self): + log.debug('_run_exporter') + REGISTRY.register(self.custom_collector) + server_address = ('', 8000) + httpd = HTTPServer(server_address, MetricsHandler) + log.info("Starting MON Prometheus exporter at port %s", 8000) + httpd.serve_forever() + + def run(self): + log.debug('_run') + self._run_exporter() + self._run_collector() + + def _run_collector(self): + log.debug('_run_collector') + t = threading.Thread(target=self._collect_metrics_forever) + t.setDaemon(True) + t.start() + + def _collect_metrics_forever(self): + log.debug('_collect_metrics_forever') + cfg = Config.instance() + while True: + time.sleep(cfg.OSMMON_COLLECTOR_INTERVAL) + metrics = self.mon_collector.collect_metrics() + self.custom_collector.metrics = metrics + + +class CustomCollector(object): + + def __init__(self): + self.mon_collector = MonCollector() + self.metrics = [] + + def describe(self): + log.debug('describe') + return [] + + def collect(self): + log.debug("collect") + metrics = self.mon_collector.collect_metrics() + return metrics + + +if __name__ == '__main__': + MonPrometheusExporter().run() diff --git a/osm_mon/core/message_bus/common_consumer.py b/osm_mon/core/message_bus/common_consumer.py index 0b61e1e..b2677d8 100755 --- a/osm_mon/core/message_bus/common_consumer.py +++ b/osm_mon/core/message_bus/common_consumer.py @@ -91,6 +91,8 @@ class CommonConsumer: topics = ['metric_request', 'alarm_request', 'vim_account'] common_consumer.subscribe(topics) + common_consumer.poll() + common_consumer.seek_to_end() log.info("Listening for messages...") for message in common_consumer: diff --git a/osm_mon/core/settings.py b/osm_mon/core/settings.py index 6574f59..9700af5 100644 --- a/osm_mon/core/settings.py +++ b/osm_mon/core/settings.py @@ -66,7 +66,8 @@ class Config(object): CfgParam('OS_DEFAULT_GRANULARITY', "300", six.text_type), CfgParam('REQUEST_TIMEOUT', 10, int), CfgParam('OSMMON_LOG_LEVEL', "INFO", six.text_type), - CfgParam('OSMMON_KAFKA_LOG_LEVEL', "INFO", six.text_type), + CfgParam('OSMMON_KAFKA_LOG_LEVEL', "WARN", six.text_type), + CfgParam('OSMMON_COLLECTOR_INTERVAL', 10, int), ] _config_dict = {cfg.key: cfg for cfg in _configuration} diff --git a/osm_mon/exporter/__init__.py b/osm_mon/exporter/__init__.py deleted file mode 100644 index 8fc00af..0000000 --- a/osm_mon/exporter/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2018 Whitestack, LLC -# ************************************************************* - -# This file is part of OSM Monitoring module -# All Rights Reserved to Whitestack, LLC - -# 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. - -# For those usages not covered by the Apache License, Version 2.0 please -# contact: bdiaz@whitestack.com or glavado@whitestack.com -## \ No newline at end of file diff --git a/osm_mon/exporter/exporter.py b/osm_mon/exporter/exporter.py deleted file mode 100644 index b7893e0..0000000 --- a/osm_mon/exporter/exporter.py +++ /dev/null @@ -1,125 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2018 Whitestack, LLC -# ************************************************************* - -# This file is part of OSM Monitoring module -# All Rights Reserved to Whitestack, LLC - -# 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. -# For those usages not covered by the Apache License, Version 2.0 please -# contact: bdiaz@whitestack.com or glavado@whitestack.com -## -import json -import logging -import random -import threading -import time -import uuid - -from kafka import KafkaProducer, KafkaConsumer -from osm_common import dbmongo -from prometheus_client import start_http_server, Gauge - -from osm_mon.core.settings import Config - -log = logging.getLogger(__name__) - - -class MonExporter: - - def __init__(self): - cfg = Config.instance() - self.kafka_server = cfg.BROKER_URI - self.common_db_host = cfg.MONGO_URI.split(':')[0] - self.common_db_port = cfg.MONGO_URI.split(':')[1] - self.collector_interval = 5 - self.metrics = {} - - def _run_exporter(self): - start_http_server(8000) - - def _run_collector(self): - producer = KafkaProducer(bootstrap_servers=self.kafka_server, - key_serializer=str.encode, - value_serializer=str.encode) - consumer = KafkaConsumer(bootstrap_servers=self.kafka_server, - key_deserializer=bytes.decode, - value_deserializer=bytes.decode, - consumer_timeout_ms=10000, - group_id='mon-collector-' + str(uuid.uuid4())) - consumer.subscribe(['metric_response']) - common_db = dbmongo.DbMongo() - common_db.db_connect({'host': self.common_db_host, 'port': int(self.common_db_port), 'name': 'osm'}) - - while True: - try: - time.sleep(self.collector_interval) - vnfrs = common_db.get_list('vnfrs') - for vnfr in vnfrs: - vnfd = common_db.get_one('vnfds', {"_id": vnfr['vnfd-id']}) - for vdur in vnfr['vdur']: - vdu = next( - filter(lambda vdu: vdu['id'] == vdur['vdu-id-ref'], vnfd['vdu']) - ) - if 'monitoring-param' in vdu: - for param in vdu['monitoring-param']: - metric_name = param['nfvi-metric'] - nsr_id = vnfr['nsr-id-ref'] - vnf_member_index = vnfr['member-vnf-index-ref'] - vdu_name = vdur['name'] - cor_id = random.randint(1, 10e7) - payload = { - 'correlation_id': cor_id, - 'metric_name': metric_name, - 'ns_id': nsr_id, - 'vnf_member_index': vnf_member_index, - 'vdu_name': vdu_name, - 'collection_period': 1, - 'collection_unit': 'DAY', - } - producer.send(topic='metric_request', key='read_metric_data_request', - value=json.dumps(payload)) - producer.flush() - for message in consumer: - if message.key == 'read_metric_data_response': - content = json.loads(message.value) - if content['correlation_id'] == cor_id and len( - content['metrics_data']['metrics_series']): - metric_reading = content['metrics_data']['metrics_series'][-1] - if metric_name not in self.metrics.keys(): - self.metrics[metric_name] = Gauge(metric_name, - 'Metric generated by MON collector', - ['ns_id', - 'vnf_member_index', - 'vdu_name']) - self.metrics[metric_name].labels( - ns_id=nsr_id, - vnf_member_index=vnf_member_index, - vdu_name=vdu_name - ).set(metric_reading) - break - - - except Exception: - log.exception("Error collecting metrics: ") - - def run(self): - t1 = threading.Thread(target=self._run_exporter) - t1.start() - t2 = threading.Thread(target=self._run_collector) - t2.start() - - -if __name__ == '__main__': - MonExporter().run() diff --git a/osm_mon/plugins/OpenStack/Aodh/notifier.py b/osm_mon/plugins/OpenStack/Aodh/notifier.py index b63e581..71c6c1c 100644 --- a/osm_mon/plugins/OpenStack/Aodh/notifier.py +++ b/osm_mon/plugins/OpenStack/Aodh/notifier.py @@ -131,7 +131,6 @@ def run(server_class=HTTPServer, handler_class=NotifierHandler, port=8662): try: server_address = ('', port) httpd = server_class(server_address, handler_class) - print('Starting alarm notifier...') log.info("Starting alarm notifier server on port: %s", port) httpd.serve_forever() except Exception as exc: diff --git a/osm_mon/test/CloudWatch/test_schemas/alarm_details/acknowledge_alarm.json b/osm_mon/test/CloudWatch/test_schemas/alarm_details/acknowledge_alarm.json deleted file mode 100644 index 341b2bd..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/alarm_details/acknowledge_alarm.json +++ /dev/null @@ -1,11 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "alarm_ack", -"vim_type": "AWS", -"ack_details": -{ -"alarm_uuid": "CPU_Utilization_i-098da78cbd8304e17", -"resource_uuid": "i-098da78cbd8304e17", -"tenant_uuid": "" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/create_alarm/create_alarm_differentName_differentInstance.json b/osm_mon/test/CloudWatch/test_schemas/create_alarm/create_alarm_differentName_differentInstance.json deleted file mode 100644 index ecf403e..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/create_alarm/create_alarm_differentName_differentInstance.json +++ /dev/null @@ -1,18 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "create_alarm_request", -"vim_type": "AWS", -"alarm_create_request": -{ -"correlation_id": "SO123", -"alarm_name": "CPU_Utilization_Above_Threshold", -"resource_uuid": "i-098da78cbd8304e17", -"description": "", -"severity": "Critical", -"operation": "GE", -"threshold_value": 1.5, -"unit": "", -"metric_name": "CPU_UTILIZATION", -"statistic": "MAXIMUM" -} -} diff --git a/osm_mon/test/CloudWatch/test_schemas/create_alarm/create_alarm_differentName_sameInstance.json b/osm_mon/test/CloudWatch/test_schemas/create_alarm/create_alarm_differentName_sameInstance.json deleted file mode 100644 index 17c423d..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/create_alarm/create_alarm_differentName_sameInstance.json +++ /dev/null @@ -1,18 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "create_alarm_request", -"vim_type": "AWS", -"alarm_create_request": -{ -"correlation_id": "SO123", -"alarm_name": "CPU_Utilization_Above_Threshold1", -"resource_uuid": "i-098da78cbd8304e17", -"description": "", -"severity": "Critical", -"operation": "GE", -"threshold_value": 1.5, -"unit": "", -"metric_name": "CPU_UTILIZATION", -"statistic": "MAXIMUM" -} -} diff --git a/osm_mon/test/CloudWatch/test_schemas/create_alarm/create_alarm_sameName_differentInstance.json b/osm_mon/test/CloudWatch/test_schemas/create_alarm/create_alarm_sameName_differentInstance.json deleted file mode 100644 index b2f5acb..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/create_alarm/create_alarm_sameName_differentInstance.json +++ /dev/null @@ -1,18 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "create_alarm_request", -"vim_type": "AWS", -"alarm_create_request": -{ -"correlation_id": "SO123", -"alarm_name": "CPU_Utilization_Above_Threshold", -"resource_uuid": "i-09462760703837b26", -"description": "", -"severity": "Critical", -"operation": "GE", -"threshold_value": 1.5, -"unit": "", -"metric_name": "CPU_UTILIZATION", -"statistic": "MAXIMUM" -} -} diff --git a/osm_mon/test/CloudWatch/test_schemas/create_alarm/create_alarm_sameName_sameInstance.json b/osm_mon/test/CloudWatch/test_schemas/create_alarm/create_alarm_sameName_sameInstance.json deleted file mode 100644 index ecf403e..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/create_alarm/create_alarm_sameName_sameInstance.json +++ /dev/null @@ -1,18 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "create_alarm_request", -"vim_type": "AWS", -"alarm_create_request": -{ -"correlation_id": "SO123", -"alarm_name": "CPU_Utilization_Above_Threshold", -"resource_uuid": "i-098da78cbd8304e17", -"description": "", -"severity": "Critical", -"operation": "GE", -"threshold_value": 1.5, -"unit": "", -"metric_name": "CPU_UTILIZATION", -"statistic": "MAXIMUM" -} -} diff --git a/osm_mon/test/CloudWatch/test_schemas/create_alarm/operation_invalid.json b/osm_mon/test/CloudWatch/test_schemas/create_alarm/operation_invalid.json deleted file mode 100644 index 31e1e0b..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/create_alarm/operation_invalid.json +++ /dev/null @@ -1,18 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "create_alarm_request", -"vim_type": "AWS", -"alarm_create_request": -{ -"correlation_id": "SO123", -"alarm_name": "CPU_Utilization_Above_Threshold2", -"resource_uuid": "i-098da78cbd8304e17", -"description": "", -"severity": "Critical", -"operation": "Greaterthan", -"threshold_value": 1.5, -"unit": "", -"metric_name": "CPU_UTILIZATION", -"statistic": "MAXIMUM" -} -} diff --git a/osm_mon/test/CloudWatch/test_schemas/create_alarm/operation_valid.json b/osm_mon/test/CloudWatch/test_schemas/create_alarm/operation_valid.json deleted file mode 100644 index adb789b..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/create_alarm/operation_valid.json +++ /dev/null @@ -1,18 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "create_alarm_request", -"vim_type": "AWS", -"alarm_create_request": -{ -"correlation_id": "SO123", -"alarm_name": "CPU_Utilization_Above_Threshold2", -"resource_uuid": "i-098da78cbd8304e17", -"description": "", -"severity": "Critical", -"operation": "GE", -"threshold_value": 1.5, -"unit": "", -"metric_name": "CPU_UTILIZATION", -"statistic": "MAXIMUM" -} -} diff --git a/osm_mon/test/CloudWatch/test_schemas/create_alarm/statistic_invalid.json b/osm_mon/test/CloudWatch/test_schemas/create_alarm/statistic_invalid.json deleted file mode 100644 index 8c2e68d..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/create_alarm/statistic_invalid.json +++ /dev/null @@ -1,18 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "create_alarm_request", -"vim_type": "AWS", -"alarm_create_request": -{ -"correlation_id": "SO123", -"alarm_name": "CPU_Utilization_Above_Threshold2", -"resource_uuid": "i-098da78cbd8304e17", -"description": "", -"severity": "Critical", -"operation": "GE", -"threshold_value": 1.5, -"unit": "", -"metric_name": "CPU_UTILIZATION", -"statistic": "MAX" -} -} diff --git a/osm_mon/test/CloudWatch/test_schemas/create_alarm/statistic_valid.json b/osm_mon/test/CloudWatch/test_schemas/create_alarm/statistic_valid.json deleted file mode 100644 index adb789b..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/create_alarm/statistic_valid.json +++ /dev/null @@ -1,18 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "create_alarm_request", -"vim_type": "AWS", -"alarm_create_request": -{ -"correlation_id": "SO123", -"alarm_name": "CPU_Utilization_Above_Threshold2", -"resource_uuid": "i-098da78cbd8304e17", -"description": "", -"severity": "Critical", -"operation": "GE", -"threshold_value": 1.5, -"unit": "", -"metric_name": "CPU_UTILIZATION", -"statistic": "MAXIMUM" -} -} diff --git a/osm_mon/test/CloudWatch/test_schemas/create_metrics/create_metric_req_invalid.json b/osm_mon/test/CloudWatch/test_schemas/create_metrics/create_metric_req_invalid.json deleted file mode 100644 index 0fe0dcb..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/create_metrics/create_metric_req_invalid.json +++ /dev/null @@ -1,13 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "create_metrics_request", -"tenant_uuid": "", -"correlation_id": "SO123", -"vim_type": "AWS", -"metric_create": -{ -"metric_name": "CPU_UTILIZ", -"metric_unit": "", -"resource_uuid": "i-098da78cbd8304e17" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/create_metrics/create_metric_req_valid.json b/osm_mon/test/CloudWatch/test_schemas/create_metrics/create_metric_req_valid.json deleted file mode 100644 index 18cc23c..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/create_metrics/create_metric_req_valid.json +++ /dev/null @@ -1,13 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "create_metrics_request", -"tenant_uuid": "", -"correlation_id": "SO123", -"vim_type": "AWS", -"metric_create": -{ -"metric_name": "CPU_UTILIZATION", -"metric_unit": "", -"resource_uuid": "i-098da78cbd8304e17" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_invalid.json b/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_invalid.json deleted file mode 100644 index e51a670..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_invalid.json +++ /dev/null @@ -1,10 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "delete_alarm_request", -"vim_type": "AWS", -"alarm_delete_request": -{ -"alarm_uuid": "CPU_Utilization_Above_Threshold_i-098da78cbd8304e16", -"correlation_id": "SO123" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_valid.json b/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_valid.json deleted file mode 100644 index a2cd4b5..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_valid.json +++ /dev/null @@ -1,10 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "delete_alarm_request", -"vim_type": "AWS", -"alarm_delete_request": -{ -"alarm_uuid": "CPU_Utilization_Above_Threshold_i-098da78cbd8304e17", -"correlation_id": "SO123" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_valid_delete1.json b/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_valid_delete1.json deleted file mode 100644 index f465df7..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_valid_delete1.json +++ /dev/null @@ -1,10 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "delete_alarm_request", -"vim_type": "AWS", -"alarm_delete_request": -{ -"alarm_uuid": "CPU_Utilization_Above_Threshold1_i-098da78cbd8304e17", -"correlation_id": "SO123" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_valid_delete2.json b/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_valid_delete2.json deleted file mode 100644 index 1fa6870..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_valid_delete2.json +++ /dev/null @@ -1,10 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "delete_alarm_request", -"vim_type": "AWS", -"alarm_delete_request": -{ -"alarm_uuid": "CPU_Utilization_Above_Threshold_i-09462760703837b26", -"correlation_id": "SO123" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_valid_delete3.json b/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_valid_delete3.json deleted file mode 100644 index 6c35ab2..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_valid_delete3.json +++ /dev/null @@ -1,10 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "delete_alarm_request", -"vim_type": "AWS", -"alarm_delete_request": -{ -"alarm_uuid": "CPU_Utilization_Above_Threshold2_i-098da78cbd8304e17", -"correlation_id": "SO123" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_valid_delete4.json b/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_valid_delete4.json deleted file mode 100644 index 716b039..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/delete_alarm/name_valid_delete4.json +++ /dev/null @@ -1,10 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "delete_alarm_request", -"vim_type": "AWS", -"alarm_delete_request": -{ -"alarm_uuid": "CPU_Utilization_Above_Threshold4_i-098da78cbd8304e17", -"correlation_id": "SO123" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/delete_metrics/delete_metric_req_invalid.json b/osm_mon/test/CloudWatch/test_schemas/delete_metrics/delete_metric_req_invalid.json deleted file mode 100644 index f30ab87..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/delete_metrics/delete_metric_req_invalid.json +++ /dev/null @@ -1,10 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "delete_metric_data_request", -"metric_name": "CPU_UTILIATION", -"metric_uuid": "", -"resource_uuid": "i-098da78cbd8304e17", -"tenant_uuid": "", -"correlation_uuid": "S0123", -"vim_type": "AWS" -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/delete_metrics/delete_metric_req_valid.json b/osm_mon/test/CloudWatch/test_schemas/delete_metrics/delete_metric_req_valid.json deleted file mode 100644 index ea3922b..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/delete_metrics/delete_metric_req_valid.json +++ /dev/null @@ -1,10 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "delete_metric_data_request", -"metric_name": "CPU_UTILIZATION", -"metric_uuid": "", -"resource_uuid": "i-098da78cbd8304e17", -"tenant_uuid": "", -"correlation_uuid": "S0123", -"vim_type": "AWS" -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/list_alarm/list_alarm_valid_no_arguments.json b/osm_mon/test/CloudWatch/test_schemas/list_alarm/list_alarm_valid_no_arguments.json deleted file mode 100644 index a4d02a3..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/list_alarm/list_alarm_valid_no_arguments.json +++ /dev/null @@ -1,12 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "list_alarm_request", -"vim_type": "AWS", -"alarm_list_request": -{ -"correlation_id": "SO123", -"resource_uuid": "", -"alarm_name": "", -"severity": "" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/list_alarm/list_alarm_valid_one_argument.json b/osm_mon/test/CloudWatch/test_schemas/list_alarm/list_alarm_valid_one_argument.json deleted file mode 100644 index d0f31f2..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/list_alarm/list_alarm_valid_one_argument.json +++ /dev/null @@ -1,12 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "list_alarm_request", -"vim_type": "AWS", -"alarm_list_request": -{ -"correlation_id": "SO123", -"resource_uuid": "i-098da78cbd8304e17", -"alarm_name": "", -"severity": "" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/list_alarm/list_alarm_valid_two_arguments.json b/osm_mon/test/CloudWatch/test_schemas/list_alarm/list_alarm_valid_two_arguments.json deleted file mode 100644 index bf46579..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/list_alarm/list_alarm_valid_two_arguments.json +++ /dev/null @@ -1,12 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "list_alarm_request", -"vim_type": "AWS", -"alarm_list_request": -{ -"correlation_id": "SO123", -"resource_uuid": "i-098da78cbd8304e17", -"alarm_name": "", -"severity": "Critical" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/list_metrics/list_metric_req_invalid.json b/osm_mon/test/CloudWatch/test_schemas/list_metrics/list_metric_req_invalid.json deleted file mode 100644 index 6108e77..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/list_metrics/list_metric_req_invalid.json +++ /dev/null @@ -1,11 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "list_metrics_request", -"vim_type": "AWS", -"metrics_list_request": -{ -"metric_name": "CPU_UTILZATION", -"correlation_id": "SO123", -"resource_uuid": "i-098da78cbd8304e17" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/list_metrics/list_metric_req_valid.json b/osm_mon/test/CloudWatch/test_schemas/list_metrics/list_metric_req_valid.json deleted file mode 100644 index b1bd9de..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/list_metrics/list_metric_req_valid.json +++ /dev/null @@ -1,11 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "list_metrics_request", -"vim_type": "AWS", -"metrics_list_request": -{ -"metric_name": "CPU_UTILIZATION", -"correlation_id": "SO123", -"resource_uuid": "i-098da78cbd8304e17" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/read_metrics_data/read_coll_period_req_invalid.json b/osm_mon/test/CloudWatch/test_schemas/read_metrics_data/read_coll_period_req_invalid.json deleted file mode 100644 index 815edf9..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/read_metrics_data/read_coll_period_req_invalid.json +++ /dev/null @@ -1,12 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "read_metric_data_request", -"metric_name": "CPU_UTILIZATION", -"metric_uuid": "0", -"resource_uuid": "i-098da78cbd8304e17", -"tenant_uuid": "", -"correlation_uuid": "SO123", -"vim_type":"AWS", -"collection_period":"3500" , -"collection_unit": "" -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/read_metrics_data/read_coll_period_req_valid.json b/osm_mon/test/CloudWatch/test_schemas/read_metrics_data/read_coll_period_req_valid.json deleted file mode 100644 index dad9a24..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/read_metrics_data/read_coll_period_req_valid.json +++ /dev/null @@ -1,12 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "read_metric_data_request", -"metric_name": "CPU_UTILIZATION", -"metric_uuid": "0", -"resource_uuid": "i-098da78cbd8304e17", -"tenant_uuid": "", -"correlation_uuid": "SO123", -"vim_type":"AWS", -"collection_period":"3600" , -"collection_unit": "" -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/read_metrics_data/read_metric_name_req_invalid.json b/osm_mon/test/CloudWatch/test_schemas/read_metrics_data/read_metric_name_req_invalid.json deleted file mode 100644 index 0ff4f0e..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/read_metrics_data/read_metric_name_req_invalid.json +++ /dev/null @@ -1,12 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "read_metric_data_request", -"metric_name": "CPU_UTLIZATION", -"metric_uuid": "0", -"resource_uuid": "i-098da78cbd8304e17", -"tenant_uuid": "", -"correlation_uuid": "SO123", -"vim_type":"AWS", -"collection_period":"3600" , -"collection_unit": "" -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/read_metrics_data/read_metric_name_req_valid.json b/osm_mon/test/CloudWatch/test_schemas/read_metrics_data/read_metric_name_req_valid.json deleted file mode 100644 index dad9a24..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/read_metrics_data/read_metric_name_req_valid.json +++ /dev/null @@ -1,12 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "read_metric_data_request", -"metric_name": "CPU_UTILIZATION", -"metric_uuid": "0", -"resource_uuid": "i-098da78cbd8304e17", -"tenant_uuid": "", -"correlation_uuid": "SO123", -"vim_type":"AWS", -"collection_period":"3600" , -"collection_unit": "" -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/update_alarm/name_invalid.json b/osm_mon/test/CloudWatch/test_schemas/update_alarm/name_invalid.json deleted file mode 100644 index fe171e4..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/update_alarm/name_invalid.json +++ /dev/null @@ -1,17 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "update_alarm_request", -"vim_type": "AWS", -"alarm_update_request": -{ -"correlation_id": "SO123", -"alarm_uuid": "CPU_Utilization_Above_Threshold_i-098da78cbd8304e13", -"description": "", -"severity": "Critical", -"operation": "LE", -"threshold_value": 1.5, -"unit": "", -"metric_name": "CPU_UTILIZATION", -"statistic": "MAXIMUM" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/update_alarm/name_valid.json b/osm_mon/test/CloudWatch/test_schemas/update_alarm/name_valid.json deleted file mode 100644 index 7070dff..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/update_alarm/name_valid.json +++ /dev/null @@ -1,17 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "update_alarm_request", -"vim_type": "AWS", -"alarm_update_request": -{ -"correlation_id": "SO123", -"alarm_uuid": "CPU_Utilization_Above_Threshold4_i-098da78cbd8304e17", -"description": "", -"severity": "Critical", -"operation": "LE", -"threshold_value": 1.5, -"unit": "", -"metric_name": "CPU_UTILIZATION", -"statistic": "MAXIMUM" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/update_alarm/operation_invalid.json b/osm_mon/test/CloudWatch/test_schemas/update_alarm/operation_invalid.json deleted file mode 100644 index 0116228..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/update_alarm/operation_invalid.json +++ /dev/null @@ -1,17 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "update_alarm_request", -"vim_type": "AWS", -"alarm_update_request": -{ -"correlation_id": "SO123", -"alarm_uuid": "CPU_Utilization_Above_Threshold_i-098da78cbd8304e17", -"description": "", -"severity": "Critical", -"operation": "Less", -"threshold_value": 1.5, -"unit": "", -"metric_name": "CPU_UTILIZATION", -"statistic": "MAXIMUM" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/update_alarm/operation_valid.json b/osm_mon/test/CloudWatch/test_schemas/update_alarm/operation_valid.json deleted file mode 100644 index 5fb8eb6..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/update_alarm/operation_valid.json +++ /dev/null @@ -1,17 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "update_alarm_request", -"vim_type": "AWS", -"alarm_update_request": -{ -"correlation_id": "SO123", -"alarm_uuid": "CPU_Utilization_Above_Threshold_i-098da78cbd8304e17", -"description": "", -"severity": "Critical", -"operation": "LE", -"threshold_value": 1.5, -"unit": "", -"metric_name": "CPU_UTILIZATION", -"statistic": "MAXIMUM" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/update_alarm/statistic_invalid.json b/osm_mon/test/CloudWatch/test_schemas/update_alarm/statistic_invalid.json deleted file mode 100644 index 991d844..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/update_alarm/statistic_invalid.json +++ /dev/null @@ -1,17 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "update_alarm_request", -"vim_type": "AWS", -"alarm_update_request": -{ -"correlation_id": "SO123", -"alarm_uuid": "CPU_Utilization_Above_Threshold_i-098da78cbd8304e17", -"description": "", -"severity": "Critical", -"operation": "LE", -"threshold_value": 1.5, -"unit": "", -"metric_name": "CPU_UTILIZATION", -"statistic": "MAX" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/update_alarm/statistic_valid.json b/osm_mon/test/CloudWatch/test_schemas/update_alarm/statistic_valid.json deleted file mode 100644 index 5fb8eb6..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/update_alarm/statistic_valid.json +++ /dev/null @@ -1,17 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "update_alarm_request", -"vim_type": "AWS", -"alarm_update_request": -{ -"correlation_id": "SO123", -"alarm_uuid": "CPU_Utilization_Above_Threshold_i-098da78cbd8304e17", -"description": "", -"severity": "Critical", -"operation": "LE", -"threshold_value": 1.5, -"unit": "", -"metric_name": "CPU_UTILIZATION", -"statistic": "MAXIMUM" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/update_alarm/update_alarm_new_alarm.json b/osm_mon/test/CloudWatch/test_schemas/update_alarm/update_alarm_new_alarm.json deleted file mode 100644 index 581fb55..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/update_alarm/update_alarm_new_alarm.json +++ /dev/null @@ -1,18 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "create_alarm_request", -"vim_type": "AWS", -"alarm_create_request": -{ -"correlation_id": "SO123", -"alarm_name": "CPU_Utilization_Above_Threshold4", -"resource_uuid": "i-098da78cbd8304e17", -"description": "", -"severity": "Critical", -"operation": "GE", -"threshold_value": 1.5, -"unit": "", -"metric_name": "CPU_UTILIZATION", -"statistic": "MAXIMUM" -} -} diff --git a/osm_mon/test/CloudWatch/test_schemas/update_metrics/update_metric_req_invalid.json b/osm_mon/test/CloudWatch/test_schemas/update_metrics/update_metric_req_invalid.json deleted file mode 100644 index 0fe0dcb..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/update_metrics/update_metric_req_invalid.json +++ /dev/null @@ -1,13 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "create_metrics_request", -"tenant_uuid": "", -"correlation_id": "SO123", -"vim_type": "AWS", -"metric_create": -{ -"metric_name": "CPU_UTILIZ", -"metric_unit": "", -"resource_uuid": "i-098da78cbd8304e17" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/test_schemas/update_metrics/update_metric_req_valid.json b/osm_mon/test/CloudWatch/test_schemas/update_metrics/update_metric_req_valid.json deleted file mode 100644 index 18cc23c..0000000 --- a/osm_mon/test/CloudWatch/test_schemas/update_metrics/update_metric_req_valid.json +++ /dev/null @@ -1,13 +0,0 @@ -{ -"schema_version": "1.0", -"schema_type": "create_metrics_request", -"tenant_uuid": "", -"correlation_id": "SO123", -"vim_type": "AWS", -"metric_create": -{ -"metric_name": "CPU_UTILIZATION", -"metric_unit": "", -"resource_uuid": "i-098da78cbd8304e17" -} -} \ No newline at end of file diff --git a/osm_mon/test/CloudWatch/unit_tests_alarms.py b/osm_mon/test/CloudWatch/unit_tests_alarms.py deleted file mode 100644 index ae036cf..0000000 --- a/osm_mon/test/CloudWatch/unit_tests_alarms.py +++ /dev/null @@ -1,408 +0,0 @@ -from connection import Connection -import unittest -import sys -import jsmin -import json -import os -import time -from jsmin import jsmin -sys.path.append("../../test/core/") -from test_producer import KafkaProducer -from kafka import KafkaConsumer -try: - import boto - import boto.ec2 - import boto.vpc - import boto.ec2.cloudwatch - import boto.ec2.connection -except: - exit("Boto not avialable. Try activating your virtualenv OR `pip install boto`") - -#-------------------------------------------------------------------------------------------------------------------------------------- - -# Test Producer object to generate request - -producer = KafkaProducer('create_alarm_request') -obj = Connection() -connections = obj.setEnvironment() -connections_res = obj.connection_instance() -cloudwatch_conn = connections_res['cloudwatch_connection'] - -#-------------------------------------------------------------------------------------------------------------------------------------- - -'''Test E2E Flow : Test cases has been tested one at a time. -1) Commom Request is generated using request function in test_producer.py(/test/core) -2) The request is then consumed by the comsumer (plugin) -3) The response is sent back on the message bus in plugin_alarm.py using - response functions in producer.py(/core/message-bus) -4) The response is then again consumed by the unit_tests_alarms.py - and the test cases has been applied on the response. -''' - -class config_alarm_name_test(unittest.TestCase): - - - def setUp(self): - pass - #To generate a request of testing new alarm name and new instance id in create alarm request - def test_differentName_differentInstance(self): - time.sleep(2) - producer.request("test_schemas/create_alarm/create_alarm_differentName_differentInstance.json",'create_alarm_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "create_alarm_response": - info = json.loads(json.loads(message.value)) - print(info) - time.sleep(1) - self.assertTrue(info['alarm_create_response']['status']) - return - - #To generate a request of testing new alarm name and existing instance id in create alarm request - def test_differentName_sameInstance(self): - time.sleep(2) - producer.request("test_schemas/create_alarm/create_alarm_differentName_sameInstance.json",'create_alarm_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "create_alarm_response": - info = json.loads(json.loads(message.value)) - print(info) - time.sleep(1) - producer.request("test_schemas/delete_alarm/name_valid_delete1.json",'delete_alarm_request','','alarm_request') - self.assertTrue(info['alarm_create_response']['status']) - return - - #To generate a request of testing existing alarm name and new instance id in create alarm request - def test_sameName_differentInstance(self): - time.sleep(2) - producer.request("test_schemas/create_alarm/create_alarm_sameName_differentInstance.json",'create_alarm_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "create_alarm_response": - info = json.loads(json.loads(message.value)) - print(info) - time.sleep(1) - producer.request("test_schemas/delete_alarm/name_valid_delete2.json",'delete_alarm_request', '','alarm_request') - self.assertTrue(info['alarm_create_response']['status']) - return - - #To generate a request of testing existing alarm name and existing instance id in create alarm request - def test_sameName_sameInstance(self): - time.sleep(2) - producer.request("test_schemas/create_alarm/create_alarm_sameName_sameInstance.json",'create_alarm_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "create_alarm_response": - info = json.loads(json.loads(message.value)) - print(info, "---") - time.sleep(1) - producer.request("test_schemas/delete_alarm/name_valid.json",'delete_alarm_request', '','alarm_request') - self.assertEqual(info, None) - return - - #To generate a request of testing valid statistics in create alarm request - def test_statisticValid(self): - time.sleep(2) - producer.request("test_schemas/create_alarm/statistic_valid.json",'create_alarm_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "create_alarm_response": - info = json.loads(json.loads(message.value)) - print(info) - time.sleep(1) - producer.request("test_schemas/delete_alarm/name_valid_delete3.json",'delete_alarm_request', '','alarm_request') - self.assertTrue(info['alarm_create_response']['status']) - return - - #To generate a request of testing Invalid statistics in create alarm request - def test_statisticValidNot(self): - time.sleep(2) - producer.request("test_schemas/create_alarm/statistic_invalid.json",'create_alarm_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "create_alarm_response": - info = json.loads(json.loads(message.value)) - print(info, "---") - time.sleep(1) - producer.request("test_schemas/delete_alarm/name_valid_delete3.json",'delete_alarm_request', '','alarm_request') - self.assertEqual(info, None) - return - - #To generate a request of testing valid operation in create alarm request - def test_operationValid(self): - time.sleep(2) - producer.request("test_schemas/create_alarm/operation_valid.json",'create_alarm_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "create_alarm_response": - info = json.loads(json.loads(message.value)) - print(info) - time.sleep(1) - producer.request("test_schemas/delete_alarm/name_valid_delete3.json",'delete_alarm_request', '','alarm_request') - self.assertTrue(info['alarm_create_response']['status']) - return - - #To generate a request of testing Invalid operation in create alarm request - def test_operationValidNot(self): - time.sleep(2) - producer.request("test_schemas/create_alarm/operation_invalid.json",'create_alarm_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "create_alarm_response": - info = json.loads(json.loads(message.value)) - print(info) - time.sleep(1) - self.assertEqual(info,None) - return - - -#-------------------------------------------------------------------------------------------------------------------------------------- -class update_alarm_name_test(unittest.TestCase): - - #To generate a request of testing valid alarm_id in update alarm request - def test_nameValid(self): - producer.request("test_schemas/update_alarm/update_alarm_new_alarm.json",'create_alarm_request', '','alarm_request') - time.sleep(2) - producer.request("test_schemas/update_alarm/name_valid.json",'update_alarm_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "update_alarm_response": - info = json.loads(json.loads(json.loads(message.value))) - print(info) - time.sleep(1) - producer.request("test_schemas/delete_alarm/name_valid_delete4.json",'delete_alarm_request', '','alarm_request') - self.assertTrue(info['alarm_update_response']['status']) - return - - #To generate a request of testing invalid alarm_id in update alarm request - def test_nameInvalid(self): - time.sleep(2) - producer.request("test_schemas/update_alarm/name_invalid.json",'update_alarm_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "update_alarm_response": - info = json.loads(json.loads(json.loads(message.value))) - print(info) - time.sleep(1) - self.assertEqual(info,None) - return - - #To generate a request of testing valid statistics in update alarm request - def test_statisticValid(self): - producer.request("test_schemas/create_alarm/create_alarm_differentName_differentInstance.json",'create_alarm_request', '','alarm_request') - time.sleep(2) - producer.request("test_schemas/update_alarm/statistic_valid.json",'update_alarm_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "update_alarm_response": - info = json.loads(json.loads(json.loads(message.value))) - print(info) - time.sleep(1) - producer.request("test_schemas/delete_alarm/name_valid.json",'delete_alarm_request', '','alarm_request') - self.assertTrue(info['alarm_update_response']['status']) - return - - #To generate a request of testing Invalid statistics in update alarm request - def test_statisticInvalid(self): - time.sleep(2) - producer.request("test_schemas/update_alarm/statistic_invalid.json",'update_alarm_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "update_alarm_response": - info = json.loads(json.loads(json.loads(message.value))) - print(info) - time.sleep(1) - self.assertEqual(info,None) - return - - #To generate a request of testing valid operation in update alarm request - def test_operationValid(self): - producer.request("test_schemas/create_alarm/create_alarm_differentName_differentInstance.json",'create_alarm_request', '','alarm_request') - time.sleep(2) - producer.request("test_schemas/update_alarm/operation_valid.json",'update_alarm_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "update_alarm_response": - info = json.loads(json.loads(json.loads(message.value))) - print(info) - time.sleep(1) - producer.request("test_schemas/delete_alarm/name_valid.json",'delete_alarm_request', '','alarm_request') - self.assertTrue(info['alarm_update_response']['status']) - return - -#-------------------------------------------------------------------------------------------------------------------------------------- -class delete_alarm_test(unittest.TestCase): - - #To generate a request of testing valid alarm_id in delete alarm request - def test_nameValid(self): - producer.request("test_schemas/create_alarm/create_alarm_differentName_differentInstance.json",'create_alarm_request', '','alarm_request') - time.sleep(2) - producer.request("test_schemas/delete_alarm/name_valid.json",'delete_alarm_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "delete_alarm_response": - info = json.loads(json.loads(json.loads(message.value))) - print(info) - time.sleep(1) - self.assertTrue(info['alarm_deletion_response']['status']) - return - - #To generate a request of testing Invalid alarm_id in delete alarm request - def test_nameInvalid(self): - time.sleep(2) - producer.request("test_schemas/delete_alarm/name_invalid.json",'delete_alarm_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "delete_alarm_response": - info = json.loads(json.loads(json.loads(message.value))) - print(info) - time.sleep(1) - self.assertEqual(info,None) - return - -#-------------------------------------------------------------------------------------------------------------------------------------- -class list_alarm_test(unittest.TestCase): - - #To generate a request of testing valid input fields in alarm list request - def test_valid_no_arguments(self): - time.sleep(2) - producer.request("test_schemas/list_alarm/list_alarm_valid_no_arguments.json",'alarm_list_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "list_alarm_response": - info = json.loads(json.loads(json.loads(message.value))) - print(info) - time.sleep(1) - self.assertEqual(type(info),dict) - return - - #To generate a request of testing valid input fields in alarm list request - def test_valid_one_arguments(self): - time.sleep(2) - producer.request("test_schemas/list_alarm/list_alarm_valid_one_arguments.json",'alarm_list_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "list_alarm_response": - info = json.loads(json.loads(json.loads(message.value))) - print(info) - time.sleep(1) - self.assertEqual(type(info),dict) - return - - #To generate a request of testing valid input fields in alarm list request - def test_valid_two_arguments(self): - time.sleep(2) - producer.request("test_schemas/list_alarm/list_alarm_valid_two_arguments.json",'alarm_list_request', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "list_alarm_response": - info = json.loads(json.loads(json.loads(message.value))) - print(info) - time.sleep(1) - self.assertEqual(type(info),dict) - return - - -#-------------------------------------------------------------------------------------------------------------------------------------- -class alarm_details_test(unittest.TestCase): - - #To generate a request of testing valid input fields in acknowledge alarm - def test_Valid(self): - time.sleep(2) - producer.request("test_schemas/alarm_details/acknowledge_alarm.json",'acknowledge_alarm', '','alarm_request') - server = {'server': 'localhost:9092', 'topic': 'alarm_request'} - - _consumer = KafkaConsumer(bootstrap_servers=server['server']) - _consumer.subscribe(['alarm_response']) - - for message in _consumer: - if message.key == "notify_alarm": - info = json.loads(json.loads(json.loads(message.value))) - print(info) - time.sleep(1) - self.assertEqual(type(info),dict) - return - -if __name__ == '__main__': - - # Saving test reults in Log file - - log_file = 'log_file.txt' - f = open(log_file, "w") - runner = unittest.TextTestRunner(f) - unittest.main(testRunner=runner) - f.close() - - # For printing results on Console - # unittest.main() diff --git a/osm_mon/test/CloudWatch/unit_tests_metrics.py b/osm_mon/test/CloudWatch/unit_tests_metrics.py deleted file mode 100644 index 625e872..0000000 --- a/osm_mon/test/CloudWatch/unit_tests_metrics.py +++ /dev/null @@ -1,208 +0,0 @@ -from connection import Connection -import unittest -import sys -import jsmin -import json -import os -import time -from jsmin import jsmin -sys.path.append("../../test/core/") -from test_producer import KafkaProducer -from kafka import KafkaConsumer -try: - import boto - import boto.ec2 - import boto.vpc - import boto.ec2.cloudwatch - import boto.ec2.connection -except: - exit("Boto not avialable. Try activating your virtualenv OR `pip install boto`") - -#-------------------------------------------------------------------------------------------------------------------------------------- - -# Test Producer object to generate request - -producer = KafkaProducer('') -obj = Connection() -connections = obj.setEnvironment() -connections_res = obj.connection_instance() -cloudwatch_conn = connections_res['cloudwatch_connection'] - -# Consumer Object to consume response from message bus -server = {'server': 'localhost:9092', 'topic': 'metric_request'} -_consumer = KafkaConsumer(bootstrap_servers=server['server']) -_consumer.subscribe(['metric_response']) - -#-------------------------------------------------------------------------------------------------------------------------------------- - -'''Test E2E Flow : Test cases has been tested one at a time. -1) Commom Request is generated using request function in test_producer.py(/core/message-bus) -2) The request is then consumed by the comsumer (plugin) -3) The response is sent back on the message bus in plugin_metrics.py using - response functions in producer.py(/core/message-bus) -4) The response is then again consumed by the unit_tests_metrics.py - and the test cases has been applied on the response. -''' -class test_create_metrics(unittest.TestCase): - - def test_status_positive(self): - time.sleep(2) - # To generate Request of testing valid meric_name in create metrics requests - producer.request("create_metrics/create_metric_req_valid.json",'create_metric_request', '','metric_request') - - for message in _consumer: - if message.key == "create_metric_response": - resp = json.loads(json.loads(json.loads(message.value))) - time.sleep(1) - self.assertTrue(resp['metric_create_response']['status']) - self.assertEqual(resp['metric_create_response']['metric_uuid'],0) - return - - def test_status_negative(self): - time.sleep(2) - # To generate Request of testing invalid meric_name in create metrics requests - producer.request("create_metrics/create_metric_req_invalid.json",'create_metric_request', '','metric_request') - - for message in _consumer: - if message.key == "create_metric_response": - resp = json.loads(json.loads(json.loads(message.value))) - time.sleep(1) - self.assertFalse(resp['metric_create_response']['status']) - self.assertEqual(resp['metric_create_response']['metric_uuid'],None) - return - -class test_metrics_data(unittest.TestCase): - - def test_met_name_positive(self): - time.sleep(2) - # To generate Request of testing valid meric_name in read_metric_data_request - producer.request("read_metrics_data/read_metric_name_req_valid.json",'read_metric_data_request', '','metric_request') - for message in _consumer: - if message.key == "read_metric_data_response": - resp = json.loads(json.loads(json.loads(message.value))) - time.sleep(1) - self.assertEqual(type(resp['metrics_data']),dict) - return - - def test_met_name_negative(self): - time.sleep(2) - # To generate Request of testing invalid meric_name in read_metric_data_request - producer.request("read_metrics_data/read_metric_name_req_invalid.json",'read_metric_data_request', '','metric_request') - for message in _consumer: - if message.key == "read_metric_data_response": - resp = json.loads(json.loads(json.loads(message.value))) - time.sleep(1) - self.assertFalse(resp['metrics_data']) - return - - def test_coll_period_positive(self): - # To generate Request of testing valid collection_period in read_metric_data_request - # For AWS metric_data_stats collection period should be a multiple of 60 - time.sleep(2) - producer.request("read_metrics_data/read_coll_period_req_valid.json",'read_metric_data_request', '','metric_request') - for message in _consumer: - if message.key == "read_metric_data_response": - resp = json.loads(json.loads(json.loads(message.value))) - time.sleep(1) - self.assertEqual(type(resp),dict) - return - - def test_coll_period_negative(self): - time.sleep(2) - # To generate Request of testing invalid collection_period in read_metric_data_request - producer.request("read_metrics_data/read_coll_period_req_invalid.json",'read_metric_data_request', '','metric_request') - for message in _consumer: - if message.key == "read_metric_data_response": - resp = json.loads(json.loads(json.loads(message.value))) - time.sleep(1) - self.assertFalse(resp['metrics_data']) - return - -class test_update_metrics(unittest.TestCase): - - def test_upd_status_positive(self): - time.sleep(2) - # To generate Request of testing valid meric_name in update metrics requests - producer.request("update_metrics/update_metric_req_valid.json",'update_metric_request', '','metric_request') - for message in _consumer: - if message.key == "update_metric_response": - resp = json.loads(json.loads(json.loads(message.value))) - time.sleep(1) - self.assertTrue(resp['metric_update_response']['status']) - self.assertEqual(resp['metric_update_response']['metric_uuid'],0) - return - - def test_upd_status_negative(self): - time.sleep(2) - # To generate Request of testing invalid meric_name in update metrics requests - producer.request("update_metrics/update_metric_req_invalid.json",'update_metric_request', '','metric_request') - for message in _consumer: - if message.key == "update_metric_response": - resp = json.loads(json.loads(json.loads(message.value))) - time.sleep(1) - self.assertFalse(resp['metric_update_response']['status']) - self.assertEqual(resp['metric_update_response']['metric_uuid'],None) - return - -class test_delete_metrics(unittest.TestCase): - - def test_del_met_name_positive(self): - time.sleep(2) - # To generate Request of testing valid meric_name in delete metrics requests - producer.request("delete_metrics/delete_metric_req_valid.json",'delete_metric_request', '','metric_request') - for message in _consumer: - if message.key == "delete_metric_response": - resp = json.loads(json.loads(json.loads(message.value))) - time.sleep(1) - self.assertFalse(resp['status']) - return - - def test_del_met_name_negative(self): - time.sleep(2) - # To generate Request of testing invalid meric_name in delete metrics requests - producer.request("delete_metrics/delete_metric_req_invalid.json",'delete_metric_request', '','metric_request') - for message in _consumer: - if message.key == "delete_metric_response": - resp = json.loads(json.loads(json.loads(message.value))) - time.sleep(1) - self.assertFalse(resp) - return - -class test_list_metrics(unittest.TestCase): - - def test_list_met_name_positive(self): - time.sleep(2) - # To generate Request of testing valid meric_name in list metrics requests - producer.request("list_metrics/list_metric_req_valid.json",'list_metric_request', '','metric_request') - for message in _consumer: - if message.key == "list_metrics_response": - resp = json.loads(json.loads(json.loads(message.value))) - time.sleep(1) - self.assertEqual(type(resp['metrics_list']),list) - return - - def test_list_met_name_negitive(self): - time.sleep(2) - # To generate Request of testing invalid meric_name in list metrics requests - producer.request("list_metrics/list_metric_req_invalid.json",'list_metric_request', '','metric_request') - for message in _consumer: - if message.key == "list_metrics_response": - resp = json.loads(json.loads(json.loads(message.value))) - time.sleep(1) - self.assertFalse(resp['metrics_list']) - return - - -if __name__ == '__main__': - - # Saving test reults in Log file - - log_file = 'log_file.txt' - f = open(log_file, "w") - runner = unittest.TextTestRunner(f) - unittest.main(testRunner=runner) - f.close() - - # For printing results on Console - # unittest.main() - diff --git a/osm_mon/test/OpenStack/__init__.py b/osm_mon/test/OpenStack/__init__.py deleted file mode 100644 index 32eb94e..0000000 --- a/osm_mon/test/OpenStack/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright 2017 Intel Research and Development Ireland Limited -# ************************************************************* - -# This file is part of OSM Monitoring module -# All Rights Reserved to 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. - -# For those usages not covered by the Apache License, Version 2.0 please -# contact: helena.mcgough@intel.com or adrian.hoban@intel.com -## diff --git a/osm_mon/test/OpenStack/integration/__init__.py b/osm_mon/test/OpenStack/integration/__init__.py deleted file mode 100644 index cd7731b..0000000 --- a/osm_mon/test/OpenStack/integration/__init__.py +++ /dev/null @@ -1,34 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2018 Whitestack, LLC -# ************************************************************* - -# This file is part of OSM Monitoring module -# All Rights Reserved to Whitestack, LLC - -# 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. - -# For those usages not covered by the Apache License, Version 2.0 please -# contact: bdiaz@whitestack.com or glavado@whitestack.com -## -import logging -import sys - -from osm_mon.core.settings import Config - -cfg = Config.instance() -logging.basicConfig(stream=sys.stdout, - format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', - datefmt='%m/%d/%Y %I:%M:%S %p', - level=logging.getLevelName(cfg.OSMMON_LOG_LEVEL)) -log = logging.getLogger(__name__) diff --git a/osm_mon/test/OpenStack/integration/test_alarm_integration.py b/osm_mon/test/OpenStack/integration/test_alarm_integration.py deleted file mode 100644 index fbec56c..0000000 --- a/osm_mon/test/OpenStack/integration/test_alarm_integration.py +++ /dev/null @@ -1,221 +0,0 @@ -# Copyright 2017 Intel Research and Development Ireland Limited -# ************************************************************* - -# This file is part of OSM Monitoring module -# All Rights Reserved to 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. - -# For those usages not covered by the Apache License, Version 2.0 please -# contact: helena.mcgough@intel.com or adrian.hoban@intel.com - -# __author__ = "Helena McGough" -"""Test an end to end Openstack alarm requests.""" - -import json -import logging -import unittest - -import mock -from kafka import KafkaConsumer -from kafka import KafkaProducer -from kafka.errors import KafkaError - -from osm_mon.core.auth import AuthManager -from osm_mon.core.database import DatabaseManager, VimCredentials -from osm_mon.plugins.OpenStack import response -from osm_mon.plugins.OpenStack.Aodh import alarm_handler -from osm_mon.plugins.OpenStack.common import Common - -log = logging.getLogger(__name__) - -mock_creds = VimCredentials() -mock_creds.config = '{}' - - -@mock.patch.object(DatabaseManager, "save_alarm", mock.Mock()) -@mock.patch.object(Common, "get_auth_token", mock.Mock()) -@mock.patch.object(Common, "get_endpoint", mock.Mock()) -class AlarmIntegrationTest(unittest.TestCase): - def setUp(self): - try: - self.producer = KafkaProducer(bootstrap_servers='localhost:9092', - key_serializer=str.encode, - value_serializer=str.encode - ) - self.req_consumer = KafkaConsumer(bootstrap_servers='localhost:9092', - key_deserializer=bytes.decode, - value_deserializer=bytes.decode, - auto_offset_reset='earliest', - consumer_timeout_ms=60000) - self.req_consumer.subscribe(['alarm_request']) - except KafkaError: - self.skipTest('Kafka server not present.') - # Set up common and alarming class instances - self.alarms = alarm_handler.OpenstackAlarmHandler() - self.openstack_auth = Common() - - def tearDown(self): - self.producer.close() - self.req_consumer.close() - - @mock.patch.object(Common, "perform_request") - @mock.patch.object(AuthManager, 'get_credentials') - @mock.patch.object(alarm_handler.OpenstackAlarmHandler, "update_alarm") - @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") - def test_update_alarm_req(self, resp, update_alarm, get_creds, perf_req): - """Test Aodh update alarm request message from KafkaProducer.""" - # Set-up message, producer and consumer for tests - payload = {"alarm_update_request": {"correlation_id": 123, - "alarm_uuid": "alarm_id", - "metric_uuid": "metric_id"}} - - get_creds.return_value = mock_creds - perf_req.return_value = type('obj', (object,), {'text': json.dumps({"metrics": {"cpu_util": "1"}})}) - resp.return_value = '' - - self.producer.send('alarm_request', key="update_alarm_request", - value=json.dumps(payload)) - - for message in self.req_consumer: - if message.key == "update_alarm_request": - # Mock a valid alarm update - update_alarm.return_value = "alarm_id" - self.alarms.handle_message(message, 'test_id') - - # A response message is generated and sent via MON's producer - resp.assert_called_with( - 'update_alarm_response', alarm_id="alarm_id", cor_id=123, - status=True) - - return - self.fail("No message received in consumer") - - @mock.patch.object(Common, "perform_request") - @mock.patch.object(AuthManager, 'get_credentials') - @mock.patch.object(alarm_handler.OpenstackAlarmHandler, "configure_alarm") - @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") - def test_create_alarm_req(self, resp, config_alarm, get_creds, perf_req): - """Test Aodh create alarm request message from KafkaProducer.""" - # Set-up message, producer and consumer for tests - payload = {"alarm_create_request": {"correlation_id": 123, - "alarm_name": "my_alarm", - "metric_name": "cpu_utilization", - "resource_uuid": "my_resource", - "severity": "WARNING", - "threshold_value": 60, - "operation": "GT", - "vdu_name": "vdu", - "vnf_member_index": "1", - "ns_id": "1"}} - - get_creds.return_value = mock_creds - perf_req.return_value = type('obj', (object,), {'text': json.dumps({"metrics": {"cpu_util": "1"}})}) - resp.return_value = '' - self.producer.send('alarm_request', key="create_alarm_request", - value=json.dumps(payload)) - - for message in self.req_consumer: - if message.key == "create_alarm_request": - # Mock a valid alarm creation - config_alarm.return_value = "alarm_id" - self.alarms.handle_message(message, 'test_id') - - # A response message is generated and sent via MON's produce - resp.assert_called_with( - 'create_alarm_response', status=True, alarm_id="alarm_id", - cor_id=123) - - return - self.fail("No message received in consumer") - - @mock.patch.object(Common, "perform_request") - @mock.patch.object(AuthManager, 'get_credentials') - @mock.patch.object(alarm_handler.OpenstackAlarmHandler, "list_alarms") - @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") - def test_list_alarm_req(self, resp, list_alarm, get_creds, perf_req): - """Test Aodh list alarm request message from KafkaProducer.""" - # Set-up message, producer and consumer for tests - payload = {"alarm_list_request": {"correlation_id": 123, - "resource_uuid": "resource_id", }} - - self.producer.send('alarm_request', key="list_alarm_request", - value=json.dumps(payload)) - - get_creds.return_value = mock_creds - perf_req.return_value = type('obj', (object,), {'text': json.dumps([])}) - resp.return_value = '' - - for message in self.req_consumer: - if message.key == "list_alarm_request": - # Mock an empty list generated by the request - list_alarm.return_value = [] - self.alarms.handle_message(message, 'test_id') - - # Response message is generated - resp.assert_called_with( - 'list_alarm_response', alarm_list=[], - cor_id=123) - - return - self.fail("No message received in consumer") - - @mock.patch.object(Common, "perform_request") - @mock.patch.object(AuthManager, 'get_credentials') - @mock.patch.object(alarm_handler.OpenstackAlarmHandler, "delete_alarm") - @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") - def test_delete_alarm_req(self, resp, del_alarm, get_creds, perf_req): - """Test Aodh delete alarm request message from KafkaProducer.""" - # Set-up message, producer and consumer for tests - payload = {"alarm_delete_request": {"correlation_id": 123, - "alarm_uuid": "alarm_id", }} - - self.producer.send('alarm_request', key="delete_alarm_request", - value=json.dumps(payload)) - - get_creds.return_value = mock_creds - perf_req.return_value = type('obj', (object,), {'text': json.dumps([])}) - resp.return_value = '' - - for message in self.req_consumer: - if message.key == "delete_alarm_request": - self.alarms.handle_message(message, 'test_id') - - # Response message is generated and sent by MON's producer - resp.assert_called_with( - 'delete_alarm_response', alarm_id="alarm_id", - status=True, cor_id=123) - - return - self.fail("No message received in consumer") - - @mock.patch.object(AuthManager, 'get_credentials') - @mock.patch.object(alarm_handler.OpenstackAlarmHandler, "update_alarm_state") - def test_ack_alarm_req(self, ack_alarm, get_creds): - """Test Aodh acknowledge alarm request message from KafkaProducer.""" - # Set-up message, producer and consumer for tests - payload = {"ack_details": {"alarm_uuid": "alarm_id", }} - - self.producer.send('alarm_request', key="acknowledge_alarm", - value=json.dumps(payload)) - - get_creds.return_value = mock_creds - ack_alarm.return_value = True - - for message in self.req_consumer: - if message.key == "acknowledge_alarm": - self.alarms.handle_message(message, 'test_id') - ack_alarm.assert_called_with(mock.ANY, mock.ANY, 'alarm_id', True) - return - - self.fail("No message received in consumer") diff --git a/osm_mon/test/OpenStack/integration/test_metric_integration.py b/osm_mon/test/OpenStack/integration/test_metric_integration.py deleted file mode 100644 index 578c8b1..0000000 --- a/osm_mon/test/OpenStack/integration/test_metric_integration.py +++ /dev/null @@ -1,242 +0,0 @@ -# Copyright 2017 Intel Research and Development Ireland Limited -# ************************************************************* - -# This file is part of OSM Monitoring module -# All Rights Reserved to 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. - -# For those usages not covered by the Apache License, Version 2.0 please -# contact: helena.mcgough@intel.com or adrian.hoban@intel.com - -# __author__ = "Helena McGough" -"""Test an end to end Openstack metric requests.""" - -import json - -import logging -import unittest - -from kafka.errors import KafkaError - -from osm_mon.core.auth import AuthManager -from osm_mon.core.database import VimCredentials - -from kafka import KafkaConsumer -from kafka import KafkaProducer - -import mock - -from osm_mon.plugins.OpenStack import response - -from osm_mon.plugins.OpenStack.Gnocchi import metric_handler - -from osm_mon.plugins.OpenStack.common import Common - -log = logging.getLogger(__name__) - -mock_creds = VimCredentials() -mock_creds.config = '{}' - - -@mock.patch.object(Common, "get_auth_token", mock.Mock()) -@mock.patch.object(Common, "get_endpoint", mock.Mock()) -class MetricIntegrationTest(unittest.TestCase): - def setUp(self): - # Set up common and alarming class instances - self.metric_req = metric_handler.OpenstackMetricHandler() - self.openstack_auth = Common() - - try: - self.producer = KafkaProducer(bootstrap_servers='localhost:9092', - key_serializer=str.encode, - value_serializer=str.encode - ) - self.req_consumer = KafkaConsumer(bootstrap_servers='localhost:9092', - key_deserializer=bytes.decode, - value_deserializer=bytes.decode, - auto_offset_reset='earliest', - consumer_timeout_ms=60000) - self.req_consumer.subscribe(['metric_request']) - except KafkaError: - self.skipTest('Kafka server not present.') - - @mock.patch.object(Common, "perform_request") - @mock.patch.object(AuthManager, 'get_credentials') - @mock.patch.object(metric_handler.OpenstackMetricHandler, "configure_metric") - @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") - def test_create_metric_req(self, resp, config_metric, get_creds, perf_req): - """Test Gnocchi create metric request message from producer.""" - # Set-up message, producer and consumer for tests - payload = {"metric_create_request": {"correlation_id": 123, - "metric_name": "cpu_utilization", - "resource_uuid": "resource_id"}} - - get_creds.return_value = mock_creds - perf_req.return_value = type('obj', (object,), {'text': json.dumps({"metrics": {"cpu_util": "1"}})}) - resp.return_value = '' - - self.producer.send('metric_request', key="create_metric_request", - value=json.dumps(payload)) - - for message in self.req_consumer: - if message.key == "create_metric_request": - # A valid metric is created - config_metric.return_value = "metric_id", "resource_id" - self.metric_req.handle_request(message, 'test_id') - - # A response message is generated and sent by MON's producer - resp.assert_called_with( - 'create_metric_response', status=True, cor_id=123, - metric_id="metric_id", resource_id="resource_id") - - return - self.fail("No message received in consumer") - - @mock.patch.object(Common, "perform_request") - @mock.patch.object(AuthManager, 'get_credentials') - @mock.patch.object(metric_handler.OpenstackMetricHandler, "delete_metric") - @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") - def test_delete_metric_req(self, resp, del_metric, get_creds, perf_req): - """Test Gnocchi delete metric request message from producer.""" - # Set-up message, producer and consumer for tests - payload = {"vim_type": "OpenSTACK", - "vim_uuid": "1", - "correlation_id": 123, - "metric_name": "cpu_utilization", - "resource_uuid": "resource_id"} - - get_creds.return_value = mock_creds - perf_req.return_value = type('obj', (object,), {'text': json.dumps({"metrics": {"cpu_util": "1"}})}) - resp.return_value = '' - - self.producer.send('metric_request', key="delete_metric_request", - value=json.dumps(payload)) - - for message in self.req_consumer: - if message.key == "delete_metric_request": - # Metric has been deleted - del_metric.return_value = True - self.metric_req.handle_request(message, 'test_id') - - # A response message is generated and sent by MON's producer - resp.assert_called_with( - 'delete_metric_response', metric_id='1', - metric_name="cpu_utilization", status=True, resource_id="resource_id", - cor_id=123) - - return - self.fail("No message received in consumer") - - @mock.patch.object(Common, "perform_request") - @mock.patch.object(AuthManager, 'get_credentials') - @mock.patch.object(metric_handler.OpenstackMetricHandler, "read_metric_data") - @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") - def test_read_metric_data_req(self, resp, read_data, get_creds, perf_req): - """Test Gnocchi read metric data request message from producer.""" - # Set-up message, producer and consumer for tests - payload = {"vim_type": "OpenSTACK", - "vim_uuid": "test_id", - "correlation_id": 123, - "metric_name": "cpu_utilization", - "resource_uuid": "resource_id"} - - get_creds.return_value = mock_creds - perf_req.return_value = type('obj', (object,), {'text': json.dumps({"metrics": {"cpu_util": "1"}})}) - resp.return_value = '' - - self.producer.send('metric_request', key="read_metric_data_request", - value=json.dumps(payload)) - - for message in self.req_consumer: - # Check the vim desired by the message - if message.key == "read_metric_data_request": - # Mock empty lists generated by the request message - read_data.return_value = [], [] - self.metric_req.handle_request(message, 'test_id') - - # A response message is generated and sent by MON's producer - resp.assert_called_with( - 'read_metric_data_response', metric_id='1', - metric_name="cpu_utilization", resource_id="resource_id", cor_id=123, times=[], - metrics=[], status=True) - - return - self.fail("No message received in consumer") - - @mock.patch.object(Common, "perform_request") - @mock.patch.object(AuthManager, 'get_credentials') - @mock.patch.object(metric_handler.OpenstackMetricHandler, "list_metrics") - @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") - def test_list_metrics_req(self, resp, list_metrics, get_creds, perf_req): - """Test Gnocchi list metrics request message from producer.""" - # Set-up message, producer and consumer for tests - payload = {"vim_type": "OpenSTACK", - "vim_uuid": "1", - "metrics_list_request": - {"correlation_id": 123, }} - - get_creds.return_value = mock_creds - perf_req.return_value = type('obj', (object,), {'text': json.dumps({"metrics": {"cpu_util": "1"}})}) - resp.return_value = '' - - self.producer.send('metric_request', key="list_metric_request", - value=json.dumps(payload)) - - for message in self.req_consumer: - # Check the vim desired by the message - if message.key == "list_metric_request": - # Mock an empty list generated by the request - list_metrics.return_value = [] - self.metric_req.handle_request(message, 'test_id') - - # A response message is generated and sent by MON's producer - resp.assert_called_with( - 'list_metric_response', metric_list=[], cor_id=123, status=True) - - return - self.fail("No message received in consumer") - - @mock.patch.object(Common, "perform_request") - @mock.patch.object(AuthManager, 'get_credentials') - @mock.patch.object(metric_handler.OpenstackMetricHandler, "get_metric_id") - @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") - def test_update_metrics_req(self, resp, get_id, get_creds, perf_req): - """Test Gnocchi update metric request message from KafkaProducer.""" - # Set-up message, producer and consumer for tests - payload = {"metric_update_request": {"metric_name": "my_metric", - "correlation_id": 123, - "resource_uuid": "resource_id", }} - - get_creds.return_value = mock_creds - perf_req.return_value = type('obj', (object,), {'text': json.dumps({"metrics": {"cpu_util": "1"}})}) - resp.return_value = '' - - self.producer.send('metric_request', key="update_metric_request", - value=json.dumps(payload)) - - for message in self.req_consumer: - # Check the vim desired by the message - if message.key == "update_metric_request": - # Gnocchi doesn't support metric updates - get_id.return_value = "metric_id" - self.metric_req.handle_request(message, 'test_id') - - # Response message is generated and sent via MON's producer - # No metric update has taken place - resp.assert_called_with( - 'update_metric_response', status=False, cor_id=123, - resource_id="resource_id", metric_id="metric_id") - - return - self.fail("No message received in consumer") diff --git a/osm_mon/test/OpenStack/integration/test_notify_alarm.py b/osm_mon/test/OpenStack/integration/test_notify_alarm.py deleted file mode 100644 index 8aa2c9f..0000000 --- a/osm_mon/test/OpenStack/integration/test_notify_alarm.py +++ /dev/null @@ -1,183 +0,0 @@ -# Copyright 2017 Intel Research and Development Ireland Limited -# ************************************************************* - -# This file is part of OSM Monitoring module -# All Rights Reserved to 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. - -# For those usages not covered by the Apache License, Version 2.0 please -# contact: helena.mcgough@intel.com or adrian.hoban@intel.com -## -"""Tests for all common OpenStack methods.""" - -from __future__ import unicode_literals -import json -import logging -import socket -import unittest -from threading import Thread - -import mock -import requests -from kafka import KafkaProducer -from six.moves.BaseHTTPServer import BaseHTTPRequestHandler -from six.moves.BaseHTTPServer import HTTPServer - -from osm_mon.core.settings import Config -from osm_mon.plugins.OpenStack.Aodh.alarm_handler import OpenstackAlarmHandler -from osm_mon.plugins.OpenStack.common import Common -from osm_mon.plugins.OpenStack.response import OpenStackResponseBuilder - -log = logging.getLogger(__name__) - -# Create an instance of the common openstack class, producer and consumer -openstack_auth = Common() - -# Mock a valid get_response for alarm details -valid_get_resp = '{"gnocchi_resources_threshold_rule":\ - {"resource_id": "my_resource_id"}}' - - -class MockResponse(object): - """Mock a response class for generating responses.""" - - def __init__(self, text): - """Initialise a mock response with a text attribute.""" - self.text = text - - -class MockNotifierHandler(BaseHTTPRequestHandler): - """Mock the NotifierHandler class for testing purposes.""" - - def _set_headers(self): - """Set the headers for a request.""" - self.send_response(200) - self.send_header('Content-type', 'text/html') - self.end_headers() - - def do_GET(self): - """Mock functionality for GET request.""" - # self.send_response(requests.codes.ok) - self._set_headers() - pass - - def do_POST(self): - """Mock functionality for a POST request.""" - self._set_headers() - content_length = int(self.headers['Content-Length']) - post_data = self.rfile.read(content_length) - try: - post_data = post_data.decode() - except AttributeError: - pass - self.notify_alarm(json.loads(post_data)) - - def notify_alarm(self, values): - """Mock the notify_alarm functionality to generate a valid response.""" - cfg = Config.instance() - self._alarming = OpenstackAlarmHandler() - self._common = Common() - self._response = OpenStackResponseBuilder() - alarm_id = values['alarm_id'] - - auth_token = Common.get_auth_token('test_id') - endpoint = Common.get_endpoint('alarming', 'test_id') - - # If authenticated generate and send response message - if auth_token is not None and endpoint is not None: - url = "{}/v2/alarms/%s".format(endpoint) % alarm_id - - # Get the resource_id of the triggered alarm and the date - result = Common.perform_request( - url, auth_token, req_type="get") - alarm_details = json.loads(result.text) - gnocchi_rule = alarm_details['gnocchi_resources_threshold_rule'] - resource_id = gnocchi_rule['resource_id'] - # Mock a date for testing purposes - a_date = "dd-mm-yyyy 00:00" - - # Process an alarm notification if resource_id is valid - if resource_id is not None: - # Try generate and send response - try: - resp_message = self._response.generate_response( - 'notify_alarm', - alarm_id=alarm_id, - resource_id=resource_id, - sev=values['severity'], date=a_date, - state=values['current'], vim_type="OpenStack") - except Exception: - log.exception("Error generating response") - - -def get_free_port(): - """Function to get a free port to run the test webserver on.""" - s = socket.socket(socket.AF_INET, type=socket.SOCK_STREAM) - s.bind(('localhost', 0)) - address, port = s.getsockname() - s.close() - return port - - -# Create the webserver, port and run it on its own thread -mock_server_port = get_free_port() -mock_server = HTTPServer(('localhost', mock_server_port), MockNotifierHandler) -mock_server_thread = Thread(target=mock_server.serve_forever) -mock_server_thread.setDaemon(True) -mock_server_thread.start() - - -def test_do_get(): - """Integration test for get request on notifier webserver.""" - url = 'http://localhost:{port}/users'.format(port=mock_server_port) - - # Send a request to the mock API server and store the response. - response = requests.get(url) - - # Confirm that the request-response cycle completed successfully. - assert response.ok - - -class AlarmNotificationTest(unittest.TestCase): - @mock.patch.object(OpenStackResponseBuilder, "generate_response") - @mock.patch.object(Common, "perform_request") - @mock.patch.object(Common, "get_endpoint") - @mock.patch.object(Common, "get_auth_token") - def test_post_notify_alarm(self, auth, endpoint, perf_req, resp): - """Integration test for notify_alarm.""" - url = 'http://localhost:{port}/users'.format(port=mock_server_port) - payload = {"severity": "critical", - "alarm_name": "my_alarm", - "current": "current_state", - "alarm_id": "my_alarm_id", - "reason": "Threshold has been broken", - "reason_data": {"count": 1, - "most_recent": "null", - "type": "threshold", - "disposition": "unknown"}, - "previous": "previous_state"} - - # Mock authenticate and request response for testing - auth.return_value = "my_auth_token" - endpoint.return_value = "my_endpoint" - perf_req.return_value = MockResponse(valid_get_resp) - - # Generate a post request for testing - response = requests.post(url, json.dumps(payload)) - self.assertEqual(response.status_code, 200) - # A response message is generated with the following details - resp.assert_called_with( - "notify_alarm", alarm_id="my_alarm_id", resource_id="my_resource_id", - sev="critical", date='dd-mm-yyyy 00:00', state="current_state", - vim_type="OpenStack") diff --git a/osm_mon/test/OpenStack/integration/test_vim_account.py b/osm_mon/test/OpenStack/integration/test_vim_account.py deleted file mode 100644 index da34bb2..0000000 --- a/osm_mon/test/OpenStack/integration/test_vim_account.py +++ /dev/null @@ -1,96 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2018 Whitestack, LLC -# ************************************************************* - -# This file is part of OSM Monitoring module -# All Rights Reserved to Whitestack, LLC - -# 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. - -# For those usages not covered by the Apache License, Version 2.0 please -# contact: bdiaz@whitestack.com or glavado@whitestack.com -## - -"""Test an end to end Openstack vim_account requests.""" - -import json -import logging -import unittest - -from osm_mon.core.auth import AuthManager -from osm_mon.core.database import DatabaseManager - -log = logging.getLogger(__name__) - - -class VimAccountTest(unittest.TestCase): - def setUp(self): - self.auth_manager = AuthManager() - self.database_manager = DatabaseManager() - self.database_manager.create_tables() - - def test_create_edit_delete_vim_account(self): - """Test vim_account creation message from KafkaProducer.""" - # Set-up message, producer and consumer for tests - create_payload = { - "_id": "test_id", - "name": "test_name", - "vim_type": "openstack", - "vim_url": "auth_url", - "vim_user": "user", - "vim_password": "password", - "vim_tenant_name": "tenant", - "config": - { - "foo": "bar" - } - } - self.auth_manager.store_auth_credentials(create_payload) - - creds = self.auth_manager.get_credentials('test_id') - - self.assertIsNotNone(creds) - self.assertEqual(creds.name, create_payload['name']) - self.assertEqual(json.loads(creds.config), create_payload['config']) - - # Set-up message, producer and consumer for tests - edit_payload = { - "_id": "test_id", - "name": "test_name_edited", - "vim_type": "openstack", - "vim_url": "auth_url", - "vim_user": "user", - "vim_password": "password", - "vim_tenant_name": "tenant", - "config": - { - "foo_edited": "bar_edited" - } - } - - self.auth_manager.store_auth_credentials(edit_payload) - - creds = self.auth_manager.get_credentials('test_id') - - self.assertEqual(creds.name, edit_payload['name']) - self.assertEqual(json.loads(creds.config), edit_payload['config']) - - delete_payload = { - "_id": "test_id" - } - - self.auth_manager.delete_auth_credentials(delete_payload) - - creds = self.auth_manager.get_credentials('test_id') - self.assertIsNone(creds) diff --git a/osm_mon/test/OpenStack/unit/__init__.py b/osm_mon/test/OpenStack/unit/__init__.py deleted file mode 100644 index cd7731b..0000000 --- a/osm_mon/test/OpenStack/unit/__init__.py +++ /dev/null @@ -1,34 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2018 Whitestack, LLC -# ************************************************************* - -# This file is part of OSM Monitoring module -# All Rights Reserved to Whitestack, LLC - -# 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. - -# For those usages not covered by the Apache License, Version 2.0 please -# contact: bdiaz@whitestack.com or glavado@whitestack.com -## -import logging -import sys - -from osm_mon.core.settings import Config - -cfg = Config.instance() -logging.basicConfig(stream=sys.stdout, - format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', - datefmt='%m/%d/%Y %I:%M:%S %p', - level=logging.getLevelName(cfg.OSMMON_LOG_LEVEL)) -log = logging.getLogger(__name__) diff --git a/osm_mon/test/OpenStack/unit/test_alarm_req.py b/osm_mon/test/OpenStack/unit/test_alarm_req.py deleted file mode 100644 index 02cec8b..0000000 --- a/osm_mon/test/OpenStack/unit/test_alarm_req.py +++ /dev/null @@ -1,150 +0,0 @@ -# Copyright 2017 iIntel Research and Development Ireland Limited -# ************************************************************** - -# This file is part of OSM Monitoring module -# All Rights Reserved to 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. - -# For those usages not covered by the Apache License, Version 2.0 please -# contact: helena.mcgough@intel.com or adrian.hoban@intel.com -## -"""Tests for all alarm request message keys.""" - -import json -import logging -import unittest -from io import UnsupportedOperation - -import mock - -from osm_mon.core.auth import AuthManager -from osm_mon.core.database import VimCredentials, DatabaseManager -from osm_mon.plugins.OpenStack.Aodh import alarm_handler as alarm_req -from osm_mon.plugins.OpenStack.Aodh.alarm_handler import OpenstackAlarmHandler -from osm_mon.plugins.OpenStack.common import Common - -log = logging.getLogger(__name__) - -mock_creds = VimCredentials() -mock_creds.config = '{}' - - -class Message(object): - """A class to mock a message object value for alarm requests.""" - - def __init__(self): - """Initialize a mocked message instance.""" - self.topic = 'alarm_request' - self.key = None - self.value = json.dumps({'mock_value': 'mock_details'}) - - -class TestAlarmKeys(unittest.TestCase): - """Integration test for alarm request keys.""" - - def setUp(self): - """Setup the tests for alarm request keys.""" - super(TestAlarmKeys, self).setUp() - self.alarming = alarm_req.OpenstackAlarmHandler() - self.alarming.common = Common() - - @mock.patch.object(AuthManager, 'get_credentials') - @mock.patch.object(Common, 'get_endpoint') - @mock.patch.object(Common, 'get_auth_token') - def test_alarming_authentication(self, get_token, get_endpoint, get_creds): - """Test getting an auth_token and endpoint for alarm requests.""" - # if auth_token is None environment variables are used to authenticate - get_creds.return_value = mock_creds - - with self.assertRaises(UnsupportedOperation): - self.alarming.handle_message('', {}, 'test_id') - - get_token.assert_called_with('test_id', verify_ssl=True) - get_endpoint.assert_any_call('alarming', 'test_id', verify_ssl=True) - - @mock.patch.object(Common, 'get_endpoint', mock.Mock()) - @mock.patch.object(Common, 'get_auth_token', mock.Mock()) - @mock.patch.object(AuthManager, 'get_credentials') - @mock.patch.object(alarm_req.OpenstackAlarmHandler, 'delete_alarm') - def test_delete_alarm_key(self, del_alarm, get_creds): - """Test the functionality for a create alarm request.""" - value = {'alarm_delete_request': { - 'correlation_id': 1, - 'alarm_uuid': 'my_alarm_id' - }} - - get_creds.return_value = mock_creds - del_alarm.return_value = {} - - # Call the alarming functionality and check delete request - self.alarming.handle_message('delete_alarm_request', value, 'test_id') - del_alarm.assert_called_with(mock.ANY, mock.ANY, 'my_alarm_id', True) - - @mock.patch.object(Common, 'get_endpoint', mock.Mock()) - @mock.patch.object(Common, 'get_auth_token', mock.Mock()) - @mock.patch.object(AuthManager, 'get_credentials') - @mock.patch.object(alarm_req.OpenstackAlarmHandler, 'list_alarms') - def test_list_alarm_key(self, list_alarm, get_creds): - """Test the functionality for a list alarm request.""" - value = {'alarm_list_request': {'correlation_id': 1}} - - get_creds.return_value = mock_creds - - list_alarm.return_value = [] - - # Call the alarming functionality and check list functionality - self.alarming.handle_message('list_alarm_request', value, 'test_id') - list_alarm.assert_called_with(mock.ANY, mock.ANY, {'correlation_id': 1}, True) - - @mock.patch.object(Common, 'get_auth_token', mock.Mock()) - @mock.patch.object(Common, 'get_endpoint', mock.Mock()) - @mock.patch.object(AuthManager, 'get_credentials') - @mock.patch.object(alarm_req.OpenstackAlarmHandler, 'update_alarm_state') - def test_ack_alarm_key(self, ack_alarm, get_creds): - """Test the functionality for an acknowledge alarm request.""" - value = {'ack_details': {'alarm_uuid': 'my_alarm_id'}} - - get_creds.return_value = mock_creds - - # Call alarming functionality and check acknowledge functionality - self.alarming.handle_message('acknowledge_alarm_request', value, 'test_id') - ack_alarm.assert_called_with(mock.ANY, mock.ANY, 'my_alarm_id', True) - - @mock.patch.object(Common, 'get_auth_token', mock.Mock()) - @mock.patch.object(Common, 'get_endpoint', mock.Mock()) - @mock.patch.object(DatabaseManager, 'save_alarm', mock.Mock()) - @mock.patch.object(Common, "perform_request") - @mock.patch.object(AuthManager, 'get_credentials') - @mock.patch.object(alarm_req.OpenstackAlarmHandler, 'configure_alarm') - def test_config_alarm_key(self, config_alarm, get_creds, perf_req): - """Test the functionality for a create alarm request.""" - value = {'alarm_create_request': {'correlation_id': 1, 'threshold_value': 50, - 'operation': 'GT', 'metric_name': 'cpu_utilization', - 'vdu_name': 'vdu', - 'vnf_member_index': '1', - 'ns_id': '1', - 'resource_uuid': '123'}} - mock_perf_req_return_value = {"metrics": {"cpu_util": 123}} - perf_req.return_value = type('obj', (object,), {'text': json.dumps(mock_perf_req_return_value, sort_keys=True)}) - get_creds.return_value = mock_creds - - # Call alarming functionality and check config alarm call - config_alarm.return_value = 'my_alarm_id' - self.alarming.handle_message('create_alarm_request', value, 'test_id') - config_alarm.assert_called_with(mock.ANY, mock.ANY, {'correlation_id': 1, 'threshold_value': 50, - 'operation': 'GT', - 'metric_name': 'cpu_utilization', - 'vdu_name': 'vdu', - 'vnf_member_index': '1', 'ns_id': '1', - 'resource_uuid': '123'}, {}, True) diff --git a/osm_mon/test/OpenStack/unit/test_alarming.py b/osm_mon/test/OpenStack/unit/test_alarming.py deleted file mode 100644 index 67486e7..0000000 --- a/osm_mon/test/OpenStack/unit/test_alarming.py +++ /dev/null @@ -1,299 +0,0 @@ -# Copyright 2017 iIntel Research and Development Ireland Limited -# ************************************************************** - -# This file is part of OSM Monitoring module -# All Rights Reserved to 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. - -# For those usages not covered by the Apache License, Version 2.0 please -# contact: helena.mcgough@intel.com or adrian.hoban@intel.com -## -"""Tests for all alarm request message keys.""" - -import json -import logging -import unittest - -import mock - -from osm_mon.core.settings import Config -from osm_mon.plugins.OpenStack.Aodh import alarm_handler as alarm_req -from osm_mon.plugins.OpenStack.common import Common - -log = logging.getLogger(__name__) - -auth_token = mock.ANY -alarm_endpoint = "alarm_endpoint" -metric_endpoint = "metric_endpoint" - - -class Response(object): - """Mock a response message class.""" - - def __init__(self, result): - """Initialise the response text and status code.""" - self.text = json.dumps(result) - self.status_code = "MOCK_STATUS_CODE" - - -class TestAlarming(unittest.TestCase): - """Tests for alarming class functions.""" - - maxDiff = None - - def setUp(self): - """Setup for tests.""" - super(TestAlarming, self).setUp() - self.alarming = alarm_req.OpenstackAlarmHandler() - - @mock.patch.object(Common, "perform_request") - def test_config_invalid_alarm_req(self, perf_req): - """Test configure an invalid alarm request.""" - # Configuring with invalid metric name results in failure - values = {"alarm_name": "my_alarm", - "metric_name": "my_metric", - "resource_uuid": "my_r_id"} - with self.assertRaises(KeyError): - self.alarming.configure_alarm(alarm_endpoint, auth_token, values, {}, True) - perf_req.assert_not_called() - perf_req.reset_mock() - - # Configuring with missing metric name results in failure - values = {"alarm_name": "disk_write_ops", - "resource_uuid": "my_r_id"} - - with self.assertRaises(KeyError): - self.alarming.configure_alarm(alarm_endpoint, auth_token, values, {}, True) - perf_req.assert_not_called() - - @mock.patch.object(Common, "perform_request") - def test_config_valid_alarm_req(self, perf_req): - """Test config a valid alarm.""" - values = {"alarm_name": "disk_write_ops", - "metric_name": "disk_write_ops", - "resource_uuid": "my_r_id", - "statistic": "AVERAGE", - "threshold_value": 60, - "operation": "GT"} - - perf_req.return_value = type('obj', (object,), {'text': '{"alarm_id":"1"}'}) - - self.alarming.configure_alarm(alarm_endpoint, auth_token, values, {}, True) - payload = {"name": "disk_write_ops", - "gnocchi_resources_threshold_rule": {"resource_type": "generic", "comparison_operator": "gt", - "granularity": "300", "metric": "disk.write.requests", - "aggregation_method": "mean", "threshold": 60, - "resource_id": "my_r_id"}, - "alarm_actions": ["http://localhost:8662"], "repeat_actions": True, "state": "ok", "type": "gnocchi_resources_threshold", - "severity": "critical"} - perf_req.assert_called_with( - "alarm_endpoint/v2/alarms/", auth_token, - req_type="post", payload=json.dumps(payload, sort_keys=True), verify_ssl=True) - - @mock.patch.object(Common, "perform_request") - def test_delete_alarm_req(self, perf_req): - """Test delete alarm request.""" - self.alarming.delete_alarm(alarm_endpoint, auth_token, "my_alarm_id", True) - - perf_req.assert_called_with( - "alarm_endpoint/v2/alarms/my_alarm_id", auth_token, req_type="delete", verify_ssl=True) - - @mock.patch.object(Common, "perform_request") - def test_invalid_list_alarm_req(self, perf_req): - """Test invalid list alarm_req.""" - # Request will not be performed without a resource_id - list_details = {"mock_details": "invalid_details"} - with self.assertRaises(KeyError): - self.alarming.list_alarms(alarm_endpoint, auth_token, list_details, True) - perf_req.assert_not_called() - - @mock.patch.object(Common, "perform_request") - def test_valid_list_alarm_req(self, perf_req): - """Test valid list alarm request.""" - # Minimum requirement for an alarm list is resource_id - list_details = {"resource_uuid": "mock_r_id", "alarm_name": "mock_alarm", "severity": "critical"} - - mock_perf_req_return_value = [ - {"alarm_id": "1", "name": "mock_alarm", "severity": "critical", - "gnocchi_resources_threshold_rule": {"resource_id": "mock_r_id"}}] - perf_req.return_value = type('obj', (object,), - {'text': json.dumps(mock_perf_req_return_value)}) - - alarm_list = self.alarming.list_alarms(alarm_endpoint, auth_token, list_details, True) - - self.assertDictEqual(alarm_list[0], mock_perf_req_return_value[0]) - - perf_req.assert_called_with( - "alarm_endpoint/v2/alarms/", auth_token, req_type="get", verify_ssl=True) - perf_req.reset_mock() - - # Check list with alarm_name defined - list_details = {"resource_uuid": "mock_r_id", - "alarm_name": "mock_alarm", - "severity": "critical"} - alarm_list = self.alarming.list_alarms(alarm_endpoint, auth_token, list_details, True) - - self.assertDictEqual(alarm_list[0], mock_perf_req_return_value[0]) - - perf_req.assert_called_with( - "alarm_endpoint/v2/alarms/", auth_token, req_type="get", verify_ssl=True) - - @mock.patch.object(Common, "perform_request") - def test_ack_alarm_req(self, perf_req): - """Test update alarm state for acknowledge alarm request.""" - resp = Response({}) - perf_req.return_value = resp - - self.alarming.update_alarm_state(alarm_endpoint, auth_token, "my_alarm_id", True) - - perf_req.assert_called_with( - "alarm_endpoint/v2/alarms/my_alarm_id/state", auth_token, req_type="put", - payload=json.dumps("ok"), verify_ssl=True) - - @mock.patch.object(Common, "perform_request") - def test_update_alarm_invalid(self, perf_req): - """Test update alarm with invalid get response.""" - values = {"alarm_uuid": "my_alarm_id"} - - perf_req.return_value = type('obj', (object,), {'invalid_prop': 'Invalid response'}) - - with self.assertRaises(Exception): - self.alarming.update_alarm(alarm_endpoint, auth_token, values, {}, True) - perf_req.assert_called_with(mock.ANY, auth_token, req_type="get") - - @mock.patch.object(Common, "perform_request") - def test_update_alarm_invalid_payload(self, perf_req): - """Test update alarm with invalid payload.""" - resp = Response({"name": "my_alarm", - "state": "alarm", - "gnocchi_resources_threshold_rule": - {"resource_id": "my_resource_id", - "metric": "my_metric"}}) - perf_req.return_value = resp - values = {"alarm_uuid": "my_alarm_id"} - - with self.assertRaises(Exception): - self.alarming.update_alarm(alarm_endpoint, auth_token, values, {}, True) - perf_req.assert_called_with(mock.ANY, auth_token, req_type="get") - self.assertEqual(perf_req.call_count, 1) - - @mock.patch.object(alarm_req.OpenstackAlarmHandler, "check_payload") - @mock.patch.object(Common, "perform_request") - def test_update_alarm_valid(self, perf_req, check_pay): - """Test valid update alarm request.""" - resp = Response({"alarm_id": "1", - "name": "my_alarm", - "state": "alarm", - "gnocchi_resources_threshold_rule": - {"resource_id": "my_resource_id", - "metric": "disk.write.requests"}}) - perf_req.return_value = resp - values = {"alarm_uuid": "my_alarm_id"} - - self.alarming.update_alarm(alarm_endpoint, auth_token, values, {}, True) - - check_pay.assert_called_with(values, "disk_write_ops", "my_resource_id", - "my_alarm", alarm_state="alarm") - - self.assertEqual(perf_req.call_count, 2) - # Second call is the update request - perf_req.assert_called_with( - 'alarm_endpoint/v2/alarms/my_alarm_id', auth_token, - req_type="put", payload=check_pay.return_value, verify_ssl=True) - - @mock.patch.object(Config, "instance") - def test_check_valid_payload(self, cfg): - """Test the check payload function for a valid payload.""" - values = {"severity": "warning", - "statistic": "COUNT", - "threshold_value": 12, - "operation": "GT", - "granularity": 300, - "resource_type": "generic"} - cfg.return_value.OS_NOTIFIER_URI = "http://localhost:8662" - payload = self.alarming.check_payload( - values, "disk_write_ops", "r_id", "alarm_name") - - self.assertDictEqual( - json.loads(payload), {"name": "alarm_name", - "gnocchi_resources_threshold_rule": - {"resource_id": "r_id", - "metric": "disk.write.requests", - "comparison_operator": "gt", - "aggregation_method": "count", - "threshold": 12, - "granularity": 300, - "resource_type": "generic"}, - "severity": "low", - "state": "ok", - "type": "gnocchi_resources_threshold", - "alarm_actions": ["http://localhost:8662"], - "repeat_actions": True}) - - @mock.patch.object(Config, "instance") - @mock.patch.object(Common, "perform_request") - def test_check_valid_state_payload(self, perform_req, cfg): - """Test the check payload function for a valid payload with state.""" - values = {"severity": "warning", - "statistic": "COUNT", - "threshold_value": 12, - "operation": "GT", - "granularity": 300, - "resource_type": "generic"} - cfg.return_value.OS_NOTIFIER_URI = "http://localhost:8662" - payload = self.alarming.check_payload( - values, "disk_write_ops", "r_id", "alarm_name", alarm_state="alarm") - - self.assertEqual( - json.loads(payload), {"name": "alarm_name", - "gnocchi_resources_threshold_rule": - {"resource_id": "r_id", - "metric": "disk.write.requests", - "comparison_operator": "gt", - "aggregation_method": "count", - "threshold": 12, - "granularity": 300, - "resource_type": "generic"}, - "severity": "low", - "state": "alarm", - "type": "gnocchi_resources_threshold", - "alarm_actions": ["http://localhost:8662"], - "repeat_actions": True}) - - def test_check_invalid_payload(self): - """Test the check payload function for an invalid payload.""" - values = {"alarm_values": "mock_invalid_details"} - with self.assertRaises(Exception): - self.alarming.check_payload(values, "my_metric", "r_id", "alarm_name") - - @mock.patch.object(Common, "perform_request") - def test_get_alarm_state(self, perf_req): - """Test the get alarm state function.""" - perf_req.return_value = type('obj', (object,), {'text': '{"alarm_id":"1"}'}) - - self.alarming.get_alarm_state(alarm_endpoint, auth_token, "alarm_id") - - perf_req.assert_called_with( - "alarm_endpoint/v2/alarms/alarm_id/state", auth_token, req_type="get") - - @mock.patch.object(Common, "perform_request") - def test_check_for_metric(self, perf_req): - """Test the check for metric function.""" - mock_perf_req_return_value = {"metrics": {"cpu_util": 123}} - perf_req.return_value = type('obj', (object,), {'text': json.dumps(mock_perf_req_return_value)}) - - self.alarming.check_for_metric(auth_token, metric_endpoint, "cpu_utilization", "r_id", True) - - perf_req.assert_called_with( - "metric_endpoint/v1/resource/generic/r_id", auth_token, req_type="get", verify_ssl=True) diff --git a/osm_mon/test/OpenStack/unit/test_common.py b/osm_mon/test/OpenStack/unit/test_common.py deleted file mode 100644 index e6c52fb..0000000 --- a/osm_mon/test/OpenStack/unit/test_common.py +++ /dev/null @@ -1,119 +0,0 @@ -# Copyright 2017 Intel Research and Development Ireland Limited -# ************************************************************* - -# This file is part of OSM Monitoring module -# All Rights Reserved to 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. - -# For those usages not covered by the Apache License, Version 2.0 please -# contact: helena.mcgough@intel.com or adrian.hoban@intel.com -## -"""Tests for all common OpenStack methods.""" - -import json -import logging -import unittest - -import mock -import requests -from keystoneclient.v3 import client - -from osm_mon.core.auth import AuthManager -from osm_mon.core.database import VimCredentials -from osm_mon.plugins.OpenStack.common import Common - -__author__ = "Helena McGough" - -log = logging.getLogger(__name__) - - -class Message(object): - """Mock a message for an access credentials request.""" - - def __init__(self): - """Initialise the topic and value of access_cred message.""" - self.topic = "access_credentials" - self.value = json.dumps({"mock_value": "mock_details", - "vim_type": "OPENSTACK", - "access_config": - {"openstack_site": "my_site", - "user": "my_user", - "password": "my_password", - "vim_tenant_name": "my_tenant"}}) - - -class TestCommon(unittest.TestCase): - """Test the common class for OpenStack plugins.""" - - def setUp(self): - """Test Setup.""" - super(TestCommon, self).setUp() - self.common = Common() - self.creds = VimCredentials() - self.creds.id = 'test_id' - self.creds.user = 'user' - self.creds.url = 'url' - self.creds.password = 'password' - self.creds.tenant_name = 'tenant_name' - - @mock.patch.object(AuthManager, "get_credentials") - @mock.patch.object(client.Client, "get_raw_token_from_identity_service") - def test_get_auth_token(self, get_token, get_creds): - """Test generating a new authentication token.""" - get_creds.return_value = self.creds - Common.get_auth_token('test_id') - get_creds.assert_called_with('test_id') - get_token.assert_called_with(auth_url='url', password='password', project_name='tenant_name', username='user', - project_domain_id='default', user_domain_id='default') - - @mock.patch.object(requests, 'post') - def test_post_req(self, post): - """Testing a post request.""" - Common.perform_request("url", "auth_token", req_type="post", - payload="payload") - - post.assert_called_with("url", data="payload", headers=mock.ANY, - timeout=mock.ANY, verify=True) - - @mock.patch.object(requests, 'get') - def test_get_req(self, get): - """Testing a get request.""" - # Run the defualt get request without any parameters - Common.perform_request("url", "auth_token", req_type="get") - - get.assert_called_with("url", params=None, headers=mock.ANY, - timeout=mock.ANY, verify=True) - - # Test with some parameters specified - get.reset_mock() - Common.perform_request("url", "auth_token", req_type="get", - params="some parameters") - - get.assert_called_with("url", params="some parameters", - headers=mock.ANY, timeout=mock.ANY, verify=True) - - @mock.patch.object(requests, 'put') - def test_put_req(self, put): - """Testing a put request.""" - Common.perform_request("url", "auth_token", req_type="put", - payload="payload") - put.assert_called_with("url", data="payload", headers=mock.ANY, - timeout=mock.ANY, verify=True) - - @mock.patch.object(requests, 'delete') - def test_delete_req(self, delete): - """Testing a delete request.""" - Common.perform_request("url", "auth_token", req_type="delete") - - delete.assert_called_with("url", headers=mock.ANY, timeout=mock.ANY, verify=True) diff --git a/osm_mon/test/OpenStack/unit/test_metric_calls.py b/osm_mon/test/OpenStack/unit/test_metric_calls.py deleted file mode 100644 index b71ca72..0000000 --- a/osm_mon/test/OpenStack/unit/test_metric_calls.py +++ /dev/null @@ -1,308 +0,0 @@ -# Copyright 2017 iIntel Research and Development Ireland Limited -# ************************************************************* - -# This file is part of OSM Monitoring module -# All Rights Reserved to 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. - -# For those usages not covered by the Apache License, Version 2.0 please -# contact: helena.mcgough@intel.com or adrian.hoban@intel.com -## -"""Tests for all metric request message keys.""" - -import json -import logging -import unittest - -import mock - -from osm_mon.core.auth import AuthManager -from osm_mon.plugins.OpenStack.Gnocchi import metric_handler as metric_req -from osm_mon.plugins.OpenStack.common import Common - -log = logging.getLogger(__name__) - -# Mock auth_token and endpoint -endpoint = mock.ANY -auth_token = mock.ANY - -# Mock a valid metric list for some tests, and a resultant list -metric_list = [{"name": "disk.write.requests", - "id": "metric_id", - "unit": "units", - "resource_id": "r_id"}] -result_list = ["metric_id", "r_id", "units", "disk_write_ops"] - - -class Response(object): - """Mock a response object for requests.""" - - def __init__(self): - """Initialise test and status code values.""" - self.text = json.dumps([{"id": "test_id"}]) - self.status_code = "STATUS_CODE" - - -def perform_request_side_effect(*args, **kwargs): - resp = Response() - if 'marker' in args[0]: - resp.text = json.dumps([]) - if 'resource/generic' in args[0]: - resp.text = json.dumps({'metrics': {'cpu_util': 'test_id'}}) - return resp - - -class TestMetricCalls(unittest.TestCase): - """Integration test for metric request keys.""" - - def setUp(self): - """Setup the tests for metric request keys.""" - super(TestMetricCalls, self).setUp() - self.metrics = metric_req.OpenstackMetricHandler() - self.metrics._common = Common() - - @mock.patch.object(metric_req.OpenstackMetricHandler, "get_metric_id") - @mock.patch.object(Common, "perform_request") - def test_invalid_config_metric_req( - self, perf_req, get_metric): - """Test the configure metric function, for an invalid metric.""" - # Test invalid configuration for creating a metric - values = {"metric_details": "invalid_metric"} - - with self.assertRaises(ValueError): - self.metrics.configure_metric(endpoint, auth_token, values, verify_ssl=False) - - perf_req.assert_not_called() - - # Test with an invalid metric name, will not perform request - values = {"resource_uuid": "r_id"} - - with self.assertRaises(ValueError): - self.metrics.configure_metric(endpoint, auth_token, values, verify_ssl=False) - - perf_req.assert_not_called() - - # If metric exists, it won't be recreated - get_metric.return_value = "metric_id" - - with self.assertRaises(ValueError): - self.metrics.configure_metric(endpoint, auth_token, values, verify_ssl=False) - - perf_req.assert_not_called() - - @mock.patch.object(metric_req.OpenstackMetricHandler, "get_metric_id") - @mock.patch.object(Common, "perform_request") - @mock.patch.object(AuthManager, "get_credentials") - def test_valid_config_metric_req( - self, get_creds, perf_req, get_metric): - """Test the configure metric function, for a valid metric.""" - # Test valid configuration and payload for creating a metric - get_creds.return_value = type('obj', (object,), {'config': '{"insecure":true}'}) - values = {"resource_uuid": "r_id", - "metric_unit": "units", - "metric_name": "cpu_util"} - get_metric.return_value = None - payload = {"id": "r_id", - "metrics": {"cpu_util": - {"archive_policy_name": "high", - "name": "cpu_util", - "unit": "units"}}} - - perf_req.return_value = type('obj', (object,), {'text': '{"metrics":{"cpu_util":1}, "id":1}'}) - - self.metrics.configure_metric(endpoint, auth_token, values, verify_ssl=False) - - perf_req.assert_called_with( - "/v1/resource/generic", auth_token, req_type="post", verify_ssl=False, - payload=json.dumps(payload, sort_keys=True)) - - @mock.patch.object(Common, "perform_request") - def test_delete_metric_req(self, perf_req): - """Test the delete metric function.""" - mock_response = Response() - mock_response.status_code = 200 - perf_req.return_value = mock_response - - self.metrics.delete_metric(endpoint, auth_token, "metric_id", verify_ssl=False) - - perf_req.assert_called_with( - "/v1/metric/metric_id", auth_token, req_type="delete", verify_ssl=False) - - @mock.patch.object(Common, "perform_request") - def test_delete_metric_invalid_status(self, perf_req): - """Test invalid response for delete request.""" - perf_req.return_value = type('obj', (object,), {"status_code": "404"}) - - with self.assertRaises(ValueError): - self.metrics.delete_metric(endpoint, auth_token, "metric_id", verify_ssl=False) - - @mock.patch.object(metric_req.OpenstackMetricHandler, "response_list") - @mock.patch.object(Common, "perform_request") - def test_complete_list_metric_req(self, perf_req, resp_list): - """Test the complete list metric function.""" - # Test listing metrics without any configuration options - values = {} - perf_req.side_effect = perform_request_side_effect - self.metrics.list_metrics(endpoint, auth_token, values, verify_ssl=False) - - perf_req.assert_any_call( - "/v1/metric?sort=name:asc", auth_token, req_type="get", verify_ssl=False) - resp_list.assert_called_with([{u'id': u'test_id'}]) - - @mock.patch.object(metric_req.OpenstackMetricHandler, "response_list") - @mock.patch.object(Common, "perform_request") - def test_resource_list_metric_req(self, perf_req, resp_list): - """Test the resource list metric function.""" - # Test listing metrics with a resource id specified - values = {"resource_uuid": "resource_id"} - perf_req.side_effect = perform_request_side_effect - self.metrics.list_metrics(endpoint, auth_token, values, verify_ssl=False) - - perf_req.assert_any_call( - "/v1/metric/test_id", auth_token, req_type="get", verify_ssl=False) - - @mock.patch.object(metric_req.OpenstackMetricHandler, "response_list") - @mock.patch.object(Common, "perform_request") - def test_name_list_metric_req(self, perf_req, resp_list): - """Test the metric_name list metric function.""" - # Test listing metrics with a metric_name specified - values = {"metric_name": "disk_write_bytes"} - perf_req.side_effect = perform_request_side_effect - self.metrics.list_metrics(endpoint, auth_token, values, verify_ssl=False) - - perf_req.assert_any_call( - "/v1/metric?sort=name:asc", auth_token, req_type="get", verify_ssl=False) - resp_list.assert_called_with( - [{u'id': u'test_id'}], metric_name="disk_write_bytes") - - @mock.patch.object(metric_req.OpenstackMetricHandler, "response_list") - @mock.patch.object(Common, "perform_request") - def test_combined_list_metric_req(self, perf_req, resp_list): - """Test the combined resource and metric list metric function.""" - # Test listing metrics with a resource id and metric name specified - - values = {"resource_uuid": "resource_id", - "metric_name": "cpu_utilization"} - perf_req.side_effect = perform_request_side_effect - self.metrics.list_metrics(endpoint, auth_token, values, verify_ssl=False) - - perf_req.assert_any_call( - "/v1/metric/test_id", auth_token, req_type="get", verify_ssl=False) - - @mock.patch.object(Common, "perform_request") - def test_get_metric_id(self, perf_req): - """Test get_metric_id function.""" - mock_response = Response() - mock_response.text = json.dumps({'metrics': {'my_metric': 'id'}}) - perf_req.return_value = mock_response - self.metrics.get_metric_id(endpoint, auth_token, "my_metric", "r_id", verify_ssl=False) - - perf_req.assert_called_with( - "/v1/resource/generic/r_id", auth_token, req_type="get", verify_ssl=False) - - @mock.patch.object(metric_req.OpenstackMetricHandler, "get_metric_id") - @mock.patch.object(Common, "perform_request") - def test_valid_read_data_req(self, perf_req, get_metric): - """Test the read metric data function, for a valid call.""" - values = {"metric_name": "disk_write_ops", - "resource_uuid": "resource_id", - "collection_unit": "DAY", - "collection_period": 1} - - perf_req.return_value = type('obj', (object,), {'text': '{"metric_data":"[]"}'}) - - get_metric.return_value = "metric_id" - self.metrics.read_metric_data(endpoint, auth_token, values, verify_ssl=False) - - perf_req.assert_called_once() - - @mock.patch.object(Common, "perform_request") - def test_invalid_read_data_req(self, perf_req): - """Test the read metric data function for an invalid call.""" - values = {} - - with self.assertRaises(KeyError): - self.metrics.read_metric_data(endpoint, auth_token, values, verify_ssl=False) - - def test_complete_response_list(self): - """Test the response list function for formatting metric lists.""" - # Mock a list for testing purposes, with valid OSM metric - resp_list = self.metrics.response_list(metric_list) - - # Check for the expected values in the resulting list - for l in result_list: - self.assertIn(l, resp_list[0].values()) - - def test_name_response_list(self): - """Test the response list with metric name configured.""" - # Mock the metric name to test a metric name list - # Test with a name that is not in the list - invalid_name = "my_metric" - resp_list = self.metrics.response_list( - metric_list, metric_name=invalid_name) - - self.assertEqual(resp_list, []) - - # Test with a name on the list - valid_name = "disk_write_ops" - resp_list = self.metrics.response_list( - metric_list, metric_name=valid_name) - - # Check for the expected values in the resulting list - for l in result_list: - self.assertIn(l, resp_list[0].values()) - - def test_resource_response_list(self): - """Test the response list with resource_id configured.""" - # Mock a resource_id to test a resource list - # Test with resource not on the list - invalid_id = "mock_resource" - resp_list = self.metrics.response_list(metric_list, resource=invalid_id) - - self.assertEqual(resp_list, []) - - # Test with a resource on the list - valid_id = "r_id" - resp_list = self.metrics.response_list(metric_list, resource=valid_id) - - # Check for the expected values in the resulting list - for l in result_list: - self.assertIn(l, resp_list[0].values()) - - def test_combined_response_list(self): - """Test the response list function with resource_id and metric_name.""" - # Test for a combined resource and name list - # resource and name are on the list - valid_name = "disk_write_ops" - valid_id = "r_id" - resp_list = self.metrics.response_list( - metric_list, metric_name=valid_name, resource=valid_id) - - # Check for the expected values in the resulting list - for l in result_list: - self.assertIn(l, resp_list[0].values()) - - # resource not on list - invalid_id = "mock_resource" - resp_list = self.metrics.response_list( - metric_list, metric_name=valid_name, resource=invalid_id) - - self.assertEqual(resp_list, []) - - # metric name not on list - invalid_name = "mock_metric" - resp_list = self.metrics.response_list( - metric_list, metric_name=invalid_name, resource=valid_id) - - self.assertEqual(resp_list, []) diff --git a/osm_mon/test/OpenStack/unit/test_metric_req.py b/osm_mon/test/OpenStack/unit/test_metric_req.py deleted file mode 100644 index 2fa31a6..0000000 --- a/osm_mon/test/OpenStack/unit/test_metric_req.py +++ /dev/null @@ -1,159 +0,0 @@ -# Copyright 2017 iIntel Research and Development Ireland Limited -# ************************************************************* - -# This file is part of OSM Monitoring module -# All Rights Reserved to 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. - -# For those usages not covered by the Apache License, Version 2.0 please -# contact: helena.mcgough@intel.com or adrian.hoban@intel.com -## -"""Tests for all metric request message keys.""" - -import json -import logging -import unittest - -import mock - -from osm_mon.core.auth import AuthManager -from osm_mon.plugins.OpenStack.Gnocchi import metric_handler as metric_req -from osm_mon.plugins.OpenStack.Gnocchi.metric_handler import OpenstackMetricHandler -from osm_mon.plugins.OpenStack.common import Common - -log = logging.getLogger(__name__) - - -class Response(object): - """Mock a response object for requests.""" - - def __init__(self): - """Initialise test and status code values.""" - self.text = json.dumps([{"id": "test_id"}]) - self.status_code = "STATUS_CODE" - - -class Message(object): - """A class to mock a message object value for metric requests.""" - - def __init__(self): - """Initialize a mocked message instance.""" - self.topic = "metric_request" - self.key = None - self.value = json.dumps({"mock_message": "message_details"}) - - -class TestMetricReq(unittest.TestCase): - """Integration test for metric request keys.""" - - def setUp(self): - """Setup the tests for metric request keys.""" - super(TestMetricReq, self).setUp() - self.metrics = metric_req.OpenstackMetricHandler() - - @mock.patch.object(Common, "get_auth_token", mock.Mock()) - @mock.patch.object(Common, "get_endpoint", mock.Mock()) - @mock.patch.object(metric_req.OpenstackMetricHandler, "delete_metric") - @mock.patch.object(metric_req.OpenstackMetricHandler, "get_metric_id") - @mock.patch.object(AuthManager, "get_credentials") - def test_delete_metric_key(self, get_creds, get_metric_id, del_metric): - """Test the functionality for a delete metric request.""" - value = {"metric_name": "disk_write_ops", "resource_uuid": "my_r_id", "correlation_id": 1} - - get_creds.return_value = type('obj', (object,), { - 'config': '{"insecure":true}' - }) - del_metric.return_value = True - - # Call the metric functionality and check delete request - get_metric_id.return_value = "my_metric_id" - self.metrics.handle_request('delete_metric_request', value, 'test_id') - del_metric.assert_called_with(mock.ANY, mock.ANY, "my_metric_id", False) - - @mock.patch.object(Common, "get_auth_token", mock.Mock()) - @mock.patch.object(Common, 'get_endpoint', mock.Mock()) - @mock.patch.object(metric_req.OpenstackMetricHandler, "list_metrics") - @mock.patch.object(AuthManager, "get_credentials") - def test_list_metric_key(self, get_creds, list_metrics): - """Test the functionality for a list metric request.""" - value = {"metrics_list_request": {"correlation_id": 1}} - - get_creds.return_value = type('obj', (object,), { - 'config': '{"insecure":true}' - }) - - list_metrics.return_value = [] - - # Call the metric functionality and check list functionality - self.metrics.handle_request('list_metric_request', value, 'test_id') - list_metrics.assert_called_with(mock.ANY, mock.ANY, {"correlation_id": 1}, False) - - @mock.patch.object(Common, "get_auth_token", mock.Mock()) - @mock.patch.object(Common, 'get_endpoint', mock.Mock()) - @mock.patch.object(AuthManager, "get_credentials") - @mock.patch.object(Common, "perform_request") - def test_update_metric_key(self, perf_req, get_creds): - """Test the functionality for an update metric request.""" - value = {"metric_update_request": - {"correlation_id": 1, - "metric_name": "my_metric", - "resource_uuid": "my_r_id"}} - - get_creds.return_value = type('obj', (object,), { - 'config': '{"insecure":true}' - }) - - mock_response = Response() - mock_response.text = json.dumps({'metrics': {'my_metric': 'id'}}) - perf_req.return_value = mock_response - - # Call metric functionality and confirm no function is called - # Gnocchi does not support updating a metric configuration - self.metrics.handle_request('update_metric_request', value, 'test_id') - - @mock.patch.object(Common, "get_auth_token", mock.Mock()) - @mock.patch.object(Common, 'get_endpoint', mock.Mock()) - @mock.patch.object(OpenstackMetricHandler, "configure_metric") - @mock.patch.object(AuthManager, "get_credentials") - def test_config_metric_key(self, get_credentials, config_metric): - """Test the functionality for a create metric request.""" - value = {"metric_create_request": {"correlation_id": 123}} - get_credentials.return_value = type('obj', (object,), {'config': '{"insecure":true}'}) - # Call metric functionality and check config metric - config_metric.return_value = "metric_id", "resource_id" - self.metrics.handle_request('create_metric_request', value, 'test_id') - config_metric.assert_called_with(mock.ANY, mock.ANY, {"correlation_id": 123}, False) - - @mock.patch.object(Common, "get_auth_token", mock.Mock()) - @mock.patch.object(Common, 'get_endpoint', mock.Mock()) - @mock.patch.object(OpenstackMetricHandler, "read_metric_data") - @mock.patch.object(AuthManager, "get_credentials") - @mock.patch.object(Common, "perform_request") - def test_read_data_key(self, perf_req, get_creds, read_data): - """Test the functionality for a read metric data request.""" - value = {"correlation_id": 123, "metric_name": "cpu_utilization", "resource_uuid": "uuid"} - - get_creds.return_value = type('obj', (object,), { - 'config': '{"insecure":true}' - }) - - mock_response = Response() - mock_response.text = json.dumps({'metrics': {'cpu_util': 'id'}}) - perf_req.return_value = mock_response - - # Call metric functionality and check read data metrics - read_data.return_value = "time_stamps", "data_values" - self.metrics.handle_request('read_metric_data_request', value, 'test_id') - read_data.assert_called_with( - mock.ANY, mock.ANY, value, False) diff --git a/osm_mon/test/OpenStack/unit/test_notifier.py b/osm_mon/test/OpenStack/unit/test_notifier.py deleted file mode 100644 index a420c70..0000000 --- a/osm_mon/test/OpenStack/unit/test_notifier.py +++ /dev/null @@ -1,133 +0,0 @@ -# Copyright 2017 Intel Research and Development Ireland Limited -# ************************************************************* - -# This file is part of OSM Monitoring module -# All Rights Reserved to 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. - -# For those usages not covered by the Apache License, Version 2.0 please -# contact: helena.mcgough@intel.com or adrian.hoban@intel.com -## -"""Tests for all common OpenStack methods.""" - -import json -import unittest - -import mock -from kafka import KafkaProducer - -from osm_mon.core.database import DatabaseManager, Alarm -from osm_mon.plugins.OpenStack.Aodh.notifier import NotifierHandler - -post_data = {"severity": "critical", - "alarm_name": "my_alarm", - "current": "current_state", - "alarm_id": "my_alarm_id", - "reason": "Threshold has been broken", - "reason_data": {"count": 1, - "most_recent": "null", - "type": "threshold", - "disposition": "unknown"}, - "previous": "previous_state"} - - -class Response(object): - """Mock a response class for generating responses.""" - - def __init__(self, text): - """Initialise a mock response with a text attribute.""" - self.text = text - - -class RFile(): - def read(self, content_length): - return json.dumps(post_data, sort_keys=True) - - -class MockNotifierHandler(NotifierHandler): - """Mock the NotifierHandler class for testing purposes.""" - - def __init__(self): - """Initialise mock NotifierHandler.""" - self.headers = {'Content-Length': '20'} - self.rfile = RFile() - - def setup(self): - """Mock setup function.""" - pass - - def handle(self): - """Mock handle function.""" - pass - - def finish(self): - """Mock finish function.""" - pass - - -@mock.patch.object(KafkaProducer, "__init__", lambda *args, **kwargs: None) -@mock.patch.object(KafkaProducer, "flush", mock.Mock()) -class TestNotifier(unittest.TestCase): - """Test the NotifierHandler class for requests from aodh.""" - - def setUp(self): - """Setup tests.""" - super(TestNotifier, self).setUp() - self.handler = MockNotifierHandler() - - @mock.patch.object(NotifierHandler, "_set_headers") - def test_do_GET(self, set_head): - """Tests do_GET. Validates _set_headers has been called.""" - self.handler.do_GET() - - set_head.assert_called_once() - - @mock.patch.object(NotifierHandler, "notify_alarm") - @mock.patch.object(NotifierHandler, "_set_headers") - def test_do_POST(self, set_head, notify): - """Tests do_POST. Validates notify_alarm has been called.""" - self.handler.do_POST() - - set_head.assert_called_once() - notify.assert_called_with(post_data) - - @mock.patch.object(NotifierHandler, "_publish_response") - @mock.patch.object(DatabaseManager, "get_alarm") - def test_notify_alarm_valid_alarm( - self, get_alarm, notify): - """ - Tests notify_alarm when request from OpenStack references an existing alarm in the DB. - Validates KafkaProducer.notify_alarm has been called. - """ - # Generate return values for valid notify_alarm operation - mock_alarm = Alarm() - get_alarm.return_value = mock_alarm - - self.handler.notify_alarm(post_data) - notify.assert_called_with('notify_alarm', mock.ANY) - - @mock.patch.object(NotifierHandler, "_publish_response") - @mock.patch.object(DatabaseManager, "get_alarm") - def test_notify_alarm_invalid_alarm( - self, get_alarm, notify): - """ - Tests notify_alarm when request from OpenStack references a non existing alarm in the DB. - Validates Exception is thrown and KafkaProducer.notify_alarm has not been called. - """ - # Generate return values for valid notify_alarm operation - get_alarm.return_value = None - - with self.assertRaises(Exception): - self.handler.notify_alarm(post_data) - notify.assert_not_called() diff --git a/osm_mon/test/OpenStack/unit/test_responses.py b/osm_mon/test/OpenStack/unit/test_responses.py deleted file mode 100644 index 1377bc0..0000000 --- a/osm_mon/test/OpenStack/unit/test_responses.py +++ /dev/null @@ -1,116 +0,0 @@ -# Copyright 2017 iIntel Research and Development Ireland Limited -# ************************************************************* - -# This file is part of OSM Monitoring module -# All Rights Reserved to 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. - -# For those usages not covered by the Apache License, Version 2.0 please -# contact: helena.mcgough@intel.com or adrian.hoban@intel.com -## -"""Test that the correct responses are generated for each message.""" - -import logging -import unittest - -import mock - -from osm_mon.plugins.OpenStack import response as resp - -log = logging.getLogger(__name__) - - -class TestOpenStackResponse(unittest.TestCase): - """Tests for responses generated by the OpenStack plugins.""" - - def setUp(self): - """Setup for testing OpenStack plugin responses.""" - super(TestOpenStackResponse, self).setUp() - self.plugin_resp = resp.OpenStackResponseBuilder() - - def test_invalid_key(self): - """Test if an invalid key is entered for a response.""" - message = self.plugin_resp.generate_response("mock_invalid_key") - self.assertEqual(message, None) - - @mock.patch.object( - resp.OpenStackResponseBuilder, "alarm_list_response") - def test_list_alarm_resp(self, alarm_list_resp): - """Test out a function call for a list alarm response.""" - message = self.plugin_resp.generate_response("list_alarm_response") - self.assertEqual(alarm_list_resp.return_value, message) - - @mock.patch.object( - resp.OpenStackResponseBuilder, "list_metric_response") - def test_list_metric_resp(self, metric_list_resp): - """Test list metric response function call.""" - message = self.plugin_resp.generate_response("list_metric_response") - self.assertEqual(message, metric_list_resp.return_value) - - @mock.patch.object( - resp.OpenStackResponseBuilder, "delete_alarm_response") - def test_delete_alarm_resp(self, del_alarm_resp): - """Test delete alarm response function call.""" - message = self.plugin_resp.generate_response("delete_alarm_response") - self.assertEqual(message, del_alarm_resp.return_value) - - @mock.patch.object( - resp.OpenStackResponseBuilder, "delete_metric_response") - def test_delete_metric_resp(self, del_metric_resp): - """Test the response functionality of delete metric response.""" - message = self.plugin_resp.generate_response("delete_metric_response") - self.assertEqual(message, del_metric_resp.return_value) - - @mock.patch.object( - resp.OpenStackResponseBuilder, "create_alarm_response") - def test_create_alarm_resp(self, config_alarm_resp): - """Test create alarm response function call.""" - message = self.plugin_resp.generate_response("create_alarm_response") - self.assertEqual(message, config_alarm_resp.return_value) - - @mock.patch.object( - resp.OpenStackResponseBuilder, "metric_create_response") - def test_create_metric_resp(self, config_metric_resp): - """Test create metric response function call.""" - message = self.plugin_resp.generate_response("create_metric_response") - self.assertEqual(message, config_metric_resp.return_value) - - @mock.patch.object( - resp.OpenStackResponseBuilder, "update_alarm_response") - def test_update_alarm_resp(self, up_alarm_resp): - """Test update alarm response function call.""" - message = self.plugin_resp.generate_response("update_alarm_response") - self.assertEqual(message, up_alarm_resp.return_value) - - @mock.patch.object( - resp.OpenStackResponseBuilder, "update_metric_response") - def test_update_metric_resp(self, up_metric_resp): - """Test update metric response function call.""" - message = self.plugin_resp.generate_response("update_metric_response") - self.assertEqual(message, up_metric_resp.return_value) - - @mock.patch.object( - resp.OpenStackResponseBuilder, "notify_alarm") - def test_notify_alarm(self, notify_alarm): - """Test notify alarm response function call.""" - message = self.plugin_resp.generate_response("notify_alarm") - self.assertEqual(message, notify_alarm.return_value) - - @mock.patch.object( - resp.OpenStackResponseBuilder, "read_metric_data_response") - def test_read_metric_data_resp(self, read_data_resp): - """Test read metric data response function call.""" - message = self.plugin_resp.generate_response( - "read_metric_data_response") - self.assertEqual(message, read_data_resp.return_value) diff --git a/osm_mon/test/OpenStack/unit/test_settings.py b/osm_mon/test/OpenStack/unit/test_settings.py deleted file mode 100644 index 42619f8..0000000 --- a/osm_mon/test/OpenStack/unit/test_settings.py +++ /dev/null @@ -1,46 +0,0 @@ -# Copyright 2017 Intel Research and Development Ireland Limited -# ************************************************************* - -# This file is part of OSM Monitoring module -# All Rights Reserved to 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. - -# For those usages not covered by the Apache License, Version 2.0 please -# contact: helena.mcgough@intel.com or adrian.hoban@intel.com -## -"""Tests for settings for OpenStack plugins configurations.""" - -import logging -import os -import unittest - -from osm_mon.core.settings import Config - -log = logging.getLogger(__name__) - - -class TestSettings(unittest.TestCase): - """Test the settings class for OpenStack plugin configuration.""" - - def setUp(self): - """Test Setup.""" - super(TestSettings, self).setUp() - self.cfg = Config.instance() - - def test_set_os_username(self): - """Test reading the environment for OpenStack plugin configuration.""" - os.environ["OS_NOTIFIER_URI"] = "test" - self.cfg.read_environ() - - self.assertEqual(self.cfg.OS_NOTIFIER_URI, "test") diff --git a/osm_mon/test/VMware/__init__.py b/osm_mon/test/VMware/__init__.py deleted file mode 100644 index 64d5d51..0000000 --- a/osm_mon/test/VMware/__init__.py +++ /dev/null @@ -1,37 +0,0 @@ -# -*- coding: utf-8 -*- - -## -# Copyright 2017-2018 VMware Inc. -# This file is part of ETSI OSM -# 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. -# -# For those usages not covered by the Apache License, Version 2.0 please -# contact: osslegalrouting@vmware.com -## - -"""VMware MON plugin tests.""" - -import logging -import sys - -from osm_mon.core.settings import Config - -cfg = Config.instance() -logging.basicConfig(stream=sys.stdout, - format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', - datefmt='%m/%d/%Y %I:%M:%S %p', - level=logging.getLevelName(cfg.OSMMON_LOG_LEVEL)) -log = logging.getLogger(__name__) - diff --git a/osm_mon/test/VMware/test_mon_plugin_vrops.py b/osm_mon/test/VMware/test_mon_plugin_vrops.py deleted file mode 100644 index 2d10d1b..0000000 --- a/osm_mon/test/VMware/test_mon_plugin_vrops.py +++ /dev/null @@ -1,3083 +0,0 @@ -# -*- coding: utf-8 -*- - -## -# Copyright 2017-2018 VMware Inc. -# This file is part of ETSI OSM -# 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. -# -# For those usages not covered by the Apache License, Version 2.0 please -# contact: osslegalrouting@vmware.com -## - -""" Mock tests for VMware vROPs Mon plugin """ - -import os -import sys -import unittest - -import mock -import requests - -sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..")) - -from osm_mon.plugins.vRealiseOps import mon_plugin_vrops as monPlugin - -from pyvcloud.vcd.client import Client - - -class TestMonPlugin(unittest.TestCase): - """Test class for vROPs Mon Plugin class methods""" - - def setUp(self): - """Setup the tests for Mon Plugin class methods""" - super(TestMonPlugin, self).setUp() - - self.m_vim_access_config = {'vrops_site': 'abc', - 'vrops_user': 'user', - 'vrops_password': 'passwd', - 'vim_url': 'vcd_url', - 'admin_username': 'admin', - 'admin_password': 'admin_passwd', - 'vim_uuid': '1', - 'tenant_id': 'org_vdc_1'} - self.mon_plugin = monPlugin.MonPlugin(self.m_vim_access_config) - # create client object - self.vca = Client('test', verify_ssl_certs=False) - # create session - self.session = requests.Session() - - def test_get_default_Params_valid_metric_alarm_name(self): - """Test get default params method""" - - # Mock valid metric_alarm_name and response - metric_alarm_name = "Average_Memory_Usage_Above_Threshold" - expected_return = {'impact': 'risk', 'cancel_cycles': 2, 'adapter_kind': 'VMWARE', - 'repeat': False, 'cancel_period': 300, 'alarm_type': 16, - 'vrops_alarm': 'Avg_Mem_Usage_Above_Thr', 'enabled': True, 'period': 300, - 'resource_kind': 'VirtualMachine', 'alarm_subType': 19, - 'action': 'acknowledge', 'evaluation': 2, 'unit': '%'} - - # call get default param function under test - actual_return = self.mon_plugin.get_default_Params(metric_alarm_name) - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - def test_get_default_Params_invalid_metric_alarm_name(self): - """Test get default params method invalid metric alarm""" - - # Mock valid metric_alarm_name and response - metric_alarm_name = "Invalid_Alarm" - expected_return = {} - - # call get default param function under test - actual_return = self.mon_plugin.get_default_Params(metric_alarm_name) - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'post') - def test_create_symptom_valid_req_response(self, m_post): - """Test create symptom method-valid request""" - - # Mock valid symptom params and mock responses - symptom_param = {'threshold_value': 0, 'cancel_cycles': 1, 'adapter_kind_key': 'VMWARE', - 'resource_kind_key': 'VirtualMachine', 'severity': 'CRITICAL', - 'symptom_name': \ - 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'operation': 'GT', 'wait_cycles': 1, 'metric_key': 'cpu|usage_average'} - - m_post.return_value.status_code = 201 - m_post.return_value.content = \ - '{"id":"SymptomDefinition-351c23b4-bc3c-4c7b-b4af-1ad90a673c5d",\ - "name":"CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ - "adapterKindKey":"VMWARE","resourceKindKey":"VirtualMachine",\ - "waitCycles":1,"cancelCycles":1,\ - "state":{"severity":"CRITICAL","condition":{"type":"CONDITION_HT",\ - "key":"cpu|usage_average","operator":"GT","value":"0.0",\ - "valueType":"NUMERIC",\ - "instanced":false,"thresholdType":"STATIC"}}}' - - expected_return = "SymptomDefinition-351c23b4-bc3c-4c7b-b4af-1ad90a673c5d" - - # call create symptom method under test - actual_return = self.mon_plugin.create_symptom(symptom_param) - - # verify that mocked method is called - m_post.assert_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'post') - def test_create_symptom_invalid_req_response(self, m_post): - """Test create symptom method-invalid response""" - - # Mock valid symptom params and invalid mock responses - symptom_param = {'threshold_value': 0, 'cancel_cycles': 1, 'adapter_kind_key': 'VMWARE', - 'resource_kind_key': 'VirtualMachine', 'severity': 'CRITICAL', - 'symptom_name': \ - 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'operation': 'GT', 'wait_cycles': 1, 'metric_key': 'cpu|usage_average'} - - m_post.return_value.status_code = 404 - m_post.return_value.content = '404 Not Found' - - expected_return = None - - # call create symptom method under test - actual_return = self.mon_plugin.create_symptom(symptom_param) - - # verify that mocked method is called - m_post.assert_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'post') - def test_create_symptom_incorrect_data(self, m_post): - """Test create symptom method-incorrect data""" - - # Mock valid symptom params and invalid mock responses - symptom_param = {'threshold_value': 0, 'cancel_cycles': 1, 'adapter_kind_key': 'VMWARE', - 'resource_kind_key': 'VirtualMachine', 'severity': 'CRITICAL', - 'symptom_name': \ - 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'operation': 'GT', 'metric_key': 'cpu|usage_average'} - - expected_return = None - - # call create symptom method under test - actual_return = self.mon_plugin.create_symptom(symptom_param) - - # verify that mocked method is not called - m_post.assert_not_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'post') - def test_create_alarm_definition_valid_req_response(self, m_post): - """Test create alarm definition method-valid response""" - - # Mock valid alarm params and mock responses - alarm_param = {'description': 'CPU_Utilization_Above_Threshold', 'cancelCycles': 1, - 'subType': 19, 'waitCycles': 1, - 'severity': 'CRITICAL', 'impact': 'risk', 'adapterKindKey': 'VMWARE', - 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'resourceKindKey': 'VirtualMachine', 'type': 16, - 'symptomDefinitionId': \ - 'SymptomDefinition-25278b06-bff8-4409-a141-9b4e064235df'} - - m_post.return_value.status_code = 201 - m_post.return_value.content = \ - '{"id":"AlertDefinition-d4f21e4b-770a-45d6-b298-022eaf489115",\ - "name":"CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ - "description":"CPU_Utilization_Above_Threshold","adapterKindKey":"VMWARE",\ - "resourceKindKey":"VirtualMachine","waitCycles":1,"cancelCycles":1,\ - "type":16,"subType":19,\ - "states":[{"severity":"CRITICAL","base-symptom-set":{"type":"SYMPTOM_SET",\ - "relation":"SELF","aggregation":"ALL","symptomSetOperator":"AND",\ - "symptomDefinitionIds":\ - ["SymptomDefinition-25278b06-bff8-4409-a141-9b4e064235df"]},\ - "impact":{"impactType":"BADGE","detail":"risk"}}]}' - - expected_return = "AlertDefinition-d4f21e4b-770a-45d6-b298-022eaf489115" - - # call create alarm definition method under test - actual_return = self.mon_plugin.create_alarm_definition(alarm_param) - - # verify that mocked method is called - m_post.assert_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'post') - def test_create_alarm_definition_invalid_req_response(self, m_post): - """Test create alarm definition method-invalid response""" - - # Mock valid alarm params and mock responses - alarm_param = {'description': 'CPU_Utilization_Above_Threshold', 'cancelCycles': 1, - 'subType': 19, 'waitCycles': 1, - 'severity': 'CRITICAL', 'impact': 'risk', 'adapterKindKey': 'VMWARE', - 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'resourceKindKey': 'VirtualMachine', 'type': 16, - 'symptomDefinitionId': \ - 'SymptomDefinition-25278b06-bff8-4409-a141-9b4e064235df'} - - m_post.return_value.status_code = 404 - m_post.return_value.content = '404 Not Found' - - expected_return = None - - # call create alarm definition method under test - actual_return = self.mon_plugin.create_alarm_definition(alarm_param) - - # verify that mocked method is called - m_post.assert_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'post') - def test_create_alarm_definition_incorrect_data(self, m_post): - """Test create alarm definition method-incorrect data""" - - # Mock incorrect alarm param - alarm_param = {'description': 'CPU_Utilization_Above_Threshold', 'cancelCycles': 1, - 'subType': 19, 'waitCycles': 1, 'type': 16, - 'severity': 'CRITICAL', 'impact': 'risk', 'adapterKindKey': 'VMWARE', - 'symptomDefinitionId': \ - 'SymptomDefinition-25278b06-bff8-4409-a141-9b4e064235df'} - expected_return = None - - # call create symptom method under test - actual_return = self.mon_plugin.create_alarm_definition(alarm_param) - - # verify that mocked method is not called - m_post.assert_not_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') - @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') - @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') - @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') - def test_configure_alarm_valid_req(self, m_get_default_Params, - m_get_alarm_defination_by_name, - m_create_symptom, - m_create_alarm_definition, - m_get_vm_moref_id, - m_get_vm_resource_id, - m_create_alarm_notification_rule, - m_save_alarm): - """Test configure alarm valid request creating alarm""" - - # Mock input configuration dictionary - config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', - 'alarm_name': 'CPU_Utilization_Above_Threshold', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'statistic': 'AVERAGE', 'metric_name': 'cpu_utilization', - 'vdu_name': 'vdu1', 'vnf_member_index': 'index1', 'ns_id': 'nsd1', - 'operation': 'GT', 'unit': '%', - 'description': 'CPU_Utilization_Above_Threshold'} - - # symptom parameters to be passed for symptom creation - symptom_params = {'threshold_value': 0, - 'cancel_cycles': 1, - 'adapter_kind_key': 'VMWARE', - 'resource_kind_key': 'VirtualMachine', - 'severity': 'CRITICAL', - 'symptom_name': \ - 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'operation': 'GT', - 'wait_cycles': 1, - 'metric_key': 'cpu|usage_average'} - - # alarm parameters to be passed for alarm creation - alarm_params = {'description': 'CPU_Utilization_Above_Threshold', - 'cancelCycles': 1, 'subType': 19, - 'waitCycles': 1, 'severity': 'CRITICAL', - 'impact': 'risk', 'adapterKindKey': 'VMWARE', - 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'resourceKindKey': 'VirtualMachine', - 'symptomDefinitionId': \ - 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804', - 'type': 16} - - vm_moref_id = 'vm-6626' - vrops_alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - alarm_def = 'AlertDefinition-0f3cdcb3-4e1b-4a0b-86d0-66d4b3f65220' - resource_id = 'ac87622f-b761-40a0-b151-00872a2a456e' - alarm_def_uuid = '0f3cdcb3-4e1b-4a0b-86d0-66d4b3f65220' - - # Mock default Parameters for alarm & metric configuration - m_get_default_Params.side_effect = [{'impact': 'risk', 'cancel_cycles': 1, - 'adapter_kind': 'VMWARE', 'repeat': False, - 'cancel_period': 300, 'alarm_type': 16, - 'vrops_alarm': 'CPU_Utilization_Above_Thr', - 'enabled': True, 'period': 300, - 'resource_kind': 'VirtualMachine', - 'alarm_subType': 19, 'action': 'acknowledge', - 'evaluation': 1, 'unit': 'msec'}, - {'metric_key': 'cpu|usage_average', 'unit': '%'} - ] - - # set mocked function return values - m_get_alarm_defination_by_name.return_value = [] - m_create_symptom.return_value = 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804' - m_create_alarm_definition.return_value = \ - 'AlertDefinition-0f3cdcb3-4e1b-4a0b-86d0-66d4b3f65220' - m_get_vm_moref_id.return_value = vm_moref_id - m_get_vm_resource_id.return_value = 'ac87622f-b761-40a0-b151-00872a2a456e' - m_create_alarm_notification_rule.return_value = 'f37900e7-dd01-4383-b84c-08f519530d71' - - # Call configure_alarm method under test - return_value = self.mon_plugin.configure_alarm(config_dict) - - # Verify that mocked methods are called with correct parameters - self.assertEqual(m_get_default_Params.call_count, 2) - m_get_alarm_defination_by_name.assert_called_with(vrops_alarm_name) - m_create_symptom.assert_called_with(symptom_params) - m_create_alarm_definition.assert_called_with(alarm_params) - m_get_vm_moref_id.assert_called_with(config_dict['resource_uuid']) - m_get_vm_resource_id.assert_called_with(vm_moref_id) - m_create_alarm_notification_rule.assert_called_with(vrops_alarm_name, - alarm_def, - resource_id) - m_save_alarm.assert_called_with(vrops_alarm_name, '1', - config_dict['threshold_value'], - config_dict['operation'], - config_dict['metric_name'], - config_dict['vdu_name'], - config_dict['vnf_member_index'], - config_dict['ns_id']) - - # Verify return value with expected value of alarm_def_uuid - self.assertEqual(return_value, alarm_def_uuid) - - @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') - @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') - @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') - @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') - def test_configure_alarm_invalid_alarm_name_req(self, m_get_default_Params, - m_get_alarm_defination_by_name, - m_create_symptom, - m_create_alarm_definition, - m_get_vm_moref_id, - m_get_vm_resource_id, - m_create_alarm_notification_rule, - m_save_alarm): - """Test configure alarm invalid test: for invalid alarm name""" - - # Mock input configuration dictionary - config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', - 'alarm_name': 'CPU_Utilization_Above_Threshold', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'statistic': 'AVERAGE', 'metric_name': 'CPU_UTILIZATION', - 'operation': 'GT', 'unit': '%', - 'description': 'CPU_Utilization_Above_Threshold'} - - alarm_def_uuid = None - - # Mock default Parameters return value to None - m_get_default_Params.return_value = {} - - # Call configure_alarm method under test - return_value = self.mon_plugin.configure_alarm(config_dict) - - # Verify that mocked methods are called with correct parameters - m_get_default_Params.assert_called_with(config_dict['alarm_name']) - m_get_alarm_defination_by_name.assert_not_called() - m_create_symptom.assert_not_called() - m_create_alarm_definition.assert_not_called() - m_get_vm_moref_id.assert_not_called() - m_get_vm_resource_id.assert_not_called() - m_create_alarm_notification_rule.assert_not_called() - m_save_alarm.assert_not_called() - - # Verify return value with expected value i.e. None - self.assertEqual(return_value, alarm_def_uuid) - - @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') - @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') - @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') - @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') - def test_configure_alarm_invalid_metric_name_req(self, m_get_default_Params, - m_get_alarm_defination_by_name, - m_create_symptom, - m_create_alarm_definition, - m_get_vm_moref_id, - m_get_vm_resource_id, - m_create_alarm_notification_rule, - m_save_alarm): - """Test configure alarm invalid test: for invalid metric name""" - - # Mock input configuration dictionary - config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', - 'alarm_name': 'CPU_Utilization_Above_Threshold', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'statistic': 'AVERAGE', 'metric_name': 'CPU_UTILIZATION', - 'operation': 'GT', 'unit': '%', - 'description': 'CPU_Utilization_Above_Threshold'} - - alarm_def_uuid = None - - # Mock default Parameters return values for metrics to None - m_get_default_Params.side_effect = [{'impact': 'risk', 'cancel_cycles': 1, - 'adapter_kind': 'VMWARE', 'repeat': False, - 'cancel_period': 300, 'alarm_type': 16, - 'vrops_alarm': 'CPU_Utilization_Above_Thr', - 'enabled': True, 'period': 300, - 'resource_kind': 'VirtualMachine', - 'alarm_subType': 19, 'action': 'acknowledge', - 'evaluation': 1, 'unit': 'msec'}, - {} - ] - - # Call configure_alarm method under test - return_value = self.mon_plugin.configure_alarm(config_dict) - - # Verify that mocked methods are called with correct parameters - self.assertEqual(m_get_default_Params.call_count, 2) - m_get_alarm_defination_by_name.assert_not_called() - m_create_symptom.assert_not_called() - m_create_alarm_definition.assert_not_called() - m_get_vm_moref_id.assert_not_called() - m_get_vm_resource_id.assert_not_called() - m_create_alarm_notification_rule.assert_not_called() - m_save_alarm.assert_not_called() - - # Verify return value with expected value i.e. None - self.assertEqual(return_value, alarm_def_uuid) - - @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') - @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') - @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') - @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') - def test_configure_alarm_invalid_already_exists(self, m_get_default_Params, - m_get_alarm_defination_by_name, - m_create_symptom, - m_create_alarm_definition, - m_get_vm_moref_id, - m_get_vm_resource_id, - m_create_alarm_notification_rule, - m_save_alarm): - """Test configure alarm invalid test: for alarm that already exists""" - - # Mock input configuration dictionary - config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', - 'alarm_name': 'CPU_Utilization_Above_Threshold', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'statistic': 'AVERAGE', 'metric_name': 'CPU_UTILIZATION', - 'operation': 'GT', 'unit': '%', - 'description': 'CPU_Utilization_Above_Threshold'} - - vrops_alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - alarm_def_uuid = None - - # Mock default Parameters for alarm & metric configuration - m_get_default_Params.side_effect = [{'impact': 'risk', 'cancel_cycles': 1, - 'adapter_kind': 'VMWARE', 'repeat': False, - 'cancel_period': 300, 'alarm_type': 16, - 'vrops_alarm': 'CPU_Utilization_Above_Thr', - 'enabled': True, 'period': 300, - 'resource_kind': 'VirtualMachine', - 'alarm_subType': 19, 'action': 'acknowledge', - 'evaluation': 1, 'unit': 'msec'}, - {'metric_key': 'cpu|usage_average', 'unit': '%'} - ] - # set mocked function return value - m_get_alarm_defination_by_name.return_value = ['mocked_alarm_CPU_Utilization_Above_Thr'] - - # Call configure_alarm method under test - return_value = self.mon_plugin.configure_alarm(config_dict) - - # Verify that mocked methods are called with correct parameters - self.assertEqual(m_get_default_Params.call_count, 2) - m_get_alarm_defination_by_name.assert_called_with(vrops_alarm_name) - m_create_symptom.assert_not_called() - m_create_alarm_definition.assert_not_called() - m_get_vm_moref_id.assert_not_called() - m_get_vm_resource_id.assert_not_called() - m_create_alarm_notification_rule.assert_not_called() - m_save_alarm.assert_not_called() - # Verify return value with expected value of alarm_def_uuid - self.assertEqual(return_value, alarm_def_uuid) - - @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') - @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') - @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') - @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') - def test_configure_alarm_failed_symptom_creation(self, m_get_default_Params, - m_get_alarm_defination_by_name, - m_create_symptom, - m_create_alarm_definition, - m_get_vm_moref_id, - m_get_vm_resource_id, - m_create_alarm_notification_rule, - m_save_alarm): - """Test configure alarm: failed to create symptom""" - - # Mock input configuration dictionary - config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', - 'alarm_name': 'CPU_Utilization_Above_Threshold', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'statistic': 'AVERAGE', 'metric_name': 'CPU_UTILIZATION', - 'operation': 'GT', 'unit': '%', - 'description': 'CPU_Utilization_Above_Threshold'} - - # symptom parameters to be passed for symptom creation - symptom_params = {'threshold_value': 0, - 'cancel_cycles': 1, - 'adapter_kind_key': 'VMWARE', - 'resource_kind_key': 'VirtualMachine', - 'severity': 'CRITICAL', - 'symptom_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'operation': 'GT', - 'wait_cycles': 1, - 'metric_key': 'cpu|usage_average'} - vrops_alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - alarm_def_uuid = None - - # Mock default Parameters for alarm & metric configuration - m_get_default_Params.side_effect = [{'impact': 'risk', 'cancel_cycles': 1, - 'adapter_kind': 'VMWARE', 'repeat': False, - 'cancel_period': 300, 'alarm_type': 16, - 'vrops_alarm': 'CPU_Utilization_Above_Thr', - 'enabled': True, 'period': 300, - 'resource_kind': 'VirtualMachine', - 'alarm_subType': 19, 'action': 'acknowledge', - 'evaluation': 1, 'unit': 'msec'}, - {'metric_key': 'cpu|usage_average', 'unit': '%'} - ] - # set mocked function return values - m_get_alarm_defination_by_name.return_value = [] - m_create_symptom.return_value = None - - # Call configure_alarm method under test - return_value = self.mon_plugin.configure_alarm(config_dict) - - # Verify that mocked methods are called with correct parameters - self.assertEqual(m_get_default_Params.call_count, 2) - m_get_alarm_defination_by_name.assert_called_with(vrops_alarm_name) - m_create_symptom.assert_called_with(symptom_params) - m_create_alarm_definition.assert_not_called() - m_get_vm_moref_id.assert_not_called() - m_get_vm_resource_id.assert_not_called() - m_create_alarm_notification_rule.assert_not_called() - m_save_alarm.assert_not_called() - - # Verify return value with expected value of alarm_def_uuid - self.assertEqual(return_value, alarm_def_uuid) - - @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') - @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') - @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') - @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') - def test_configure_alarm_failed_alert_creation(self, m_get_default_Params, - m_get_alarm_defination_by_name, - m_create_symptom, - m_create_alarm_definition, - m_get_vm_moref_id, - m_get_vm_resource_id, - m_create_alarm_notification_rule, - m_save_alarm): - """Test configure alarm: failed to create alert in vROPs""" - - # Mock input configuration dictionary - config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', - 'alarm_name': 'CPU_Utilization_Above_Threshold', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'statistic': 'AVERAGE', 'metric_name': 'CPU_UTILIZATION', - 'operation': 'GT', 'unit': '%', - 'description': 'CPU_Utilization_Above_Threshold'} - - # symptom parameters to be passed for symptom creation - symptom_params = {'threshold_value': 0, - 'cancel_cycles': 1, - 'adapter_kind_key': 'VMWARE', - 'resource_kind_key': 'VirtualMachine', - 'severity': 'CRITICAL', - 'symptom_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'operation': 'GT', - 'wait_cycles': 1, - 'metric_key': 'cpu|usage_average'} - - # alarm parameters to be passed for alarm creation - alarm_params = {'description': 'CPU_Utilization_Above_Threshold', - 'cancelCycles': 1, 'subType': 19, - 'waitCycles': 1, 'severity': 'CRITICAL', - 'impact': 'risk', 'adapterKindKey': 'VMWARE', - 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'resourceKindKey': 'VirtualMachine', - 'symptomDefinitionId': 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804', - 'type': 16} - - vrops_alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - alarm_def_uuid = None - - # Mock default Parameters for alarm & metric configuration - m_get_default_Params.side_effect = [{'impact': 'risk', 'cancel_cycles': 1, - 'adapter_kind': 'VMWARE', 'repeat': False, - 'cancel_period': 300, 'alarm_type': 16, - 'vrops_alarm': 'CPU_Utilization_Above_Thr', - 'enabled': True, 'period': 300, - 'resource_kind': 'VirtualMachine', - 'alarm_subType': 19, 'action': 'acknowledge', - 'evaluation': 1, 'unit': 'msec'}, - {'metric_key': 'cpu|usage_average', 'unit': '%'} - ] - # set mocked function return values - m_get_alarm_defination_by_name.return_value = [] - m_create_symptom.return_value = 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804' - m_create_alarm_definition.return_value = None - - # Call configure_alarm method under test - return_value = self.mon_plugin.configure_alarm(config_dict) - - # Verify that mocked methods are called with correct parameters - self.assertEqual(m_get_default_Params.call_count, 2) - m_get_alarm_defination_by_name.assert_called_with(vrops_alarm_name) - m_create_symptom.assert_called_with(symptom_params) - m_create_alarm_definition.assert_called_with(alarm_params) - m_get_vm_moref_id.assert_not_called() - m_get_vm_resource_id.assert_not_called() - m_create_alarm_notification_rule.assert_not_called() - m_save_alarm.assert_not_called() - - # Verify return value with expected value of alarm_def_uuid - self.assertEqual(return_value, alarm_def_uuid) - - @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') - @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') - @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') - @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') - def test_configure_alarm_failed_to_get_vm_moref_id(self, m_get_default_Params, - m_get_alarm_defination_by_name, - m_create_symptom, - m_create_alarm_definition, - m_get_vm_moref_id, - m_get_vm_resource_id, - m_create_alarm_notification_rule, - m_save_alarm): - """Test configure alarm: failed to get vm_moref_id""" - - # Mock input configuration dictionary - config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', - 'alarm_name': 'CPU_Utilization_Above_Threshold', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'statistic': 'AVERAGE', 'metric_name': 'CPU_UTILIZATION', - 'operation': 'GT', 'unit': '%', - 'description': 'CPU_Utilization_Above_Threshold'} - - # symptom parameters to be passed for symptom creation - symptom_params = {'threshold_value': 0, - 'cancel_cycles': 1, - 'adapter_kind_key': 'VMWARE', - 'resource_kind_key': 'VirtualMachine', - 'severity': 'CRITICAL', - 'symptom_name': \ - 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'operation': 'GT', - 'wait_cycles': 1, - 'metric_key': 'cpu|usage_average'} - - # alarm parameters to be passed for alarm creation - alarm_params = {'description': 'CPU_Utilization_Above_Threshold', - 'cancelCycles': 1, 'subType': 19, - 'waitCycles': 1, 'severity': 'CRITICAL', - 'impact': 'risk', 'adapterKindKey': 'VMWARE', - 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'resourceKindKey': 'VirtualMachine', - 'symptomDefinitionId': \ - 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804', - 'type': 16} - - vrops_alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - alarm_def_uuid = None - - # Mock default Parameters for alarm & metric configuration - m_get_default_Params.side_effect = [{'impact': 'risk', 'cancel_cycles': 1, - 'adapter_kind': 'VMWARE', 'repeat': False, - 'cancel_period': 300, 'alarm_type': 16, - 'vrops_alarm': 'CPU_Utilization_Above_Thr', - 'enabled': True, 'period': 300, - 'resource_kind': 'VirtualMachine', - 'alarm_subType': 19, 'action': 'acknowledge', - 'evaluation': 1, 'unit': 'msec'}, - {'metric_key': 'cpu|usage_average', 'unit': '%'} - ] - # set mocked function return values - m_get_alarm_defination_by_name.return_value = [] - m_create_symptom.return_value = 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804' - m_create_alarm_definition.return_value = \ - 'AlertDefinition-0f3cdcb3-4e1b-4a0b-86d0-66d4b3f65220' - m_get_vm_moref_id.return_value = None - - # Call configure_alarm method under test - return_value = self.mon_plugin.configure_alarm(config_dict) - - # Verify that mocked methods are called with correct parameters - self.assertEqual(m_get_default_Params.call_count, 2) - m_get_alarm_defination_by_name.assert_called_with(vrops_alarm_name) - m_create_symptom.assert_called_with(symptom_params) - m_create_alarm_definition.assert_called_with(alarm_params) - m_get_vm_moref_id.assert_called_with(config_dict['resource_uuid']) - m_get_vm_resource_id.assert_not_called() - m_create_alarm_notification_rule.assert_not_called() - m_save_alarm.assert_not_called() - - # Verify return value with expected value of alarm_def_uuid - self.assertEqual(return_value, alarm_def_uuid) - - @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') - @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') - @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') - @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') - def test_configure_alarm_failed_to_get_vm_resource_id(self, m_get_default_Params, - m_get_alarm_defination_by_name, - m_create_symptom, - m_create_alarm_definition, - m_get_vm_moref_id, - m_get_vm_resource_id, - m_create_alarm_notification_rule, - m_save_alarm): - """Test configure alarm: failed to get vm resource_id""" - - # Mock input configuration dictionary - config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', - 'alarm_name': 'CPU_Utilization_Above_Threshold', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'statistic': 'AVERAGE', 'metric_name': 'CPU_UTILIZATION', - 'operation': 'GT', 'unit': '%', - 'description': 'CPU_Utilization_Above_Threshold'} - - # symptom parameters to be passed for symptom creation - symptom_params = {'threshold_value': 0, - 'cancel_cycles': 1, - 'adapter_kind_key': 'VMWARE', - 'resource_kind_key': 'VirtualMachine', - 'severity': 'CRITICAL', - 'symptom_name': \ - 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'operation': 'GT', - 'wait_cycles': 1, - 'metric_key': 'cpu|usage_average'} - - # alarm parameters to be passed for alarm creation - alarm_params = {'description': 'CPU_Utilization_Above_Threshold', - 'cancelCycles': 1, 'subType': 19, - 'waitCycles': 1, 'severity': 'CRITICAL', - 'impact': 'risk', 'adapterKindKey': 'VMWARE', - 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'resourceKindKey': 'VirtualMachine', - 'symptomDefinitionId': \ - 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804', - 'type': 16} - - vrops_alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - vm_moref_id = 'vm-6626' - alarm_def_uuid = None - - # Mock default Parameters for alarm & metric configuration - m_get_default_Params.side_effect = [{'impact': 'risk', 'cancel_cycles': 1, - 'adapter_kind': 'VMWARE', 'repeat': False, - 'cancel_period': 300, 'alarm_type': 16, - 'vrops_alarm': 'CPU_Utilization_Above_Thr', - 'enabled': True, 'period': 300, - 'resource_kind': 'VirtualMachine', - 'alarm_subType': 19, 'action': 'acknowledge', - 'evaluation': 1, 'unit': 'msec'}, - {'metric_key': 'cpu|usage_average', 'unit': '%'} - ] - # set mocked function return values - m_get_alarm_defination_by_name.return_value = [] - m_create_symptom.return_value = 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804' - m_create_alarm_definition.return_value = \ - 'AlertDefinition-0f3cdcb3-4e1b-4a0b-86d0-66d4b3f65220' - m_get_vm_moref_id.return_value = vm_moref_id - m_get_vm_resource_id.return_value = None - m_save_alarm.assert_not_called() - - # Call configure_alarm method under test - return_value = self.mon_plugin.configure_alarm(config_dict) - - # Verify that mocked methods are called with correct parameters - self.assertEqual(m_get_default_Params.call_count, 2) - m_get_alarm_defination_by_name.assert_called_with(vrops_alarm_name) - m_create_symptom.assert_called_with(symptom_params) - m_create_alarm_definition.assert_called_with(alarm_params) - m_get_vm_moref_id.assert_called_with(config_dict['resource_uuid']) - m_get_vm_resource_id.assert_called_with(vm_moref_id) - m_create_alarm_notification_rule.assert_not_called() - - # Verify return value with expected value of alarm_def_uuid - self.assertEqual(return_value, alarm_def_uuid) - - @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') - @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') - @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') - @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') - @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') - def test_configure_alarm_failed_to_create_alarm_notification_rule(self, m_get_default_Params, - m_get_alarm_defination_by_name, - m_create_symptom, - m_create_alarm_definition, - m_get_vm_moref_id, - m_get_vm_resource_id, - m_create_alarm_notification_rule, - m_save_alarm): - """Test configure alarm: failed to create alarm notification rule""" - - # Mock input configuration dictionary - config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', - 'alarm_name': 'CPU_Utilization_Above_Threshold', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'statistic': 'AVERAGE', 'metric_name': 'CPU_UTILIZATION', - 'operation': 'GT', 'unit': '%', - 'description': 'CPU_Utilization_Above_Threshold'} - - # symptom parameters to be passed for symptom creation - symptom_params = {'threshold_value': 0, - 'cancel_cycles': 1, - 'adapter_kind_key': 'VMWARE', - 'resource_kind_key': 'VirtualMachine', - 'severity': 'CRITICAL', - 'symptom_name': \ - 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'operation': 'GT', - 'wait_cycles': 1, - 'metric_key': 'cpu|usage_average'} - - # alarm parameters to be passed for alarm creation - alarm_params = {'description': 'CPU_Utilization_Above_Threshold', - 'cancelCycles': 1, 'subType': 19, - 'waitCycles': 1, 'severity': 'CRITICAL', - 'impact': 'risk', 'adapterKindKey': 'VMWARE', - 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'resourceKindKey': 'VirtualMachine', - 'symptomDefinitionId': \ - 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804', - 'type': 16} - - vrops_alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - vm_moref_id = 'vm-6626' - alarm_def = 'AlertDefinition-0f3cdcb3-4e1b-4a0b-86d0-66d4b3f65220' - resource_id = 'ac87622f-b761-40a0-b151-00872a2a456e' - alarm_def_uuid = None - - # Mock default Parameters for alarm & metric configuration - m_get_default_Params.side_effect = [{'impact': 'risk', 'cancel_cycles': 1, - 'adapter_kind': 'VMWARE', 'repeat': False, - 'cancel_period': 300, 'alarm_type': 16, - 'vrops_alarm': 'CPU_Utilization_Above_Thr', - 'enabled': True, 'period': 300, - 'resource_kind': 'VirtualMachine', - 'alarm_subType': 19, 'action': 'acknowledge', - 'evaluation': 1, 'unit': 'msec'}, - {'metric_key': 'cpu|usage_average', 'unit': '%'} - ] - # set mocked function return values - m_get_alarm_defination_by_name.return_value = [] - m_create_symptom.return_value = 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804' - m_create_alarm_definition.return_value = \ - 'AlertDefinition-0f3cdcb3-4e1b-4a0b-86d0-66d4b3f65220' - m_get_vm_moref_id.return_value = vm_moref_id - m_get_vm_resource_id.return_value = 'ac87622f-b761-40a0-b151-00872a2a456e' - m_create_alarm_notification_rule.return_value = None - - # Call configure_alarm method under test - return_value = self.mon_plugin.configure_alarm(config_dict) - - # Verify that mocked methods are called with correct parameters - self.assertEqual(m_get_default_Params.call_count, 2) - m_get_alarm_defination_by_name.assert_called_with(vrops_alarm_name) - m_create_symptom.assert_called_with(symptom_params) - m_create_alarm_definition.assert_called_with(alarm_params) - m_get_vm_moref_id.assert_called_with(config_dict['resource_uuid']) - m_get_vm_resource_id.assert_called_with(vm_moref_id) - m_create_alarm_notification_rule.assert_called_with(vrops_alarm_name, alarm_def, resource_id) - m_save_alarm.assert_not_called() - - # Verify return value with expected value of alarm_def_uuid - self.assertEqual(return_value, alarm_def_uuid) - - @mock.patch.object(monPlugin.requests, 'get') - def test_get_alarm_defination_details_valid_rest_req_response(self, m_get): - """Test get_alarm_defination_details: For a valid REST request response""" - - alarm_uuid = '9a6d8a14-9f25-4d81-bf91-4d773497444d' - - # Set mocked function's return values - m_get.return_value.status_code = 200 - m_get.return_value.content = '{"id":"AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d",\ - "name":"CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ - "description":"CPU_Utilization_Above_Threshold",\ - "adapterKindKey":"VMWARE","resourceKindKey":"VirtualMachine",\ - "waitCycles":1,"cancelCycles":1,"type":16,"subType":19,\ - "states":[{"severity":"CRITICAL","base-symptom-set":\ - {"type":"SYMPTOM_SET","relation":"SELF",\ - "aggregation":"ALL","symptomSetOperator":"AND","symptomDefinitionIds":\ - ["SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278"]},\ - "impact":{"impactType":"BADGE","detail":"risk"}}]}' - - expected_alarm_details = {'adapter_kind': 'VMWARE', 'symptom_definition_id': \ - 'SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278', - 'alarm_name': \ - 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'alarm_id': 'AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d', - 'resource_kind': 'VirtualMachine', 'type': 16, 'sub_type': 19} - - expected_alarm_details_json = {'states': - [{'impact': - {'impactType': 'BADGE', 'detail': 'risk'}, 'severity': 'CRITICAL', - 'base-symptom-set': {'symptomDefinitionIds': \ - [ - 'SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278'], - 'relation': 'SELF', 'type': 'SYMPTOM_SET', - 'aggregation': 'ALL', 'symptomSetOperator': 'AND'}}], - 'adapterKindKey': 'VMWARE', - 'description': 'CPU_Utilization_Above_Threshold', - 'type': 16, 'cancelCycles': 1, - 'resourceKindKey': 'VirtualMachine', - 'subType': 19, 'waitCycles': 1, - 'id': 'AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d', - 'name': \ - 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4'} - - # Call get_alarm_defination_details method under test - alarm_details_json, alarm_details = self.mon_plugin.get_alarm_defination_details(alarm_uuid) - - # Verify that mocked method is called - m_get.assert_called() - - # Verify return value with expected value - self.assertEqual(expected_alarm_details, alarm_details) - self.assertEqual(expected_alarm_details_json, alarm_details_json) - - @mock.patch.object(monPlugin.requests, 'get') - def test_get_alarm_defination_details_invalid_rest_req_response(self, m_get): - """Test get_alarm_defination_details: For an invalid REST request response""" - - alarm_uuid = '9a6d8a14-9f25-4d81-bf91-4d773497444d' - - # Set mocked function's return values - m_get.return_value.status_code = 404 - m_get.return_value.content = '{"message": "No such AlertDefinition - \ - AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444.",\ - "httpStatusCode": 404,"apiErrorCode": 404}' - - expected_alarm_details = None - expected_alarm_details_json = None - - # Call get_alarm_defination_details method under test - alarm_details_json, alarm_details = self.mon_plugin.get_alarm_defination_details(alarm_uuid) - - # verify that mocked method is called - m_get.assert_called() - - # Verify return value with expected value - self.assertEqual(expected_alarm_details, alarm_details) - self.assertEqual(expected_alarm_details_json, alarm_details_json) - - @mock.patch.object(monPlugin.requests, 'get') - def test_get_alarm_defination_by_name_valid_rest_req_response(self, m_get): - """Test get_alarm_defination_by_name: For a valid REST request response""" - - alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - - # Set mocked function's return values - m_get.return_value.status_code = 200 - m_get.return_value.content = '{"pageInfo": {"totalCount": 1,"page": 0,"pageSize": 1000},\ - "links": [\ - {"href": "/suite-api/api/alertdefinitions?page=0&pageSize=1000",\ - "rel": "SELF","name": "current"},\ - {"href": "/suite-api/api/alertdefinitions?page=0&pageSize=1000",\ - "rel": "RELATED","name": "first"},\ - {"href": "/suite-api/api/alertdefinitions?page=0&pageSize=1000",\ - "rel": "RELATED","name": "last"}],\ - "alertDefinitions": [{\ - "id": "AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d",\ - "name": "CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ - "description": "CPU_Utilization_Above_Threshold",\ - "adapterKindKey": "VMWARE","resourceKindKey": "VirtualMachine",\ - "waitCycles": 1,"cancelCycles": 1,"type": 16,"subType": 19,\ - "states": [{"impact": {"impactType": "BADGE","detail": "risk"},\ - "severity": "CRITICAL",\ - "base-symptom-set": {"type": "SYMPTOM_SET",\ - "relation": "SELF","aggregation": "ALL",\ - "symptomSetOperator": "AND",\ - "symptomDefinitionIds": [\ - "SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278"]}}]\ - }]}' - - # Expected return match list - Exp_alert_match_list = [{'states': - [{'impact': {'impactType': 'BADGE', 'detail': 'risk'}, - 'severity': 'CRITICAL', - 'base-symptom-set': { - 'symptomDefinitionIds': \ - ['SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278'], - 'relation': 'SELF', - 'type': 'SYMPTOM_SET', - 'aggregation': 'ALL', - 'symptomSetOperator': 'AND'} - }], - 'adapterKindKey': 'VMWARE', - 'description': 'CPU_Utilization_Above_Threshold', - 'type': 16, - 'cancelCycles': 1, - 'resourceKindKey': 'VirtualMachine', - 'subType': 19, 'waitCycles': 1, - 'id': 'AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d', - 'name': \ - 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - }] - - # Call get_alarm_defination_by_name method under test - alert_match_list = self.mon_plugin.get_alarm_defination_by_name(alarm_name) - - # Verify that mocked method is called - m_get.assert_called() - - # Verify return value with expected value - self.assertEqual(Exp_alert_match_list, alert_match_list) - - @mock.patch.object(monPlugin.requests, 'get') - def test_get_alarm_defination_by_name_no_valid_alarm_found(self, m_get): - """Test get_alarm_defination_by_name: With no valid alarm found in returned list""" - - alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda5' - - # Set mocked function's return values - m_get.return_value.status_code = 200 - m_get.return_value.content = '{"pageInfo": {"totalCount": 1,"page": 0,"pageSize": 1000},\ - "links": [\ - {"href": "/suite-api/api/alertdefinitions?page=0&pageSize=1000",\ - "rel": "SELF","name": "current"},\ - {"href": "/suite-api/api/alertdefinitions?page=0&pageSize=1000",\ - "rel": "RELATED","name": "first"},\ - {"href": "/suite-api/api/alertdefinitions?page=0&pageSize=1000",\ - "rel": "RELATED","name": "last"}],\ - "alertDefinitions": [{\ - "id": "AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d",\ - "name": "CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ - "description": "CPU_Utilization_Above_Threshold",\ - "adapterKindKey": "VMWARE","resourceKindKey": "VirtualMachine",\ - "waitCycles": 1,"cancelCycles": 1,"type": 16,"subType": 19,\ - "states": [{"impact": {"impactType": "BADGE","detail": "risk"},\ - "severity": "CRITICAL",\ - "base-symptom-set": {"type": "SYMPTOM_SET",\ - "relation": "SELF","aggregation": "ALL",\ - "symptomSetOperator": "AND",\ - "symptomDefinitionIds": [\ - "SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278"]}}]\ - }]}' - - # Expected return match list - Exp_alert_match_list = [] - - # Call get_alarm_defination_by_name method under test - alert_match_list = self.mon_plugin.get_alarm_defination_by_name(alarm_name) - - # Verify that mocked method is called - m_get.assert_called() - - # Verify return value with expected value - self.assertEqual(Exp_alert_match_list, alert_match_list) - - @mock.patch.object(monPlugin.requests, 'put') - @mock.patch.object(monPlugin.MonPlugin, 'get_symptom_defination_details') - def test_update_symptom_defination_valid_symptom_req_response(self, - m_get_symptom_defination_details, - m_put): - """Test update_symptom_defination: With valid REST response, update symptom""" - - # Expected symptom to be updated - symptom_defination_id = 'SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278' - new_alarm_config = {'severity': "CRITICAL", - 'operation': 'GT', - 'threshold_value': 5, - 'alarm_uuid': '9a6d8a14-9f25-4d81-bf91-4d773497444d' - } - - # Set mocked function's return values - m_get_symptom_defination_details.return_value = { - "id": "SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278", - "name": "CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4", - "adapterKindKey": "VMWARE", - "resourceKindKey": "VirtualMachine", - "waitCycles": 1, - "cancelCycles": 1, - "state": {"severity": "CRITICAL", - "condition": { - "type": "CONDITION_HT", - "key": "cpu|usage_average", "operator": "GT", "value": "0.0", - "valueType": "NUMERIC", "instanced": False, - "thresholdType": "STATIC"} - } - } - - m_put.return_value.status_code = 200 - m_put.return_value.content = '{\ - "id":"SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278",\ - "name":"CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ - "adapterKindKey":"VMWARE","resourceKindKey":"VirtualMachine","waitCycles":1,\ - "cancelCycles":1,\ - "state":{\ - "severity":"CRITICAL",\ - "condition":{\ - "type":"CONDITION_HT","key":"cpu|usage_average","operator":"GT","value":"5.0",\ - "valueType":"NUMERIC","instanced":False,"thresholdType":"STATIC"}}}' - - # Call update_symptom_defination method under test - symptom_uuid = self.mon_plugin.update_symptom_defination(symptom_defination_id, - new_alarm_config) - - # Verify that mocked method is called with required parameters - m_get_symptom_defination_details.assert_called_with(symptom_defination_id) - # m_put.assert_called_with(symptom_defination_id,new_alarm_config) - - # Verify return value with expected value - self.assertEqual(symptom_defination_id, symptom_uuid) - - @mock.patch.object(monPlugin.requests, 'put') - @mock.patch.object(monPlugin.MonPlugin, 'get_symptom_defination_details') - def test_update_symptom_defination_invalid_symptom_req_response(self, - m_get_symptom_defination_details, - m_put): - """Test update_symptom_defination: If invalid REST response received, return None""" - - # Expected symptom to be updated - symptom_defination_id = 'SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278' - new_alarm_config = {'severity': "CRITICAL", - 'operation': 'GT', - 'threshold_value': 5, - 'alarm_uuid': '9a6d8a14-9f25-4d81-bf91-4d773497444d' - } - - # Set mocked function's return values - m_get_symptom_defination_details.return_value = { - "id": "SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278", - "name": "CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4", - "adapterKindKey": "VMWARE", - "resourceKindKey": "VirtualMachine", - "waitCycles": 1, - "cancelCycles": 1, - "state": {"severity": "CRITICAL", - "condition": { - "type": "CONDITION_HT", - "key": "cpu|usage_average", "operator": "GT", "value": "0.0", - "valueType": "NUMERIC", "instanced": False, - "thresholdType": "STATIC"} - } - } - - m_put.return_value.status_code = 500 - m_put.return_value.content = '{\ - "message": "Internal Server error, cause unknown.",\ - "moreInformation": [\ - {"name": "errorMessage",\ - "value": "Symptom Definition CPU_Utilization_Above_Thr-e14b203c-\ - 6bf2-4e2f-a91c-8c19d240eda4 does not exist and hence cannot be updated."},\ - {"name": "localizedMessage",\ - "value": "Symptom Definition CPU_Utilization_Above_Thr-e14b203c-\ - 6bf2-4e2f-a91c-8c19d240eda4 does not exist and hence cannot be updated.;"}],\ - "httpStatusCode": 500,"apiErrorCode": 500}' - - # Call update_symptom_defination method under test - symptom_uuid = self.mon_plugin.update_symptom_defination(symptom_defination_id, - new_alarm_config) - - # Verify that mocked method is called with required parameters - m_get_symptom_defination_details.assert_called_with(symptom_defination_id) - m_put.assert_called() - - # Verify return value with expected value - self.assertEqual(symptom_uuid, None) - - @mock.patch.object(monPlugin.requests, 'put') - @mock.patch.object(monPlugin.MonPlugin, 'get_symptom_defination_details') - def test_update_symptom_defination_failed_to_get_symptom_defination(self, - m_get_symptom_defination_details, - m_put): - """Test update_symptom_defination: if fails to get symptom_defination returns None""" - - # Expected symptom to be updated - symptom_defination_id = 'SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278' - new_alarm_config = {'severity': "CRITICAL", - 'operation': 'GT', - 'threshold_value': 5, - 'alarm_uuid': '9a6d8a14-9f25-4d81-bf91-4d773497444d' - } - - # Set mocked function's return values - m_get_symptom_defination_details.return_value = None - - # Call update_symptom_defination method under test - symptom_uuid = self.mon_plugin.update_symptom_defination(symptom_defination_id, - new_alarm_config) - - # Verify that mocked method is called with required parameters - m_get_symptom_defination_details.assert_called_with(symptom_defination_id) - m_put.assert_not_called() - - # Verify return value with expected value - self.assertEqual(symptom_uuid, None) - - @mock.patch.object(monPlugin.requests, 'get') - def test_get_symptom_defination_details_valid_req_response(self, m_get): - """Test update_symptom_defination: With valid REST response symptom is created""" - - # Expected symptom to be updated - symptom_uuid = 'SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278' - - # Set mocked function's return values - m_get.return_value.status_code = 200 - m_get.return_value.content = '{\ - "id": "SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278",\ - "name": "CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ - "adapterKindKey": "VMWARE","resourceKindKey": "VirtualMachine","waitCycles": 1,\ - "cancelCycles": 1,"state": {"severity": "CRITICAL","condition": {"type": "CONDITION_HT",\ - "key": "cpu|usage_average","operator": "GT","value": "6.0","valueType": "NUMERIC",\ - "instanced": false,"thresholdType": "STATIC"}}}' - expected_symptom_details = { \ - "id": "SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278", - "name": "CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4", - "adapterKindKey": "VMWARE", "resourceKindKey": "VirtualMachine", "waitCycles": 1, - "cancelCycles": 1, "state": {"severity": "CRITICAL", "condition": {"type": "CONDITION_HT", - "key": "cpu|usage_average", - "operator": "GT", "value": "6.0", - "valueType": "NUMERIC", - "instanced": False, - "thresholdType": "STATIC"}}} - - # Call update_symptom_defination method under test - symptom_details = self.mon_plugin.get_symptom_defination_details(symptom_uuid) - - # Verify that mocked method is called with required parameters - m_get.assert_called() - - # Verify return value with expected value - self.assertEqual(expected_symptom_details, symptom_details) - - @mock.patch.object(monPlugin.requests, 'get') - def test_get_symptom_defination_details_invalid_req_response(self, m_get): - """Test update_symptom_defination: if invalid REST response received return None""" - - # Expected symptom to be updated - symptom_uuid = 'SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278' - - # Set mocked function's return values - m_get.return_value.status_code = 404 - m_get.return_value.content = '{"message": "No such SymptomDefinition\ - - SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278.",\ - "httpStatusCode": 404,"apiErrorCode": 404}' - - expected_symptom_details = None - - # Call update_symptom_defination method under test - symptom_details = self.mon_plugin.get_symptom_defination_details(symptom_uuid) - - # Verify that mocked method is called with required parameters - m_get.assert_called() - - # Verify return value with expected value - self.assertEqual(expected_symptom_details, symptom_details) - - @mock.patch.object(monPlugin.requests, 'get') - def test_get_symptom_defination_details_symptom_uuid_not_provided(self, m_get): - """Test update_symptom_defination: if required symptom uuid is not provided""" - - # Expected symptom to be updated - symptom_uuid = None - expected_symptom_details = None - - # Call update_symptom_defination method under test - symptom_details = self.mon_plugin.get_symptom_defination_details(symptom_uuid) - - # Verify that mocked method is called with required parameters - m_get.assert_not_called() - - # Verify return value with expected value - self.assertEqual(expected_symptom_details, symptom_details) - - @mock.patch.object(monPlugin.requests, 'put') - def test_reconfigure_alarm_valid_req_response(self, m_put): - """Test reconfigure_alarm: for valid REST response""" - - # Set input parameters to reconfigure_alarm - alarm_details_json = { - 'id': 'AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d', - 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'description': 'CPU_Utilization_Above_Threshold', 'adapterKindKey': 'VMWARE', - 'states': [{'impact': {'impactType': 'BADGE', 'detail': 'risk'}, 'severity': 'CRITICAL', - 'base-symptom-set': { - 'symptomDefinitionIds': ['SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278'], - 'relation': 'SELF', 'type': 'SYMPTOM_SET', 'aggregation': 'ALL', - 'symptomSetOperator': 'AND'}}], - 'type': 16, 'cancelCycles': 1, 'resourceKindKey': 'VirtualMachine', 'subType': 19, - 'waitCycles': 1} - - new_alarm_config = {'severity': 'WARNING', - 'description': 'CPU_Utilization_Above_Threshold_Warning'} - - # Set mocked function's return values - m_put.return_value.status_code = 200 - m_put.return_value.content = '{"id":"AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d",\ - "name":"CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ - "description":"CPU_Utilization_Above_Threshold_Warning","adapterKindKey":"VMWARE",\ - "resourceKindKey":"VirtualMachine","waitCycles":1,"cancelCycles":1,"type":16,\ - "subType":19,"states":[{"severity":"WARNING","base-symptom-set":{"type":"SYMPTOM_SET",\ - "relation":"SELF","aggregation":"ALL","symptomSetOperator":"AND",\ - "symptomDefinitionIds":["SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278"]},\ - "impact":{"impactType":"BADGE","detail":"risk"}}]}' - - # Expected alarm_def_uuid to be returned - expected_alarm_def_uuid = '9a6d8a14-9f25-4d81-bf91-4d773497444d' - - # Call reconfigure_alarm method under test - alarm_def_uuid = self.mon_plugin.reconfigure_alarm(alarm_details_json, new_alarm_config) - - # Verify that mocked method is called with required parameters - m_put.assert_called() - - # Verify return value with expected value - self.assertEqual(expected_alarm_def_uuid, alarm_def_uuid) - - @mock.patch.object(monPlugin.requests, 'put') - def test_reconfigure_alarm_invalid_req_response(self, m_put): - """Test reconfigure_alarm: for invalid REST response, return None""" - - # Set input parameters to reconfigure_alarm - alarm_details_json = { - 'id': 'AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d', - 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'description': 'CPU_Utilization_Above_Threshold', 'adapterKindKey': 'VMWARE', - 'states': [{'impact': {'impactType': 'BADGE', 'detail': 'risk'}, 'severity': 'CRITICAL', - 'base-symptom-set': { - 'symptomDefinitionIds': ['SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278'], - 'relation': 'SELF', 'type': 'SYMPTOM_SET', 'aggregation': 'ALL', - 'symptomSetOperator': 'AND'}}], - 'type': 16, 'cancelCycles': 1, 'resourceKindKey': 'VirtualMachine', 'subType': 19, - 'waitCycles': 1} - - new_alarm_config = {'severity': 'WARNING', - 'description': 'CPU_Utilization_Above_Threshold_Warning'} - - # Set mocked function's return values - m_put.return_value.status_code = 500 - m_put.return_value.content = '{"message": "Internal Server error, cause unknown.",\ - "moreInformation": [{"name": "errorMessage",\ - "value": "Cannot update Alert Definition CPU_Utilization_Above_Thr-\ - e14b203c-6bf2-4e2f-a91c-8c19d240eda4 since it does not exist"},\ - {"name": "localizedMessage",\ - "value": "Cannot update Alert Definition CPU_Utilization_Above_Thr-\ - e14b203c-6bf2-4e2f-a91c-8c19d240eda4 since it does not exist;"}],\ - "httpStatusCode": 500,"apiErrorCode": 500}' - - # Expected alarm_def_uuid to be returned - expected_alarm_def_uuid = None - - # Call reconfigure_alarm method under test - alarm_def_uuid = self.mon_plugin.reconfigure_alarm(alarm_details_json, new_alarm_config) - - # Verify that mocked method is called with required parameters - m_put.assert_called() - - # Verify return value with expected value - self.assertEqual(expected_alarm_def_uuid, alarm_def_uuid) - - @mock.patch.object(monPlugin.MonPlugin, 'delete_symptom_definition') - @mock.patch.object(monPlugin.MonPlugin, 'delete_alarm_defination') - @mock.patch.object(monPlugin.MonPlugin, 'delete_notification_rule') - @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_details') - def test_delete_alarm_configuration_successful_alarm_deletion(self, - m_get_alarm_defination_details, - m_delete_notification_rule, - m_delete_alarm_defination, - m_delete_symptom_definition): - """Test delete_alarm_configuration: for successful alarm deletion, return alarm uuid""" - - # Set input parameters to delete_alarm_configuration - delete_alarm_req_dict = {'alarm_uuid': '9a6d8a14-9f25-4d81-bf91-4d773497444d'} - - # Set mocked function's return values - alarm_details_json = { - 'id': 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d', - 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4', - 'symptomDefinitionIds': ['SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278']} - alarm_details = { - 'alarm_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4', - 'alarm_id': 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d', - 'symptom_definition_id': 'SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278'} - - m_get_alarm_defination_details.return_value = (alarm_details_json, alarm_details) - m_delete_notification_rule.return_value = '989e7293-d78d-4405-92e30ec4f247' - m_delete_alarm_defination.return_value = alarm_details['alarm_id'] - m_delete_symptom_definition.return_value = alarm_details['symptom_definition_id'] - - # Call reconfigure_alarm method under test - alarm_uuid = self.mon_plugin.delete_alarm_configuration(delete_alarm_req_dict) - - # Verify that mocked method is called with required parameters - m_get_alarm_defination_details.assert_called_with(delete_alarm_req_dict['alarm_uuid']) - m_delete_notification_rule.assert_called_with(alarm_details['alarm_name']) - m_delete_alarm_defination.assert_called_with(alarm_details['alarm_id']) - m_delete_symptom_definition.assert_called_with(alarm_details['symptom_definition_id']) - - # Verify return value with expected value - self.assertEqual(alarm_uuid, delete_alarm_req_dict['alarm_uuid']) - - @mock.patch.object(monPlugin.MonPlugin, 'delete_symptom_definition') - @mock.patch.object(monPlugin.MonPlugin, 'delete_alarm_defination') - @mock.patch.object(monPlugin.MonPlugin, 'delete_notification_rule') - @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_details') - def test_delete_alarm_configuration_failed_to_get_alarm_defination(self, - m_get_alarm_defination_details, - m_delete_notification_rule, - m_delete_alarm_defination, - m_delete_symptom_definition): - """Test delete_alarm_configuration: if failed to get alarm definition, return None""" - - # Set input parameters to delete_alarm_configuration - delete_alarm_req_dict = {'alarm_uuid': '9a6d8a14-9f25-4d81-bf91-4d773497444d'} - - # Set mocked function's return values - alarm_details_json = None - alarm_details = None - - m_get_alarm_defination_details.return_value = (alarm_details_json, alarm_details) - - # Call reconfigure_alarm method under test - alarm_uuid = self.mon_plugin.delete_alarm_configuration(delete_alarm_req_dict) - - # Verify that mocked method is called with required parameters - m_get_alarm_defination_details.assert_called_with(delete_alarm_req_dict['alarm_uuid']) - m_delete_notification_rule.assert_not_called() - m_delete_alarm_defination.assert_not_called() - m_delete_symptom_definition.assert_not_called() - - # Verify return value with expected value - self.assertEqual(alarm_uuid, None) - - @mock.patch.object(monPlugin.MonPlugin, 'delete_symptom_definition') - @mock.patch.object(monPlugin.MonPlugin, 'delete_alarm_defination') - @mock.patch.object(monPlugin.MonPlugin, 'delete_notification_rule') - @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_details') - def test_delete_alarm_configuration_failed_to_delete_notification_rule(self, - m_get_alarm_defination_details, - m_delete_notification_rule, - m_delete_alarm_defination, - m_delete_symptom_definition): - """Test delete_alarm_configuration: if failed to delete notification rule, return None""" - - # Set input parameters to delete_alarm_configuration - delete_alarm_req_dict = {'alarm_uuid': '9a6d8a14-9f25-4d81-bf91-4d773497444d'} - - # Set mocked function's return values - alarm_details_json = { - 'id': 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d', - 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4', - 'symptomDefinitionIds': ['SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278']} - alarm_details = { - 'alarm_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4', - 'alarm_id': 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d', - 'symptom_definition_id': 'SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278'} - - m_get_alarm_defination_details.return_value = (alarm_details_json, alarm_details) - m_delete_notification_rule.return_value = None - - # Call reconfigure_alarm method under test - alarm_uuid = self.mon_plugin.delete_alarm_configuration(delete_alarm_req_dict) - - # Verify that mocked method is called with required parameters - m_get_alarm_defination_details.assert_called_with(delete_alarm_req_dict['alarm_uuid']) - m_delete_notification_rule.assert_called_with(alarm_details['alarm_name']) - m_delete_alarm_defination.assert_not_called() - m_delete_symptom_definition.assert_not_called() - - # Verify return value with expected value - self.assertEqual(alarm_uuid, None) - - @mock.patch.object(monPlugin.MonPlugin, 'delete_symptom_definition') - @mock.patch.object(monPlugin.MonPlugin, 'delete_alarm_defination') - @mock.patch.object(monPlugin.MonPlugin, 'delete_notification_rule') - @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_details') - def test_delete_alarm_configuration_failed_to_delete_alarm_defination(self, - m_get_alarm_defination_details, - m_delete_notification_rule, - m_delete_alarm_defination, - m_delete_symptom_definition): - """Test delete_alarm_configuration: if failed to delete alarm definition, return None""" - - # Set input parameters to delete_alarm_configuration - delete_alarm_req_dict = {'alarm_uuid': '9a6d8a14-9f25-4d81-bf91-4d773497444d'} - - # Set mocked function's return values - alarm_details_json = { - 'id': 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d', - 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4', - 'symptomDefinitionIds': ['SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278']} - alarm_details = { - 'alarm_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4', - 'alarm_id': 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d', - 'symptom_definition_id': 'SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278'} - - m_get_alarm_defination_details.return_value = (alarm_details_json, alarm_details) - m_delete_notification_rule.return_value = '989e7293-d78d-4405-92e30ec4f247' - m_delete_alarm_defination.return_value = None - - # Call reconfigure_alarm method under test - alarm_uuid = self.mon_plugin.delete_alarm_configuration(delete_alarm_req_dict) - - # Verify that mocked method is called with required parameters - m_get_alarm_defination_details.assert_called_with(delete_alarm_req_dict['alarm_uuid']) - m_delete_notification_rule.assert_called_with(alarm_details['alarm_name']) - m_delete_alarm_defination.assert_called_with(alarm_details['alarm_id']) - m_delete_symptom_definition.assert_not_called() - - # Verify return value with expected value - self.assertEqual(alarm_uuid, None) - - @mock.patch.object(monPlugin.MonPlugin, 'delete_symptom_definition') - @mock.patch.object(monPlugin.MonPlugin, 'delete_alarm_defination') - @mock.patch.object(monPlugin.MonPlugin, 'delete_notification_rule') - @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_details') - def test_delete_alarm_configuration_failed_to_delete_symptom_definition(self, - m_get_alarm_defination_details, - m_delete_notification_rule, - m_delete_alarm_defination, - m_delete_symptom_definition): - """Test delete_alarm_configuration: if failed to delete symptom definition, return None""" - - # Set input parameters to delete_alarm_configuration - delete_alarm_req_dict = {'alarm_uuid': '9a6d8a14-9f25-4d81-bf91-4d773497444d'} - - # Set mocked function's return values - alarm_details_json = { - 'id': 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d', - 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4', - 'symptomDefinitionIds': ['SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278']} - alarm_details = { - 'alarm_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4', - 'alarm_id': 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d', - 'symptom_definition_id': 'SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278'} - - m_get_alarm_defination_details.return_value = (alarm_details_json, alarm_details) - m_delete_notification_rule.return_value = '989e7293-d78d-4405-92e30ec4f247' - m_delete_alarm_defination.return_value = alarm_details['alarm_id'] - m_delete_symptom_definition.return_value = None - - # Call reconfigure_alarm method under test - alarm_uuid = self.mon_plugin.delete_alarm_configuration(delete_alarm_req_dict) - - # Verify that mocked method is called with required parameters - m_get_alarm_defination_details.assert_called_with(delete_alarm_req_dict['alarm_uuid']) - m_delete_notification_rule.assert_called_with(alarm_details['alarm_name']) - m_delete_alarm_defination.assert_called_with(alarm_details['alarm_id']) - m_delete_symptom_definition.assert_called_with(alarm_details['symptom_definition_id']) - - # Verify return value with expected value - self.assertEqual(alarm_uuid, None) - - @mock.patch.object(monPlugin.requests, 'delete') - @mock.patch.object(monPlugin.MonPlugin, 'get_notification_rule_id_by_alarm_name') - def test_delete_notification_rule_successful_deletion_req_response(self, - m_get_notification_rule_id_by_alarm_name, - m_delete): - """Test delete_notification_rule: Valid notification rule is deleted & returns rule_id""" - - # Set input parameters to delete_notification_rule - alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4' - - # Set mocked function's return values - m_get_notification_rule_id_by_alarm_name.return_value = '8db86441-71d8-4830-9e1a-a90be3776d12' - m_delete.return_value.status_code = 204 - - # Call delete_notification_rule method under test - rule_id = self.mon_plugin.delete_notification_rule(alarm_name) - - # Verify that mocked method is called with required parameters - m_get_notification_rule_id_by_alarm_name.assert_called_with(alarm_name) - m_delete.assert_called() - - # Verify return value with expected value - self.assertEqual(rule_id, '8db86441-71d8-4830-9e1a-a90be3776d12') - - @mock.patch.object(monPlugin.requests, 'delete') - @mock.patch.object(monPlugin.MonPlugin, 'get_notification_rule_id_by_alarm_name') - def test_delete_notification_rule_failed_to_get_notification_rule_id(self, - m_get_notification_rule_id_by_alarm_name, - m_delete): - """Test delete_notification_rule: if notification rule is not found, returns None""" - - # Set input parameters to delete_notification_rule - alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4' - - # Set mocked function's return values - m_get_notification_rule_id_by_alarm_name.return_value = None - - # Call delete_notification_rule method under test - rule_id = self.mon_plugin.delete_notification_rule(alarm_name) - - # Verify that mocked method is called with required parameters - m_get_notification_rule_id_by_alarm_name.assert_called_with(alarm_name) - m_delete.assert_not_called() - - # verify return value with expected value - self.assertEqual(rule_id, None) - - @mock.patch.object(monPlugin.requests, 'delete') - @mock.patch.object(monPlugin.MonPlugin, 'get_notification_rule_id_by_alarm_name') - def test_delete_notification_rule_invalid_deletion_req_response(self, - m_get_notification_rule_id_by_alarm_name, - m_delete): - """Test delete_notification_rule: If an invalid response is received, returns None""" - - # Set input parameters to delete_notification_rule - alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4' - - # Set mocked function's return values - m_get_notification_rule_id_by_alarm_name.return_value = '8db86441-71d8-4830-9e1a-a90be3776d12' - m_delete.return_value.status_code = 404 - - # Call delete_notification_rule method under test - rule_id = self.mon_plugin.delete_notification_rule(alarm_name) - - # Verify that mocked method is called with required parameters - m_get_notification_rule_id_by_alarm_name.assert_called_with(alarm_name) - m_delete.assert_called() - - # Verify return value with expected value - self.assertEqual(rule_id, None) - - @mock.patch.object(monPlugin.requests, 'get') - def test_get_notification_rule_id_by_alarm_name_valid_req_response(self, m_get): - """Test get_notification_rule_id_by_alarm_name: A valid request response received, - returns notification_id - """ - - # Set input parameters to get_notification_rule_id_by_alarm_name - alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - - # Set mocked function's return values - m_get.return_value.status_code = 200 - m_get.return_value.content = '{\ - "pageInfo": {"totalCount": 0,"page": 0,"pageSize": 1000},\ - "links": [\ - {"href": "/suite-api/api/notifications/rules?page=0&pageSize=1000",\ - "rel": "SELF","name": "current"},\ - {"href": "/suite-api/api/notifications/rules?page=0&pageSize=1000",\ - "rel": "RELATED","name": "first"},\ - {"href": "/suite-api/api/notifications/rules?page=0&pageSize=1000",\ - "rel": "RELATED","name": "last"}],\ - "notification-rule": [{\ - "id": "2b86fa23-0c15-445c-a2b1-7bd725c46f59",\ - "name": "notify_CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ - "pluginId": "03053f51-f829-438d-993d-cc33a435d76a",\ - "links": [{"href": "/suite-api/api/notifications/rules/2b86fa23-0c15-445c-a2b1-7bd725c46f59",\ - "rel": "SELF","name": "linkToSelf"}]}]}' - - # Call get_notification_rule_id_by_alarm_name method under test - notification_id = self.mon_plugin.get_notification_rule_id_by_alarm_name(alarm_name) - - # Verify that mocked method is called with required parameters - m_get.assert_called() - - # Verify return value with expected value - self.assertEqual(notification_id, '2b86fa23-0c15-445c-a2b1-7bd725c46f59') - - @mock.patch.object(monPlugin.requests, 'get') - def test_get_notification_rule_id_by_alarm_name_invalid_req_response(self, m_get): - """Test get_notification_rule_id_by_alarm_name: If an invalid response received,\ - returns None - """ - - # Set input parameters to delete_alarm_configuration - alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - - # Set mocked function's return values - m_get.return_value.status_code = 404 - - # Call get_notification_rule_id_by_alarm_name method under test - notification_id = self.mon_plugin.get_notification_rule_id_by_alarm_name(alarm_name) - - # Verify that mocked method is called with required parameters - m_get.assert_called() - - # Verify return value with expected value - self.assertEqual(notification_id, None) - - @mock.patch.object(monPlugin.requests, 'get') - def test_get_notification_rule_id_by_alarm_name_rule_not_found(self, m_get): - """Test get_notification_rule_id_by_alarm_name: If a notification rule is not found, - returns None - """ - - # Set input parameters to delete_alarm_configuration - alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda' - - # Set mocked function's return values - m_get.return_value.status_code = 200 - m_get.return_value.content = '{\ - "pageInfo": {"totalCount": 0,"page": 0,"pageSize": 1000},\ - "links": [\ - {"href": "/suite-api/api/notifications/rules?page=0&pageSize=1000",\ - "rel": "SELF","name": "current"},\ - {"href": "/suite-api/api/notifications/rules?page=0&pageSize=1000",\ - "rel": "RELATED","name": "first"},\ - {"href": "/suite-api/api/notifications/rules?page=0&pageSize=1000",\ - "rel": "RELATED","name": "last"}],\ - "notification-rule": [{\ - "id": "2b86fa23-0c15-445c-a2b1-7bd725c46f59",\ - "name": "notify_CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ - "pluginId": "03053f51-f829-438d-993d-cc33a435d76a",\ - "links": [{"href": "/suite-api/api/notifications/rules/2b86fa23-0c15-445c-a2b1-7bd725c46f59",\ - "rel": "SELF","name": "linkToSelf"}]}]}' - - # Call get_notification_rule_id_by_alarm_name method under test - notification_id = self.mon_plugin.get_notification_rule_id_by_alarm_name(alarm_name) - - # Verify that mocked method is called with required parameters - m_get.assert_called() - - # Verify return value with expected value - self.assertEqual(notification_id, None) - - @mock.patch.object(monPlugin.requests, 'delete') - def test_delete_alarm_defination_valid_req_response(self, m_delete): - """Test delete_alarm_defination: A valid request response received, - returns symptom_id - """ - - # Set input parameters to delete_alarm_definition - alarm_definition_id = 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d' - - # Set mocked function's return values - m_delete.return_value.status_code = 204 - - # Call delete_alarm_defination method under test - actual_alarm_id = self.mon_plugin.delete_alarm_defination(alarm_definition_id) - - # Verify that mocked method is called with required parameters - m_delete.assert_called() - - # Verify return value with expected value - self.assertEqual(actual_alarm_id, alarm_definition_id) - - @mock.patch.object(monPlugin.requests, 'delete') - def test_delete_alarm_defination_invalid_req_response(self, m_delete): - """Test delete_alarm_defination: If an invalid request response received, - returns None - """ - - # Set input parameters to delete_alarm_definition - alarm_definition_id = 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d' - - # Set mocked function's return values - m_delete.return_value.status_code = 404 - - # Call delete_alarm_defination method under test - actual_alarm_id = self.mon_plugin.delete_alarm_defination(alarm_definition_id) - - # Verify that mocked method is called with required parameters - m_delete.assert_called() - - # Verify return value with expected value - self.assertEqual(actual_alarm_id, None) - - @mock.patch.object(monPlugin.requests, 'delete') - def test_delete_symptom_definition_valid_req_response(self, m_delete): - """Test delete_symptom_definition: A valid request response received, - returns symptom_id - """ - - # Set input parameters to delete_symptom_definition - symptom_definition_id = 'SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278' - - # Set mocked function's return values - m_delete.return_value.status_code = 204 - - # Call delete_symptom_definition method under test - actual_symptom_id = self.mon_plugin.delete_symptom_definition(symptom_definition_id) - - # Verify that mocked method is called with required parameters - m_delete.assert_called() - - # Verify return value with expected value - self.assertEqual(actual_symptom_id, symptom_definition_id) - - @mock.patch.object(monPlugin.requests, 'delete') - def test_delete_symptom_definition_invalid_req_response(self, m_delete): - """Test delete_symptom_definition: If an invalid request response received, - returns None - """ - - # Set input parameters to delete_symptom_definition - symptom_definition_id = 'SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278' - - # Set mocked function's return values - m_delete.return_value.status_code = 404 - - # Call delete_symptom_definition method under test - actual_symptom_id = self.mon_plugin.delete_symptom_definition(symptom_definition_id) - - # Verify that mocked method is called with required parameters - m_delete.assert_called() - - # Verify return value with expected value - self.assertEqual(actual_symptom_id, None) - - @mock.patch.object(monPlugin.requests, 'post') - @mock.patch.object(monPlugin.MonPlugin, 'check_if_plugin_configured') - def test_configure_rest_plugin_valid_plugin_id(self, m_check_if_plugin_configured, m_post): - """Test configure rest plugin method-valid plugin id""" - - # mock return values - expected_return = m_check_if_plugin_configured.return_value = "mock_pluginid" - - # call configure rest plugin method under test - actual_return = self.mon_plugin.configure_rest_plugin() - - # verify that mocked method is called - m_check_if_plugin_configured.assert_called() - m_post.assert_not_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.MonPlugin, 'enable_rest_plugin') - @mock.patch.object(monPlugin.requests, 'post') - @mock.patch.object(monPlugin.MonPlugin, 'check_if_plugin_configured') - def est_configure_rest_plugin_invalid_plugin_id(self, m_check_if_plugin_configured, m_post, m_enable_rest_plugin): - """Test configure rest plugin method-invalid plugin id""" - - # mock return values - m_check_if_plugin_configured.return_value = None # not configured - m_post.return_value.status_code = 201 # success - m_post.return_value.content = '{"pluginTypeId":"RestPlugin","pluginId":"1ef15663-9739-49fe-8c41-022bcc9f690c",\ - "name":"MON_module_REST_Plugin","version":1518693747871,"enabled":false,\ - "configValues":[{"name":"Url","value":"https://MON.lxd:8080/notify/"},\ - {"name":"Content-type","value":"application/json"},{"name":"Certificate",\ - "value":"AA:E7:3E:A5:34:E0:25:FB:28:84:3B:74:B2:18:74:C0:C3:E8:26:50"},\ - {"name":"ConnectionCount","value":"20"}]}' - - m_enable_rest_plugin.return_value = True # success - expected_return = '1ef15663-9739-49fe-8c41-022bcc9f690c' - - # call configure rest plugin method under test - actual_return = self.mon_plugin.configure_rest_plugin() - - # verify that mocked method is called - m_check_if_plugin_configured.assert_called() - m_post.assert_called() - m_enable_rest_plugin.assert_called_with('1ef15663-9739-49fe-8c41-022bcc9f690c', 'MON_module_REST_Plugin') - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.MonPlugin, 'enable_rest_plugin') - @mock.patch.object(monPlugin.requests, 'post') - @mock.patch.object(monPlugin.MonPlugin, 'check_if_plugin_configured') - def est_configure_rest_plugin_failed_to_enable_plugin(self, m_check_if_plugin_configured, m_post, - m_enable_rest_plugin): - """Test configure rest plugin method-failed to enable plugin case""" - - # mock return values - m_check_if_plugin_configured.return_value = None # not configured - m_post.return_value.status_code = 201 # success - m_post.return_value.content = '{"pluginTypeId":"RestPlugin","pluginId":"1ef15663-9739-49fe-8c41-022bcc9f690c",\ - "name":"MON_module_REST_Plugin","version":1518693747871,"enabled":false,\ - "configValues":[{"name":"Url","value":"https://MON.lxd:8080/notify/"},\ - {"name":"Content-type","value":"application/json"},{"name":"Certificate",\ - "value":"AA:E7:3E:A5:34:E0:25:FB:28:84:3B:74:B2:18:74:C0:C3:E8:26:50"},\ - {"name":"ConnectionCount","value":"20"}]}' - - m_enable_rest_plugin.return_value = False # return failure - expected_return = None - - # call configure rest plugin method under test - actual_return = self.mon_plugin.configure_rest_plugin() - - # verify that mocked method is called - m_check_if_plugin_configured.assert_called() - m_post.assert_called() - m_enable_rest_plugin.assert_called_with('1ef15663-9739-49fe-8c41-022bcc9f690c', 'MON_module_REST_Plugin') - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'get') - def test_check_if_plugin_configured_valid_req_response(self, m_get): - """Test check if plugin configured method-valid request response""" - - plugin_name = 'MON_module_REST_Plugin' - # mock return values - m_get.return_value.status_code = 200 - expected_return = '1ef15663-9739-49fe-8c41-022bcc9f690c' - m_get.return_value.content = '{"notificationPluginInstances":\ - [{"pluginTypeId":"RestPlugin",\ - "pluginId":"1ef15663-9739-49fe-8c41-022bcc9f690c",\ - "name":"MON_module_REST_Plugin","version":1518694966987,\ - "enabled":true,"configValues":[{"name":"Url",\ - "value":"https://MON.lxd:8080/notify/"},\ - {"name":"Content-type","value":"application/json"},\ - {"name":"Certificate",\ - "value":"AA:E7:3E:A5:34:E0:25:FB:28:84:3B:74:B2:18:74:C0"},\ - {"name":"ConnectionCount","value":"20"}]}]}' - - # call check if plugin configured method under test - actual_return = self.mon_plugin.check_if_plugin_configured(plugin_name) - - # verify that mocked method is called - m_get.assert_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'get') - def test_check_if_plugin_configured_invalid_req_response(self, m_get): - """Test check if plugin configured method-invalid request response""" - - plugin_name = 'MON_module_REST_Plugin' - # mock return values - m_get.return_value.status_code = 201 - expected_return = None - m_get.return_value.content = '{"notificationPluginInstances":\ - [{"pluginTypeId":"RestPlugin",\ - "pluginId":"1ef15663-9739-49fe-8c41-022bcc9f690c",\ - "name":"MON_module_REST_Plugin","version":1518694966987,\ - "enabled":true,"configValues":[{"name":"Url",\ - "value":"https://MON.lxd:8080/notify/"},\ - {"name":"Content-type","value":"application/json"},\ - {"name":"Certificate",\ - "value":"AA:E7:3E:A5:34:E0:25:FB:28:84:3B:74:B2:18:74:C0"},\ - {"name":"ConnectionCount","value":"20"}]}]}' - - # call check if plugin configured method under test - actual_return = self.mon_plugin.check_if_plugin_configured(plugin_name) - - # verify that mocked method is called - m_get.assert_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'put') - def test_enable_rest_plugin_valid_req_response(self, m_put): - """Test enable rest plugin method-valid request response""" - - plugin_name = 'MON_module_REST_Plugin' - plugin_id = '1ef15663-9739-49fe-8c41-022bcc9f690c' - # mock return values - m_put.return_value.status_code = 204 - expected_return = True - m_put.return_value.content = '' - - # call enable rest plugin configured method under test - actual_return = self.mon_plugin.enable_rest_plugin(plugin_id, plugin_name) - - # verify that mocked method is called - m_put.assert_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'put') - def test_enable_rest_plugin_invalid_req_response(self, m_put): - """Test enable rest plugin method-invalid request response""" - - plugin_name = 'MON_module_REST_Plugin' - plugin_id = '08018c0f-8879-4ca1-9b92-00e22d2ff81b' # invalid plugin id - # mock return values - m_put.return_value.status_code = 404 # api Error code - expected_return = False - m_put.return_value.content = '\ - No such Notification Plugin - 08018c0f-8879-4ca1-9b92-\ - 00e22d2ff81b.' - - # call enable rest plugin configured method under test - actual_return = self.mon_plugin.enable_rest_plugin(plugin_id, plugin_name) - - # verify that mocked method is called - m_put.assert_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'post') - @mock.patch.object(monPlugin.MonPlugin, 'check_if_plugin_configured') - def test_create_alarm_notification_rule_valid_req(self, m_check_if_plugin_configured, m_post): - """Test create alarm notification rule method valid request response""" - - alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - alarm_id = 'AlertDefinition-f1163767-6eac-438f-8e60-a7a867257e14' - res_id = 'ac87622f-b761-40a0-b151-00872a2a456e' - expected_return = "8db86441-71d8-4830-9e1a-a90be3776d12" - - # mock return values - m_check_if_plugin_configured.return_value = '03053f51-f829-438d-993d-cc33a435d76a' - m_post.return_value.status_code = 201 - m_post.return_value.content = '{"id":"8db86441-71d8-4830-9e1a-a90be3776d12",\ - "name":"notify_CPU_Utilization_Above_Thr-e14b203c",\ - "pluginId":"03053f51-f829-438d-993d-cc33a435d76a",\ - "alertControlStates":[],"alertStatuses":[],\ - "resourceFilter":{"matchResourceIdOnly":true,\ - "childrenResourceKindFilters":[],\ - "resourceId":"ac87622f-b761-40a0-b151-00872a2a456e"},\ - "alertTypeFilters":[],"alertDefinitionIdFilters":{"values":[\ - "AlertDefinition-f1163767-6eac-438f-8e60-a7a867257e14"]}}' - - # call enable rest plugin configured method under test - actual_return = self.mon_plugin.create_alarm_notification_rule(alarm_name, alarm_id, res_id) - - # verify that mocked method is called - m_check_if_plugin_configured.assert_called_with('MON_module_REST_Plugin') - m_post.assert_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'post') - @mock.patch.object(monPlugin.MonPlugin, 'check_if_plugin_configured') - def test_create_alarm_notification_rule_invalid_req(self, m_check_if_plugin_configured, m_post): - """Test create alarm notification rule method invalid request response""" - - alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - alarm_id = 'AlertDefinition-f1163767-6eac-438f-8e60-a7a867257e14' - res_id = 'ac87622f-b761-40a0-b151-00872a2a456e' - expected_return = None # invalid req should retrun none - - # mock return values - m_check_if_plugin_configured.return_value = '03053f51-f829-438d-993d-cc33a435d76a' - m_post.return_value.status_code = 500 - m_post.return_value.content = '{"message":"Internal Server error, cause unknown.",\ - "moreInformation":[{"name":"errorMessage","value":\ - "there is already a rule with the same rule name"},\ - {"name":"localizedMessage","value":"there is already \ - a rule with the same rule name;"}],"httpStatusCode":500,\ - "apiErrorCode":500}' - - # call enable rest plugin configured method under test - actual_return = self.mon_plugin.create_alarm_notification_rule(alarm_name, alarm_id, res_id) - - # verify that mocked method is called - m_check_if_plugin_configured.assert_called_with('MON_module_REST_Plugin') - m_post.assert_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'post') - @mock.patch.object(monPlugin.MonPlugin, 'check_if_plugin_configured') - def test_create_alarm_notification_rule_failed_to_get_plugin_id(self, - m_check_if_plugin_configured, m_post): - """Test create alarm notification rule method invalid plugin id""" - - alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - alarm_id = 'AlertDefinition-f1163767-6eac-438f-8e60-a7a867257e14' - res_id = 'ac87622f-b761-40a0-b151-00872a2a456e' - expected_return = None # invalid req should retrun none - - # mock return values - m_check_if_plugin_configured.return_value = None - - # call enable rest plugin configured method under test - actual_return = self.mon_plugin.create_alarm_notification_rule(alarm_name, alarm_id, res_id) - - # verify that mocked method is called - m_check_if_plugin_configured.assert_called_with('MON_module_REST_Plugin') - m_post.assert_not_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'get') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') - def test_get_metrics_data_valid_rest_req_response(self, m_get_default_Params, - m_get_vm_moref_id, - m_get_vm_resource_id, - m_get): - """Test get metrics data of resource method valid request response""" - - metrics = {'collection_period': 1, 'metric_name': 'CPU_UTILIZATION', 'metric_uuid': None, - 'schema_version': 1.0, 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'schema_type': 'read_metric_data_request', 'vim_type': 'VMware', - 'collection_unit': 'HR', 'vim_uuid': '1'} - - # mock return value - m_get_default_Params.return_value = {'metric_key': 'cpu|usage_average', 'unit': '%'} - vm_moref_id = m_get_vm_moref_id.return_value = 'vm-6626' - m_get_vm_resource_id.return_value = 'ac87622f-b761-40a0-b151-00872a2a456e' - m_get.return_value.status_code = 200 - m_get.return_value.content = '{"values":[{"resourceId":"ac87622f-b761-40a0-b151-\ - 00872a2a456e","stat-list":{"stat":[{"timestamps":\ - [1519716874297,1519717174294,1519717474295,1519717774298,\ - 1519718074300,1519718374299,1519718674314,1519718974325,\ - 1519719274304,1519719574298,1519719874298,1519720174301],\ - "statKey":{"key":"cpu|usage_average"},"intervalUnit":\ - {"quantifier":1},"data":[0.1120000034570694,\ - 0.11866666376590729,0.11599999666213989,0.11400000005960464,\ - 0.12066666781902313,0.11533333361148834,0.11800000071525574,\ - 0.11533333361148834,0.12200000137090683,0.11400000005960464,\ - 0.1459999978542328,0.12133333086967468]}]}}]}' - - # call get matrics data method under test - actual_return = self.mon_plugin.get_metrics_data(metrics) - - # verify that mocked method is called - m_get_default_Params.assert_called_with(metrics['metric_name']) - m_get_vm_moref_id.assert_called_with(metrics['resource_uuid']) - m_get_vm_resource_id.assert_called_with(vm_moref_id) - m_get.assert_called() - - # verify return value with expected value - # self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'get') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') - def test_get_metrics_data_invalid_rest_req_response(self, m_get_default_Params, - m_get_vm_moref_id, - m_get_vm_resource_id, - m_get): - """Test get metrics data of resource method invalid request response""" - - metrics = {'collection_period': 1, 'metric_name': 'CPU_UTILIZATION', 'metric_uuid': None, - 'schema_version': 1.0, 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'schema_type': 'read_metric_data_request', 'vim_type': 'VMware', - 'collection_unit': 'HR', 'vim_uuid': '1'} - - # mock return value - m_get_default_Params.return_value = {'metric_key': 'cpu|usage_average', 'unit': '%'} - vm_moref_id = m_get_vm_moref_id.return_value = 'vm-6626' - m_get_vm_resource_id.return_value = 'ac87622f-b761-40a0-b151-00872a2a456e' - m_get.return_value.status_code = 400 - expected_return = {'metric_name': 'CPU_UTILIZATION', 'metric_uuid': '0', - 'schema_version': '1.0', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'metrics_data': {'time_series': [], 'metrics_series': []}, - 'schema_type': 'read_metric_data_response', - 'unit': '%', 'vim_uuid': '1'} - - # call get metrics data method under test - actual_return = self.mon_plugin.get_metrics_data(metrics) - - # verify that mocked method is called - m_get_default_Params.assert_called_with(metrics['metric_name']) - m_get_vm_moref_id.assert_called_with(metrics['resource_uuid']) - m_get_vm_resource_id.assert_called_with(vm_moref_id) - m_get.assert_called() - - m_get.return_value.content = '{"message":"Invalid request... #1 violations found.",\ - "validationFailures":[{"failureMessage":"Invalid Parameter",\ - "violationPath":"end"}],"httpStatusCode":400,\ - "apiErrorCode":400}' - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'get') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') - def test_get_metrics_data_metric_not_supported(self, m_get_default_Params, - m_get_vm_moref_id, - m_get_vm_resource_id, - m_get): - """Test get metrics data of resource method invalid metric name""" - - metrics = {'collection_period': 1, 'metric_name': 'invalid_metric', 'metric_uuid': None, - 'schema_version': 1.0, - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'schema_type': 'read_metric_data_request', 'vim_type': 'VMware', - 'collection_unit': 'HR', 'vim_uuid': '1'} - - # mock return value - m_get_default_Params.return_value = {} # returns empty dict - - expected_return = {'metric_name': 'invalid_metric', 'metric_uuid': '0', 'vim_uuid': '1', - 'schema_version': '1.0', 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'metrics_data': {'time_series': [], 'metrics_series': []}, - 'schema_type': 'read_metric_data_response', 'unit': None} - - # call get matrics data method under test - actual_return = self.mon_plugin.get_metrics_data(metrics) - - # verify that mocked method is called/not called - m_get_default_Params.assert_called_with(metrics['metric_name']) - m_get_vm_moref_id.assert_not_called() - m_get_vm_resource_id.assert_not_called() - m_get.assert_not_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'get') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') - def test_get_metrics_data_failed_to_get_vm_moref_id(self, m_get_default_Params, - m_get_vm_moref_id, - m_get_vm_resource_id, - m_get): - """Test get metrics data method negative scenario- invalid resource id""" - - metrics = {'collection_period': 1, 'metric_name': 'cpu_utilization', 'metric_uuid': None, - 'schema_version': 1.0, 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'schema_type': 'read_metric_data_request', 'vim_type': 'VMware', - 'collection_unit': 'HR', 'vim_uuid': '1'} - - # mock return value - m_get_default_Params.return_value = {'metric_key': 'cpu|usage_average', 'unit': '%'} - m_get_vm_moref_id.return_value = None - expected_return = {'metric_name': 'cpu_utilization', 'metric_uuid': '0', - 'schema_version': '1.0', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'metrics_data': {'time_series': [], 'metrics_series': []}, - 'schema_type': 'read_metric_data_response', - 'unit': '%', 'vim_uuid': '1'} - - # call get matrics data method under test - actual_return = self.mon_plugin.get_metrics_data(metrics) - - # verify that mocked method is called/not called - m_get_default_Params.assert_called_with(metrics['metric_name']) - m_get_vm_moref_id.assert_called_with(metrics['resource_uuid']) - m_get_vm_resource_id.assert_not_called() - m_get.assert_not_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'get') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') - def test_get_metrics_data_failed_to_get_vm_resource_id(self, m_get_default_Params, - m_get_vm_moref_id, - m_get_vm_resource_id, - m_get): - """Test get metrics data method negative scenario- invalid moref id""" - - metrics = {'collection_period': 1, 'metric_name': 'CPU_UTILIZATION', 'metric_uuid': None, - 'schema_version': 1.0, 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'schema_type': 'read_metric_data_request', 'vim_type': 'VMware', - 'collection_unit': 'HR', 'vim_uuid': '1'} - - # mock return value - m_get_default_Params.return_value = {'metric_key': 'cpu|usage_average', 'unit': '%'} - m_get_vm_moref_id.return_value = 'Invalid-vm-6626' - m_get_vm_resource_id.return_value = None - expected_return = {'metric_name': 'CPU_UTILIZATION', 'metric_uuid': '0', - 'schema_version': '1.0', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', - 'metrics_data': {'time_series': [], 'metrics_series': []}, - 'schema_type': 'read_metric_data_response', - 'unit': '%', 'vim_uuid': '1'} - - # call get matrics data method under test - actual_return = self.mon_plugin.get_metrics_data(metrics) - - # verify that mocked method is called/not called - m_get_default_Params.assert_called_with(metrics['metric_name']) - m_get_vm_moref_id.assert_called_with(metrics['resource_uuid']) - m_get_vm_resource_id.assert_called() - m_get_vm_resource_id.assert_called_with('Invalid-vm-6626') - m_get.assert_not_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.MonPlugin, 'reconfigure_alarm') - @mock.patch.object(monPlugin.MonPlugin, 'update_symptom_defination') - @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_details') - def test_update_alarm_configuration_successful_updation(self, m_get_alarm_defination_details, - m_update_symptom_defination, - m_reconfigure_alarm): - """Test update alarm configuration method""" - - alarm_config = {'alarm_uuid': 'f1163767-6eac-438f-8e60-a7a867257e14', - 'correlation_id': 14203, - 'description': 'CPU_Utilization_Above_Threshold_L', 'operation': 'GT'} - - # mock return value - alarm_details_json = {'states': [{'impact': {'impactType': 'BADGE', 'detail': 'risk'}, - 'severity': 'CRITICAL', 'base-symptom-set': {'symptomDefinitionIds': - [ - 'SymptomDefinition-47c88675-bea8-436a-bb41-8d2231428f44'], - 'relation': 'SELF', - 'type': 'SYMPTOM_SET', - 'aggregation': 'ALL'}}], - 'description': 'CPU_Utilization_Above_Threshold', 'type': 16, - 'id': 'AlertDefinition-f1163767-6eac-438f-8e60-a7a867257e14', - 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d2'} - alarm_details = {'symptom_definition_id': 'SymptomDefinition-47c88675-bea8-436a-bb41-\ - 8d2231428f44', 'alarm_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-\ - a91c-8c19d2', 'alarm_id': 'AlertDefinition-f1163767-6eac-438f-8e60-\ - a7a867257e14', 'resource_kind': 'VirtualMachine', 'type': 16} - m_get_alarm_defination_details.return_value = (alarm_details_json, alarm_details) - m_update_symptom_defination.return_value = 'SymptomDefinition-47c88675-bea8-436a-bb41-\ - 8d2231428f44' - expected_return = m_reconfigure_alarm.return_value = 'f1163767-6eac-438f-8e60-a7a867257e14' - - # call update alarm configuration method under test - actual_return = self.mon_plugin.update_alarm_configuration(alarm_config) - - # verify that mocked method is called - m_get_alarm_defination_details.assert_called_with(alarm_config['alarm_uuid']) - m_update_symptom_defination.assert_called_with(alarm_details['symptom_definition_id'], - alarm_config) - m_reconfigure_alarm.assert_called_with(alarm_details_json, alarm_config) - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.MonPlugin, 'reconfigure_alarm') - @mock.patch.object(monPlugin.MonPlugin, 'update_symptom_defination') - @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_details') - def test_update_alarm_configuration_failed_to_reconfigure_alarm(self, - m_get_alarm_defination_details, - m_update_symptom_defination, - m_reconfigure_alarm): - """Test update alarm configuration method- failed to reconfigure alarm""" - - alarm_config = {'alarm_uuid': 'f1163767-6eac-438f-8e60-a7a867257e14', - 'correlation_id': 14203, - 'description': 'CPU_Utilization_Above_Threshold_L', 'operation': 'GT'} - - # mock return value - alarm_details_json = {'states': [{'impact': {'impactType': 'BADGE', 'detail': 'risk'}, - 'severity': 'CRITICAL', 'base-symptom-set': {'symptomDefinitionIds': - [ - 'SymptomDefinition-47c88675-bea8-436a-bb41-8d2231428f44'], - 'relation': 'SELF', - 'type': 'SYMPTOM_SET', - 'aggregation': 'ALL'}}], - 'description': 'CPU_Utilization_Above_Threshold', 'type': 16, - 'id': 'AlertDefinition-f1163767-6eac-438f-8e60-a7a867257e14', - 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d2'} - alarm_details = {'symptom_definition_id': 'SymptomDefinition-47c88675-bea8-436a-bb41-\ - 8d2231428f44', 'alarm_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-\ - a91c-8c19d2', 'alarm_id': 'AlertDefinition-f1163767-6eac-438f-8e60-\ - a7a867257e14', 'resource_kind': 'VirtualMachine', 'type': 16} - m_get_alarm_defination_details.return_value = (alarm_details_json, alarm_details) - m_update_symptom_defination.return_value = 'SymptomDefinition-47c88675-bea8-436a-bb41-\ - 8d2231428f44' - expected_return = m_reconfigure_alarm.return_value = None # failed to reconfigure - - # call update alarm configuration method under test - actual_return = self.mon_plugin.update_alarm_configuration(alarm_config) - - # verify that mocked method is called - m_get_alarm_defination_details.assert_called_with(alarm_config['alarm_uuid']) - m_update_symptom_defination.assert_called_with(alarm_details['symptom_definition_id'], - alarm_config) - m_reconfigure_alarm.assert_called_with(alarm_details_json, alarm_config) - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.MonPlugin, 'reconfigure_alarm') - @mock.patch.object(monPlugin.MonPlugin, 'update_symptom_defination') - @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_details') - def test_update_alarm_configuration_failed_to_update_symptom(self, - m_get_alarm_defination_details, - m_update_symptom_defination, - m_reconfigure_alarm): - """Test update alarm configuration method- failed to update alarm""" - - alarm_config = {'alarm_uuid': 'f1163767-6eac-438f-8e60-a7a867257e14', - 'correlation_id': 14203, - 'description': 'CPU_Utilization_Above_Threshold_L', 'operation': 'GT'} - - # mock return value - alarm_details_json = {'states': [{'impact': {'impactType': 'BADGE', 'detail': 'risk'}, - 'severity': 'CRITICAL', 'base-symptom-set': {'symptomDefinitionIds': - [ - 'SymptomDefinition-47c88675-bea8-436a-bb41-8d2231428f44'], - 'relation': 'SELF', - 'type': 'SYMPTOM_SET', - 'aggregation': 'ALL'}}], - 'description': 'CPU_Utilization_Above_Threshold', 'type': 16, - 'id': 'AlertDefinition-f1163767-6eac-438f-8e60-a7a867257e14', - 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d2'} - alarm_details = {'symptom_definition_id': 'Invalid-47c88675-bea8-436a-bb41-\ - 8d2231428f44', 'alarm_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-\ - a91c-8c19d2', 'alarm_id': 'AlertDefinition-f1163767-6eac-438f-8e60-\ - a7a867257e14', 'resource_kind': 'VirtualMachine', 'type': 16} - m_get_alarm_defination_details.return_value = (alarm_details_json, alarm_details) - expected_return = m_update_symptom_defination.return_value = None - - # call update alarm configuration method under test - actual_return = self.mon_plugin.update_alarm_configuration(alarm_config) - - # verify that mocked method is called - m_get_alarm_defination_details.assert_called_with(alarm_config['alarm_uuid']) - m_update_symptom_defination.assert_called_with(alarm_details['symptom_definition_id'], - alarm_config) - m_reconfigure_alarm.assert_not_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') - def test_verify_metric_support_metric_supported_with_unit(self, m_get_default_Params): - """Test verify metric support method for supported metric""" - - # mock return value - metric_info = {'metric_unit': '%', 'metric_name': 'cpu_utilization', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4'} - m_get_default_Params.return_value = {'metric_key': 'cpu|usage_average', 'unit': '%'} - expected_return = True # supported metric returns True - - # call verify metric support method under test - actual_return = self.mon_plugin.verify_metric_support(metric_info) - - # verify that mocked method is called - m_get_default_Params.assert_called_with(metric_info['metric_name']) - # m_get_default_Params.assert_called_with(metric_info) - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') - def test_verify_metric_support_metric_not_supported(self, m_get_default_Params): - """Test verify metric support method for un-supported metric""" - - # mock return value - metric_info = {'metric_unit': '%', 'metric_name': 'invalid_metric', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4'} - m_get_default_Params.return_value = {} - expected_return = False # supported metric returns True - - # call verify metric support method under test - actual_return = self.mon_plugin.verify_metric_support(metric_info) - - # verify that mocked method is called - m_get_default_Params.assert_called_with(metric_info['metric_name']) - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') - def test_verify_metric_support_metric_supported_with_mismatched_unit(self, - m_get_default_Params): - """Test verify metric support method for supported metric with mismatched unit""" - - # mock return value - metric_info = {'metric_unit': '', 'metric_name': 'invalid_metric', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4'} - m_get_default_Params.return_value = {'metric_key': 'cpu|usage_average', 'unit': '%'} - expected_return = True # supported metric returns True - - # call verify metric support method under test - actual_return = self.mon_plugin.verify_metric_support(metric_info) - - # verify that mocked method is called - m_get_default_Params.assert_called_with(metric_info['metric_name']) - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.MonPlugin, 'get_triggered_alarms_on_resource') - @mock.patch.object(monPlugin.MonPlugin, 'get_vrops_resourceid_from_ro_uuid') - def test_get_triggered_alarms_list_returns_triggered_alarms(self, - m_get_vrops_resourceid, - m_triggered_alarms): - """Test get triggered alarm list method valid input""" - - # Mock list alarm input - list_alarm_input = {'severity': 'CRITICAL', - 'correlation_id': 'e14b203c', - 'alarm_name': 'CPU_Utilization_Above_Threshold', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4'} - - resource_id = m_get_vrops_resourceid.return_value = 'ac87622f-b761-40a0-b151-00872a2a456e' - expected_return = m_triggered_alarms.return_value = [{'status': 'ACTIVE', - 'update_date': '2018-01-12T08:34:05', - 'severity': 'CRITICAL', 'resource_uuid': 'e14b203c', - 'cancel_date': '0000-00-00T00:00:00', - 'alarm_instance_uuid': 'd9e3bc84', - 'alarm_uuid': '5714977d', 'vim_type': 'VMware', - 'start_date': '2018-01-12T08:34:05'}, - {'status': 'CANCELED', - 'update_date': '2017-12-20T09:37:57', - 'severity': 'CRITICAL', 'resource_uuid': 'e14b203c', - 'cancel_date': '2018-01-12T06:49:19', - 'alarm_instance_uuid': 'd3bbeef6', - 'alarm_uuid': '7ba1bf3e', 'vim_type': 'VMware', - 'start_date': '2017-12-20T09:37:57'}] - - # call get triggered alarms list method under test - actual_return = self.mon_plugin.get_triggered_alarms_list(list_alarm_input) - - # verify that mocked method is called - m_get_vrops_resourceid.assert_called_with(list_alarm_input['resource_uuid']) - m_triggered_alarms.assert_called_with(list_alarm_input['resource_uuid'], resource_id) - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.MonPlugin, 'get_triggered_alarms_on_resource') - @mock.patch.object(monPlugin.MonPlugin, 'get_vrops_resourceid_from_ro_uuid') - def test_get_triggered_alarms_list_invalid_resource_uuid(self, - m_get_vrops_resourceid, - m_triggered_alarms): - """Test get triggered alarm list method invalid resource uuid""" - - # Mock list alarm input - list_alarm_input = {'severity': 'CRITICAL', - 'correlation_id': 'e14b203c', - 'alarm_name': 'CPU_Utilization_Above_Threshold', - 'resource_uuid': '12345'} # invalid resource uuid - - expected_return = m_get_vrops_resourceid.return_value = None # returns empty list - - # call get triggered alarms list method under test - actual_return = self.mon_plugin.get_triggered_alarms_list(list_alarm_input) - - # verify that mocked method is called - m_get_vrops_resourceid.assert_called_with(list_alarm_input['resource_uuid']) - m_triggered_alarms.assert_not_called() - - # verify return value with expected value - self.assertEqual([], actual_return) - - @mock.patch.object(monPlugin.MonPlugin, 'get_triggered_alarms_on_resource') - @mock.patch.object(monPlugin.MonPlugin, 'get_vrops_resourceid_from_ro_uuid') - def test_get_triggered_alarms_list_resource_uuid_not_present(self, - m_get_vrops_resourceid, - m_triggered_alarms): - """Test get triggered alarm list method resource not present""" - - # Mock list alarm input - list_alarm_input = {'severity': 'CRITICAL', - 'correlation_id': 'e14b203c', - 'alarm_name': 'CPU_Utilization_Above_Threshold'} - - # call get triggered alarms list method under test - actual_return = self.mon_plugin.get_triggered_alarms_list(list_alarm_input) - - # verify that mocked method is called - m_get_vrops_resourceid.assert_not_called() - m_triggered_alarms.assert_not_called() - - # verify return value with expected value - self.assertEqual([], actual_return) - - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') - def test_get_vrops_resourceid_from_ro_uuid(self, m_get_vm_moref_id, m_get_vm_resource_id): - """Test get vrops resourceid from ro uuid method""" - - # Mock the inputs - ro_resource_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - vm_moref_id = m_get_vm_moref_id.return_value = 'vm-6626' - expected_return = m_get_vm_resource_id.return_value = 'ac87622f-b761-40a0-b151-00872a2a456e' - - # call get_vrops_resourceid_from_ro_uuid method under test - actual_return = self.mon_plugin.get_vrops_resourceid_from_ro_uuid(ro_resource_uuid) - - # verify that mocked method is called - m_get_vm_moref_id.assert_called_with(ro_resource_uuid) - m_get_vm_resource_id.assert_called_with(vm_moref_id) - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') - def test_get_vrops_resourceid_from_ro_uuid_failed_to_get_vm_resource_id(self, - m_get_vm_moref_id, - m_get_vm_resource_id): - """Test get vrops resourceid from ro uuid method negative scenario""" - - # Mock the inputs - ro_resource_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - vm_moref_id = m_get_vm_moref_id.return_value = 'vm-6626' - expected_return = m_get_vm_resource_id.return_value = None - - # call get_vrops_resourceid_from_ro_uuid method under test - actual_return = self.mon_plugin.get_vrops_resourceid_from_ro_uuid(ro_resource_uuid) - - # verify that mocked method is called - m_get_vm_moref_id.assert_called_with(ro_resource_uuid) - m_get_vm_resource_id.assert_called_with(vm_moref_id) - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') - @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') - def test_get_vrops_resourceid_from_ro_uuid_failed_to_get_vm_moref_id(self, - m_get_vm_moref_id, - m_get_vm_resource_id): - """Test get vrops resourceid from ro uuid method negative scenario""" - - # Mock the inputs - ro_resource_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - expected_return = vm_moref_id = m_get_vm_moref_id.return_value = None - - # call get_vrops_resourceid_from_ro_uuid method under test - actual_return = self.mon_plugin.get_vrops_resourceid_from_ro_uuid(ro_resource_uuid) - - # verify that mocked method is called - m_get_vm_moref_id.assert_called_with(ro_resource_uuid) - m_get_vm_resource_id.assert_not_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'get') - def test_get_triggered_alarms_on_resource_valid_req_response(self, m_get): - """Test get triggered alarms on resource method for valid request""" - - # Mock the inputs - ro_resource_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - vrops_resource_id = 'ac87622f-b761-40a0-b151-00872a2a456e' - m_get.return_value.status_code = 200 - expected_return = [{'status': 'ACTIVE', 'update_date': '2018-01-12T08:34:05', - 'severity': 'CRITICAL', 'start_date': '2018-01-12T08:34:05', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'cancel_date': '2018-02-12T08:24:48', 'vim_type': 'VMware', - 'alarm_instance_uuid': 'd9e3bc84-dcb4-4905-b592-00a55f4cdaf1', - 'alarm_uuid': '5714977d-56f6-4222-adc7-43fa6c6e7e39'}] - - m_get.return_value.content = '{"alerts": [\ - {\ - "alertId": "d9e3bc84-dcb4-4905-b592-00a55f4cdaf1",\ - "resourceId": "ac87622f-b761-40a0-b151-00872a2a456e",\ - "alertLevel": "CRITICAL",\ - "status": "ACTIVE",\ - "startTimeUTC": 1515746045278,\ - "cancelTimeUTC": 1518423888708,\ - "updateTimeUTC": 1515746045278,\ - "alertDefinitionId": "AlertDefinition-5714977d-56f6-4222-adc7-43fa6c6e7e39",\ - "alertDefinitionName": "CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4"\ - },\ - {\ - "alertId": "5fb5e940-e161-4253-a729-7255c6d6b1f5",\ - "resourceId": "ac87622f-b761-40a0-b151-00872a2a456e",\ - "alertLevel": "WARNING",\ - "status": "CANCELED",\ - "startTimeUTC": 1506684979154,\ - "cancelTimeUTC": 0,\ - "updateTimeUTC": 1520471975507,\ - "alertDefinitionId": "AlertDefinition-9ec5a921-1a54-411d-85ec-4c1c9b26dd02",\ - "alertDefinitionName": "VM_CPU_Usage_Alarm"\ - }]}' - - # call get_vrops_resourceid_from_ro_uuid method under test - actual_return = self.mon_plugin.get_triggered_alarms_on_resource(ro_resource_uuid, - vrops_resource_id) - - # verify that mocked method is called - m_get.assert_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'get') - def test_get_triggered_alarms_on_resource_invalid_req_response(self, m_get): - """Test get triggered alarms on resource method for invalid request""" - - # Mock the inputs - ro_resource_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - vrops_resource_id = 'ac87622f-b761-40a0-b151-00872a2a456e' - m_get.return_value.status_code = 204 - expected_return = None - - # call get_vrops_resourceid_from_ro_uuid method under test - actual_return = self.mon_plugin.get_triggered_alarms_on_resource(ro_resource_uuid, - vrops_resource_id) - - # verify that mocked method is called - m_get.assert_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'get') - def test_get_triggered_alarms_on_resource_no_alarms_present(self, m_get): - """Test get triggered alarms on resource method for no alarms present""" - - # Mock the inputs - ro_resource_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - vrops_resource_id = 'ac87622f-b761-40a0-b151-00872a2a456e' - m_get.return_value.status_code = 200 - expected_return = [] - m_get.return_value.content = '{"alerts": []}' - - # call get_vrops_resourceid_from_ro_uuid method under test - actual_return = self.mon_plugin.get_triggered_alarms_on_resource(ro_resource_uuid, - vrops_resource_id) - - # verify that mocked method is called - m_get.assert_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - def test_convert_date_time_valid_date_time(self): - """Test convert date time method valid input""" - - # Mock the inputs - date_time = 1515746045278 - expected_return = '2018-01-12T08:34:05' - - # call convert_date_time method under test - actual_return = self.mon_plugin.convert_date_time(date_time) - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - def test_convert_date_time_invalid_date_time(self): - """Test convert date time method invalid input""" - - # Mock the inputs - date_time = 0 - expected_return = '0000-00-00T00:00:00' - - # call convert_date_time method under test - actual_return = self.mon_plugin.convert_date_time(date_time) - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'get') - def test_get_vm_resource_id_rest_valid_req_response(self, m_get): - """Test get vms resource id valid request""" - - # Mock the inputs - vm_moref_id = 'vm-6626' - m_get.return_value.status_code = 200 - expected_return = "ac87622f-b761-40a0-b151-00872a2a456e" - m_get.return_value.content = \ - '{ \ - "resourceList": [\ - {\ - "creationTime": 1497770174130,\ - "resourceKey": {\ - "name": "OCInst2.ubuntu(4337d51f-1e65-4ab0-9c08-4897778d4fda)",\ - "adapterKindKey": "VMWARE",\ - "resourceKindKey": "VirtualMachine",\ - "resourceIdentifiers": [\ - {\ - "identifierType": {\ - "name": "VMEntityObjectID",\ - "dataType": "STRING",\ - "isPartOfUniqueness": true\ - },\ - "value": "vm-6626"\ - }\ - ]\ - },\ - "identifier": "ac87622f-b761-40a0-b151-00872a2a456e"\ - }\ - ]\ - }' - - # call get_vm_resource_id method under test - actual_return = self.mon_plugin.get_vm_resource_id(vm_moref_id) - - # verify that mocked method is called - m_get.assert_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'get') - def test_get_vm_resource_id_rest_invalid_req_response(self, m_get): - """Test get vms resource id invalid request""" - - # Mock the inputs - vm_moref_id = 'vm-6626' - m_get.return_value.status_code = 406 - expected_return = None - m_get.return_value.content = '406 Not Acceptable' - - # call get_vm_resource_id method under test - actual_return = self.mon_plugin.get_vm_resource_id(vm_moref_id) - - # verify that mocked method is called - m_get.assert_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'get') - def test_get_vm_resource_id_rest_invalid_response(self, m_get): - """Test get vms resource id invalid response""" - - # Mock the inputs - vm_moref_id = 'vm-6626' - m_get.return_value.status_code = 200 - expected_return = None - m_get.return_value.content = \ - '{ \ - "resourceList": \ - {\ - "creationTime": 1497770174130,\ - "resourceKey": {\ - "name": "OCInst2.ubuntu(4337d51f-1e65-4ab0-9c08-4897778d4fda)",\ - "adapterKindKey": "VMWARE",\ - "resourceKindKey": "VirtualMachine",\ - "resourceIdentifiers": [\ - {\ - "identifierType": {\ - "name": "VMEntityObjectID",\ - "dataType": "STRING",\ - "isPartOfUniqueness": true\ - },\ - "value": "vm-6626"\ - }\ - ]\ - },\ - "identifier": "ac87622f-b761-40a0-b151-00872a2a456e"\ - }\ - }' - - # call get_vm_resource_id method under test - actual_return = self.mon_plugin.get_vm_resource_id(vm_moref_id) - - # verify that mocked method is called - # m_get.assert_called - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.MonPlugin, 'get_vapp_details_rest') - def test_get_vm_moref_id_valid_id_found(self, m_get_vapp_details_rest): - """Test get vm moref id valid scenario""" - - # mock the inputs - vapp_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - m_get_vapp_details_rest.return_value = {'vm_vcenter_info': {'vm_moref_id': 'vm-6626'}} - expected_return = 'vm-6626' - - # call get_vm_resource_id method under test - actual_return = self.mon_plugin.get_vm_moref_id(vapp_uuid) - - # verify that mocked method is called - m_get_vapp_details_rest.assert_called_with(vapp_uuid) - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.MonPlugin, 'get_vapp_details_rest') - def test_get_vm_moref_id_valid_id_not_found(self, m_get_vapp_details_rest): - """Test get vm moref id invalid scenario""" - - # mock the inputs - vapp_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda' # invalid uuid - m_get_vapp_details_rest.return_value = {} - expected_return = None - - # call get_vm_resource_id method under test - actual_return = self.mon_plugin.get_vm_moref_id(vapp_uuid) - - # verify that mocked method is called - m_get_vapp_details_rest.assert_called_with(vapp_uuid) - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'get') - @mock.patch.object(monPlugin.MonPlugin, 'connect_as_admin') - def test_get_vapp_details_rest_valid_req_response(self, m_connect_as_admin, m_get): - """Test get vapp details rest method for valid request response""" - - # mock the inputs - vapp_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - m_connect_as_admin.return_value = self.vca - self.vca._session = self.session - self.vca._session.headers['x-vcloud-authorization'] = '2ec69b2cc6264ad0a47aaf4e3e280d16' - m_get.return_value.status_code = 200 - expected_return = {'vm_vcenter_info': {'vm_moref_id': 'vm-6626'}} - m_get.return_value.content = '\ - \ - \ - \ - \ - \ - \ - \ - vm-6626\ - VIRTUAL_MACHINE\ - \ - \ - \ - \ - \ - ' - - # call get_vapp_details_rest method under test - actual_return = self.mon_plugin.get_vapp_details_rest(vapp_uuid) - - # verify that mocked method is called - m_connect_as_admin.assert_called_with() - m_get.assert_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'get') - @mock.patch.object(monPlugin.MonPlugin, 'connect_as_admin') - def test_get_vapp_details_rest_invalid_req_response(self, m_connect_as_admin, m_get): - """Test get vapp details rest method for invalid request response""" - - # mock the inputs - vapp_uuid = 'Invalid-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - m_connect_as_admin.return_value = self.vca - self.vca._session = self.session - self.vca._session.headers['x-vcloud-authorization'] = '2ec69b2cc6264ad0a47aaf4e3e280d16' - m_get.return_value.status_code = 400 - expected_return = {} - m_get.return_value.content = 'Bad Request' - - # call get_vapp_details_rest method under test - actual_return = self.mon_plugin.get_vapp_details_rest(vapp_uuid) - - # verify that mocked method is called - m_connect_as_admin.assert_called_with() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'get') - @mock.patch.object(monPlugin.MonPlugin, 'connect_as_admin') - def test_get_vapp_details_rest_failed_to_connect_vcd(self, m_connect_as_admin, m_get): - """Test get vapp details rest method for failed to connect to vcd""" - - # mock the inputs - vapp_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - m_connect_as_admin.return_value = None - expected_return = {} - - # call get_vapp_details_rest method under test - actual_return = self.mon_plugin.get_vapp_details_rest(vapp_uuid) - - # verify that mocked method is called - m_connect_as_admin.assert_called_with() - m_get.assert_not_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.requests, 'get') - @mock.patch.object(monPlugin.MonPlugin, 'connect_as_admin') - def test_get_vapp_details_rest_invalid_response(self, m_connect_as_admin, m_get): - """Test get vapp details rest method for invalid response""" - - # mock the inputs - vapp_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' - m_connect_as_admin.return_value = self.vca - self.vca._session = self.session - self.vca._session.headers['x-vcloud-authorization'] = '2ec69b2cc6264ad0a47aaf4e3e280d16' - m_get.return_value.status_code = 200 - expected_return = {} - m_get.return_value.content = '\ - \ - \ - \ - \ - \ - \ - \ - vm-6626\ - VIRTUAL_MACHINE\ - \ - \ - \ - \ - ' - - # call get_vapp_details_rest method under test - actual_return = self.mon_plugin.get_vapp_details_rest(vapp_uuid) - - # verify that mocked method is called - m_connect_as_admin.assert_called_with() - m_get.assert_called() - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - - @mock.patch.object(monPlugin.Client, 'set_credentials') - @mock.patch.object(monPlugin, 'Client') - def test_connect_as_admin(self, m_client, m_set_credentials): - """Test connect as admin to vCD method""" - - # mock the inputs and mocked returns - expected_return = m_client.return_value = self.vca - m_set_credentials.retrun_value = True - - # call connect_as_admin method under test - actual_return = self.mon_plugin.connect_as_admin() - - # verify that mocked method is called - m_client.assert_called_with(self.m_vim_access_config['vim_url'], - verify_ssl_certs=False) - - # verify return value with expected value - self.assertEqual(expected_return, actual_return) - -# For testing purpose -# if __name__ == '__main__': -# unittest.main() diff --git a/osm_mon/test/VMware/test_plugin_receiver.py b/osm_mon/test/VMware/test_plugin_receiver.py deleted file mode 100644 index cc5dea9..0000000 --- a/osm_mon/test/VMware/test_plugin_receiver.py +++ /dev/null @@ -1,927 +0,0 @@ -# -*- coding: utf-8 -*- - -## -# Copyright 2017-2018 VMware Inc. -# This file is part of ETSI OSM -# 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. -# -# For those usages not covered by the Apache License, Version 2.0 please -# contact: osslegalrouting@vmware.com -## - -""" Mock tests for VMware vROPs plugin recevier """ - -import json -import logging -import os -import sys -import unittest -from io import UnsupportedOperation - -import mock - -# sys.path.append("/root/MON/") - -log = logging.getLogger(__name__) - -sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..")) - -from osm_mon.plugins.vRealiseOps import plugin_receiver as monPluginRec -from osm_mon.core.database import VimCredentials - - -class Message(object): - """A class to mock a message object value for alarm and matric requests""" - - def __init__(self): - """Initialize a mocked message instance""" - self.topic = "alarm_or_metric_request" - self.key = None - self.value = json.dumps({"mock_value": "mock_details"}) - self.partition = 1 - self.offset = 100 - - -class TestPluginReceiver(unittest.TestCase): - """Test class for Plugin Receiver class methods""" - - def setUp(self): - """Setup the tests for plugin_receiver class methods""" - super(TestPluginReceiver, self).setUp() - self.plugin_receiver = monPluginRec.PluginReceiver() - - @mock.patch.object(monPluginRec.PluginReceiver, 'publish_create_alarm_status') - @mock.patch.object(monPluginRec.PluginReceiver, 'create_alarm') - def test_consume_create_alarm_request_key(self, m_create_alarm, m_publish_create_alarm_status): - """Test functionality of consume for create_alarm_request key""" - - vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" - - value = {"vim_uuid": vim_uuid, "alarm_create_request": "alarm_details"} - m_create_alarm.return_value = "test_alarm_id" - - # Call the consume method of plugin_receiver - self.plugin_receiver.handle_alarm_requests('create_alarm_request', value, vim_uuid) - - # verify if create_alarm and publish methods called with correct params - m_create_alarm.assert_called_with(value) - m_publish_create_alarm_status.assert_called_with("test_alarm_id", value) - - @mock.patch.object(monPluginRec.PluginReceiver, 'publish_update_alarm_status') - @mock.patch.object(monPluginRec.PluginReceiver, 'update_alarm') - def test_consume_update_alarm_request_key(self, m_update_alarm, - m_publish_update_alarm_status): - """Test functionality of consume for update_alarm_request key""" - - vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" - - value = {"vim_uuid": vim_uuid, "alarm_update_request": "alarm_details"} - - # set return value to mocked method - m_update_alarm.return_value = "test_alarm_id" - - # Call the consume method of plugin_receiver - self.plugin_receiver.handle_alarm_requests('update_alarm_request', value, vim_uuid) - - # verify update_alarm and publish method called with correct params - m_update_alarm.assert_called_with(value) - m_publish_update_alarm_status.assert_called_with("test_alarm_id", value) - - @mock.patch.object(monPluginRec.PluginReceiver, 'publish_delete_alarm_status') - @mock.patch.object(monPluginRec.PluginReceiver, 'delete_alarm') - def test_consume_delete_alarm_request_key(self, m_delete_alarm, - m_publish_delete_alarm_status): - """Test functionality of consume for delete_alarm_request key""" - - vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" - - value = {"vim_uuid": vim_uuid, "alarm_delete_request": "alarm_details"} - m_delete_alarm.return_value = "test_alarm_id" - - # Call the consume method of plugin_receiver and check delete_alarm request - self.plugin_receiver.handle_alarm_requests('delete_alarm_request', value, vim_uuid) - m_delete_alarm.assert_called_with(value) - - # Check if publish method called with correct parameters - m_publish_delete_alarm_status.assert_called_with("test_alarm_id", value) - - @mock.patch.object(monPluginRec.PluginReceiver, 'publish_list_alarm_response') - @mock.patch.object(monPluginRec.PluginReceiver, 'list_alarms') - def test_consume_list_alarm_request_key(self, m_list_alarms, - m_publish_list_alarm_response): - """ Test functionality of list alarm request key""" - - vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" - value = {"vim_uuid": vim_uuid, "alarm_list_request": "alarm_details"} - - test_alarm_list = [{"alarm_uuid": "alarm1_details"}, {"alarm_uuid": "alarm2_details"}] - - m_list_alarms.return_value = test_alarm_list - - # Call the consume method of plugin_receiver and check delete_alarm request - self.plugin_receiver.handle_alarm_requests('list_alarm_request', value, vim_uuid) - m_list_alarms.assert_called_with(value) - - # Check if publish method called with correct parameters - m_publish_list_alarm_response.assert_called_with(test_alarm_list, value) - - @mock.patch.object(monPluginRec.PluginReceiver, 'publish_create_alarm_status') - @mock.patch.object(monPluginRec.PluginReceiver, 'create_alarm') - def test_consume_invalid_alarm_request_key(self, m_create_alarm, - m_publish_create_alarm_status): - """Test functionality of consume for vim_access_credentials invalid request key""" - - vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" - - # Call the consume method of plugin_receiver - with self.assertRaises(UnsupportedOperation): - self.plugin_receiver.handle_alarm_requests('invalid_key', {}, vim_uuid) - - # verify that create_alarm and publish_create_alarm_status methods not called - m_create_alarm.assert_not_called() - m_publish_create_alarm_status.assert_not_called() - - @mock.patch.object(monPluginRec.PluginReceiver, 'publish_metrics_data_status') - @mock.patch.object(monPluginRec.MonPlugin, 'get_metrics_data') - def test_consume_invalid_metric_request_key(self, m_get_metrics_data, - m_publish_metric_data_status): - """Test functionality of invalid metric key request""" - - vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" - - # Call the consume method of plugin_receiver - with self.assertRaises(UnsupportedOperation): - self.plugin_receiver.handle_metric_requests('invalid_key', {}, vim_uuid) - - # verify that get metrics data and publish methods not called - m_get_metrics_data.assert_not_called() - m_publish_metric_data_status.assert_not_called() - - @mock.patch.object(monPluginRec.PluginReceiver, 'publish_metrics_data_status') - @mock.patch.object(monPluginRec.MonPlugin, 'get_metrics_data') - @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') - def test_consume_read_metric_data_request_key(self, m_get_vim_access_config, - m_get_metrics_data, - m_publish_metric_data_status): - """Test functionality of consume for read_metric_data_request key""" - - vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" - - value = {"vim_uuid": vim_uuid, "metric_name": "metric_details"} - m_get_metrics_data.return_value = {"metrics_data": "metrics_details"} - - m_get_vim_access_config.return_value = {'vrops_site': 'abc', - 'vrops_user': 'user', - 'vrops_password': 'passwd', - 'vim_url': 'vcd_url', - 'admin_username': 'admin', - 'admin_password': 'admin_passwd', - 'vim_uuid': '1', - 'tenant_id': 'org_vdc_1'} - - # Call the consume method of plugin_receiver - self.plugin_receiver.handle_metric_requests('read_metric_data_request', value, vim_uuid) - m_get_metrics_data.assert_called_with(value) - - # Check if publish method called with correct parameters - m_publish_metric_data_status.assert_called_with({"metrics_data": "metrics_details"}) - - @mock.patch.object(monPluginRec.PluginReceiver, 'publish_create_metric_response') - @mock.patch.object(monPluginRec.PluginReceiver, 'verify_metric') - def test_consume_create_metric_request_key(self, m_verify_metric, - m_publish_create_metric_response): - """Test functionality of consume for create_metric_request key""" - - vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" - value = {"vim_uuid": vim_uuid, "metric_create": "metric_details"} - - # set the return value - m_verify_metric.return_value = True - - # Call the consume method of plugin_receiver - self.plugin_receiver.handle_metric_requests('create_metric_request', value, vim_uuid) - m_verify_metric.assert_called_with(value) - - # Check if publish method called with correct parameters - m_publish_create_metric_response.assert_called_with(value, True) - - @mock.patch.object(monPluginRec.PluginReceiver, 'publish_update_metric_response') - @mock.patch.object(monPluginRec.PluginReceiver, 'verify_metric') - def test_consume_update_metric_request_key(self, m_verify_metric, - m_publish_update_metric_response): - """Test functionality of update metric request key""" - - vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" - - value = {"vim_uuid": vim_uuid, "metric_create": "metric_details"} - - # set the return value - m_verify_metric.return_value = True - - # Call the consume method of plugin_receiver - self.plugin_receiver.handle_metric_requests('update_metric_request', value, vim_uuid) - - # verify mocked methods called with correct parameters - m_verify_metric.assert_called_with(value) - m_publish_update_metric_response.assert_called_with(value, True) - - @mock.patch.object(monPluginRec.PluginReceiver, 'publish_delete_metric_response') - def test_consume_delete_metric_request_key(self, m_publish_delete_metric_response): - """Test functionality of consume for delete_metric_request key""" - - # Note: vROPS doesn't support deleting metric data - vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" - - value = {"vim_uuid": vim_uuid, "metric_name": "metric_details"} - - # Call the consume method of plugin_receiver - self.plugin_receiver.handle_metric_requests('delete_metric_request', value, vim_uuid) - - # Check if publish method called with correct parameters - m_publish_delete_metric_response.assert_called_with(value) - - @mock.patch.object(monPluginRec.MonPlugin, 'configure_alarm') - @mock.patch.object(monPluginRec.MonPlugin, 'configure_rest_plugin') - @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') - def test_create_alarm_successful(self, m_get_vim_access_config, - m_configure_rest_plugin, - m_configure_alarm): - """ Test functionality of create alarm method-positive case""" - - # Mock config_alarm_info - config_alarm_info = {"schema_version": 1.0, - "schema_type": "create_alarm_request", - "vim_type": "VMware", - "vim_uuid": "1", - "alarm_create_request": {"correlation_id": 1, - "alarm_name": "CPU_Utilize_Threshold", - "metric_name": "CPU_UTILIZATION", - "tenant_uuid": "tenant_uuid", - "resource_uuid": "resource_uuid", - "description": "test_create_alarm", - "severity": "CRITICAL", - "operation": "GT", - "threshold_value": 10, - "unit": "%", - "statistic": "AVERAGE"}} - - # set return value to plugin uuid - m_get_vim_access_config.return_value = {'vrops_site': 'abc', - 'vrops_user': 'user', - 'vrops_password': 'passwd', - 'vim_url': 'vcd_url', - 'admin_username': 'admin', - 'admin_password': 'admin_passwd', - 'vim_uuid': '1', - 'tenant_id': 'org_vdc_1'} - - m_configure_rest_plugin.retrun_value = "plugin_uuid" - m_configure_alarm.return_value = "alarm_uuid" - - # call create alarm method under test - self.plugin_receiver.create_alarm(config_alarm_info) - - # verify mocked methods get called with correct params - m_get_vim_access_config.assert_called_with(config_alarm_info['vim_uuid']) - m_configure_rest_plugin.assert_called_with() - m_configure_alarm.assert_called_with(config_alarm_info["alarm_create_request"]) - - @mock.patch.object(monPluginRec.MonPlugin, 'configure_alarm') - @mock.patch.object(monPluginRec.MonPlugin, 'configure_rest_plugin') - @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') - def test_create_alarm_failed(self, m_get_vim_access_config, - m_configure_rest_plugin, - m_configure_alarm): - """ Test functionality of create alarm method negative case""" - - # Mock config_alarm_info - config_alarm_info = {"schema_version": 1.0, - "schema_type": "create_alarm_request", - "vim_type": "VMware", - "vim_uuid": "1", - "alarm_create_request": {"correlation_id": 1, - "alarm_name": "CPU_Utilize_Threshold", - "metric_name": "CPU_UTILIZATION", - "tenant_uuid": "tenant_uuid", - "resource_uuid": "resource_uuid", - "description": "test_create_alarm", - "severity": "CRITICAL", - "operation": "GT", - "threshold_value": 10, - "unit": "%", - "statistic": "AVERAGE"}} - - # set return value to plugin uuid and alarm_uuid to None - m_get_vim_access_config.return_value = {'vrops_site': 'abc', - 'vrops_user': 'user', - 'vrops_password': 'passwd', - 'vim_url': 'vcd_url', - 'admin_username': 'admin', - 'admin_password': 'admin_passwd', - 'vim_uuid': '1', - 'tenant_id': 'org_vdc_1'} - m_configure_rest_plugin.retrun_value = "plugin_uuid" - m_configure_alarm.return_value = None - - # call create alarm method under test - alarm_uuid = self.plugin_receiver.create_alarm(config_alarm_info) - - # verify mocked method called with correct params - m_get_vim_access_config.assert_called_with(config_alarm_info['vim_uuid']) - m_configure_rest_plugin.assert_called_with() - m_configure_alarm.assert_called_with(config_alarm_info["alarm_create_request"]) - - # verify create alarm method returns None when failed - self.assertEqual(alarm_uuid, None) - - @mock.patch.object(monPluginRec.MonPlugin, 'update_alarm_configuration') - @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') - def test_update_alarm_successful(self, m_get_vim_access_config, m_update_alarm_configuration): - """ Test functionality of update alarm method-positive case""" - - # Mock update_alarm_info - update_alarm_info = {"schema_version": 1.0, "schema_type": "update_alarm_request", - "vim_type": "VMware", "vim_uuid": "1", - "alarm_update_request": {'alarm_uuid': 'abc', 'correlation_id': 14203}} - - # set return value to mocked method - m_update_alarm_configuration.return_value = "alarm_uuid" - m_get_vim_access_config.return_value = {'vrops_site': 'abc', - 'vrops_user': 'user', - 'vrops_password': 'passwd', - 'vim_url': 'vcd_url', - 'admin_username': 'admin', - 'admin_password': 'admin_passwd', - 'vim_uuid': '1', - 'tenant_id': 'org_vdc_1'} - - # check update alarm gets called and returned correct value - ret_value = self.plugin_receiver.update_alarm(update_alarm_info) - - # check mocked method get called with correct param - m_get_vim_access_config.assert_called_with(update_alarm_info['vim_uuid']) - m_update_alarm_configuration.assert_called_with(update_alarm_info["alarm_update_request"]) - - # check return value and passed values are correct - self.assertEqual(ret_value, "alarm_uuid") - - @mock.patch.object(monPluginRec.MonPlugin, 'update_alarm_configuration') - @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') - def test_update_alarm_failed(self, m_get_vim_access_config, m_update_alarm_configuration): - """ Test functionality of update alarm method negative case""" - - # Mock update_alarm_info - update_alarm_info = {"schema_version": 1.0, "schema_type": "update_alarm_request", - "vim_type": "VMware", "vim_uuid": "1", - "alarm_update_request": {'alarm_uuid': 'abc', 'correlation_id': 14203}} - - # set return value to mocked method - m_update_alarm_configuration.return_value = None - m_get_vim_access_config.return_value = {'vrops_site': 'abc', - 'vrops_user': 'user', - 'vrops_password': 'passwd', - 'vim_url': 'vcd_url', - 'admin_username': 'admin', - 'admin_password': 'admin_passwd', - 'vim_uuid': '1', - 'tenant_id': 'org_vdc_1'} - - # check update alarm gets called and returned correct value - ret_value = self.plugin_receiver.update_alarm(update_alarm_info) - - # check mocked method get called with correct param - m_get_vim_access_config.assert_called_with(update_alarm_info['vim_uuid']) - m_update_alarm_configuration.assert_called_with(update_alarm_info["alarm_update_request"]) - - # check return value and passed values are correct - self.assertEqual(ret_value, None) - - @mock.patch.object(monPluginRec.MonPlugin, 'delete_alarm_configuration') - @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') - def test_delete_alarm_successful(self, m_get_vim_access_config, m_delete_alarm_configuration): - """ Test functionality of delete alarm method-positive case""" - - # Mock delete_alarm_info - delete_alarm_info = {"schema_version": 1.0, "schema_type": "delete_alarm_request", - "vim_type": "VMware", "vim_uuid": "1", - "alarm_delete_request": {'alarm_uuid': 'abc', 'correlation_id': 14203}} - - # set return value to mocked method - m_delete_alarm_configuration.return_value = "alarm_uuid" - m_get_vim_access_config.return_value = {'vrops_site': 'abc', - 'vrops_user': 'user', - 'vrops_password': 'passwd', - 'vim_url': 'vcd_url', - 'admin_username': 'admin', - 'admin_password': 'admin_passwd', - 'vim_uuid': '1', - 'tenant_id': 'org_vdc_1'} - - # check delete alarm gets called and returned correct value - ret_value = self.plugin_receiver.delete_alarm(delete_alarm_info) - - # check mocked method get called with correct param - m_get_vim_access_config.assert_called_with(delete_alarm_info['vim_uuid']) - m_delete_alarm_configuration.assert_called_with(delete_alarm_info["alarm_delete_request"]) - - # check return value and passed values are correct - self.assertEqual(ret_value, "alarm_uuid") - - @mock.patch.object(monPluginRec.MonPlugin, 'delete_alarm_configuration') - @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') - def test_delete_alarm_failed(self, m_get_vim_access_config, m_delete_alarm_configuration): - """ Test functionality of delete alarm method-negative case""" - - # Mock update_alarm_info - delete_alarm_info = {"schema_version": 1.0, "schema_type": "delete_alarm_request", - "vim_type": "VMware", "vim_uuid": "1", - "alarm_delete_request": {'alarm_uuid': 'abc', 'correlation_id': 14203}} - - # set return value to mocked method - m_delete_alarm_configuration.return_value = None - m_get_vim_access_config.return_value = {'vrops_site': 'abc', - 'vrops_user': 'user', - 'vrops_password': 'passwd', - 'vim_url': 'vcd_url', - 'admin_username': 'admin', - 'admin_password': 'admin_passwd', - 'vim_uuid': '1', - 'tenant_id': 'org_vdc_1'} - - # check delete alarm gets called and returned correct value - ret_value = self.plugin_receiver.delete_alarm(delete_alarm_info) - - # check mocked method get called with correct param - m_get_vim_access_config.assert_called_with(delete_alarm_info['vim_uuid']) - m_delete_alarm_configuration.assert_called_with(delete_alarm_info["alarm_delete_request"]) - - # check return value to check failed status - self.assertEqual(ret_value, None) - - def test_publish_create_alarm_status(self): - """ Test functionality of publish create alarm status method""" - - # Mock config_alarm_info - config_alarm_info = {'vim_type': 'VMware', "vim_uuid": "1", - 'alarm_create_request': { - 'threshold_value': 0, - 'severity': 'CRITICAL', - 'alarm_name': 'CPU_Utilization_Above_Threshold', - 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', - 'correlation_id': 1234, - 'statistic': 'AVERAGE', - 'metric_name': 'CPU_UTILIZATION'} - } - - alarm_uuid = "xyz" - - # call publish create status method under test - self.plugin_receiver.publish_create_alarm_status(alarm_uuid, config_alarm_info) - - # verify mocked method called with correct params - # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) - - def test_publish_update_alarm_status(self): - """ Test functionality of publish update alarm status method""" - - # Mock update_alarm_info - update_alarm_info = {'vim_type': 'VMware', - 'vim_uuid': '1', - 'schema_type': 'update_alarm_request', - 'alarm_update_request': {'alarm_uuid': '6486e69', - 'correlation_id': 14203, - 'operation': 'GT' - } - } - - alarm_uuid = "xyz" - - # call publish update alarm status method under test - self.plugin_receiver.publish_update_alarm_status(alarm_uuid, update_alarm_info) - - # verify mocked method called with correct params - # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) - - def test_publish_delete_alarm_status(self): - """ Test functionality of publish delete alarm status method""" - - # Mock delete_alarm_info - delete_alarm_info = {'vim_type': 'VMware', - "vim_uuid": "1", - 'schema_type': 'delete_alarm_request', - 'alarm_delete_request': {'alarm_uuid': '6486e69', - 'correlation_id': 14203, - 'operation': 'GT' - } - } - - alarm_uuid = "xyz" - - # call publish delete alarm status method under test - self.plugin_receiver.publish_delete_alarm_status(alarm_uuid, delete_alarm_info) - - # verify mocked method called with correct params - # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) - - def test_publish_metrics_data_status(self): - """ Test functionality of publish metrics data status method""" - - # Mock metrics data - metrics_data = { - 'vim_uuid': '1', - 'metric_name': 'CPU_UTILIZATION', 'metric_uuid': '0', - 'resource_uuid': 'e14b20', 'correlation_id': 14203, - 'metrics_data': {'time_series': [15162011, 15162044], - 'metrics_series': [0.1166666671, 0.1266666650]}, - 'tenant_uuid': 123, 'unit': '%' - } - - # call publish metrics data status method under test - self.plugin_receiver.publish_metrics_data_status(metrics_data) - - # verify mocked method called with correct params - # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) - - @mock.patch.object(monPluginRec.MonPlugin, 'verify_metric_support') - @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') - def test_verify_metric_supported_metric(self, m_get_vim_access_config, - m_verify_metric_support): - """ Test functionality of verify metric method""" - - # mock metric_info - metric_info = {'vim_uuid': '1', - 'metric_create_request': {'metric_unit': '%', - 'metric_name': 'CPU_UTILIZATION', - 'resource_uuid': 'e14b203'}} - - # set mocked function return value to true - m_verify_metric_support.return_value = True - m_get_vim_access_config.return_value = {'vrops_site': 'abc', - 'vrops_user': 'user', - 'vrops_password': 'passwd', - 'vim_url': 'vcd_url', - 'admin_username': 'admin', - 'admin_password': 'admin_passwd', - 'vim_uuid': '1', - 'tenant_id': 'org_vdc_1'} - - # call verify_metric method under test - ret_value = self.plugin_receiver.verify_metric(metric_info) - - # verify mocked method called with correct params - m_get_vim_access_config.assert_called_with(metric_info['vim_uuid']) - m_verify_metric_support.assert_called_with(metric_info['metric_create_request']) - - # verify the return value - self.assertEqual(ret_value, True) - - @mock.patch.object(monPluginRec.MonPlugin, 'verify_metric_support') - @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') - def test_verify_metric_unsupported_metric(self, m_get_vim_access_config, - m_verify_metric_support): - """ Test functionality of verify metric method-negative case""" - - # mock metric_info with unsupported metrics name - metric_info = {'vim_uuid': '1', - 'metric_create_request': {'metric_unit': '%', - 'metric_name': 'Invalid', - 'resource_uuid': 'e14b203'}} - - # set mocked function return value to true - m_verify_metric_support.return_value = False - m_get_vim_access_config.return_value = {'vrops_site': 'abc', - 'vrops_user': 'user', - 'vrops_password': 'passwd', - 'vim_url': 'vcd_url', - 'admin_username': 'admin', - 'admin_password': 'admin_passwd', - 'vim_uuid': '1', - 'tenant_id': 'org_vdc_1'} - - # call verify_metric method under test - ret_value = self.plugin_receiver.verify_metric(metric_info) - - # verify mocked method called with correct params - m_get_vim_access_config.assert_called_with(metric_info['vim_uuid']) - m_verify_metric_support.assert_called_with(metric_info['metric_create_request']) - - # verify the return value - self.assertEqual(ret_value, False) - - def test_publish_create_metric_response(self): - """ Test functionality of publish create metric response method""" - - # Mock metric_info - metric_info = { - 'vim_uuid': '1', - 'vim_type': 'VMware', - 'correlation_id': 14203, - 'schema_type': 'create_metric_request', - 'metric_create_request': { - 'resource_uuid': '6486e69', - 'metric_name': 'CPU_UTILIZATION', - 'metric_unit': '%' - } - } - - metric_status = True - - # call publish create metric method under test - self.plugin_receiver.publish_create_metric_response(metric_info, metric_status) - - # verify mocked method called with correct params - # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) - - def test_publish_update_metric_response(self): - """ Test functionality of publish update metric response method""" - - # Mock metric_info - metric_info = { - 'vim_uuid': '1', - 'vim_type': 'VMware', - 'correlation_id': 14203, - 'schema_type': 'update_metric_request', - 'metric_create': { - 'resource_uuid': '6486e69', - 'metric_name': 'CPU_UTILIZATION', - 'metric_unit': '%' - } - } - - metric_status = True - - # call publish update metric method under test - self.plugin_receiver.publish_update_metric_response(metric_info, metric_status) - - # verify mocked method called with correct params - # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) - - def test_publish_delete_metric_response(self): - """ Test functionality of publish delete metric response method""" - - # Mock metric_info - metric_info = {'vim_uuid': '1', 'vim_type': 'VMware', 'correlation_id': 14203, - 'metric_uuid': 'e14b203c', 'resource_uuid': '6486e69', - 'metric_name': 'CPU_UTILIZATION', - 'schema_type': 'delete_metric_request'} - - # call publish delete metric method under test-vROPS doesn't support - # delete metric,just returns response with success - self.plugin_receiver.publish_delete_metric_response(metric_info) - - # verify mocked method called with correct params - # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) - - @mock.patch.object(monPluginRec.MonPlugin, 'get_triggered_alarms_list') - @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') - def test_list_alarms(self, m_get_vim_access_config, m_get_triggered_alarms_list): - """ Test functionality of list alarms method""" - - # Mock list alarm input - list_alarm_input = { - 'vim_uuid': '1', - 'vim_type': 'VMware', - 'alarm_list_request': { - 'severity': 'CRITICAL', - 'correlation_id': 14203, - 'alarm_name': 'CPU_Utilization_Above_Threshold', - 'resource_uuid': 'd14b203c'}} - - # set return value to mocked method - m_return = [{'status': 'ACTIVE', 'update_date': '2018-01-12T08:34:05', - 'severity': 'CRITICAL', 'resource_uuid': 'e14b203c', - 'cancel_date': '0000-00-00T00:00:00', 'alarm_instance_uuid': 'd9e3bc84', - 'alarm_uuid': '5714977d', 'vim_type': 'VMware', - 'start_date': '2018-01-12T08:34:05'}, - {'status': 'CANCELED', 'update_date': '2017-12-20T09:37:57', - 'severity': 'CRITICAL', 'resource_uuid': 'e14b203c', - 'cancel_date': '2018-01-12T06:49:19', 'alarm_instance_uuid': 'd3bbeef6', - 'alarm_uuid': '7ba1bf3e', 'vim_type': 'VMware', - 'start_date': '2017-12-20T09:37:57'}] - m_get_triggered_alarms_list.return_value = m_return - - m_get_vim_access_config.return_value = {'vrops_site': 'abc', - 'vrops_user': 'user', - 'vrops_password': 'passwd', - 'vim_url': 'vcd_url', - 'admin_username': 'admin', - 'admin_password': 'admin_passwd', - 'vim_uuid': '1', - 'tenant_id': 'org_vdc_1'} - - # call list alarms method under test - return_value = self.plugin_receiver.list_alarms(list_alarm_input) - - # verify mocked method called with correct params - m_get_vim_access_config.assert_called_with(list_alarm_input['vim_uuid']) - m_get_triggered_alarms_list.assert_called_with(list_alarm_input['alarm_list_request']) - - # verify list alarm method returns correct list - self.assertEqual(return_value, m_return) - - def test_publish_list_alarm_response(self): - """ Test functionality of publish list alarm response method""" - - # Mock list alarm input - msg_key = 'list_alarm_response' - topic = 'alarm_response' - list_alarm_input = {'vim_uuid': '1', - 'vim_type': 'VMware', - 'alarm_list_request': { - 'severity': 'CRITICAL', - 'correlation_id': 14203, - 'alarm_name': 'CPU_Utilization_Above_Threshold', - 'resource_uuid': 'd14b203c'}} - - triggered_alarm_list = [{'status': 'ACTIVE', 'update_date': '2018-01-12T08:34:05', - 'severity': 'CRITICAL', 'resource_uuid': 'e14b203c', - 'cancel_date': '0000-00-00T00:00:00', - 'start_date': '2018-01-12T08:34:05', - 'alarm_instance_uuid': 'd9e3bc84', - 'alarm_uuid': '5714977d', - 'vim_type': 'VMware' - }] - - # call publish list alarm response method under test - response = self.plugin_receiver.publish_list_alarm_response(triggered_alarm_list, list_alarm_input) - - # verify mocked method called with correct params - # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) - - def test_publish_access_update_response(self): - """ Test functionality of publish access update response method""" - - # Mock required inputs - access_update_status = True - access_info_req = {'vim_type': 'VMware', - 'vim_uuid': '1', - 'access_config': {'vrops_password': 'vmware', - 'vcloud-site': 'https://192.169.241.105', - 'vrops_user': 'Admin', 'correlation_id': 14203, - 'tenant_id': 'Org2'} - } - - # call publish access update response method under test - response = self.plugin_receiver.publish_access_update_response(access_update_status, access_info_req) - - # verify mocked method called with correct params - # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) - - @mock.patch.object(monPluginRec.PluginReceiver, 'write_access_config') - def test_update_access_credentials_successful(self, m_write_access_config): - """ Test functionality of update access credentials-positive case""" - - # Mock access_info - access_info = {'vrops_site': 'https://192.169.241.13', 'vrops_user': 'admin', - 'vrops_password': 'vmware', 'vcloud-site': 'https://192.169.241.15', - 'admin_username': 'admin', 'admin_password': 'vmware', - 'vcenter_ip': '192.169.241.13', 'vcenter_port': '443', - 'vcenter_user': 'admin', 'vcenter_password': 'vmware', - 'vim_tenant_name': 'Org2', 'orgname': 'Org2', 'tenant_id': 'Org2'} - - # Mock return values - expected_status = m_write_access_config.return_value = True - - # call publish update access credentials method under test - actual_status = self.plugin_receiver.update_access_credentials(access_info) - - # check write_access_config called with correct params - m_write_access_config.assert_called_with(access_info) - - # verify update access credentials returns correct status - self.assertEqual(expected_status, actual_status) - - @mock.patch.object(monPluginRec.PluginReceiver, 'write_access_config') - def test_update_access_credentials_less_config_params(self, m_write_access_config): - """ Test functionality of update access credentials-negative case""" - - # Mock access_info - access_info = {'vrops_site': 'https://192.169.241.13', 'vrops_user': 'admin', - 'vrops_password': 'vmware', 'vcloud-site': 'https://192.169.241.15', - 'admin_username': 'admin', 'admin_password': 'vmware', - 'vcenter_ip': '192.169.241.13', 'vcenter_port': '443', 'vcenter_user': 'admin', - 'vim_tenant_name': 'Org2', 'orgname': 'Org2', 'tenant_id': 'Org2'} - - # Mock return values - expected_status = m_write_access_config.return_value = False - - # call publish update access credentials method under test - actual_status = self.plugin_receiver.update_access_credentials(access_info) - - # check if mocked method not called - m_write_access_config.assert_not_called() - - # verify update access credentials returns correct status - self.assertEqual(expected_status, actual_status) - - @mock.patch.object(monPluginRec.PluginReceiver, 'write_access_config') - def test_update_access_credentials_failed(self, m_write_access_config): - """ Test functionality of update access credentials-failed case """ - - # Mock access_info - access_info = {'vrops_site': 'https://192.169.241.13', 'vrops_user': 'admin', - 'vrops_password': 'vmware', 'vcloud-site': 'https://192.169.241.15', - 'admin_username': 'admin', 'admin_password': 'vmware', - 'vcenter_ip': '192.169.241.13', 'vcenter_port': '443', - 'vcenter_user': 'admin', 'vcenter_password': 'vmware', - 'vim_tenant_name': 'Org2', 'orgname': 'Org2', 'tenant_id': 'Org2'} - - # Mock return values - expected_status = m_write_access_config.return_value = False - - # call publish update access credentials method under test - actual_status = self.plugin_receiver.update_access_credentials(access_info) - - # check write_access_config called with correct params - m_write_access_config.assert_called_with(access_info) - - # verify update access credentials returns correct status - self.assertEqual(expected_status, actual_status) - - def test_write_access_config_successful(self): - """ Test functionality of write access config method-positive case""" - - # Mock access_info - access_info = {'vrops_sit': 'https://192.169.241.13', 'vrops_user': 'admin', - 'vrops_password': 'vmware', 'vcloud-site': 'https://192.169.241.15', - 'admin_username': 'admin', 'admin_password': 'vmware', - 'vcenter_ip': '192.169.241.13', 'vcenter_port': '443', - 'vcenter_user': 'admin', 'vcenter_password': 'vmware', - 'vim_tenant_name': 'Org2', 'orgname': 'Org2', 'tenant_id': 'Org2'} - - # call write access config method under test - actual_status = self.plugin_receiver.write_access_config(access_info) - - # verify write access config returns correct status - self.assertEqual(True, actual_status) - - def test_write_access_config_failed(self): - """ Test functionality of write access config method-negative case""" - - # Mock access_info - access_info = [] # provided incorrect info to generate error - - # call write access config method under test - actual_status = self.plugin_receiver.write_access_config(access_info) - - # verify write access config returns correct status - self.assertEqual(False, actual_status) - - @mock.patch.object(monPluginRec.AuthManager, 'get_credentials') - def test_get_vim_access_config(self, m_get_credentials): - """ Test functionality of get_vim_access_config method-positive case""" - - # Mock vim_uuid & access_info - vim_uuid = '1' - vim_details = VimCredentials() - vim_details.name = "vrops_vcd82" - vim_details.password = "passwd" - vim_details.tenant_name = "MANO-VDC" - vim_details.type = "VMware" - vim_details.url = "https://10.10.1.1" - vim_details.user = "admin" - vim_details.uuid = "1" - vim_details.config = '{"orgname": "MANO-Org", "tenant_id": "MANO-VDC",\ - "admin_username": "administrator","admin_password": "vcd_pwd",\ - "vrops_user": "admin", "vrops_password": "vrops_pwd",\ - "vrops_site": "https://10.10.1.2","nsx_user": "admin",\ - "nsx_manager": "https://10.10.1.3", "nsx_password":"nsx_pwd",\ - "sdn_controller": "None", "sdn_port_mapping": "None",\ - "vcenter_ip": "10.10.1.4", "vcenter_user": "admin@vsphere.local",\ - "vcenter_password": "vcenter_pwd", "vcenter_port": "443"}' - m_get_credentials.return_value = vim_details - expected_config = {'vrops_password': 'vrops_pwd', 'vcenter_password': 'vcenter_pwd', - 'name': 'vrops_vcd82', 'org_user': 'admin', - 'org_password': 'passwd', 'nsx_user': 'admin', 'vim_tenant_name': 'MANO-VDC', - 'admin_username': 'administrator', 'vcenter_port': '443', - 'vim_url': 'https://10.10.1.1', 'orgname': 'MANO-Org', - 'admin_password': 'vcd_pwd', 'vrops_user': 'admin', 'vcenter_ip': '10.10.1.4', - 'vrops_site': 'https://10.10.1.2', 'nsx_manager': 'https://10.10.1.3', - 'nsx_password': 'nsx_pwd', 'vim_type': 'VMware', 'vim_uuid': '1', - 'vcenter_user': 'admin@vsphere.local'} - - # call get_vim_access_config method under test - actual_config = self.plugin_receiver.get_vim_access_config('1') - - # verify that mocked method is called - m_get_credentials.assert_called_with(vim_uuid) - - # Verify return value with expected value - self.assertEqual(expected_config, actual_config) - -# For testing purpose -# if __name__ == '__main__': - -# unittest.main() diff --git a/osm_mon/test/collector/__init__.py b/osm_mon/test/collector/__init__.py new file mode 100644 index 0000000..2d39b96 --- /dev/null +++ b/osm_mon/test/collector/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- + +# Copyright 2018 Whitestack, LLC +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to Whitestack, LLC + +# 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. +# For those usages not covered by the Apache License, Version 2.0 please +# contact: bdiaz@whitestack.com or glavado@whitestack.com +## \ No newline at end of file diff --git a/osm_mon/test/collector/test_collector.py b/osm_mon/test/collector/test_collector.py new file mode 100644 index 0000000..b4ec741 --- /dev/null +++ b/osm_mon/test/collector/test_collector.py @@ -0,0 +1,206 @@ +# -*- coding: utf-8 -*- + +# Copyright 2018 Whitestack, LLC +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to Whitestack, LLC + +# 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. +# For those usages not covered by the Apache License, Version 2.0 please +# contact: bdiaz@whitestack.com or glavado@whitestack.com +## +import unittest + +import mock +from kafka import KafkaProducer +from kafka.errors import KafkaError +from osm_common import dbmongo + +from osm_mon.collector.collector import MonCollector +from osm_mon.core.database import VimCredentials, DatabaseManager +from osm_mon.core.message_bus.common_consumer import CommonConsumer + + +@mock.patch.object(dbmongo.DbMongo, "db_connect", mock.Mock()) +class MonCollectorTest(unittest.TestCase): + def test_generate_metric_data_payloads(self): + vnfr = { + "_id": "0d9d06ad-3fc2-418c-9934-465e815fafe2", + "ip-address": "192.168.160.2", + "created-time": 1535392482.0044956, + "vim-account-id": "be48ae31-1d46-4892-a4b4-d69abd55714b", + "vdur": [ + { + "interfaces": [ + { + "mac-address": "fa:16:3e:71:fd:b8", + "name": "eth0", + "ip-address": "192.168.160.2" + } + ], + "status": "ACTIVE", + "vim-id": "63a65636-9fc8-4022-b070-980823e6266a", + "name": "cirros_ns-1-cirros_vnfd-VM-1", + "status-detailed": None, + "ip-address": "192.168.160.2", + "vdu-id-ref": "cirros_vnfd-VM" + } + ], + "id": "0d9d06ad-3fc2-418c-9934-465e815fafe2", + "vnfd-ref": "cirros_vdu_scaling_vnf", + "vnfd-id": "63f44c41-45ee-456b-b10d-5f08fb1796e0", + "_admin": { + "created": 1535392482.0067868, + "projects_read": [ + "admin" + ], + "modified": 1535392482.0067868, + "projects_write": [ + "admin" + ] + }, + "nsr-id-ref": "87776f33-b67c-417a-8119-cb08e4098951", + "member-vnf-index-ref": "1", + "connection-point": [ + { + "name": "eth0", + "id": None, + "connection-point-id": None + } + ] + } + vnfd = { + "_id": "63f44c41-45ee-456b-b10d-5f08fb1796e0", + "name": "cirros_vdu_scaling_vnf", + "vendor": "OSM", + "vdu": [ + { + "name": "cirros_vnfd-VM", + "monitoring-param": [ + { + "id": "cirros_vnfd-VM_memory_util", + "nfvi-metric": "average_memory_utilization" + } + ], + "vm-flavor": { + "vcpu-count": 1, + "memory-mb": 256, + "storage-gb": 2 + }, + "description": "cirros_vnfd-VM", + "count": 1, + "id": "cirros_vnfd-VM", + "interface": [ + { + "name": "eth0", + "external-connection-point-ref": "eth0", + "type": "EXTERNAL", + "virtual-interface": { + "bandwidth": "0", + "type": "VIRTIO", + "vpci": "0000:00:0a.0" + } + } + ], + "image": "cirros034" + } + ], + "monitoring-param": [ + { + "id": "cirros_vnf_memory_util", + "name": "cirros_vnf_memory_util", + "aggregation-type": "AVERAGE", + "vdu-monitoring-param-ref": "cirros_vnfd-VM_memory_util", + "vdu-ref": "cirros_vnfd-VM" + } + ], + "description": "Simple VNF example with a cirros and a scaling group descriptor", + "id": "cirros_vdu_scaling_vnf", + "logo": "cirros-64.png", + "version": "1.0", + "connection-point": [ + { + "name": "eth0", + "type": "VPORT" + } + ], + "mgmt-interface": { + "cp": "eth0" + }, + "scaling-group-descriptor": [ + { + "name": "scale_cirros_vnfd-VM", + "min-instance-count": 1, + "vdu": [ + { + "count": 1, + "vdu-id-ref": "cirros_vnfd-VM" + } + ], + "max-instance-count": 10, + "scaling-policy": [ + { + "name": "auto_memory_util_above_threshold", + "scaling-type": "automatic", + "cooldown-time": 60, + "threshold-time": 10, + "scaling-criteria": [ + { + "name": "group1_memory_util_above_threshold", + "vnf-monitoring-param-ref": "cirros_vnf_memory_util", + "scale-out-threshold": 80, + "scale-out-relational-operation": "GT", + "scale-in-relational-operation": "LT", + "scale-in-threshold": 20 + } + ] + } + ] + } + ], + "short-name": "cirros_vdu_scaling_vnf", + "_admin": { + "created": 1535392242.6281035, + "modified": 1535392242.6281035, + "storage": { + "zipfile": "package.tar.gz", + "pkg-dir": "cirros_vnf", + "path": "/app/storage/", + "folder": "63f44c41-45ee-456b-b10d-5f08fb1796e0", + "fs": "local", + "descriptor": "cirros_vnf/cirros_vdu_scaling_vnfd.yaml" + }, + "usageSate": "NOT_IN_USE", + "onboardingState": "ONBOARDED", + "userDefinedData": { + + }, + "projects_read": [ + "admin" + ], + "operationalState": "ENABLED", + "projects_write": [ + "admin" + ] + } + } + payloads = MonCollector._generate_metric_data_payloads(vnfr, vnfd) + expected_payload = {'ns_id': '87776f33-b67c-417a-8119-cb08e4098951', + 'vnf_member_index': '1', + 'metric_name': 'average_memory_utilization', + 'collection_period': 1, + 'collection_unit': 'DAY', + 'vdu_name': 'cirros_ns-1-cirros_vnfd-VM-1'} + self.assertEqual(len(payloads), 1) + self.assertEqual(set(expected_payload.items()).issubset(set(payloads[0].items())), True) diff --git a/osm_mon/test/core/test_common_consumer.py b/osm_mon/test/core/test_common_consumer.py index eaf06c1..adbcb1d 100644 --- a/osm_mon/test/core/test_common_consumer.py +++ b/osm_mon/test/core/test_common_consumer.py @@ -1,3 +1,25 @@ +# -*- coding: utf-8 -*- + +# Copyright 2018 Whitestack, LLC +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to Whitestack, LLC + +# 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. +# For those usages not covered by the Apache License, Version 2.0 please +# contact: bdiaz@whitestack.com or glavado@whitestack.com +## import unittest import mock diff --git a/osm_mon/test/functional/__init__.py b/osm_mon/test/functional/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/osm_mon/test/plugins/CloudWatch/__init__.py b/osm_mon/test/plugins/CloudWatch/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/alarm_details/acknowledge_alarm.json b/osm_mon/test/plugins/CloudWatch/test_schemas/alarm_details/acknowledge_alarm.json new file mode 100644 index 0000000..341b2bd --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/alarm_details/acknowledge_alarm.json @@ -0,0 +1,11 @@ +{ +"schema_version": "1.0", +"schema_type": "alarm_ack", +"vim_type": "AWS", +"ack_details": +{ +"alarm_uuid": "CPU_Utilization_i-098da78cbd8304e17", +"resource_uuid": "i-098da78cbd8304e17", +"tenant_uuid": "" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/create_alarm_differentName_differentInstance.json b/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/create_alarm_differentName_differentInstance.json new file mode 100644 index 0000000..ecf403e --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/create_alarm_differentName_differentInstance.json @@ -0,0 +1,18 @@ +{ +"schema_version": "1.0", +"schema_type": "create_alarm_request", +"vim_type": "AWS", +"alarm_create_request": +{ +"correlation_id": "SO123", +"alarm_name": "CPU_Utilization_Above_Threshold", +"resource_uuid": "i-098da78cbd8304e17", +"description": "", +"severity": "Critical", +"operation": "GE", +"threshold_value": 1.5, +"unit": "", +"metric_name": "CPU_UTILIZATION", +"statistic": "MAXIMUM" +} +} diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/create_alarm_differentName_sameInstance.json b/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/create_alarm_differentName_sameInstance.json new file mode 100644 index 0000000..17c423d --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/create_alarm_differentName_sameInstance.json @@ -0,0 +1,18 @@ +{ +"schema_version": "1.0", +"schema_type": "create_alarm_request", +"vim_type": "AWS", +"alarm_create_request": +{ +"correlation_id": "SO123", +"alarm_name": "CPU_Utilization_Above_Threshold1", +"resource_uuid": "i-098da78cbd8304e17", +"description": "", +"severity": "Critical", +"operation": "GE", +"threshold_value": 1.5, +"unit": "", +"metric_name": "CPU_UTILIZATION", +"statistic": "MAXIMUM" +} +} diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/create_alarm_sameName_differentInstance.json b/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/create_alarm_sameName_differentInstance.json new file mode 100644 index 0000000..b2f5acb --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/create_alarm_sameName_differentInstance.json @@ -0,0 +1,18 @@ +{ +"schema_version": "1.0", +"schema_type": "create_alarm_request", +"vim_type": "AWS", +"alarm_create_request": +{ +"correlation_id": "SO123", +"alarm_name": "CPU_Utilization_Above_Threshold", +"resource_uuid": "i-09462760703837b26", +"description": "", +"severity": "Critical", +"operation": "GE", +"threshold_value": 1.5, +"unit": "", +"metric_name": "CPU_UTILIZATION", +"statistic": "MAXIMUM" +} +} diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/create_alarm_sameName_sameInstance.json b/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/create_alarm_sameName_sameInstance.json new file mode 100644 index 0000000..ecf403e --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/create_alarm_sameName_sameInstance.json @@ -0,0 +1,18 @@ +{ +"schema_version": "1.0", +"schema_type": "create_alarm_request", +"vim_type": "AWS", +"alarm_create_request": +{ +"correlation_id": "SO123", +"alarm_name": "CPU_Utilization_Above_Threshold", +"resource_uuid": "i-098da78cbd8304e17", +"description": "", +"severity": "Critical", +"operation": "GE", +"threshold_value": 1.5, +"unit": "", +"metric_name": "CPU_UTILIZATION", +"statistic": "MAXIMUM" +} +} diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/operation_invalid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/operation_invalid.json new file mode 100644 index 0000000..31e1e0b --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/operation_invalid.json @@ -0,0 +1,18 @@ +{ +"schema_version": "1.0", +"schema_type": "create_alarm_request", +"vim_type": "AWS", +"alarm_create_request": +{ +"correlation_id": "SO123", +"alarm_name": "CPU_Utilization_Above_Threshold2", +"resource_uuid": "i-098da78cbd8304e17", +"description": "", +"severity": "Critical", +"operation": "Greaterthan", +"threshold_value": 1.5, +"unit": "", +"metric_name": "CPU_UTILIZATION", +"statistic": "MAXIMUM" +} +} diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/operation_valid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/operation_valid.json new file mode 100644 index 0000000..adb789b --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/operation_valid.json @@ -0,0 +1,18 @@ +{ +"schema_version": "1.0", +"schema_type": "create_alarm_request", +"vim_type": "AWS", +"alarm_create_request": +{ +"correlation_id": "SO123", +"alarm_name": "CPU_Utilization_Above_Threshold2", +"resource_uuid": "i-098da78cbd8304e17", +"description": "", +"severity": "Critical", +"operation": "GE", +"threshold_value": 1.5, +"unit": "", +"metric_name": "CPU_UTILIZATION", +"statistic": "MAXIMUM" +} +} diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/statistic_invalid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/statistic_invalid.json new file mode 100644 index 0000000..8c2e68d --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/statistic_invalid.json @@ -0,0 +1,18 @@ +{ +"schema_version": "1.0", +"schema_type": "create_alarm_request", +"vim_type": "AWS", +"alarm_create_request": +{ +"correlation_id": "SO123", +"alarm_name": "CPU_Utilization_Above_Threshold2", +"resource_uuid": "i-098da78cbd8304e17", +"description": "", +"severity": "Critical", +"operation": "GE", +"threshold_value": 1.5, +"unit": "", +"metric_name": "CPU_UTILIZATION", +"statistic": "MAX" +} +} diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/statistic_valid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/statistic_valid.json new file mode 100644 index 0000000..adb789b --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/create_alarm/statistic_valid.json @@ -0,0 +1,18 @@ +{ +"schema_version": "1.0", +"schema_type": "create_alarm_request", +"vim_type": "AWS", +"alarm_create_request": +{ +"correlation_id": "SO123", +"alarm_name": "CPU_Utilization_Above_Threshold2", +"resource_uuid": "i-098da78cbd8304e17", +"description": "", +"severity": "Critical", +"operation": "GE", +"threshold_value": 1.5, +"unit": "", +"metric_name": "CPU_UTILIZATION", +"statistic": "MAXIMUM" +} +} diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/create_metrics/create_metric_req_invalid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/create_metrics/create_metric_req_invalid.json new file mode 100644 index 0000000..0fe0dcb --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/create_metrics/create_metric_req_invalid.json @@ -0,0 +1,13 @@ +{ +"schema_version": "1.0", +"schema_type": "create_metrics_request", +"tenant_uuid": "", +"correlation_id": "SO123", +"vim_type": "AWS", +"metric_create": +{ +"metric_name": "CPU_UTILIZ", +"metric_unit": "", +"resource_uuid": "i-098da78cbd8304e17" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/create_metrics/create_metric_req_valid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/create_metrics/create_metric_req_valid.json new file mode 100644 index 0000000..18cc23c --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/create_metrics/create_metric_req_valid.json @@ -0,0 +1,13 @@ +{ +"schema_version": "1.0", +"schema_type": "create_metrics_request", +"tenant_uuid": "", +"correlation_id": "SO123", +"vim_type": "AWS", +"metric_create": +{ +"metric_name": "CPU_UTILIZATION", +"metric_unit": "", +"resource_uuid": "i-098da78cbd8304e17" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_invalid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_invalid.json new file mode 100644 index 0000000..e51a670 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_invalid.json @@ -0,0 +1,10 @@ +{ +"schema_version": "1.0", +"schema_type": "delete_alarm_request", +"vim_type": "AWS", +"alarm_delete_request": +{ +"alarm_uuid": "CPU_Utilization_Above_Threshold_i-098da78cbd8304e16", +"correlation_id": "SO123" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_valid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_valid.json new file mode 100644 index 0000000..a2cd4b5 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_valid.json @@ -0,0 +1,10 @@ +{ +"schema_version": "1.0", +"schema_type": "delete_alarm_request", +"vim_type": "AWS", +"alarm_delete_request": +{ +"alarm_uuid": "CPU_Utilization_Above_Threshold_i-098da78cbd8304e17", +"correlation_id": "SO123" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_valid_delete1.json b/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_valid_delete1.json new file mode 100644 index 0000000..f465df7 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_valid_delete1.json @@ -0,0 +1,10 @@ +{ +"schema_version": "1.0", +"schema_type": "delete_alarm_request", +"vim_type": "AWS", +"alarm_delete_request": +{ +"alarm_uuid": "CPU_Utilization_Above_Threshold1_i-098da78cbd8304e17", +"correlation_id": "SO123" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_valid_delete2.json b/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_valid_delete2.json new file mode 100644 index 0000000..1fa6870 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_valid_delete2.json @@ -0,0 +1,10 @@ +{ +"schema_version": "1.0", +"schema_type": "delete_alarm_request", +"vim_type": "AWS", +"alarm_delete_request": +{ +"alarm_uuid": "CPU_Utilization_Above_Threshold_i-09462760703837b26", +"correlation_id": "SO123" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_valid_delete3.json b/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_valid_delete3.json new file mode 100644 index 0000000..6c35ab2 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_valid_delete3.json @@ -0,0 +1,10 @@ +{ +"schema_version": "1.0", +"schema_type": "delete_alarm_request", +"vim_type": "AWS", +"alarm_delete_request": +{ +"alarm_uuid": "CPU_Utilization_Above_Threshold2_i-098da78cbd8304e17", +"correlation_id": "SO123" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_valid_delete4.json b/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_valid_delete4.json new file mode 100644 index 0000000..716b039 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/delete_alarm/name_valid_delete4.json @@ -0,0 +1,10 @@ +{ +"schema_version": "1.0", +"schema_type": "delete_alarm_request", +"vim_type": "AWS", +"alarm_delete_request": +{ +"alarm_uuid": "CPU_Utilization_Above_Threshold4_i-098da78cbd8304e17", +"correlation_id": "SO123" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/delete_metrics/delete_metric_req_invalid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/delete_metrics/delete_metric_req_invalid.json new file mode 100644 index 0000000..f30ab87 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/delete_metrics/delete_metric_req_invalid.json @@ -0,0 +1,10 @@ +{ +"schema_version": "1.0", +"schema_type": "delete_metric_data_request", +"metric_name": "CPU_UTILIATION", +"metric_uuid": "", +"resource_uuid": "i-098da78cbd8304e17", +"tenant_uuid": "", +"correlation_uuid": "S0123", +"vim_type": "AWS" +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/delete_metrics/delete_metric_req_valid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/delete_metrics/delete_metric_req_valid.json new file mode 100644 index 0000000..ea3922b --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/delete_metrics/delete_metric_req_valid.json @@ -0,0 +1,10 @@ +{ +"schema_version": "1.0", +"schema_type": "delete_metric_data_request", +"metric_name": "CPU_UTILIZATION", +"metric_uuid": "", +"resource_uuid": "i-098da78cbd8304e17", +"tenant_uuid": "", +"correlation_uuid": "S0123", +"vim_type": "AWS" +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/list_alarm/list_alarm_valid_no_arguments.json b/osm_mon/test/plugins/CloudWatch/test_schemas/list_alarm/list_alarm_valid_no_arguments.json new file mode 100644 index 0000000..a4d02a3 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/list_alarm/list_alarm_valid_no_arguments.json @@ -0,0 +1,12 @@ +{ +"schema_version": "1.0", +"schema_type": "list_alarm_request", +"vim_type": "AWS", +"alarm_list_request": +{ +"correlation_id": "SO123", +"resource_uuid": "", +"alarm_name": "", +"severity": "" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/list_alarm/list_alarm_valid_one_argument.json b/osm_mon/test/plugins/CloudWatch/test_schemas/list_alarm/list_alarm_valid_one_argument.json new file mode 100644 index 0000000..d0f31f2 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/list_alarm/list_alarm_valid_one_argument.json @@ -0,0 +1,12 @@ +{ +"schema_version": "1.0", +"schema_type": "list_alarm_request", +"vim_type": "AWS", +"alarm_list_request": +{ +"correlation_id": "SO123", +"resource_uuid": "i-098da78cbd8304e17", +"alarm_name": "", +"severity": "" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/list_alarm/list_alarm_valid_two_arguments.json b/osm_mon/test/plugins/CloudWatch/test_schemas/list_alarm/list_alarm_valid_two_arguments.json new file mode 100644 index 0000000..bf46579 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/list_alarm/list_alarm_valid_two_arguments.json @@ -0,0 +1,12 @@ +{ +"schema_version": "1.0", +"schema_type": "list_alarm_request", +"vim_type": "AWS", +"alarm_list_request": +{ +"correlation_id": "SO123", +"resource_uuid": "i-098da78cbd8304e17", +"alarm_name": "", +"severity": "Critical" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/list_metrics/list_metric_req_invalid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/list_metrics/list_metric_req_invalid.json new file mode 100644 index 0000000..6108e77 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/list_metrics/list_metric_req_invalid.json @@ -0,0 +1,11 @@ +{ +"schema_version": "1.0", +"schema_type": "list_metrics_request", +"vim_type": "AWS", +"metrics_list_request": +{ +"metric_name": "CPU_UTILZATION", +"correlation_id": "SO123", +"resource_uuid": "i-098da78cbd8304e17" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/list_metrics/list_metric_req_valid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/list_metrics/list_metric_req_valid.json new file mode 100644 index 0000000..b1bd9de --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/list_metrics/list_metric_req_valid.json @@ -0,0 +1,11 @@ +{ +"schema_version": "1.0", +"schema_type": "list_metrics_request", +"vim_type": "AWS", +"metrics_list_request": +{ +"metric_name": "CPU_UTILIZATION", +"correlation_id": "SO123", +"resource_uuid": "i-098da78cbd8304e17" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/read_metrics_data/read_coll_period_req_invalid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/read_metrics_data/read_coll_period_req_invalid.json new file mode 100644 index 0000000..815edf9 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/read_metrics_data/read_coll_period_req_invalid.json @@ -0,0 +1,12 @@ +{ +"schema_version": "1.0", +"schema_type": "read_metric_data_request", +"metric_name": "CPU_UTILIZATION", +"metric_uuid": "0", +"resource_uuid": "i-098da78cbd8304e17", +"tenant_uuid": "", +"correlation_uuid": "SO123", +"vim_type":"AWS", +"collection_period":"3500" , +"collection_unit": "" +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/read_metrics_data/read_coll_period_req_valid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/read_metrics_data/read_coll_period_req_valid.json new file mode 100644 index 0000000..dad9a24 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/read_metrics_data/read_coll_period_req_valid.json @@ -0,0 +1,12 @@ +{ +"schema_version": "1.0", +"schema_type": "read_metric_data_request", +"metric_name": "CPU_UTILIZATION", +"metric_uuid": "0", +"resource_uuid": "i-098da78cbd8304e17", +"tenant_uuid": "", +"correlation_uuid": "SO123", +"vim_type":"AWS", +"collection_period":"3600" , +"collection_unit": "" +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/read_metrics_data/read_metric_name_req_invalid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/read_metrics_data/read_metric_name_req_invalid.json new file mode 100644 index 0000000..0ff4f0e --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/read_metrics_data/read_metric_name_req_invalid.json @@ -0,0 +1,12 @@ +{ +"schema_version": "1.0", +"schema_type": "read_metric_data_request", +"metric_name": "CPU_UTLIZATION", +"metric_uuid": "0", +"resource_uuid": "i-098da78cbd8304e17", +"tenant_uuid": "", +"correlation_uuid": "SO123", +"vim_type":"AWS", +"collection_period":"3600" , +"collection_unit": "" +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/read_metrics_data/read_metric_name_req_valid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/read_metrics_data/read_metric_name_req_valid.json new file mode 100644 index 0000000..dad9a24 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/read_metrics_data/read_metric_name_req_valid.json @@ -0,0 +1,12 @@ +{ +"schema_version": "1.0", +"schema_type": "read_metric_data_request", +"metric_name": "CPU_UTILIZATION", +"metric_uuid": "0", +"resource_uuid": "i-098da78cbd8304e17", +"tenant_uuid": "", +"correlation_uuid": "SO123", +"vim_type":"AWS", +"collection_period":"3600" , +"collection_unit": "" +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/name_invalid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/name_invalid.json new file mode 100644 index 0000000..fe171e4 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/name_invalid.json @@ -0,0 +1,17 @@ +{ +"schema_version": "1.0", +"schema_type": "update_alarm_request", +"vim_type": "AWS", +"alarm_update_request": +{ +"correlation_id": "SO123", +"alarm_uuid": "CPU_Utilization_Above_Threshold_i-098da78cbd8304e13", +"description": "", +"severity": "Critical", +"operation": "LE", +"threshold_value": 1.5, +"unit": "", +"metric_name": "CPU_UTILIZATION", +"statistic": "MAXIMUM" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/name_valid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/name_valid.json new file mode 100644 index 0000000..7070dff --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/name_valid.json @@ -0,0 +1,17 @@ +{ +"schema_version": "1.0", +"schema_type": "update_alarm_request", +"vim_type": "AWS", +"alarm_update_request": +{ +"correlation_id": "SO123", +"alarm_uuid": "CPU_Utilization_Above_Threshold4_i-098da78cbd8304e17", +"description": "", +"severity": "Critical", +"operation": "LE", +"threshold_value": 1.5, +"unit": "", +"metric_name": "CPU_UTILIZATION", +"statistic": "MAXIMUM" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/operation_invalid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/operation_invalid.json new file mode 100644 index 0000000..0116228 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/operation_invalid.json @@ -0,0 +1,17 @@ +{ +"schema_version": "1.0", +"schema_type": "update_alarm_request", +"vim_type": "AWS", +"alarm_update_request": +{ +"correlation_id": "SO123", +"alarm_uuid": "CPU_Utilization_Above_Threshold_i-098da78cbd8304e17", +"description": "", +"severity": "Critical", +"operation": "Less", +"threshold_value": 1.5, +"unit": "", +"metric_name": "CPU_UTILIZATION", +"statistic": "MAXIMUM" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/operation_valid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/operation_valid.json new file mode 100644 index 0000000..5fb8eb6 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/operation_valid.json @@ -0,0 +1,17 @@ +{ +"schema_version": "1.0", +"schema_type": "update_alarm_request", +"vim_type": "AWS", +"alarm_update_request": +{ +"correlation_id": "SO123", +"alarm_uuid": "CPU_Utilization_Above_Threshold_i-098da78cbd8304e17", +"description": "", +"severity": "Critical", +"operation": "LE", +"threshold_value": 1.5, +"unit": "", +"metric_name": "CPU_UTILIZATION", +"statistic": "MAXIMUM" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/statistic_invalid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/statistic_invalid.json new file mode 100644 index 0000000..991d844 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/statistic_invalid.json @@ -0,0 +1,17 @@ +{ +"schema_version": "1.0", +"schema_type": "update_alarm_request", +"vim_type": "AWS", +"alarm_update_request": +{ +"correlation_id": "SO123", +"alarm_uuid": "CPU_Utilization_Above_Threshold_i-098da78cbd8304e17", +"description": "", +"severity": "Critical", +"operation": "LE", +"threshold_value": 1.5, +"unit": "", +"metric_name": "CPU_UTILIZATION", +"statistic": "MAX" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/statistic_valid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/statistic_valid.json new file mode 100644 index 0000000..5fb8eb6 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/statistic_valid.json @@ -0,0 +1,17 @@ +{ +"schema_version": "1.0", +"schema_type": "update_alarm_request", +"vim_type": "AWS", +"alarm_update_request": +{ +"correlation_id": "SO123", +"alarm_uuid": "CPU_Utilization_Above_Threshold_i-098da78cbd8304e17", +"description": "", +"severity": "Critical", +"operation": "LE", +"threshold_value": 1.5, +"unit": "", +"metric_name": "CPU_UTILIZATION", +"statistic": "MAXIMUM" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/update_alarm_new_alarm.json b/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/update_alarm_new_alarm.json new file mode 100644 index 0000000..581fb55 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/update_alarm/update_alarm_new_alarm.json @@ -0,0 +1,18 @@ +{ +"schema_version": "1.0", +"schema_type": "create_alarm_request", +"vim_type": "AWS", +"alarm_create_request": +{ +"correlation_id": "SO123", +"alarm_name": "CPU_Utilization_Above_Threshold4", +"resource_uuid": "i-098da78cbd8304e17", +"description": "", +"severity": "Critical", +"operation": "GE", +"threshold_value": 1.5, +"unit": "", +"metric_name": "CPU_UTILIZATION", +"statistic": "MAXIMUM" +} +} diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/update_metrics/update_metric_req_invalid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/update_metrics/update_metric_req_invalid.json new file mode 100644 index 0000000..0fe0dcb --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/update_metrics/update_metric_req_invalid.json @@ -0,0 +1,13 @@ +{ +"schema_version": "1.0", +"schema_type": "create_metrics_request", +"tenant_uuid": "", +"correlation_id": "SO123", +"vim_type": "AWS", +"metric_create": +{ +"metric_name": "CPU_UTILIZ", +"metric_unit": "", +"resource_uuid": "i-098da78cbd8304e17" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/test_schemas/update_metrics/update_metric_req_valid.json b/osm_mon/test/plugins/CloudWatch/test_schemas/update_metrics/update_metric_req_valid.json new file mode 100644 index 0000000..18cc23c --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/test_schemas/update_metrics/update_metric_req_valid.json @@ -0,0 +1,13 @@ +{ +"schema_version": "1.0", +"schema_type": "create_metrics_request", +"tenant_uuid": "", +"correlation_id": "SO123", +"vim_type": "AWS", +"metric_create": +{ +"metric_name": "CPU_UTILIZATION", +"metric_unit": "", +"resource_uuid": "i-098da78cbd8304e17" +} +} \ No newline at end of file diff --git a/osm_mon/test/plugins/CloudWatch/unit_tests_alarms.py b/osm_mon/test/plugins/CloudWatch/unit_tests_alarms.py new file mode 100644 index 0000000..ae036cf --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/unit_tests_alarms.py @@ -0,0 +1,408 @@ +from connection import Connection +import unittest +import sys +import jsmin +import json +import os +import time +from jsmin import jsmin +sys.path.append("../../test/core/") +from test_producer import KafkaProducer +from kafka import KafkaConsumer +try: + import boto + import boto.ec2 + import boto.vpc + import boto.ec2.cloudwatch + import boto.ec2.connection +except: + exit("Boto not avialable. Try activating your virtualenv OR `pip install boto`") + +#-------------------------------------------------------------------------------------------------------------------------------------- + +# Test Producer object to generate request + +producer = KafkaProducer('create_alarm_request') +obj = Connection() +connections = obj.setEnvironment() +connections_res = obj.connection_instance() +cloudwatch_conn = connections_res['cloudwatch_connection'] + +#-------------------------------------------------------------------------------------------------------------------------------------- + +'''Test E2E Flow : Test cases has been tested one at a time. +1) Commom Request is generated using request function in test_producer.py(/test/core) +2) The request is then consumed by the comsumer (plugin) +3) The response is sent back on the message bus in plugin_alarm.py using + response functions in producer.py(/core/message-bus) +4) The response is then again consumed by the unit_tests_alarms.py + and the test cases has been applied on the response. +''' + +class config_alarm_name_test(unittest.TestCase): + + + def setUp(self): + pass + #To generate a request of testing new alarm name and new instance id in create alarm request + def test_differentName_differentInstance(self): + time.sleep(2) + producer.request("test_schemas/create_alarm/create_alarm_differentName_differentInstance.json",'create_alarm_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "create_alarm_response": + info = json.loads(json.loads(message.value)) + print(info) + time.sleep(1) + self.assertTrue(info['alarm_create_response']['status']) + return + + #To generate a request of testing new alarm name and existing instance id in create alarm request + def test_differentName_sameInstance(self): + time.sleep(2) + producer.request("test_schemas/create_alarm/create_alarm_differentName_sameInstance.json",'create_alarm_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "create_alarm_response": + info = json.loads(json.loads(message.value)) + print(info) + time.sleep(1) + producer.request("test_schemas/delete_alarm/name_valid_delete1.json",'delete_alarm_request','','alarm_request') + self.assertTrue(info['alarm_create_response']['status']) + return + + #To generate a request of testing existing alarm name and new instance id in create alarm request + def test_sameName_differentInstance(self): + time.sleep(2) + producer.request("test_schemas/create_alarm/create_alarm_sameName_differentInstance.json",'create_alarm_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "create_alarm_response": + info = json.loads(json.loads(message.value)) + print(info) + time.sleep(1) + producer.request("test_schemas/delete_alarm/name_valid_delete2.json",'delete_alarm_request', '','alarm_request') + self.assertTrue(info['alarm_create_response']['status']) + return + + #To generate a request of testing existing alarm name and existing instance id in create alarm request + def test_sameName_sameInstance(self): + time.sleep(2) + producer.request("test_schemas/create_alarm/create_alarm_sameName_sameInstance.json",'create_alarm_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "create_alarm_response": + info = json.loads(json.loads(message.value)) + print(info, "---") + time.sleep(1) + producer.request("test_schemas/delete_alarm/name_valid.json",'delete_alarm_request', '','alarm_request') + self.assertEqual(info, None) + return + + #To generate a request of testing valid statistics in create alarm request + def test_statisticValid(self): + time.sleep(2) + producer.request("test_schemas/create_alarm/statistic_valid.json",'create_alarm_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "create_alarm_response": + info = json.loads(json.loads(message.value)) + print(info) + time.sleep(1) + producer.request("test_schemas/delete_alarm/name_valid_delete3.json",'delete_alarm_request', '','alarm_request') + self.assertTrue(info['alarm_create_response']['status']) + return + + #To generate a request of testing Invalid statistics in create alarm request + def test_statisticValidNot(self): + time.sleep(2) + producer.request("test_schemas/create_alarm/statistic_invalid.json",'create_alarm_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "create_alarm_response": + info = json.loads(json.loads(message.value)) + print(info, "---") + time.sleep(1) + producer.request("test_schemas/delete_alarm/name_valid_delete3.json",'delete_alarm_request', '','alarm_request') + self.assertEqual(info, None) + return + + #To generate a request of testing valid operation in create alarm request + def test_operationValid(self): + time.sleep(2) + producer.request("test_schemas/create_alarm/operation_valid.json",'create_alarm_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "create_alarm_response": + info = json.loads(json.loads(message.value)) + print(info) + time.sleep(1) + producer.request("test_schemas/delete_alarm/name_valid_delete3.json",'delete_alarm_request', '','alarm_request') + self.assertTrue(info['alarm_create_response']['status']) + return + + #To generate a request of testing Invalid operation in create alarm request + def test_operationValidNot(self): + time.sleep(2) + producer.request("test_schemas/create_alarm/operation_invalid.json",'create_alarm_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "create_alarm_response": + info = json.loads(json.loads(message.value)) + print(info) + time.sleep(1) + self.assertEqual(info,None) + return + + +#-------------------------------------------------------------------------------------------------------------------------------------- +class update_alarm_name_test(unittest.TestCase): + + #To generate a request of testing valid alarm_id in update alarm request + def test_nameValid(self): + producer.request("test_schemas/update_alarm/update_alarm_new_alarm.json",'create_alarm_request', '','alarm_request') + time.sleep(2) + producer.request("test_schemas/update_alarm/name_valid.json",'update_alarm_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "update_alarm_response": + info = json.loads(json.loads(json.loads(message.value))) + print(info) + time.sleep(1) + producer.request("test_schemas/delete_alarm/name_valid_delete4.json",'delete_alarm_request', '','alarm_request') + self.assertTrue(info['alarm_update_response']['status']) + return + + #To generate a request of testing invalid alarm_id in update alarm request + def test_nameInvalid(self): + time.sleep(2) + producer.request("test_schemas/update_alarm/name_invalid.json",'update_alarm_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "update_alarm_response": + info = json.loads(json.loads(json.loads(message.value))) + print(info) + time.sleep(1) + self.assertEqual(info,None) + return + + #To generate a request of testing valid statistics in update alarm request + def test_statisticValid(self): + producer.request("test_schemas/create_alarm/create_alarm_differentName_differentInstance.json",'create_alarm_request', '','alarm_request') + time.sleep(2) + producer.request("test_schemas/update_alarm/statistic_valid.json",'update_alarm_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "update_alarm_response": + info = json.loads(json.loads(json.loads(message.value))) + print(info) + time.sleep(1) + producer.request("test_schemas/delete_alarm/name_valid.json",'delete_alarm_request', '','alarm_request') + self.assertTrue(info['alarm_update_response']['status']) + return + + #To generate a request of testing Invalid statistics in update alarm request + def test_statisticInvalid(self): + time.sleep(2) + producer.request("test_schemas/update_alarm/statistic_invalid.json",'update_alarm_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "update_alarm_response": + info = json.loads(json.loads(json.loads(message.value))) + print(info) + time.sleep(1) + self.assertEqual(info,None) + return + + #To generate a request of testing valid operation in update alarm request + def test_operationValid(self): + producer.request("test_schemas/create_alarm/create_alarm_differentName_differentInstance.json",'create_alarm_request', '','alarm_request') + time.sleep(2) + producer.request("test_schemas/update_alarm/operation_valid.json",'update_alarm_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "update_alarm_response": + info = json.loads(json.loads(json.loads(message.value))) + print(info) + time.sleep(1) + producer.request("test_schemas/delete_alarm/name_valid.json",'delete_alarm_request', '','alarm_request') + self.assertTrue(info['alarm_update_response']['status']) + return + +#-------------------------------------------------------------------------------------------------------------------------------------- +class delete_alarm_test(unittest.TestCase): + + #To generate a request of testing valid alarm_id in delete alarm request + def test_nameValid(self): + producer.request("test_schemas/create_alarm/create_alarm_differentName_differentInstance.json",'create_alarm_request', '','alarm_request') + time.sleep(2) + producer.request("test_schemas/delete_alarm/name_valid.json",'delete_alarm_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "delete_alarm_response": + info = json.loads(json.loads(json.loads(message.value))) + print(info) + time.sleep(1) + self.assertTrue(info['alarm_deletion_response']['status']) + return + + #To generate a request of testing Invalid alarm_id in delete alarm request + def test_nameInvalid(self): + time.sleep(2) + producer.request("test_schemas/delete_alarm/name_invalid.json",'delete_alarm_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "delete_alarm_response": + info = json.loads(json.loads(json.loads(message.value))) + print(info) + time.sleep(1) + self.assertEqual(info,None) + return + +#-------------------------------------------------------------------------------------------------------------------------------------- +class list_alarm_test(unittest.TestCase): + + #To generate a request of testing valid input fields in alarm list request + def test_valid_no_arguments(self): + time.sleep(2) + producer.request("test_schemas/list_alarm/list_alarm_valid_no_arguments.json",'alarm_list_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "list_alarm_response": + info = json.loads(json.loads(json.loads(message.value))) + print(info) + time.sleep(1) + self.assertEqual(type(info),dict) + return + + #To generate a request of testing valid input fields in alarm list request + def test_valid_one_arguments(self): + time.sleep(2) + producer.request("test_schemas/list_alarm/list_alarm_valid_one_arguments.json",'alarm_list_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "list_alarm_response": + info = json.loads(json.loads(json.loads(message.value))) + print(info) + time.sleep(1) + self.assertEqual(type(info),dict) + return + + #To generate a request of testing valid input fields in alarm list request + def test_valid_two_arguments(self): + time.sleep(2) + producer.request("test_schemas/list_alarm/list_alarm_valid_two_arguments.json",'alarm_list_request', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "list_alarm_response": + info = json.loads(json.loads(json.loads(message.value))) + print(info) + time.sleep(1) + self.assertEqual(type(info),dict) + return + + +#-------------------------------------------------------------------------------------------------------------------------------------- +class alarm_details_test(unittest.TestCase): + + #To generate a request of testing valid input fields in acknowledge alarm + def test_Valid(self): + time.sleep(2) + producer.request("test_schemas/alarm_details/acknowledge_alarm.json",'acknowledge_alarm', '','alarm_request') + server = {'server': 'localhost:9092', 'topic': 'alarm_request'} + + _consumer = KafkaConsumer(bootstrap_servers=server['server']) + _consumer.subscribe(['alarm_response']) + + for message in _consumer: + if message.key == "notify_alarm": + info = json.loads(json.loads(json.loads(message.value))) + print(info) + time.sleep(1) + self.assertEqual(type(info),dict) + return + +if __name__ == '__main__': + + # Saving test reults in Log file + + log_file = 'log_file.txt' + f = open(log_file, "w") + runner = unittest.TextTestRunner(f) + unittest.main(testRunner=runner) + f.close() + + # For printing results on Console + # unittest.main() diff --git a/osm_mon/test/plugins/CloudWatch/unit_tests_metrics.py b/osm_mon/test/plugins/CloudWatch/unit_tests_metrics.py new file mode 100644 index 0000000..625e872 --- /dev/null +++ b/osm_mon/test/plugins/CloudWatch/unit_tests_metrics.py @@ -0,0 +1,208 @@ +from connection import Connection +import unittest +import sys +import jsmin +import json +import os +import time +from jsmin import jsmin +sys.path.append("../../test/core/") +from test_producer import KafkaProducer +from kafka import KafkaConsumer +try: + import boto + import boto.ec2 + import boto.vpc + import boto.ec2.cloudwatch + import boto.ec2.connection +except: + exit("Boto not avialable. Try activating your virtualenv OR `pip install boto`") + +#-------------------------------------------------------------------------------------------------------------------------------------- + +# Test Producer object to generate request + +producer = KafkaProducer('') +obj = Connection() +connections = obj.setEnvironment() +connections_res = obj.connection_instance() +cloudwatch_conn = connections_res['cloudwatch_connection'] + +# Consumer Object to consume response from message bus +server = {'server': 'localhost:9092', 'topic': 'metric_request'} +_consumer = KafkaConsumer(bootstrap_servers=server['server']) +_consumer.subscribe(['metric_response']) + +#-------------------------------------------------------------------------------------------------------------------------------------- + +'''Test E2E Flow : Test cases has been tested one at a time. +1) Commom Request is generated using request function in test_producer.py(/core/message-bus) +2) The request is then consumed by the comsumer (plugin) +3) The response is sent back on the message bus in plugin_metrics.py using + response functions in producer.py(/core/message-bus) +4) The response is then again consumed by the unit_tests_metrics.py + and the test cases has been applied on the response. +''' +class test_create_metrics(unittest.TestCase): + + def test_status_positive(self): + time.sleep(2) + # To generate Request of testing valid meric_name in create metrics requests + producer.request("create_metrics/create_metric_req_valid.json",'create_metric_request', '','metric_request') + + for message in _consumer: + if message.key == "create_metric_response": + resp = json.loads(json.loads(json.loads(message.value))) + time.sleep(1) + self.assertTrue(resp['metric_create_response']['status']) + self.assertEqual(resp['metric_create_response']['metric_uuid'],0) + return + + def test_status_negative(self): + time.sleep(2) + # To generate Request of testing invalid meric_name in create metrics requests + producer.request("create_metrics/create_metric_req_invalid.json",'create_metric_request', '','metric_request') + + for message in _consumer: + if message.key == "create_metric_response": + resp = json.loads(json.loads(json.loads(message.value))) + time.sleep(1) + self.assertFalse(resp['metric_create_response']['status']) + self.assertEqual(resp['metric_create_response']['metric_uuid'],None) + return + +class test_metrics_data(unittest.TestCase): + + def test_met_name_positive(self): + time.sleep(2) + # To generate Request of testing valid meric_name in read_metric_data_request + producer.request("read_metrics_data/read_metric_name_req_valid.json",'read_metric_data_request', '','metric_request') + for message in _consumer: + if message.key == "read_metric_data_response": + resp = json.loads(json.loads(json.loads(message.value))) + time.sleep(1) + self.assertEqual(type(resp['metrics_data']),dict) + return + + def test_met_name_negative(self): + time.sleep(2) + # To generate Request of testing invalid meric_name in read_metric_data_request + producer.request("read_metrics_data/read_metric_name_req_invalid.json",'read_metric_data_request', '','metric_request') + for message in _consumer: + if message.key == "read_metric_data_response": + resp = json.loads(json.loads(json.loads(message.value))) + time.sleep(1) + self.assertFalse(resp['metrics_data']) + return + + def test_coll_period_positive(self): + # To generate Request of testing valid collection_period in read_metric_data_request + # For AWS metric_data_stats collection period should be a multiple of 60 + time.sleep(2) + producer.request("read_metrics_data/read_coll_period_req_valid.json",'read_metric_data_request', '','metric_request') + for message in _consumer: + if message.key == "read_metric_data_response": + resp = json.loads(json.loads(json.loads(message.value))) + time.sleep(1) + self.assertEqual(type(resp),dict) + return + + def test_coll_period_negative(self): + time.sleep(2) + # To generate Request of testing invalid collection_period in read_metric_data_request + producer.request("read_metrics_data/read_coll_period_req_invalid.json",'read_metric_data_request', '','metric_request') + for message in _consumer: + if message.key == "read_metric_data_response": + resp = json.loads(json.loads(json.loads(message.value))) + time.sleep(1) + self.assertFalse(resp['metrics_data']) + return + +class test_update_metrics(unittest.TestCase): + + def test_upd_status_positive(self): + time.sleep(2) + # To generate Request of testing valid meric_name in update metrics requests + producer.request("update_metrics/update_metric_req_valid.json",'update_metric_request', '','metric_request') + for message in _consumer: + if message.key == "update_metric_response": + resp = json.loads(json.loads(json.loads(message.value))) + time.sleep(1) + self.assertTrue(resp['metric_update_response']['status']) + self.assertEqual(resp['metric_update_response']['metric_uuid'],0) + return + + def test_upd_status_negative(self): + time.sleep(2) + # To generate Request of testing invalid meric_name in update metrics requests + producer.request("update_metrics/update_metric_req_invalid.json",'update_metric_request', '','metric_request') + for message in _consumer: + if message.key == "update_metric_response": + resp = json.loads(json.loads(json.loads(message.value))) + time.sleep(1) + self.assertFalse(resp['metric_update_response']['status']) + self.assertEqual(resp['metric_update_response']['metric_uuid'],None) + return + +class test_delete_metrics(unittest.TestCase): + + def test_del_met_name_positive(self): + time.sleep(2) + # To generate Request of testing valid meric_name in delete metrics requests + producer.request("delete_metrics/delete_metric_req_valid.json",'delete_metric_request', '','metric_request') + for message in _consumer: + if message.key == "delete_metric_response": + resp = json.loads(json.loads(json.loads(message.value))) + time.sleep(1) + self.assertFalse(resp['status']) + return + + def test_del_met_name_negative(self): + time.sleep(2) + # To generate Request of testing invalid meric_name in delete metrics requests + producer.request("delete_metrics/delete_metric_req_invalid.json",'delete_metric_request', '','metric_request') + for message in _consumer: + if message.key == "delete_metric_response": + resp = json.loads(json.loads(json.loads(message.value))) + time.sleep(1) + self.assertFalse(resp) + return + +class test_list_metrics(unittest.TestCase): + + def test_list_met_name_positive(self): + time.sleep(2) + # To generate Request of testing valid meric_name in list metrics requests + producer.request("list_metrics/list_metric_req_valid.json",'list_metric_request', '','metric_request') + for message in _consumer: + if message.key == "list_metrics_response": + resp = json.loads(json.loads(json.loads(message.value))) + time.sleep(1) + self.assertEqual(type(resp['metrics_list']),list) + return + + def test_list_met_name_negitive(self): + time.sleep(2) + # To generate Request of testing invalid meric_name in list metrics requests + producer.request("list_metrics/list_metric_req_invalid.json",'list_metric_request', '','metric_request') + for message in _consumer: + if message.key == "list_metrics_response": + resp = json.loads(json.loads(json.loads(message.value))) + time.sleep(1) + self.assertFalse(resp['metrics_list']) + return + + +if __name__ == '__main__': + + # Saving test reults in Log file + + log_file = 'log_file.txt' + f = open(log_file, "w") + runner = unittest.TextTestRunner(f) + unittest.main(testRunner=runner) + f.close() + + # For printing results on Console + # unittest.main() + diff --git a/osm_mon/test/plugins/OpenStack/__init__.py b/osm_mon/test/plugins/OpenStack/__init__.py new file mode 100644 index 0000000..32eb94e --- /dev/null +++ b/osm_mon/test/plugins/OpenStack/__init__.py @@ -0,0 +1,21 @@ +# Copyright 2017 Intel Research and Development Ireland Limited +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to 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. + +# For those usages not covered by the Apache License, Version 2.0 please +# contact: helena.mcgough@intel.com or adrian.hoban@intel.com +## diff --git a/osm_mon/test/plugins/OpenStack/integration/__init__.py b/osm_mon/test/plugins/OpenStack/integration/__init__.py new file mode 100644 index 0000000..cd7731b --- /dev/null +++ b/osm_mon/test/plugins/OpenStack/integration/__init__.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- + +# Copyright 2018 Whitestack, LLC +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to Whitestack, LLC + +# 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. + +# For those usages not covered by the Apache License, Version 2.0 please +# contact: bdiaz@whitestack.com or glavado@whitestack.com +## +import logging +import sys + +from osm_mon.core.settings import Config + +cfg = Config.instance() +logging.basicConfig(stream=sys.stdout, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + datefmt='%m/%d/%Y %I:%M:%S %p', + level=logging.getLevelName(cfg.OSMMON_LOG_LEVEL)) +log = logging.getLogger(__name__) diff --git a/osm_mon/test/plugins/OpenStack/integration/test_alarm_integration.py b/osm_mon/test/plugins/OpenStack/integration/test_alarm_integration.py new file mode 100644 index 0000000..fbec56c --- /dev/null +++ b/osm_mon/test/plugins/OpenStack/integration/test_alarm_integration.py @@ -0,0 +1,221 @@ +# Copyright 2017 Intel Research and Development Ireland Limited +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to 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. + +# For those usages not covered by the Apache License, Version 2.0 please +# contact: helena.mcgough@intel.com or adrian.hoban@intel.com + +# __author__ = "Helena McGough" +"""Test an end to end Openstack alarm requests.""" + +import json +import logging +import unittest + +import mock +from kafka import KafkaConsumer +from kafka import KafkaProducer +from kafka.errors import KafkaError + +from osm_mon.core.auth import AuthManager +from osm_mon.core.database import DatabaseManager, VimCredentials +from osm_mon.plugins.OpenStack import response +from osm_mon.plugins.OpenStack.Aodh import alarm_handler +from osm_mon.plugins.OpenStack.common import Common + +log = logging.getLogger(__name__) + +mock_creds = VimCredentials() +mock_creds.config = '{}' + + +@mock.patch.object(DatabaseManager, "save_alarm", mock.Mock()) +@mock.patch.object(Common, "get_auth_token", mock.Mock()) +@mock.patch.object(Common, "get_endpoint", mock.Mock()) +class AlarmIntegrationTest(unittest.TestCase): + def setUp(self): + try: + self.producer = KafkaProducer(bootstrap_servers='localhost:9092', + key_serializer=str.encode, + value_serializer=str.encode + ) + self.req_consumer = KafkaConsumer(bootstrap_servers='localhost:9092', + key_deserializer=bytes.decode, + value_deserializer=bytes.decode, + auto_offset_reset='earliest', + consumer_timeout_ms=60000) + self.req_consumer.subscribe(['alarm_request']) + except KafkaError: + self.skipTest('Kafka server not present.') + # Set up common and alarming class instances + self.alarms = alarm_handler.OpenstackAlarmHandler() + self.openstack_auth = Common() + + def tearDown(self): + self.producer.close() + self.req_consumer.close() + + @mock.patch.object(Common, "perform_request") + @mock.patch.object(AuthManager, 'get_credentials') + @mock.patch.object(alarm_handler.OpenstackAlarmHandler, "update_alarm") + @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") + def test_update_alarm_req(self, resp, update_alarm, get_creds, perf_req): + """Test Aodh update alarm request message from KafkaProducer.""" + # Set-up message, producer and consumer for tests + payload = {"alarm_update_request": {"correlation_id": 123, + "alarm_uuid": "alarm_id", + "metric_uuid": "metric_id"}} + + get_creds.return_value = mock_creds + perf_req.return_value = type('obj', (object,), {'text': json.dumps({"metrics": {"cpu_util": "1"}})}) + resp.return_value = '' + + self.producer.send('alarm_request', key="update_alarm_request", + value=json.dumps(payload)) + + for message in self.req_consumer: + if message.key == "update_alarm_request": + # Mock a valid alarm update + update_alarm.return_value = "alarm_id" + self.alarms.handle_message(message, 'test_id') + + # A response message is generated and sent via MON's producer + resp.assert_called_with( + 'update_alarm_response', alarm_id="alarm_id", cor_id=123, + status=True) + + return + self.fail("No message received in consumer") + + @mock.patch.object(Common, "perform_request") + @mock.patch.object(AuthManager, 'get_credentials') + @mock.patch.object(alarm_handler.OpenstackAlarmHandler, "configure_alarm") + @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") + def test_create_alarm_req(self, resp, config_alarm, get_creds, perf_req): + """Test Aodh create alarm request message from KafkaProducer.""" + # Set-up message, producer and consumer for tests + payload = {"alarm_create_request": {"correlation_id": 123, + "alarm_name": "my_alarm", + "metric_name": "cpu_utilization", + "resource_uuid": "my_resource", + "severity": "WARNING", + "threshold_value": 60, + "operation": "GT", + "vdu_name": "vdu", + "vnf_member_index": "1", + "ns_id": "1"}} + + get_creds.return_value = mock_creds + perf_req.return_value = type('obj', (object,), {'text': json.dumps({"metrics": {"cpu_util": "1"}})}) + resp.return_value = '' + self.producer.send('alarm_request', key="create_alarm_request", + value=json.dumps(payload)) + + for message in self.req_consumer: + if message.key == "create_alarm_request": + # Mock a valid alarm creation + config_alarm.return_value = "alarm_id" + self.alarms.handle_message(message, 'test_id') + + # A response message is generated and sent via MON's produce + resp.assert_called_with( + 'create_alarm_response', status=True, alarm_id="alarm_id", + cor_id=123) + + return + self.fail("No message received in consumer") + + @mock.patch.object(Common, "perform_request") + @mock.patch.object(AuthManager, 'get_credentials') + @mock.patch.object(alarm_handler.OpenstackAlarmHandler, "list_alarms") + @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") + def test_list_alarm_req(self, resp, list_alarm, get_creds, perf_req): + """Test Aodh list alarm request message from KafkaProducer.""" + # Set-up message, producer and consumer for tests + payload = {"alarm_list_request": {"correlation_id": 123, + "resource_uuid": "resource_id", }} + + self.producer.send('alarm_request', key="list_alarm_request", + value=json.dumps(payload)) + + get_creds.return_value = mock_creds + perf_req.return_value = type('obj', (object,), {'text': json.dumps([])}) + resp.return_value = '' + + for message in self.req_consumer: + if message.key == "list_alarm_request": + # Mock an empty list generated by the request + list_alarm.return_value = [] + self.alarms.handle_message(message, 'test_id') + + # Response message is generated + resp.assert_called_with( + 'list_alarm_response', alarm_list=[], + cor_id=123) + + return + self.fail("No message received in consumer") + + @mock.patch.object(Common, "perform_request") + @mock.patch.object(AuthManager, 'get_credentials') + @mock.patch.object(alarm_handler.OpenstackAlarmHandler, "delete_alarm") + @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") + def test_delete_alarm_req(self, resp, del_alarm, get_creds, perf_req): + """Test Aodh delete alarm request message from KafkaProducer.""" + # Set-up message, producer and consumer for tests + payload = {"alarm_delete_request": {"correlation_id": 123, + "alarm_uuid": "alarm_id", }} + + self.producer.send('alarm_request', key="delete_alarm_request", + value=json.dumps(payload)) + + get_creds.return_value = mock_creds + perf_req.return_value = type('obj', (object,), {'text': json.dumps([])}) + resp.return_value = '' + + for message in self.req_consumer: + if message.key == "delete_alarm_request": + self.alarms.handle_message(message, 'test_id') + + # Response message is generated and sent by MON's producer + resp.assert_called_with( + 'delete_alarm_response', alarm_id="alarm_id", + status=True, cor_id=123) + + return + self.fail("No message received in consumer") + + @mock.patch.object(AuthManager, 'get_credentials') + @mock.patch.object(alarm_handler.OpenstackAlarmHandler, "update_alarm_state") + def test_ack_alarm_req(self, ack_alarm, get_creds): + """Test Aodh acknowledge alarm request message from KafkaProducer.""" + # Set-up message, producer and consumer for tests + payload = {"ack_details": {"alarm_uuid": "alarm_id", }} + + self.producer.send('alarm_request', key="acknowledge_alarm", + value=json.dumps(payload)) + + get_creds.return_value = mock_creds + ack_alarm.return_value = True + + for message in self.req_consumer: + if message.key == "acknowledge_alarm": + self.alarms.handle_message(message, 'test_id') + ack_alarm.assert_called_with(mock.ANY, mock.ANY, 'alarm_id', True) + return + + self.fail("No message received in consumer") diff --git a/osm_mon/test/plugins/OpenStack/integration/test_metric_integration.py b/osm_mon/test/plugins/OpenStack/integration/test_metric_integration.py new file mode 100644 index 0000000..578c8b1 --- /dev/null +++ b/osm_mon/test/plugins/OpenStack/integration/test_metric_integration.py @@ -0,0 +1,242 @@ +# Copyright 2017 Intel Research and Development Ireland Limited +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to 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. + +# For those usages not covered by the Apache License, Version 2.0 please +# contact: helena.mcgough@intel.com or adrian.hoban@intel.com + +# __author__ = "Helena McGough" +"""Test an end to end Openstack metric requests.""" + +import json + +import logging +import unittest + +from kafka.errors import KafkaError + +from osm_mon.core.auth import AuthManager +from osm_mon.core.database import VimCredentials + +from kafka import KafkaConsumer +from kafka import KafkaProducer + +import mock + +from osm_mon.plugins.OpenStack import response + +from osm_mon.plugins.OpenStack.Gnocchi import metric_handler + +from osm_mon.plugins.OpenStack.common import Common + +log = logging.getLogger(__name__) + +mock_creds = VimCredentials() +mock_creds.config = '{}' + + +@mock.patch.object(Common, "get_auth_token", mock.Mock()) +@mock.patch.object(Common, "get_endpoint", mock.Mock()) +class MetricIntegrationTest(unittest.TestCase): + def setUp(self): + # Set up common and alarming class instances + self.metric_req = metric_handler.OpenstackMetricHandler() + self.openstack_auth = Common() + + try: + self.producer = KafkaProducer(bootstrap_servers='localhost:9092', + key_serializer=str.encode, + value_serializer=str.encode + ) + self.req_consumer = KafkaConsumer(bootstrap_servers='localhost:9092', + key_deserializer=bytes.decode, + value_deserializer=bytes.decode, + auto_offset_reset='earliest', + consumer_timeout_ms=60000) + self.req_consumer.subscribe(['metric_request']) + except KafkaError: + self.skipTest('Kafka server not present.') + + @mock.patch.object(Common, "perform_request") + @mock.patch.object(AuthManager, 'get_credentials') + @mock.patch.object(metric_handler.OpenstackMetricHandler, "configure_metric") + @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") + def test_create_metric_req(self, resp, config_metric, get_creds, perf_req): + """Test Gnocchi create metric request message from producer.""" + # Set-up message, producer and consumer for tests + payload = {"metric_create_request": {"correlation_id": 123, + "metric_name": "cpu_utilization", + "resource_uuid": "resource_id"}} + + get_creds.return_value = mock_creds + perf_req.return_value = type('obj', (object,), {'text': json.dumps({"metrics": {"cpu_util": "1"}})}) + resp.return_value = '' + + self.producer.send('metric_request', key="create_metric_request", + value=json.dumps(payload)) + + for message in self.req_consumer: + if message.key == "create_metric_request": + # A valid metric is created + config_metric.return_value = "metric_id", "resource_id" + self.metric_req.handle_request(message, 'test_id') + + # A response message is generated and sent by MON's producer + resp.assert_called_with( + 'create_metric_response', status=True, cor_id=123, + metric_id="metric_id", resource_id="resource_id") + + return + self.fail("No message received in consumer") + + @mock.patch.object(Common, "perform_request") + @mock.patch.object(AuthManager, 'get_credentials') + @mock.patch.object(metric_handler.OpenstackMetricHandler, "delete_metric") + @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") + def test_delete_metric_req(self, resp, del_metric, get_creds, perf_req): + """Test Gnocchi delete metric request message from producer.""" + # Set-up message, producer and consumer for tests + payload = {"vim_type": "OpenSTACK", + "vim_uuid": "1", + "correlation_id": 123, + "metric_name": "cpu_utilization", + "resource_uuid": "resource_id"} + + get_creds.return_value = mock_creds + perf_req.return_value = type('obj', (object,), {'text': json.dumps({"metrics": {"cpu_util": "1"}})}) + resp.return_value = '' + + self.producer.send('metric_request', key="delete_metric_request", + value=json.dumps(payload)) + + for message in self.req_consumer: + if message.key == "delete_metric_request": + # Metric has been deleted + del_metric.return_value = True + self.metric_req.handle_request(message, 'test_id') + + # A response message is generated and sent by MON's producer + resp.assert_called_with( + 'delete_metric_response', metric_id='1', + metric_name="cpu_utilization", status=True, resource_id="resource_id", + cor_id=123) + + return + self.fail("No message received in consumer") + + @mock.patch.object(Common, "perform_request") + @mock.patch.object(AuthManager, 'get_credentials') + @mock.patch.object(metric_handler.OpenstackMetricHandler, "read_metric_data") + @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") + def test_read_metric_data_req(self, resp, read_data, get_creds, perf_req): + """Test Gnocchi read metric data request message from producer.""" + # Set-up message, producer and consumer for tests + payload = {"vim_type": "OpenSTACK", + "vim_uuid": "test_id", + "correlation_id": 123, + "metric_name": "cpu_utilization", + "resource_uuid": "resource_id"} + + get_creds.return_value = mock_creds + perf_req.return_value = type('obj', (object,), {'text': json.dumps({"metrics": {"cpu_util": "1"}})}) + resp.return_value = '' + + self.producer.send('metric_request', key="read_metric_data_request", + value=json.dumps(payload)) + + for message in self.req_consumer: + # Check the vim desired by the message + if message.key == "read_metric_data_request": + # Mock empty lists generated by the request message + read_data.return_value = [], [] + self.metric_req.handle_request(message, 'test_id') + + # A response message is generated and sent by MON's producer + resp.assert_called_with( + 'read_metric_data_response', metric_id='1', + metric_name="cpu_utilization", resource_id="resource_id", cor_id=123, times=[], + metrics=[], status=True) + + return + self.fail("No message received in consumer") + + @mock.patch.object(Common, "perform_request") + @mock.patch.object(AuthManager, 'get_credentials') + @mock.patch.object(metric_handler.OpenstackMetricHandler, "list_metrics") + @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") + def test_list_metrics_req(self, resp, list_metrics, get_creds, perf_req): + """Test Gnocchi list metrics request message from producer.""" + # Set-up message, producer and consumer for tests + payload = {"vim_type": "OpenSTACK", + "vim_uuid": "1", + "metrics_list_request": + {"correlation_id": 123, }} + + get_creds.return_value = mock_creds + perf_req.return_value = type('obj', (object,), {'text': json.dumps({"metrics": {"cpu_util": "1"}})}) + resp.return_value = '' + + self.producer.send('metric_request', key="list_metric_request", + value=json.dumps(payload)) + + for message in self.req_consumer: + # Check the vim desired by the message + if message.key == "list_metric_request": + # Mock an empty list generated by the request + list_metrics.return_value = [] + self.metric_req.handle_request(message, 'test_id') + + # A response message is generated and sent by MON's producer + resp.assert_called_with( + 'list_metric_response', metric_list=[], cor_id=123, status=True) + + return + self.fail("No message received in consumer") + + @mock.patch.object(Common, "perform_request") + @mock.patch.object(AuthManager, 'get_credentials') + @mock.patch.object(metric_handler.OpenstackMetricHandler, "get_metric_id") + @mock.patch.object(response.OpenStackResponseBuilder, "generate_response") + def test_update_metrics_req(self, resp, get_id, get_creds, perf_req): + """Test Gnocchi update metric request message from KafkaProducer.""" + # Set-up message, producer and consumer for tests + payload = {"metric_update_request": {"metric_name": "my_metric", + "correlation_id": 123, + "resource_uuid": "resource_id", }} + + get_creds.return_value = mock_creds + perf_req.return_value = type('obj', (object,), {'text': json.dumps({"metrics": {"cpu_util": "1"}})}) + resp.return_value = '' + + self.producer.send('metric_request', key="update_metric_request", + value=json.dumps(payload)) + + for message in self.req_consumer: + # Check the vim desired by the message + if message.key == "update_metric_request": + # Gnocchi doesn't support metric updates + get_id.return_value = "metric_id" + self.metric_req.handle_request(message, 'test_id') + + # Response message is generated and sent via MON's producer + # No metric update has taken place + resp.assert_called_with( + 'update_metric_response', status=False, cor_id=123, + resource_id="resource_id", metric_id="metric_id") + + return + self.fail("No message received in consumer") diff --git a/osm_mon/test/plugins/OpenStack/integration/test_notify_alarm.py b/osm_mon/test/plugins/OpenStack/integration/test_notify_alarm.py new file mode 100644 index 0000000..8aa2c9f --- /dev/null +++ b/osm_mon/test/plugins/OpenStack/integration/test_notify_alarm.py @@ -0,0 +1,183 @@ +# Copyright 2017 Intel Research and Development Ireland Limited +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to 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. + +# For those usages not covered by the Apache License, Version 2.0 please +# contact: helena.mcgough@intel.com or adrian.hoban@intel.com +## +"""Tests for all common OpenStack methods.""" + +from __future__ import unicode_literals +import json +import logging +import socket +import unittest +from threading import Thread + +import mock +import requests +from kafka import KafkaProducer +from six.moves.BaseHTTPServer import BaseHTTPRequestHandler +from six.moves.BaseHTTPServer import HTTPServer + +from osm_mon.core.settings import Config +from osm_mon.plugins.OpenStack.Aodh.alarm_handler import OpenstackAlarmHandler +from osm_mon.plugins.OpenStack.common import Common +from osm_mon.plugins.OpenStack.response import OpenStackResponseBuilder + +log = logging.getLogger(__name__) + +# Create an instance of the common openstack class, producer and consumer +openstack_auth = Common() + +# Mock a valid get_response for alarm details +valid_get_resp = '{"gnocchi_resources_threshold_rule":\ + {"resource_id": "my_resource_id"}}' + + +class MockResponse(object): + """Mock a response class for generating responses.""" + + def __init__(self, text): + """Initialise a mock response with a text attribute.""" + self.text = text + + +class MockNotifierHandler(BaseHTTPRequestHandler): + """Mock the NotifierHandler class for testing purposes.""" + + def _set_headers(self): + """Set the headers for a request.""" + self.send_response(200) + self.send_header('Content-type', 'text/html') + self.end_headers() + + def do_GET(self): + """Mock functionality for GET request.""" + # self.send_response(requests.codes.ok) + self._set_headers() + pass + + def do_POST(self): + """Mock functionality for a POST request.""" + self._set_headers() + content_length = int(self.headers['Content-Length']) + post_data = self.rfile.read(content_length) + try: + post_data = post_data.decode() + except AttributeError: + pass + self.notify_alarm(json.loads(post_data)) + + def notify_alarm(self, values): + """Mock the notify_alarm functionality to generate a valid response.""" + cfg = Config.instance() + self._alarming = OpenstackAlarmHandler() + self._common = Common() + self._response = OpenStackResponseBuilder() + alarm_id = values['alarm_id'] + + auth_token = Common.get_auth_token('test_id') + endpoint = Common.get_endpoint('alarming', 'test_id') + + # If authenticated generate and send response message + if auth_token is not None and endpoint is not None: + url = "{}/v2/alarms/%s".format(endpoint) % alarm_id + + # Get the resource_id of the triggered alarm and the date + result = Common.perform_request( + url, auth_token, req_type="get") + alarm_details = json.loads(result.text) + gnocchi_rule = alarm_details['gnocchi_resources_threshold_rule'] + resource_id = gnocchi_rule['resource_id'] + # Mock a date for testing purposes + a_date = "dd-mm-yyyy 00:00" + + # Process an alarm notification if resource_id is valid + if resource_id is not None: + # Try generate and send response + try: + resp_message = self._response.generate_response( + 'notify_alarm', + alarm_id=alarm_id, + resource_id=resource_id, + sev=values['severity'], date=a_date, + state=values['current'], vim_type="OpenStack") + except Exception: + log.exception("Error generating response") + + +def get_free_port(): + """Function to get a free port to run the test webserver on.""" + s = socket.socket(socket.AF_INET, type=socket.SOCK_STREAM) + s.bind(('localhost', 0)) + address, port = s.getsockname() + s.close() + return port + + +# Create the webserver, port and run it on its own thread +mock_server_port = get_free_port() +mock_server = HTTPServer(('localhost', mock_server_port), MockNotifierHandler) +mock_server_thread = Thread(target=mock_server.serve_forever) +mock_server_thread.setDaemon(True) +mock_server_thread.start() + + +def test_do_get(): + """Integration test for get request on notifier webserver.""" + url = 'http://localhost:{port}/users'.format(port=mock_server_port) + + # Send a request to the mock API server and store the response. + response = requests.get(url) + + # Confirm that the request-response cycle completed successfully. + assert response.ok + + +class AlarmNotificationTest(unittest.TestCase): + @mock.patch.object(OpenStackResponseBuilder, "generate_response") + @mock.patch.object(Common, "perform_request") + @mock.patch.object(Common, "get_endpoint") + @mock.patch.object(Common, "get_auth_token") + def test_post_notify_alarm(self, auth, endpoint, perf_req, resp): + """Integration test for notify_alarm.""" + url = 'http://localhost:{port}/users'.format(port=mock_server_port) + payload = {"severity": "critical", + "alarm_name": "my_alarm", + "current": "current_state", + "alarm_id": "my_alarm_id", + "reason": "Threshold has been broken", + "reason_data": {"count": 1, + "most_recent": "null", + "type": "threshold", + "disposition": "unknown"}, + "previous": "previous_state"} + + # Mock authenticate and request response for testing + auth.return_value = "my_auth_token" + endpoint.return_value = "my_endpoint" + perf_req.return_value = MockResponse(valid_get_resp) + + # Generate a post request for testing + response = requests.post(url, json.dumps(payload)) + self.assertEqual(response.status_code, 200) + # A response message is generated with the following details + resp.assert_called_with( + "notify_alarm", alarm_id="my_alarm_id", resource_id="my_resource_id", + sev="critical", date='dd-mm-yyyy 00:00', state="current_state", + vim_type="OpenStack") diff --git a/osm_mon/test/plugins/OpenStack/integration/test_vim_account.py b/osm_mon/test/plugins/OpenStack/integration/test_vim_account.py new file mode 100644 index 0000000..da34bb2 --- /dev/null +++ b/osm_mon/test/plugins/OpenStack/integration/test_vim_account.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- + +# Copyright 2018 Whitestack, LLC +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to Whitestack, LLC + +# 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. + +# For those usages not covered by the Apache License, Version 2.0 please +# contact: bdiaz@whitestack.com or glavado@whitestack.com +## + +"""Test an end to end Openstack vim_account requests.""" + +import json +import logging +import unittest + +from osm_mon.core.auth import AuthManager +from osm_mon.core.database import DatabaseManager + +log = logging.getLogger(__name__) + + +class VimAccountTest(unittest.TestCase): + def setUp(self): + self.auth_manager = AuthManager() + self.database_manager = DatabaseManager() + self.database_manager.create_tables() + + def test_create_edit_delete_vim_account(self): + """Test vim_account creation message from KafkaProducer.""" + # Set-up message, producer and consumer for tests + create_payload = { + "_id": "test_id", + "name": "test_name", + "vim_type": "openstack", + "vim_url": "auth_url", + "vim_user": "user", + "vim_password": "password", + "vim_tenant_name": "tenant", + "config": + { + "foo": "bar" + } + } + self.auth_manager.store_auth_credentials(create_payload) + + creds = self.auth_manager.get_credentials('test_id') + + self.assertIsNotNone(creds) + self.assertEqual(creds.name, create_payload['name']) + self.assertEqual(json.loads(creds.config), create_payload['config']) + + # Set-up message, producer and consumer for tests + edit_payload = { + "_id": "test_id", + "name": "test_name_edited", + "vim_type": "openstack", + "vim_url": "auth_url", + "vim_user": "user", + "vim_password": "password", + "vim_tenant_name": "tenant", + "config": + { + "foo_edited": "bar_edited" + } + } + + self.auth_manager.store_auth_credentials(edit_payload) + + creds = self.auth_manager.get_credentials('test_id') + + self.assertEqual(creds.name, edit_payload['name']) + self.assertEqual(json.loads(creds.config), edit_payload['config']) + + delete_payload = { + "_id": "test_id" + } + + self.auth_manager.delete_auth_credentials(delete_payload) + + creds = self.auth_manager.get_credentials('test_id') + self.assertIsNone(creds) diff --git a/osm_mon/test/plugins/OpenStack/unit/__init__.py b/osm_mon/test/plugins/OpenStack/unit/__init__.py new file mode 100644 index 0000000..cd7731b --- /dev/null +++ b/osm_mon/test/plugins/OpenStack/unit/__init__.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- + +# Copyright 2018 Whitestack, LLC +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to Whitestack, LLC + +# 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. + +# For those usages not covered by the Apache License, Version 2.0 please +# contact: bdiaz@whitestack.com or glavado@whitestack.com +## +import logging +import sys + +from osm_mon.core.settings import Config + +cfg = Config.instance() +logging.basicConfig(stream=sys.stdout, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + datefmt='%m/%d/%Y %I:%M:%S %p', + level=logging.getLevelName(cfg.OSMMON_LOG_LEVEL)) +log = logging.getLogger(__name__) diff --git a/osm_mon/test/plugins/OpenStack/unit/test_alarm_req.py b/osm_mon/test/plugins/OpenStack/unit/test_alarm_req.py new file mode 100644 index 0000000..02cec8b --- /dev/null +++ b/osm_mon/test/plugins/OpenStack/unit/test_alarm_req.py @@ -0,0 +1,150 @@ +# Copyright 2017 iIntel Research and Development Ireland Limited +# ************************************************************** + +# This file is part of OSM Monitoring module +# All Rights Reserved to 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. + +# For those usages not covered by the Apache License, Version 2.0 please +# contact: helena.mcgough@intel.com or adrian.hoban@intel.com +## +"""Tests for all alarm request message keys.""" + +import json +import logging +import unittest +from io import UnsupportedOperation + +import mock + +from osm_mon.core.auth import AuthManager +from osm_mon.core.database import VimCredentials, DatabaseManager +from osm_mon.plugins.OpenStack.Aodh import alarm_handler as alarm_req +from osm_mon.plugins.OpenStack.Aodh.alarm_handler import OpenstackAlarmHandler +from osm_mon.plugins.OpenStack.common import Common + +log = logging.getLogger(__name__) + +mock_creds = VimCredentials() +mock_creds.config = '{}' + + +class Message(object): + """A class to mock a message object value for alarm requests.""" + + def __init__(self): + """Initialize a mocked message instance.""" + self.topic = 'alarm_request' + self.key = None + self.value = json.dumps({'mock_value': 'mock_details'}) + + +class TestAlarmKeys(unittest.TestCase): + """Integration test for alarm request keys.""" + + def setUp(self): + """Setup the tests for alarm request keys.""" + super(TestAlarmKeys, self).setUp() + self.alarming = alarm_req.OpenstackAlarmHandler() + self.alarming.common = Common() + + @mock.patch.object(AuthManager, 'get_credentials') + @mock.patch.object(Common, 'get_endpoint') + @mock.patch.object(Common, 'get_auth_token') + def test_alarming_authentication(self, get_token, get_endpoint, get_creds): + """Test getting an auth_token and endpoint for alarm requests.""" + # if auth_token is None environment variables are used to authenticate + get_creds.return_value = mock_creds + + with self.assertRaises(UnsupportedOperation): + self.alarming.handle_message('', {}, 'test_id') + + get_token.assert_called_with('test_id', verify_ssl=True) + get_endpoint.assert_any_call('alarming', 'test_id', verify_ssl=True) + + @mock.patch.object(Common, 'get_endpoint', mock.Mock()) + @mock.patch.object(Common, 'get_auth_token', mock.Mock()) + @mock.patch.object(AuthManager, 'get_credentials') + @mock.patch.object(alarm_req.OpenstackAlarmHandler, 'delete_alarm') + def test_delete_alarm_key(self, del_alarm, get_creds): + """Test the functionality for a create alarm request.""" + value = {'alarm_delete_request': { + 'correlation_id': 1, + 'alarm_uuid': 'my_alarm_id' + }} + + get_creds.return_value = mock_creds + del_alarm.return_value = {} + + # Call the alarming functionality and check delete request + self.alarming.handle_message('delete_alarm_request', value, 'test_id') + del_alarm.assert_called_with(mock.ANY, mock.ANY, 'my_alarm_id', True) + + @mock.patch.object(Common, 'get_endpoint', mock.Mock()) + @mock.patch.object(Common, 'get_auth_token', mock.Mock()) + @mock.patch.object(AuthManager, 'get_credentials') + @mock.patch.object(alarm_req.OpenstackAlarmHandler, 'list_alarms') + def test_list_alarm_key(self, list_alarm, get_creds): + """Test the functionality for a list alarm request.""" + value = {'alarm_list_request': {'correlation_id': 1}} + + get_creds.return_value = mock_creds + + list_alarm.return_value = [] + + # Call the alarming functionality and check list functionality + self.alarming.handle_message('list_alarm_request', value, 'test_id') + list_alarm.assert_called_with(mock.ANY, mock.ANY, {'correlation_id': 1}, True) + + @mock.patch.object(Common, 'get_auth_token', mock.Mock()) + @mock.patch.object(Common, 'get_endpoint', mock.Mock()) + @mock.patch.object(AuthManager, 'get_credentials') + @mock.patch.object(alarm_req.OpenstackAlarmHandler, 'update_alarm_state') + def test_ack_alarm_key(self, ack_alarm, get_creds): + """Test the functionality for an acknowledge alarm request.""" + value = {'ack_details': {'alarm_uuid': 'my_alarm_id'}} + + get_creds.return_value = mock_creds + + # Call alarming functionality and check acknowledge functionality + self.alarming.handle_message('acknowledge_alarm_request', value, 'test_id') + ack_alarm.assert_called_with(mock.ANY, mock.ANY, 'my_alarm_id', True) + + @mock.patch.object(Common, 'get_auth_token', mock.Mock()) + @mock.patch.object(Common, 'get_endpoint', mock.Mock()) + @mock.patch.object(DatabaseManager, 'save_alarm', mock.Mock()) + @mock.patch.object(Common, "perform_request") + @mock.patch.object(AuthManager, 'get_credentials') + @mock.patch.object(alarm_req.OpenstackAlarmHandler, 'configure_alarm') + def test_config_alarm_key(self, config_alarm, get_creds, perf_req): + """Test the functionality for a create alarm request.""" + value = {'alarm_create_request': {'correlation_id': 1, 'threshold_value': 50, + 'operation': 'GT', 'metric_name': 'cpu_utilization', + 'vdu_name': 'vdu', + 'vnf_member_index': '1', + 'ns_id': '1', + 'resource_uuid': '123'}} + mock_perf_req_return_value = {"metrics": {"cpu_util": 123}} + perf_req.return_value = type('obj', (object,), {'text': json.dumps(mock_perf_req_return_value, sort_keys=True)}) + get_creds.return_value = mock_creds + + # Call alarming functionality and check config alarm call + config_alarm.return_value = 'my_alarm_id' + self.alarming.handle_message('create_alarm_request', value, 'test_id') + config_alarm.assert_called_with(mock.ANY, mock.ANY, {'correlation_id': 1, 'threshold_value': 50, + 'operation': 'GT', + 'metric_name': 'cpu_utilization', + 'vdu_name': 'vdu', + 'vnf_member_index': '1', 'ns_id': '1', + 'resource_uuid': '123'}, {}, True) diff --git a/osm_mon/test/plugins/OpenStack/unit/test_alarming.py b/osm_mon/test/plugins/OpenStack/unit/test_alarming.py new file mode 100644 index 0000000..67486e7 --- /dev/null +++ b/osm_mon/test/plugins/OpenStack/unit/test_alarming.py @@ -0,0 +1,299 @@ +# Copyright 2017 iIntel Research and Development Ireland Limited +# ************************************************************** + +# This file is part of OSM Monitoring module +# All Rights Reserved to 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. + +# For those usages not covered by the Apache License, Version 2.0 please +# contact: helena.mcgough@intel.com or adrian.hoban@intel.com +## +"""Tests for all alarm request message keys.""" + +import json +import logging +import unittest + +import mock + +from osm_mon.core.settings import Config +from osm_mon.plugins.OpenStack.Aodh import alarm_handler as alarm_req +from osm_mon.plugins.OpenStack.common import Common + +log = logging.getLogger(__name__) + +auth_token = mock.ANY +alarm_endpoint = "alarm_endpoint" +metric_endpoint = "metric_endpoint" + + +class Response(object): + """Mock a response message class.""" + + def __init__(self, result): + """Initialise the response text and status code.""" + self.text = json.dumps(result) + self.status_code = "MOCK_STATUS_CODE" + + +class TestAlarming(unittest.TestCase): + """Tests for alarming class functions.""" + + maxDiff = None + + def setUp(self): + """Setup for tests.""" + super(TestAlarming, self).setUp() + self.alarming = alarm_req.OpenstackAlarmHandler() + + @mock.patch.object(Common, "perform_request") + def test_config_invalid_alarm_req(self, perf_req): + """Test configure an invalid alarm request.""" + # Configuring with invalid metric name results in failure + values = {"alarm_name": "my_alarm", + "metric_name": "my_metric", + "resource_uuid": "my_r_id"} + with self.assertRaises(KeyError): + self.alarming.configure_alarm(alarm_endpoint, auth_token, values, {}, True) + perf_req.assert_not_called() + perf_req.reset_mock() + + # Configuring with missing metric name results in failure + values = {"alarm_name": "disk_write_ops", + "resource_uuid": "my_r_id"} + + with self.assertRaises(KeyError): + self.alarming.configure_alarm(alarm_endpoint, auth_token, values, {}, True) + perf_req.assert_not_called() + + @mock.patch.object(Common, "perform_request") + def test_config_valid_alarm_req(self, perf_req): + """Test config a valid alarm.""" + values = {"alarm_name": "disk_write_ops", + "metric_name": "disk_write_ops", + "resource_uuid": "my_r_id", + "statistic": "AVERAGE", + "threshold_value": 60, + "operation": "GT"} + + perf_req.return_value = type('obj', (object,), {'text': '{"alarm_id":"1"}'}) + + self.alarming.configure_alarm(alarm_endpoint, auth_token, values, {}, True) + payload = {"name": "disk_write_ops", + "gnocchi_resources_threshold_rule": {"resource_type": "generic", "comparison_operator": "gt", + "granularity": "300", "metric": "disk.write.requests", + "aggregation_method": "mean", "threshold": 60, + "resource_id": "my_r_id"}, + "alarm_actions": ["http://localhost:8662"], "repeat_actions": True, "state": "ok", "type": "gnocchi_resources_threshold", + "severity": "critical"} + perf_req.assert_called_with( + "alarm_endpoint/v2/alarms/", auth_token, + req_type="post", payload=json.dumps(payload, sort_keys=True), verify_ssl=True) + + @mock.patch.object(Common, "perform_request") + def test_delete_alarm_req(self, perf_req): + """Test delete alarm request.""" + self.alarming.delete_alarm(alarm_endpoint, auth_token, "my_alarm_id", True) + + perf_req.assert_called_with( + "alarm_endpoint/v2/alarms/my_alarm_id", auth_token, req_type="delete", verify_ssl=True) + + @mock.patch.object(Common, "perform_request") + def test_invalid_list_alarm_req(self, perf_req): + """Test invalid list alarm_req.""" + # Request will not be performed without a resource_id + list_details = {"mock_details": "invalid_details"} + with self.assertRaises(KeyError): + self.alarming.list_alarms(alarm_endpoint, auth_token, list_details, True) + perf_req.assert_not_called() + + @mock.patch.object(Common, "perform_request") + def test_valid_list_alarm_req(self, perf_req): + """Test valid list alarm request.""" + # Minimum requirement for an alarm list is resource_id + list_details = {"resource_uuid": "mock_r_id", "alarm_name": "mock_alarm", "severity": "critical"} + + mock_perf_req_return_value = [ + {"alarm_id": "1", "name": "mock_alarm", "severity": "critical", + "gnocchi_resources_threshold_rule": {"resource_id": "mock_r_id"}}] + perf_req.return_value = type('obj', (object,), + {'text': json.dumps(mock_perf_req_return_value)}) + + alarm_list = self.alarming.list_alarms(alarm_endpoint, auth_token, list_details, True) + + self.assertDictEqual(alarm_list[0], mock_perf_req_return_value[0]) + + perf_req.assert_called_with( + "alarm_endpoint/v2/alarms/", auth_token, req_type="get", verify_ssl=True) + perf_req.reset_mock() + + # Check list with alarm_name defined + list_details = {"resource_uuid": "mock_r_id", + "alarm_name": "mock_alarm", + "severity": "critical"} + alarm_list = self.alarming.list_alarms(alarm_endpoint, auth_token, list_details, True) + + self.assertDictEqual(alarm_list[0], mock_perf_req_return_value[0]) + + perf_req.assert_called_with( + "alarm_endpoint/v2/alarms/", auth_token, req_type="get", verify_ssl=True) + + @mock.patch.object(Common, "perform_request") + def test_ack_alarm_req(self, perf_req): + """Test update alarm state for acknowledge alarm request.""" + resp = Response({}) + perf_req.return_value = resp + + self.alarming.update_alarm_state(alarm_endpoint, auth_token, "my_alarm_id", True) + + perf_req.assert_called_with( + "alarm_endpoint/v2/alarms/my_alarm_id/state", auth_token, req_type="put", + payload=json.dumps("ok"), verify_ssl=True) + + @mock.patch.object(Common, "perform_request") + def test_update_alarm_invalid(self, perf_req): + """Test update alarm with invalid get response.""" + values = {"alarm_uuid": "my_alarm_id"} + + perf_req.return_value = type('obj', (object,), {'invalid_prop': 'Invalid response'}) + + with self.assertRaises(Exception): + self.alarming.update_alarm(alarm_endpoint, auth_token, values, {}, True) + perf_req.assert_called_with(mock.ANY, auth_token, req_type="get") + + @mock.patch.object(Common, "perform_request") + def test_update_alarm_invalid_payload(self, perf_req): + """Test update alarm with invalid payload.""" + resp = Response({"name": "my_alarm", + "state": "alarm", + "gnocchi_resources_threshold_rule": + {"resource_id": "my_resource_id", + "metric": "my_metric"}}) + perf_req.return_value = resp + values = {"alarm_uuid": "my_alarm_id"} + + with self.assertRaises(Exception): + self.alarming.update_alarm(alarm_endpoint, auth_token, values, {}, True) + perf_req.assert_called_with(mock.ANY, auth_token, req_type="get") + self.assertEqual(perf_req.call_count, 1) + + @mock.patch.object(alarm_req.OpenstackAlarmHandler, "check_payload") + @mock.patch.object(Common, "perform_request") + def test_update_alarm_valid(self, perf_req, check_pay): + """Test valid update alarm request.""" + resp = Response({"alarm_id": "1", + "name": "my_alarm", + "state": "alarm", + "gnocchi_resources_threshold_rule": + {"resource_id": "my_resource_id", + "metric": "disk.write.requests"}}) + perf_req.return_value = resp + values = {"alarm_uuid": "my_alarm_id"} + + self.alarming.update_alarm(alarm_endpoint, auth_token, values, {}, True) + + check_pay.assert_called_with(values, "disk_write_ops", "my_resource_id", + "my_alarm", alarm_state="alarm") + + self.assertEqual(perf_req.call_count, 2) + # Second call is the update request + perf_req.assert_called_with( + 'alarm_endpoint/v2/alarms/my_alarm_id', auth_token, + req_type="put", payload=check_pay.return_value, verify_ssl=True) + + @mock.patch.object(Config, "instance") + def test_check_valid_payload(self, cfg): + """Test the check payload function for a valid payload.""" + values = {"severity": "warning", + "statistic": "COUNT", + "threshold_value": 12, + "operation": "GT", + "granularity": 300, + "resource_type": "generic"} + cfg.return_value.OS_NOTIFIER_URI = "http://localhost:8662" + payload = self.alarming.check_payload( + values, "disk_write_ops", "r_id", "alarm_name") + + self.assertDictEqual( + json.loads(payload), {"name": "alarm_name", + "gnocchi_resources_threshold_rule": + {"resource_id": "r_id", + "metric": "disk.write.requests", + "comparison_operator": "gt", + "aggregation_method": "count", + "threshold": 12, + "granularity": 300, + "resource_type": "generic"}, + "severity": "low", + "state": "ok", + "type": "gnocchi_resources_threshold", + "alarm_actions": ["http://localhost:8662"], + "repeat_actions": True}) + + @mock.patch.object(Config, "instance") + @mock.patch.object(Common, "perform_request") + def test_check_valid_state_payload(self, perform_req, cfg): + """Test the check payload function for a valid payload with state.""" + values = {"severity": "warning", + "statistic": "COUNT", + "threshold_value": 12, + "operation": "GT", + "granularity": 300, + "resource_type": "generic"} + cfg.return_value.OS_NOTIFIER_URI = "http://localhost:8662" + payload = self.alarming.check_payload( + values, "disk_write_ops", "r_id", "alarm_name", alarm_state="alarm") + + self.assertEqual( + json.loads(payload), {"name": "alarm_name", + "gnocchi_resources_threshold_rule": + {"resource_id": "r_id", + "metric": "disk.write.requests", + "comparison_operator": "gt", + "aggregation_method": "count", + "threshold": 12, + "granularity": 300, + "resource_type": "generic"}, + "severity": "low", + "state": "alarm", + "type": "gnocchi_resources_threshold", + "alarm_actions": ["http://localhost:8662"], + "repeat_actions": True}) + + def test_check_invalid_payload(self): + """Test the check payload function for an invalid payload.""" + values = {"alarm_values": "mock_invalid_details"} + with self.assertRaises(Exception): + self.alarming.check_payload(values, "my_metric", "r_id", "alarm_name") + + @mock.patch.object(Common, "perform_request") + def test_get_alarm_state(self, perf_req): + """Test the get alarm state function.""" + perf_req.return_value = type('obj', (object,), {'text': '{"alarm_id":"1"}'}) + + self.alarming.get_alarm_state(alarm_endpoint, auth_token, "alarm_id") + + perf_req.assert_called_with( + "alarm_endpoint/v2/alarms/alarm_id/state", auth_token, req_type="get") + + @mock.patch.object(Common, "perform_request") + def test_check_for_metric(self, perf_req): + """Test the check for metric function.""" + mock_perf_req_return_value = {"metrics": {"cpu_util": 123}} + perf_req.return_value = type('obj', (object,), {'text': json.dumps(mock_perf_req_return_value)}) + + self.alarming.check_for_metric(auth_token, metric_endpoint, "cpu_utilization", "r_id", True) + + perf_req.assert_called_with( + "metric_endpoint/v1/resource/generic/r_id", auth_token, req_type="get", verify_ssl=True) diff --git a/osm_mon/test/plugins/OpenStack/unit/test_common.py b/osm_mon/test/plugins/OpenStack/unit/test_common.py new file mode 100644 index 0000000..e6c52fb --- /dev/null +++ b/osm_mon/test/plugins/OpenStack/unit/test_common.py @@ -0,0 +1,119 @@ +# Copyright 2017 Intel Research and Development Ireland Limited +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to 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. + +# For those usages not covered by the Apache License, Version 2.0 please +# contact: helena.mcgough@intel.com or adrian.hoban@intel.com +## +"""Tests for all common OpenStack methods.""" + +import json +import logging +import unittest + +import mock +import requests +from keystoneclient.v3 import client + +from osm_mon.core.auth import AuthManager +from osm_mon.core.database import VimCredentials +from osm_mon.plugins.OpenStack.common import Common + +__author__ = "Helena McGough" + +log = logging.getLogger(__name__) + + +class Message(object): + """Mock a message for an access credentials request.""" + + def __init__(self): + """Initialise the topic and value of access_cred message.""" + self.topic = "access_credentials" + self.value = json.dumps({"mock_value": "mock_details", + "vim_type": "OPENSTACK", + "access_config": + {"openstack_site": "my_site", + "user": "my_user", + "password": "my_password", + "vim_tenant_name": "my_tenant"}}) + + +class TestCommon(unittest.TestCase): + """Test the common class for OpenStack plugins.""" + + def setUp(self): + """Test Setup.""" + super(TestCommon, self).setUp() + self.common = Common() + self.creds = VimCredentials() + self.creds.id = 'test_id' + self.creds.user = 'user' + self.creds.url = 'url' + self.creds.password = 'password' + self.creds.tenant_name = 'tenant_name' + + @mock.patch.object(AuthManager, "get_credentials") + @mock.patch.object(client.Client, "get_raw_token_from_identity_service") + def test_get_auth_token(self, get_token, get_creds): + """Test generating a new authentication token.""" + get_creds.return_value = self.creds + Common.get_auth_token('test_id') + get_creds.assert_called_with('test_id') + get_token.assert_called_with(auth_url='url', password='password', project_name='tenant_name', username='user', + project_domain_id='default', user_domain_id='default') + + @mock.patch.object(requests, 'post') + def test_post_req(self, post): + """Testing a post request.""" + Common.perform_request("url", "auth_token", req_type="post", + payload="payload") + + post.assert_called_with("url", data="payload", headers=mock.ANY, + timeout=mock.ANY, verify=True) + + @mock.patch.object(requests, 'get') + def test_get_req(self, get): + """Testing a get request.""" + # Run the defualt get request without any parameters + Common.perform_request("url", "auth_token", req_type="get") + + get.assert_called_with("url", params=None, headers=mock.ANY, + timeout=mock.ANY, verify=True) + + # Test with some parameters specified + get.reset_mock() + Common.perform_request("url", "auth_token", req_type="get", + params="some parameters") + + get.assert_called_with("url", params="some parameters", + headers=mock.ANY, timeout=mock.ANY, verify=True) + + @mock.patch.object(requests, 'put') + def test_put_req(self, put): + """Testing a put request.""" + Common.perform_request("url", "auth_token", req_type="put", + payload="payload") + put.assert_called_with("url", data="payload", headers=mock.ANY, + timeout=mock.ANY, verify=True) + + @mock.patch.object(requests, 'delete') + def test_delete_req(self, delete): + """Testing a delete request.""" + Common.perform_request("url", "auth_token", req_type="delete") + + delete.assert_called_with("url", headers=mock.ANY, timeout=mock.ANY, verify=True) diff --git a/osm_mon/test/plugins/OpenStack/unit/test_metric_calls.py b/osm_mon/test/plugins/OpenStack/unit/test_metric_calls.py new file mode 100644 index 0000000..b71ca72 --- /dev/null +++ b/osm_mon/test/plugins/OpenStack/unit/test_metric_calls.py @@ -0,0 +1,308 @@ +# Copyright 2017 iIntel Research and Development Ireland Limited +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to 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. + +# For those usages not covered by the Apache License, Version 2.0 please +# contact: helena.mcgough@intel.com or adrian.hoban@intel.com +## +"""Tests for all metric request message keys.""" + +import json +import logging +import unittest + +import mock + +from osm_mon.core.auth import AuthManager +from osm_mon.plugins.OpenStack.Gnocchi import metric_handler as metric_req +from osm_mon.plugins.OpenStack.common import Common + +log = logging.getLogger(__name__) + +# Mock auth_token and endpoint +endpoint = mock.ANY +auth_token = mock.ANY + +# Mock a valid metric list for some tests, and a resultant list +metric_list = [{"name": "disk.write.requests", + "id": "metric_id", + "unit": "units", + "resource_id": "r_id"}] +result_list = ["metric_id", "r_id", "units", "disk_write_ops"] + + +class Response(object): + """Mock a response object for requests.""" + + def __init__(self): + """Initialise test and status code values.""" + self.text = json.dumps([{"id": "test_id"}]) + self.status_code = "STATUS_CODE" + + +def perform_request_side_effect(*args, **kwargs): + resp = Response() + if 'marker' in args[0]: + resp.text = json.dumps([]) + if 'resource/generic' in args[0]: + resp.text = json.dumps({'metrics': {'cpu_util': 'test_id'}}) + return resp + + +class TestMetricCalls(unittest.TestCase): + """Integration test for metric request keys.""" + + def setUp(self): + """Setup the tests for metric request keys.""" + super(TestMetricCalls, self).setUp() + self.metrics = metric_req.OpenstackMetricHandler() + self.metrics._common = Common() + + @mock.patch.object(metric_req.OpenstackMetricHandler, "get_metric_id") + @mock.patch.object(Common, "perform_request") + def test_invalid_config_metric_req( + self, perf_req, get_metric): + """Test the configure metric function, for an invalid metric.""" + # Test invalid configuration for creating a metric + values = {"metric_details": "invalid_metric"} + + with self.assertRaises(ValueError): + self.metrics.configure_metric(endpoint, auth_token, values, verify_ssl=False) + + perf_req.assert_not_called() + + # Test with an invalid metric name, will not perform request + values = {"resource_uuid": "r_id"} + + with self.assertRaises(ValueError): + self.metrics.configure_metric(endpoint, auth_token, values, verify_ssl=False) + + perf_req.assert_not_called() + + # If metric exists, it won't be recreated + get_metric.return_value = "metric_id" + + with self.assertRaises(ValueError): + self.metrics.configure_metric(endpoint, auth_token, values, verify_ssl=False) + + perf_req.assert_not_called() + + @mock.patch.object(metric_req.OpenstackMetricHandler, "get_metric_id") + @mock.patch.object(Common, "perform_request") + @mock.patch.object(AuthManager, "get_credentials") + def test_valid_config_metric_req( + self, get_creds, perf_req, get_metric): + """Test the configure metric function, for a valid metric.""" + # Test valid configuration and payload for creating a metric + get_creds.return_value = type('obj', (object,), {'config': '{"insecure":true}'}) + values = {"resource_uuid": "r_id", + "metric_unit": "units", + "metric_name": "cpu_util"} + get_metric.return_value = None + payload = {"id": "r_id", + "metrics": {"cpu_util": + {"archive_policy_name": "high", + "name": "cpu_util", + "unit": "units"}}} + + perf_req.return_value = type('obj', (object,), {'text': '{"metrics":{"cpu_util":1}, "id":1}'}) + + self.metrics.configure_metric(endpoint, auth_token, values, verify_ssl=False) + + perf_req.assert_called_with( + "/v1/resource/generic", auth_token, req_type="post", verify_ssl=False, + payload=json.dumps(payload, sort_keys=True)) + + @mock.patch.object(Common, "perform_request") + def test_delete_metric_req(self, perf_req): + """Test the delete metric function.""" + mock_response = Response() + mock_response.status_code = 200 + perf_req.return_value = mock_response + + self.metrics.delete_metric(endpoint, auth_token, "metric_id", verify_ssl=False) + + perf_req.assert_called_with( + "/v1/metric/metric_id", auth_token, req_type="delete", verify_ssl=False) + + @mock.patch.object(Common, "perform_request") + def test_delete_metric_invalid_status(self, perf_req): + """Test invalid response for delete request.""" + perf_req.return_value = type('obj', (object,), {"status_code": "404"}) + + with self.assertRaises(ValueError): + self.metrics.delete_metric(endpoint, auth_token, "metric_id", verify_ssl=False) + + @mock.patch.object(metric_req.OpenstackMetricHandler, "response_list") + @mock.patch.object(Common, "perform_request") + def test_complete_list_metric_req(self, perf_req, resp_list): + """Test the complete list metric function.""" + # Test listing metrics without any configuration options + values = {} + perf_req.side_effect = perform_request_side_effect + self.metrics.list_metrics(endpoint, auth_token, values, verify_ssl=False) + + perf_req.assert_any_call( + "/v1/metric?sort=name:asc", auth_token, req_type="get", verify_ssl=False) + resp_list.assert_called_with([{u'id': u'test_id'}]) + + @mock.patch.object(metric_req.OpenstackMetricHandler, "response_list") + @mock.patch.object(Common, "perform_request") + def test_resource_list_metric_req(self, perf_req, resp_list): + """Test the resource list metric function.""" + # Test listing metrics with a resource id specified + values = {"resource_uuid": "resource_id"} + perf_req.side_effect = perform_request_side_effect + self.metrics.list_metrics(endpoint, auth_token, values, verify_ssl=False) + + perf_req.assert_any_call( + "/v1/metric/test_id", auth_token, req_type="get", verify_ssl=False) + + @mock.patch.object(metric_req.OpenstackMetricHandler, "response_list") + @mock.patch.object(Common, "perform_request") + def test_name_list_metric_req(self, perf_req, resp_list): + """Test the metric_name list metric function.""" + # Test listing metrics with a metric_name specified + values = {"metric_name": "disk_write_bytes"} + perf_req.side_effect = perform_request_side_effect + self.metrics.list_metrics(endpoint, auth_token, values, verify_ssl=False) + + perf_req.assert_any_call( + "/v1/metric?sort=name:asc", auth_token, req_type="get", verify_ssl=False) + resp_list.assert_called_with( + [{u'id': u'test_id'}], metric_name="disk_write_bytes") + + @mock.patch.object(metric_req.OpenstackMetricHandler, "response_list") + @mock.patch.object(Common, "perform_request") + def test_combined_list_metric_req(self, perf_req, resp_list): + """Test the combined resource and metric list metric function.""" + # Test listing metrics with a resource id and metric name specified + + values = {"resource_uuid": "resource_id", + "metric_name": "cpu_utilization"} + perf_req.side_effect = perform_request_side_effect + self.metrics.list_metrics(endpoint, auth_token, values, verify_ssl=False) + + perf_req.assert_any_call( + "/v1/metric/test_id", auth_token, req_type="get", verify_ssl=False) + + @mock.patch.object(Common, "perform_request") + def test_get_metric_id(self, perf_req): + """Test get_metric_id function.""" + mock_response = Response() + mock_response.text = json.dumps({'metrics': {'my_metric': 'id'}}) + perf_req.return_value = mock_response + self.metrics.get_metric_id(endpoint, auth_token, "my_metric", "r_id", verify_ssl=False) + + perf_req.assert_called_with( + "/v1/resource/generic/r_id", auth_token, req_type="get", verify_ssl=False) + + @mock.patch.object(metric_req.OpenstackMetricHandler, "get_metric_id") + @mock.patch.object(Common, "perform_request") + def test_valid_read_data_req(self, perf_req, get_metric): + """Test the read metric data function, for a valid call.""" + values = {"metric_name": "disk_write_ops", + "resource_uuid": "resource_id", + "collection_unit": "DAY", + "collection_period": 1} + + perf_req.return_value = type('obj', (object,), {'text': '{"metric_data":"[]"}'}) + + get_metric.return_value = "metric_id" + self.metrics.read_metric_data(endpoint, auth_token, values, verify_ssl=False) + + perf_req.assert_called_once() + + @mock.patch.object(Common, "perform_request") + def test_invalid_read_data_req(self, perf_req): + """Test the read metric data function for an invalid call.""" + values = {} + + with self.assertRaises(KeyError): + self.metrics.read_metric_data(endpoint, auth_token, values, verify_ssl=False) + + def test_complete_response_list(self): + """Test the response list function for formatting metric lists.""" + # Mock a list for testing purposes, with valid OSM metric + resp_list = self.metrics.response_list(metric_list) + + # Check for the expected values in the resulting list + for l in result_list: + self.assertIn(l, resp_list[0].values()) + + def test_name_response_list(self): + """Test the response list with metric name configured.""" + # Mock the metric name to test a metric name list + # Test with a name that is not in the list + invalid_name = "my_metric" + resp_list = self.metrics.response_list( + metric_list, metric_name=invalid_name) + + self.assertEqual(resp_list, []) + + # Test with a name on the list + valid_name = "disk_write_ops" + resp_list = self.metrics.response_list( + metric_list, metric_name=valid_name) + + # Check for the expected values in the resulting list + for l in result_list: + self.assertIn(l, resp_list[0].values()) + + def test_resource_response_list(self): + """Test the response list with resource_id configured.""" + # Mock a resource_id to test a resource list + # Test with resource not on the list + invalid_id = "mock_resource" + resp_list = self.metrics.response_list(metric_list, resource=invalid_id) + + self.assertEqual(resp_list, []) + + # Test with a resource on the list + valid_id = "r_id" + resp_list = self.metrics.response_list(metric_list, resource=valid_id) + + # Check for the expected values in the resulting list + for l in result_list: + self.assertIn(l, resp_list[0].values()) + + def test_combined_response_list(self): + """Test the response list function with resource_id and metric_name.""" + # Test for a combined resource and name list + # resource and name are on the list + valid_name = "disk_write_ops" + valid_id = "r_id" + resp_list = self.metrics.response_list( + metric_list, metric_name=valid_name, resource=valid_id) + + # Check for the expected values in the resulting list + for l in result_list: + self.assertIn(l, resp_list[0].values()) + + # resource not on list + invalid_id = "mock_resource" + resp_list = self.metrics.response_list( + metric_list, metric_name=valid_name, resource=invalid_id) + + self.assertEqual(resp_list, []) + + # metric name not on list + invalid_name = "mock_metric" + resp_list = self.metrics.response_list( + metric_list, metric_name=invalid_name, resource=valid_id) + + self.assertEqual(resp_list, []) diff --git a/osm_mon/test/plugins/OpenStack/unit/test_metric_req.py b/osm_mon/test/plugins/OpenStack/unit/test_metric_req.py new file mode 100644 index 0000000..2fa31a6 --- /dev/null +++ b/osm_mon/test/plugins/OpenStack/unit/test_metric_req.py @@ -0,0 +1,159 @@ +# Copyright 2017 iIntel Research and Development Ireland Limited +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to 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. + +# For those usages not covered by the Apache License, Version 2.0 please +# contact: helena.mcgough@intel.com or adrian.hoban@intel.com +## +"""Tests for all metric request message keys.""" + +import json +import logging +import unittest + +import mock + +from osm_mon.core.auth import AuthManager +from osm_mon.plugins.OpenStack.Gnocchi import metric_handler as metric_req +from osm_mon.plugins.OpenStack.Gnocchi.metric_handler import OpenstackMetricHandler +from osm_mon.plugins.OpenStack.common import Common + +log = logging.getLogger(__name__) + + +class Response(object): + """Mock a response object for requests.""" + + def __init__(self): + """Initialise test and status code values.""" + self.text = json.dumps([{"id": "test_id"}]) + self.status_code = "STATUS_CODE" + + +class Message(object): + """A class to mock a message object value for metric requests.""" + + def __init__(self): + """Initialize a mocked message instance.""" + self.topic = "metric_request" + self.key = None + self.value = json.dumps({"mock_message": "message_details"}) + + +class TestMetricReq(unittest.TestCase): + """Integration test for metric request keys.""" + + def setUp(self): + """Setup the tests for metric request keys.""" + super(TestMetricReq, self).setUp() + self.metrics = metric_req.OpenstackMetricHandler() + + @mock.patch.object(Common, "get_auth_token", mock.Mock()) + @mock.patch.object(Common, "get_endpoint", mock.Mock()) + @mock.patch.object(metric_req.OpenstackMetricHandler, "delete_metric") + @mock.patch.object(metric_req.OpenstackMetricHandler, "get_metric_id") + @mock.patch.object(AuthManager, "get_credentials") + def test_delete_metric_key(self, get_creds, get_metric_id, del_metric): + """Test the functionality for a delete metric request.""" + value = {"metric_name": "disk_write_ops", "resource_uuid": "my_r_id", "correlation_id": 1} + + get_creds.return_value = type('obj', (object,), { + 'config': '{"insecure":true}' + }) + del_metric.return_value = True + + # Call the metric functionality and check delete request + get_metric_id.return_value = "my_metric_id" + self.metrics.handle_request('delete_metric_request', value, 'test_id') + del_metric.assert_called_with(mock.ANY, mock.ANY, "my_metric_id", False) + + @mock.patch.object(Common, "get_auth_token", mock.Mock()) + @mock.patch.object(Common, 'get_endpoint', mock.Mock()) + @mock.patch.object(metric_req.OpenstackMetricHandler, "list_metrics") + @mock.patch.object(AuthManager, "get_credentials") + def test_list_metric_key(self, get_creds, list_metrics): + """Test the functionality for a list metric request.""" + value = {"metrics_list_request": {"correlation_id": 1}} + + get_creds.return_value = type('obj', (object,), { + 'config': '{"insecure":true}' + }) + + list_metrics.return_value = [] + + # Call the metric functionality and check list functionality + self.metrics.handle_request('list_metric_request', value, 'test_id') + list_metrics.assert_called_with(mock.ANY, mock.ANY, {"correlation_id": 1}, False) + + @mock.patch.object(Common, "get_auth_token", mock.Mock()) + @mock.patch.object(Common, 'get_endpoint', mock.Mock()) + @mock.patch.object(AuthManager, "get_credentials") + @mock.patch.object(Common, "perform_request") + def test_update_metric_key(self, perf_req, get_creds): + """Test the functionality for an update metric request.""" + value = {"metric_update_request": + {"correlation_id": 1, + "metric_name": "my_metric", + "resource_uuid": "my_r_id"}} + + get_creds.return_value = type('obj', (object,), { + 'config': '{"insecure":true}' + }) + + mock_response = Response() + mock_response.text = json.dumps({'metrics': {'my_metric': 'id'}}) + perf_req.return_value = mock_response + + # Call metric functionality and confirm no function is called + # Gnocchi does not support updating a metric configuration + self.metrics.handle_request('update_metric_request', value, 'test_id') + + @mock.patch.object(Common, "get_auth_token", mock.Mock()) + @mock.patch.object(Common, 'get_endpoint', mock.Mock()) + @mock.patch.object(OpenstackMetricHandler, "configure_metric") + @mock.patch.object(AuthManager, "get_credentials") + def test_config_metric_key(self, get_credentials, config_metric): + """Test the functionality for a create metric request.""" + value = {"metric_create_request": {"correlation_id": 123}} + get_credentials.return_value = type('obj', (object,), {'config': '{"insecure":true}'}) + # Call metric functionality and check config metric + config_metric.return_value = "metric_id", "resource_id" + self.metrics.handle_request('create_metric_request', value, 'test_id') + config_metric.assert_called_with(mock.ANY, mock.ANY, {"correlation_id": 123}, False) + + @mock.patch.object(Common, "get_auth_token", mock.Mock()) + @mock.patch.object(Common, 'get_endpoint', mock.Mock()) + @mock.patch.object(OpenstackMetricHandler, "read_metric_data") + @mock.patch.object(AuthManager, "get_credentials") + @mock.patch.object(Common, "perform_request") + def test_read_data_key(self, perf_req, get_creds, read_data): + """Test the functionality for a read metric data request.""" + value = {"correlation_id": 123, "metric_name": "cpu_utilization", "resource_uuid": "uuid"} + + get_creds.return_value = type('obj', (object,), { + 'config': '{"insecure":true}' + }) + + mock_response = Response() + mock_response.text = json.dumps({'metrics': {'cpu_util': 'id'}}) + perf_req.return_value = mock_response + + # Call metric functionality and check read data metrics + read_data.return_value = "time_stamps", "data_values" + self.metrics.handle_request('read_metric_data_request', value, 'test_id') + read_data.assert_called_with( + mock.ANY, mock.ANY, value, False) diff --git a/osm_mon/test/plugins/OpenStack/unit/test_notifier.py b/osm_mon/test/plugins/OpenStack/unit/test_notifier.py new file mode 100644 index 0000000..a420c70 --- /dev/null +++ b/osm_mon/test/plugins/OpenStack/unit/test_notifier.py @@ -0,0 +1,133 @@ +# Copyright 2017 Intel Research and Development Ireland Limited +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to 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. + +# For those usages not covered by the Apache License, Version 2.0 please +# contact: helena.mcgough@intel.com or adrian.hoban@intel.com +## +"""Tests for all common OpenStack methods.""" + +import json +import unittest + +import mock +from kafka import KafkaProducer + +from osm_mon.core.database import DatabaseManager, Alarm +from osm_mon.plugins.OpenStack.Aodh.notifier import NotifierHandler + +post_data = {"severity": "critical", + "alarm_name": "my_alarm", + "current": "current_state", + "alarm_id": "my_alarm_id", + "reason": "Threshold has been broken", + "reason_data": {"count": 1, + "most_recent": "null", + "type": "threshold", + "disposition": "unknown"}, + "previous": "previous_state"} + + +class Response(object): + """Mock a response class for generating responses.""" + + def __init__(self, text): + """Initialise a mock response with a text attribute.""" + self.text = text + + +class RFile(): + def read(self, content_length): + return json.dumps(post_data, sort_keys=True) + + +class MockNotifierHandler(NotifierHandler): + """Mock the NotifierHandler class for testing purposes.""" + + def __init__(self): + """Initialise mock NotifierHandler.""" + self.headers = {'Content-Length': '20'} + self.rfile = RFile() + + def setup(self): + """Mock setup function.""" + pass + + def handle(self): + """Mock handle function.""" + pass + + def finish(self): + """Mock finish function.""" + pass + + +@mock.patch.object(KafkaProducer, "__init__", lambda *args, **kwargs: None) +@mock.patch.object(KafkaProducer, "flush", mock.Mock()) +class TestNotifier(unittest.TestCase): + """Test the NotifierHandler class for requests from aodh.""" + + def setUp(self): + """Setup tests.""" + super(TestNotifier, self).setUp() + self.handler = MockNotifierHandler() + + @mock.patch.object(NotifierHandler, "_set_headers") + def test_do_GET(self, set_head): + """Tests do_GET. Validates _set_headers has been called.""" + self.handler.do_GET() + + set_head.assert_called_once() + + @mock.patch.object(NotifierHandler, "notify_alarm") + @mock.patch.object(NotifierHandler, "_set_headers") + def test_do_POST(self, set_head, notify): + """Tests do_POST. Validates notify_alarm has been called.""" + self.handler.do_POST() + + set_head.assert_called_once() + notify.assert_called_with(post_data) + + @mock.patch.object(NotifierHandler, "_publish_response") + @mock.patch.object(DatabaseManager, "get_alarm") + def test_notify_alarm_valid_alarm( + self, get_alarm, notify): + """ + Tests notify_alarm when request from OpenStack references an existing alarm in the DB. + Validates KafkaProducer.notify_alarm has been called. + """ + # Generate return values for valid notify_alarm operation + mock_alarm = Alarm() + get_alarm.return_value = mock_alarm + + self.handler.notify_alarm(post_data) + notify.assert_called_with('notify_alarm', mock.ANY) + + @mock.patch.object(NotifierHandler, "_publish_response") + @mock.patch.object(DatabaseManager, "get_alarm") + def test_notify_alarm_invalid_alarm( + self, get_alarm, notify): + """ + Tests notify_alarm when request from OpenStack references a non existing alarm in the DB. + Validates Exception is thrown and KafkaProducer.notify_alarm has not been called. + """ + # Generate return values for valid notify_alarm operation + get_alarm.return_value = None + + with self.assertRaises(Exception): + self.handler.notify_alarm(post_data) + notify.assert_not_called() diff --git a/osm_mon/test/plugins/OpenStack/unit/test_responses.py b/osm_mon/test/plugins/OpenStack/unit/test_responses.py new file mode 100644 index 0000000..1377bc0 --- /dev/null +++ b/osm_mon/test/plugins/OpenStack/unit/test_responses.py @@ -0,0 +1,116 @@ +# Copyright 2017 iIntel Research and Development Ireland Limited +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to 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. + +# For those usages not covered by the Apache License, Version 2.0 please +# contact: helena.mcgough@intel.com or adrian.hoban@intel.com +## +"""Test that the correct responses are generated for each message.""" + +import logging +import unittest + +import mock + +from osm_mon.plugins.OpenStack import response as resp + +log = logging.getLogger(__name__) + + +class TestOpenStackResponse(unittest.TestCase): + """Tests for responses generated by the OpenStack plugins.""" + + def setUp(self): + """Setup for testing OpenStack plugin responses.""" + super(TestOpenStackResponse, self).setUp() + self.plugin_resp = resp.OpenStackResponseBuilder() + + def test_invalid_key(self): + """Test if an invalid key is entered for a response.""" + message = self.plugin_resp.generate_response("mock_invalid_key") + self.assertEqual(message, None) + + @mock.patch.object( + resp.OpenStackResponseBuilder, "alarm_list_response") + def test_list_alarm_resp(self, alarm_list_resp): + """Test out a function call for a list alarm response.""" + message = self.plugin_resp.generate_response("list_alarm_response") + self.assertEqual(alarm_list_resp.return_value, message) + + @mock.patch.object( + resp.OpenStackResponseBuilder, "list_metric_response") + def test_list_metric_resp(self, metric_list_resp): + """Test list metric response function call.""" + message = self.plugin_resp.generate_response("list_metric_response") + self.assertEqual(message, metric_list_resp.return_value) + + @mock.patch.object( + resp.OpenStackResponseBuilder, "delete_alarm_response") + def test_delete_alarm_resp(self, del_alarm_resp): + """Test delete alarm response function call.""" + message = self.plugin_resp.generate_response("delete_alarm_response") + self.assertEqual(message, del_alarm_resp.return_value) + + @mock.patch.object( + resp.OpenStackResponseBuilder, "delete_metric_response") + def test_delete_metric_resp(self, del_metric_resp): + """Test the response functionality of delete metric response.""" + message = self.plugin_resp.generate_response("delete_metric_response") + self.assertEqual(message, del_metric_resp.return_value) + + @mock.patch.object( + resp.OpenStackResponseBuilder, "create_alarm_response") + def test_create_alarm_resp(self, config_alarm_resp): + """Test create alarm response function call.""" + message = self.plugin_resp.generate_response("create_alarm_response") + self.assertEqual(message, config_alarm_resp.return_value) + + @mock.patch.object( + resp.OpenStackResponseBuilder, "metric_create_response") + def test_create_metric_resp(self, config_metric_resp): + """Test create metric response function call.""" + message = self.plugin_resp.generate_response("create_metric_response") + self.assertEqual(message, config_metric_resp.return_value) + + @mock.patch.object( + resp.OpenStackResponseBuilder, "update_alarm_response") + def test_update_alarm_resp(self, up_alarm_resp): + """Test update alarm response function call.""" + message = self.plugin_resp.generate_response("update_alarm_response") + self.assertEqual(message, up_alarm_resp.return_value) + + @mock.patch.object( + resp.OpenStackResponseBuilder, "update_metric_response") + def test_update_metric_resp(self, up_metric_resp): + """Test update metric response function call.""" + message = self.plugin_resp.generate_response("update_metric_response") + self.assertEqual(message, up_metric_resp.return_value) + + @mock.patch.object( + resp.OpenStackResponseBuilder, "notify_alarm") + def test_notify_alarm(self, notify_alarm): + """Test notify alarm response function call.""" + message = self.plugin_resp.generate_response("notify_alarm") + self.assertEqual(message, notify_alarm.return_value) + + @mock.patch.object( + resp.OpenStackResponseBuilder, "read_metric_data_response") + def test_read_metric_data_resp(self, read_data_resp): + """Test read metric data response function call.""" + message = self.plugin_resp.generate_response( + "read_metric_data_response") + self.assertEqual(message, read_data_resp.return_value) diff --git a/osm_mon/test/plugins/OpenStack/unit/test_settings.py b/osm_mon/test/plugins/OpenStack/unit/test_settings.py new file mode 100644 index 0000000..42619f8 --- /dev/null +++ b/osm_mon/test/plugins/OpenStack/unit/test_settings.py @@ -0,0 +1,46 @@ +# Copyright 2017 Intel Research and Development Ireland Limited +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to 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. + +# For those usages not covered by the Apache License, Version 2.0 please +# contact: helena.mcgough@intel.com or adrian.hoban@intel.com +## +"""Tests for settings for OpenStack plugins configurations.""" + +import logging +import os +import unittest + +from osm_mon.core.settings import Config + +log = logging.getLogger(__name__) + + +class TestSettings(unittest.TestCase): + """Test the settings class for OpenStack plugin configuration.""" + + def setUp(self): + """Test Setup.""" + super(TestSettings, self).setUp() + self.cfg = Config.instance() + + def test_set_os_username(self): + """Test reading the environment for OpenStack plugin configuration.""" + os.environ["OS_NOTIFIER_URI"] = "test" + self.cfg.read_environ() + + self.assertEqual(self.cfg.OS_NOTIFIER_URI, "test") diff --git a/osm_mon/test/plugins/VMware/__init__.py b/osm_mon/test/plugins/VMware/__init__.py new file mode 100644 index 0000000..64d5d51 --- /dev/null +++ b/osm_mon/test/plugins/VMware/__init__.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- + +## +# Copyright 2017-2018 VMware Inc. +# This file is part of ETSI OSM +# 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. +# +# For those usages not covered by the Apache License, Version 2.0 please +# contact: osslegalrouting@vmware.com +## + +"""VMware MON plugin tests.""" + +import logging +import sys + +from osm_mon.core.settings import Config + +cfg = Config.instance() +logging.basicConfig(stream=sys.stdout, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + datefmt='%m/%d/%Y %I:%M:%S %p', + level=logging.getLevelName(cfg.OSMMON_LOG_LEVEL)) +log = logging.getLogger(__name__) + diff --git a/osm_mon/test/plugins/VMware/test_mon_plugin_vrops.py b/osm_mon/test/plugins/VMware/test_mon_plugin_vrops.py new file mode 100644 index 0000000..2d10d1b --- /dev/null +++ b/osm_mon/test/plugins/VMware/test_mon_plugin_vrops.py @@ -0,0 +1,3083 @@ +# -*- coding: utf-8 -*- + +## +# Copyright 2017-2018 VMware Inc. +# This file is part of ETSI OSM +# 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. +# +# For those usages not covered by the Apache License, Version 2.0 please +# contact: osslegalrouting@vmware.com +## + +""" Mock tests for VMware vROPs Mon plugin """ + +import os +import sys +import unittest + +import mock +import requests + +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..")) + +from osm_mon.plugins.vRealiseOps import mon_plugin_vrops as monPlugin + +from pyvcloud.vcd.client import Client + + +class TestMonPlugin(unittest.TestCase): + """Test class for vROPs Mon Plugin class methods""" + + def setUp(self): + """Setup the tests for Mon Plugin class methods""" + super(TestMonPlugin, self).setUp() + + self.m_vim_access_config = {'vrops_site': 'abc', + 'vrops_user': 'user', + 'vrops_password': 'passwd', + 'vim_url': 'vcd_url', + 'admin_username': 'admin', + 'admin_password': 'admin_passwd', + 'vim_uuid': '1', + 'tenant_id': 'org_vdc_1'} + self.mon_plugin = monPlugin.MonPlugin(self.m_vim_access_config) + # create client object + self.vca = Client('test', verify_ssl_certs=False) + # create session + self.session = requests.Session() + + def test_get_default_Params_valid_metric_alarm_name(self): + """Test get default params method""" + + # Mock valid metric_alarm_name and response + metric_alarm_name = "Average_Memory_Usage_Above_Threshold" + expected_return = {'impact': 'risk', 'cancel_cycles': 2, 'adapter_kind': 'VMWARE', + 'repeat': False, 'cancel_period': 300, 'alarm_type': 16, + 'vrops_alarm': 'Avg_Mem_Usage_Above_Thr', 'enabled': True, 'period': 300, + 'resource_kind': 'VirtualMachine', 'alarm_subType': 19, + 'action': 'acknowledge', 'evaluation': 2, 'unit': '%'} + + # call get default param function under test + actual_return = self.mon_plugin.get_default_Params(metric_alarm_name) + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + def test_get_default_Params_invalid_metric_alarm_name(self): + """Test get default params method invalid metric alarm""" + + # Mock valid metric_alarm_name and response + metric_alarm_name = "Invalid_Alarm" + expected_return = {} + + # call get default param function under test + actual_return = self.mon_plugin.get_default_Params(metric_alarm_name) + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'post') + def test_create_symptom_valid_req_response(self, m_post): + """Test create symptom method-valid request""" + + # Mock valid symptom params and mock responses + symptom_param = {'threshold_value': 0, 'cancel_cycles': 1, 'adapter_kind_key': 'VMWARE', + 'resource_kind_key': 'VirtualMachine', 'severity': 'CRITICAL', + 'symptom_name': \ + 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'operation': 'GT', 'wait_cycles': 1, 'metric_key': 'cpu|usage_average'} + + m_post.return_value.status_code = 201 + m_post.return_value.content = \ + '{"id":"SymptomDefinition-351c23b4-bc3c-4c7b-b4af-1ad90a673c5d",\ + "name":"CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ + "adapterKindKey":"VMWARE","resourceKindKey":"VirtualMachine",\ + "waitCycles":1,"cancelCycles":1,\ + "state":{"severity":"CRITICAL","condition":{"type":"CONDITION_HT",\ + "key":"cpu|usage_average","operator":"GT","value":"0.0",\ + "valueType":"NUMERIC",\ + "instanced":false,"thresholdType":"STATIC"}}}' + + expected_return = "SymptomDefinition-351c23b4-bc3c-4c7b-b4af-1ad90a673c5d" + + # call create symptom method under test + actual_return = self.mon_plugin.create_symptom(symptom_param) + + # verify that mocked method is called + m_post.assert_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'post') + def test_create_symptom_invalid_req_response(self, m_post): + """Test create symptom method-invalid response""" + + # Mock valid symptom params and invalid mock responses + symptom_param = {'threshold_value': 0, 'cancel_cycles': 1, 'adapter_kind_key': 'VMWARE', + 'resource_kind_key': 'VirtualMachine', 'severity': 'CRITICAL', + 'symptom_name': \ + 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'operation': 'GT', 'wait_cycles': 1, 'metric_key': 'cpu|usage_average'} + + m_post.return_value.status_code = 404 + m_post.return_value.content = '404 Not Found' + + expected_return = None + + # call create symptom method under test + actual_return = self.mon_plugin.create_symptom(symptom_param) + + # verify that mocked method is called + m_post.assert_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'post') + def test_create_symptom_incorrect_data(self, m_post): + """Test create symptom method-incorrect data""" + + # Mock valid symptom params and invalid mock responses + symptom_param = {'threshold_value': 0, 'cancel_cycles': 1, 'adapter_kind_key': 'VMWARE', + 'resource_kind_key': 'VirtualMachine', 'severity': 'CRITICAL', + 'symptom_name': \ + 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'operation': 'GT', 'metric_key': 'cpu|usage_average'} + + expected_return = None + + # call create symptom method under test + actual_return = self.mon_plugin.create_symptom(symptom_param) + + # verify that mocked method is not called + m_post.assert_not_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'post') + def test_create_alarm_definition_valid_req_response(self, m_post): + """Test create alarm definition method-valid response""" + + # Mock valid alarm params and mock responses + alarm_param = {'description': 'CPU_Utilization_Above_Threshold', 'cancelCycles': 1, + 'subType': 19, 'waitCycles': 1, + 'severity': 'CRITICAL', 'impact': 'risk', 'adapterKindKey': 'VMWARE', + 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'resourceKindKey': 'VirtualMachine', 'type': 16, + 'symptomDefinitionId': \ + 'SymptomDefinition-25278b06-bff8-4409-a141-9b4e064235df'} + + m_post.return_value.status_code = 201 + m_post.return_value.content = \ + '{"id":"AlertDefinition-d4f21e4b-770a-45d6-b298-022eaf489115",\ + "name":"CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ + "description":"CPU_Utilization_Above_Threshold","adapterKindKey":"VMWARE",\ + "resourceKindKey":"VirtualMachine","waitCycles":1,"cancelCycles":1,\ + "type":16,"subType":19,\ + "states":[{"severity":"CRITICAL","base-symptom-set":{"type":"SYMPTOM_SET",\ + "relation":"SELF","aggregation":"ALL","symptomSetOperator":"AND",\ + "symptomDefinitionIds":\ + ["SymptomDefinition-25278b06-bff8-4409-a141-9b4e064235df"]},\ + "impact":{"impactType":"BADGE","detail":"risk"}}]}' + + expected_return = "AlertDefinition-d4f21e4b-770a-45d6-b298-022eaf489115" + + # call create alarm definition method under test + actual_return = self.mon_plugin.create_alarm_definition(alarm_param) + + # verify that mocked method is called + m_post.assert_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'post') + def test_create_alarm_definition_invalid_req_response(self, m_post): + """Test create alarm definition method-invalid response""" + + # Mock valid alarm params and mock responses + alarm_param = {'description': 'CPU_Utilization_Above_Threshold', 'cancelCycles': 1, + 'subType': 19, 'waitCycles': 1, + 'severity': 'CRITICAL', 'impact': 'risk', 'adapterKindKey': 'VMWARE', + 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'resourceKindKey': 'VirtualMachine', 'type': 16, + 'symptomDefinitionId': \ + 'SymptomDefinition-25278b06-bff8-4409-a141-9b4e064235df'} + + m_post.return_value.status_code = 404 + m_post.return_value.content = '404 Not Found' + + expected_return = None + + # call create alarm definition method under test + actual_return = self.mon_plugin.create_alarm_definition(alarm_param) + + # verify that mocked method is called + m_post.assert_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'post') + def test_create_alarm_definition_incorrect_data(self, m_post): + """Test create alarm definition method-incorrect data""" + + # Mock incorrect alarm param + alarm_param = {'description': 'CPU_Utilization_Above_Threshold', 'cancelCycles': 1, + 'subType': 19, 'waitCycles': 1, 'type': 16, + 'severity': 'CRITICAL', 'impact': 'risk', 'adapterKindKey': 'VMWARE', + 'symptomDefinitionId': \ + 'SymptomDefinition-25278b06-bff8-4409-a141-9b4e064235df'} + expected_return = None + + # call create symptom method under test + actual_return = self.mon_plugin.create_alarm_definition(alarm_param) + + # verify that mocked method is not called + m_post.assert_not_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') + @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') + @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') + @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') + def test_configure_alarm_valid_req(self, m_get_default_Params, + m_get_alarm_defination_by_name, + m_create_symptom, + m_create_alarm_definition, + m_get_vm_moref_id, + m_get_vm_resource_id, + m_create_alarm_notification_rule, + m_save_alarm): + """Test configure alarm valid request creating alarm""" + + # Mock input configuration dictionary + config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', + 'alarm_name': 'CPU_Utilization_Above_Threshold', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'statistic': 'AVERAGE', 'metric_name': 'cpu_utilization', + 'vdu_name': 'vdu1', 'vnf_member_index': 'index1', 'ns_id': 'nsd1', + 'operation': 'GT', 'unit': '%', + 'description': 'CPU_Utilization_Above_Threshold'} + + # symptom parameters to be passed for symptom creation + symptom_params = {'threshold_value': 0, + 'cancel_cycles': 1, + 'adapter_kind_key': 'VMWARE', + 'resource_kind_key': 'VirtualMachine', + 'severity': 'CRITICAL', + 'symptom_name': \ + 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'operation': 'GT', + 'wait_cycles': 1, + 'metric_key': 'cpu|usage_average'} + + # alarm parameters to be passed for alarm creation + alarm_params = {'description': 'CPU_Utilization_Above_Threshold', + 'cancelCycles': 1, 'subType': 19, + 'waitCycles': 1, 'severity': 'CRITICAL', + 'impact': 'risk', 'adapterKindKey': 'VMWARE', + 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'resourceKindKey': 'VirtualMachine', + 'symptomDefinitionId': \ + 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804', + 'type': 16} + + vm_moref_id = 'vm-6626' + vrops_alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + alarm_def = 'AlertDefinition-0f3cdcb3-4e1b-4a0b-86d0-66d4b3f65220' + resource_id = 'ac87622f-b761-40a0-b151-00872a2a456e' + alarm_def_uuid = '0f3cdcb3-4e1b-4a0b-86d0-66d4b3f65220' + + # Mock default Parameters for alarm & metric configuration + m_get_default_Params.side_effect = [{'impact': 'risk', 'cancel_cycles': 1, + 'adapter_kind': 'VMWARE', 'repeat': False, + 'cancel_period': 300, 'alarm_type': 16, + 'vrops_alarm': 'CPU_Utilization_Above_Thr', + 'enabled': True, 'period': 300, + 'resource_kind': 'VirtualMachine', + 'alarm_subType': 19, 'action': 'acknowledge', + 'evaluation': 1, 'unit': 'msec'}, + {'metric_key': 'cpu|usage_average', 'unit': '%'} + ] + + # set mocked function return values + m_get_alarm_defination_by_name.return_value = [] + m_create_symptom.return_value = 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804' + m_create_alarm_definition.return_value = \ + 'AlertDefinition-0f3cdcb3-4e1b-4a0b-86d0-66d4b3f65220' + m_get_vm_moref_id.return_value = vm_moref_id + m_get_vm_resource_id.return_value = 'ac87622f-b761-40a0-b151-00872a2a456e' + m_create_alarm_notification_rule.return_value = 'f37900e7-dd01-4383-b84c-08f519530d71' + + # Call configure_alarm method under test + return_value = self.mon_plugin.configure_alarm(config_dict) + + # Verify that mocked methods are called with correct parameters + self.assertEqual(m_get_default_Params.call_count, 2) + m_get_alarm_defination_by_name.assert_called_with(vrops_alarm_name) + m_create_symptom.assert_called_with(symptom_params) + m_create_alarm_definition.assert_called_with(alarm_params) + m_get_vm_moref_id.assert_called_with(config_dict['resource_uuid']) + m_get_vm_resource_id.assert_called_with(vm_moref_id) + m_create_alarm_notification_rule.assert_called_with(vrops_alarm_name, + alarm_def, + resource_id) + m_save_alarm.assert_called_with(vrops_alarm_name, '1', + config_dict['threshold_value'], + config_dict['operation'], + config_dict['metric_name'], + config_dict['vdu_name'], + config_dict['vnf_member_index'], + config_dict['ns_id']) + + # Verify return value with expected value of alarm_def_uuid + self.assertEqual(return_value, alarm_def_uuid) + + @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') + @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') + @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') + @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') + def test_configure_alarm_invalid_alarm_name_req(self, m_get_default_Params, + m_get_alarm_defination_by_name, + m_create_symptom, + m_create_alarm_definition, + m_get_vm_moref_id, + m_get_vm_resource_id, + m_create_alarm_notification_rule, + m_save_alarm): + """Test configure alarm invalid test: for invalid alarm name""" + + # Mock input configuration dictionary + config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', + 'alarm_name': 'CPU_Utilization_Above_Threshold', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'statistic': 'AVERAGE', 'metric_name': 'CPU_UTILIZATION', + 'operation': 'GT', 'unit': '%', + 'description': 'CPU_Utilization_Above_Threshold'} + + alarm_def_uuid = None + + # Mock default Parameters return value to None + m_get_default_Params.return_value = {} + + # Call configure_alarm method under test + return_value = self.mon_plugin.configure_alarm(config_dict) + + # Verify that mocked methods are called with correct parameters + m_get_default_Params.assert_called_with(config_dict['alarm_name']) + m_get_alarm_defination_by_name.assert_not_called() + m_create_symptom.assert_not_called() + m_create_alarm_definition.assert_not_called() + m_get_vm_moref_id.assert_not_called() + m_get_vm_resource_id.assert_not_called() + m_create_alarm_notification_rule.assert_not_called() + m_save_alarm.assert_not_called() + + # Verify return value with expected value i.e. None + self.assertEqual(return_value, alarm_def_uuid) + + @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') + @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') + @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') + @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') + def test_configure_alarm_invalid_metric_name_req(self, m_get_default_Params, + m_get_alarm_defination_by_name, + m_create_symptom, + m_create_alarm_definition, + m_get_vm_moref_id, + m_get_vm_resource_id, + m_create_alarm_notification_rule, + m_save_alarm): + """Test configure alarm invalid test: for invalid metric name""" + + # Mock input configuration dictionary + config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', + 'alarm_name': 'CPU_Utilization_Above_Threshold', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'statistic': 'AVERAGE', 'metric_name': 'CPU_UTILIZATION', + 'operation': 'GT', 'unit': '%', + 'description': 'CPU_Utilization_Above_Threshold'} + + alarm_def_uuid = None + + # Mock default Parameters return values for metrics to None + m_get_default_Params.side_effect = [{'impact': 'risk', 'cancel_cycles': 1, + 'adapter_kind': 'VMWARE', 'repeat': False, + 'cancel_period': 300, 'alarm_type': 16, + 'vrops_alarm': 'CPU_Utilization_Above_Thr', + 'enabled': True, 'period': 300, + 'resource_kind': 'VirtualMachine', + 'alarm_subType': 19, 'action': 'acknowledge', + 'evaluation': 1, 'unit': 'msec'}, + {} + ] + + # Call configure_alarm method under test + return_value = self.mon_plugin.configure_alarm(config_dict) + + # Verify that mocked methods are called with correct parameters + self.assertEqual(m_get_default_Params.call_count, 2) + m_get_alarm_defination_by_name.assert_not_called() + m_create_symptom.assert_not_called() + m_create_alarm_definition.assert_not_called() + m_get_vm_moref_id.assert_not_called() + m_get_vm_resource_id.assert_not_called() + m_create_alarm_notification_rule.assert_not_called() + m_save_alarm.assert_not_called() + + # Verify return value with expected value i.e. None + self.assertEqual(return_value, alarm_def_uuid) + + @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') + @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') + @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') + @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') + def test_configure_alarm_invalid_already_exists(self, m_get_default_Params, + m_get_alarm_defination_by_name, + m_create_symptom, + m_create_alarm_definition, + m_get_vm_moref_id, + m_get_vm_resource_id, + m_create_alarm_notification_rule, + m_save_alarm): + """Test configure alarm invalid test: for alarm that already exists""" + + # Mock input configuration dictionary + config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', + 'alarm_name': 'CPU_Utilization_Above_Threshold', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'statistic': 'AVERAGE', 'metric_name': 'CPU_UTILIZATION', + 'operation': 'GT', 'unit': '%', + 'description': 'CPU_Utilization_Above_Threshold'} + + vrops_alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + alarm_def_uuid = None + + # Mock default Parameters for alarm & metric configuration + m_get_default_Params.side_effect = [{'impact': 'risk', 'cancel_cycles': 1, + 'adapter_kind': 'VMWARE', 'repeat': False, + 'cancel_period': 300, 'alarm_type': 16, + 'vrops_alarm': 'CPU_Utilization_Above_Thr', + 'enabled': True, 'period': 300, + 'resource_kind': 'VirtualMachine', + 'alarm_subType': 19, 'action': 'acknowledge', + 'evaluation': 1, 'unit': 'msec'}, + {'metric_key': 'cpu|usage_average', 'unit': '%'} + ] + # set mocked function return value + m_get_alarm_defination_by_name.return_value = ['mocked_alarm_CPU_Utilization_Above_Thr'] + + # Call configure_alarm method under test + return_value = self.mon_plugin.configure_alarm(config_dict) + + # Verify that mocked methods are called with correct parameters + self.assertEqual(m_get_default_Params.call_count, 2) + m_get_alarm_defination_by_name.assert_called_with(vrops_alarm_name) + m_create_symptom.assert_not_called() + m_create_alarm_definition.assert_not_called() + m_get_vm_moref_id.assert_not_called() + m_get_vm_resource_id.assert_not_called() + m_create_alarm_notification_rule.assert_not_called() + m_save_alarm.assert_not_called() + # Verify return value with expected value of alarm_def_uuid + self.assertEqual(return_value, alarm_def_uuid) + + @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') + @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') + @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') + @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') + def test_configure_alarm_failed_symptom_creation(self, m_get_default_Params, + m_get_alarm_defination_by_name, + m_create_symptom, + m_create_alarm_definition, + m_get_vm_moref_id, + m_get_vm_resource_id, + m_create_alarm_notification_rule, + m_save_alarm): + """Test configure alarm: failed to create symptom""" + + # Mock input configuration dictionary + config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', + 'alarm_name': 'CPU_Utilization_Above_Threshold', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'statistic': 'AVERAGE', 'metric_name': 'CPU_UTILIZATION', + 'operation': 'GT', 'unit': '%', + 'description': 'CPU_Utilization_Above_Threshold'} + + # symptom parameters to be passed for symptom creation + symptom_params = {'threshold_value': 0, + 'cancel_cycles': 1, + 'adapter_kind_key': 'VMWARE', + 'resource_kind_key': 'VirtualMachine', + 'severity': 'CRITICAL', + 'symptom_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'operation': 'GT', + 'wait_cycles': 1, + 'metric_key': 'cpu|usage_average'} + vrops_alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + alarm_def_uuid = None + + # Mock default Parameters for alarm & metric configuration + m_get_default_Params.side_effect = [{'impact': 'risk', 'cancel_cycles': 1, + 'adapter_kind': 'VMWARE', 'repeat': False, + 'cancel_period': 300, 'alarm_type': 16, + 'vrops_alarm': 'CPU_Utilization_Above_Thr', + 'enabled': True, 'period': 300, + 'resource_kind': 'VirtualMachine', + 'alarm_subType': 19, 'action': 'acknowledge', + 'evaluation': 1, 'unit': 'msec'}, + {'metric_key': 'cpu|usage_average', 'unit': '%'} + ] + # set mocked function return values + m_get_alarm_defination_by_name.return_value = [] + m_create_symptom.return_value = None + + # Call configure_alarm method under test + return_value = self.mon_plugin.configure_alarm(config_dict) + + # Verify that mocked methods are called with correct parameters + self.assertEqual(m_get_default_Params.call_count, 2) + m_get_alarm_defination_by_name.assert_called_with(vrops_alarm_name) + m_create_symptom.assert_called_with(symptom_params) + m_create_alarm_definition.assert_not_called() + m_get_vm_moref_id.assert_not_called() + m_get_vm_resource_id.assert_not_called() + m_create_alarm_notification_rule.assert_not_called() + m_save_alarm.assert_not_called() + + # Verify return value with expected value of alarm_def_uuid + self.assertEqual(return_value, alarm_def_uuid) + + @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') + @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') + @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') + @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') + def test_configure_alarm_failed_alert_creation(self, m_get_default_Params, + m_get_alarm_defination_by_name, + m_create_symptom, + m_create_alarm_definition, + m_get_vm_moref_id, + m_get_vm_resource_id, + m_create_alarm_notification_rule, + m_save_alarm): + """Test configure alarm: failed to create alert in vROPs""" + + # Mock input configuration dictionary + config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', + 'alarm_name': 'CPU_Utilization_Above_Threshold', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'statistic': 'AVERAGE', 'metric_name': 'CPU_UTILIZATION', + 'operation': 'GT', 'unit': '%', + 'description': 'CPU_Utilization_Above_Threshold'} + + # symptom parameters to be passed for symptom creation + symptom_params = {'threshold_value': 0, + 'cancel_cycles': 1, + 'adapter_kind_key': 'VMWARE', + 'resource_kind_key': 'VirtualMachine', + 'severity': 'CRITICAL', + 'symptom_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'operation': 'GT', + 'wait_cycles': 1, + 'metric_key': 'cpu|usage_average'} + + # alarm parameters to be passed for alarm creation + alarm_params = {'description': 'CPU_Utilization_Above_Threshold', + 'cancelCycles': 1, 'subType': 19, + 'waitCycles': 1, 'severity': 'CRITICAL', + 'impact': 'risk', 'adapterKindKey': 'VMWARE', + 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'resourceKindKey': 'VirtualMachine', + 'symptomDefinitionId': 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804', + 'type': 16} + + vrops_alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + alarm_def_uuid = None + + # Mock default Parameters for alarm & metric configuration + m_get_default_Params.side_effect = [{'impact': 'risk', 'cancel_cycles': 1, + 'adapter_kind': 'VMWARE', 'repeat': False, + 'cancel_period': 300, 'alarm_type': 16, + 'vrops_alarm': 'CPU_Utilization_Above_Thr', + 'enabled': True, 'period': 300, + 'resource_kind': 'VirtualMachine', + 'alarm_subType': 19, 'action': 'acknowledge', + 'evaluation': 1, 'unit': 'msec'}, + {'metric_key': 'cpu|usage_average', 'unit': '%'} + ] + # set mocked function return values + m_get_alarm_defination_by_name.return_value = [] + m_create_symptom.return_value = 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804' + m_create_alarm_definition.return_value = None + + # Call configure_alarm method under test + return_value = self.mon_plugin.configure_alarm(config_dict) + + # Verify that mocked methods are called with correct parameters + self.assertEqual(m_get_default_Params.call_count, 2) + m_get_alarm_defination_by_name.assert_called_with(vrops_alarm_name) + m_create_symptom.assert_called_with(symptom_params) + m_create_alarm_definition.assert_called_with(alarm_params) + m_get_vm_moref_id.assert_not_called() + m_get_vm_resource_id.assert_not_called() + m_create_alarm_notification_rule.assert_not_called() + m_save_alarm.assert_not_called() + + # Verify return value with expected value of alarm_def_uuid + self.assertEqual(return_value, alarm_def_uuid) + + @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') + @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') + @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') + @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') + def test_configure_alarm_failed_to_get_vm_moref_id(self, m_get_default_Params, + m_get_alarm_defination_by_name, + m_create_symptom, + m_create_alarm_definition, + m_get_vm_moref_id, + m_get_vm_resource_id, + m_create_alarm_notification_rule, + m_save_alarm): + """Test configure alarm: failed to get vm_moref_id""" + + # Mock input configuration dictionary + config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', + 'alarm_name': 'CPU_Utilization_Above_Threshold', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'statistic': 'AVERAGE', 'metric_name': 'CPU_UTILIZATION', + 'operation': 'GT', 'unit': '%', + 'description': 'CPU_Utilization_Above_Threshold'} + + # symptom parameters to be passed for symptom creation + symptom_params = {'threshold_value': 0, + 'cancel_cycles': 1, + 'adapter_kind_key': 'VMWARE', + 'resource_kind_key': 'VirtualMachine', + 'severity': 'CRITICAL', + 'symptom_name': \ + 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'operation': 'GT', + 'wait_cycles': 1, + 'metric_key': 'cpu|usage_average'} + + # alarm parameters to be passed for alarm creation + alarm_params = {'description': 'CPU_Utilization_Above_Threshold', + 'cancelCycles': 1, 'subType': 19, + 'waitCycles': 1, 'severity': 'CRITICAL', + 'impact': 'risk', 'adapterKindKey': 'VMWARE', + 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'resourceKindKey': 'VirtualMachine', + 'symptomDefinitionId': \ + 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804', + 'type': 16} + + vrops_alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + alarm_def_uuid = None + + # Mock default Parameters for alarm & metric configuration + m_get_default_Params.side_effect = [{'impact': 'risk', 'cancel_cycles': 1, + 'adapter_kind': 'VMWARE', 'repeat': False, + 'cancel_period': 300, 'alarm_type': 16, + 'vrops_alarm': 'CPU_Utilization_Above_Thr', + 'enabled': True, 'period': 300, + 'resource_kind': 'VirtualMachine', + 'alarm_subType': 19, 'action': 'acknowledge', + 'evaluation': 1, 'unit': 'msec'}, + {'metric_key': 'cpu|usage_average', 'unit': '%'} + ] + # set mocked function return values + m_get_alarm_defination_by_name.return_value = [] + m_create_symptom.return_value = 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804' + m_create_alarm_definition.return_value = \ + 'AlertDefinition-0f3cdcb3-4e1b-4a0b-86d0-66d4b3f65220' + m_get_vm_moref_id.return_value = None + + # Call configure_alarm method under test + return_value = self.mon_plugin.configure_alarm(config_dict) + + # Verify that mocked methods are called with correct parameters + self.assertEqual(m_get_default_Params.call_count, 2) + m_get_alarm_defination_by_name.assert_called_with(vrops_alarm_name) + m_create_symptom.assert_called_with(symptom_params) + m_create_alarm_definition.assert_called_with(alarm_params) + m_get_vm_moref_id.assert_called_with(config_dict['resource_uuid']) + m_get_vm_resource_id.assert_not_called() + m_create_alarm_notification_rule.assert_not_called() + m_save_alarm.assert_not_called() + + # Verify return value with expected value of alarm_def_uuid + self.assertEqual(return_value, alarm_def_uuid) + + @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') + @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') + @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') + @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') + def test_configure_alarm_failed_to_get_vm_resource_id(self, m_get_default_Params, + m_get_alarm_defination_by_name, + m_create_symptom, + m_create_alarm_definition, + m_get_vm_moref_id, + m_get_vm_resource_id, + m_create_alarm_notification_rule, + m_save_alarm): + """Test configure alarm: failed to get vm resource_id""" + + # Mock input configuration dictionary + config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', + 'alarm_name': 'CPU_Utilization_Above_Threshold', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'statistic': 'AVERAGE', 'metric_name': 'CPU_UTILIZATION', + 'operation': 'GT', 'unit': '%', + 'description': 'CPU_Utilization_Above_Threshold'} + + # symptom parameters to be passed for symptom creation + symptom_params = {'threshold_value': 0, + 'cancel_cycles': 1, + 'adapter_kind_key': 'VMWARE', + 'resource_kind_key': 'VirtualMachine', + 'severity': 'CRITICAL', + 'symptom_name': \ + 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'operation': 'GT', + 'wait_cycles': 1, + 'metric_key': 'cpu|usage_average'} + + # alarm parameters to be passed for alarm creation + alarm_params = {'description': 'CPU_Utilization_Above_Threshold', + 'cancelCycles': 1, 'subType': 19, + 'waitCycles': 1, 'severity': 'CRITICAL', + 'impact': 'risk', 'adapterKindKey': 'VMWARE', + 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'resourceKindKey': 'VirtualMachine', + 'symptomDefinitionId': \ + 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804', + 'type': 16} + + vrops_alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + vm_moref_id = 'vm-6626' + alarm_def_uuid = None + + # Mock default Parameters for alarm & metric configuration + m_get_default_Params.side_effect = [{'impact': 'risk', 'cancel_cycles': 1, + 'adapter_kind': 'VMWARE', 'repeat': False, + 'cancel_period': 300, 'alarm_type': 16, + 'vrops_alarm': 'CPU_Utilization_Above_Thr', + 'enabled': True, 'period': 300, + 'resource_kind': 'VirtualMachine', + 'alarm_subType': 19, 'action': 'acknowledge', + 'evaluation': 1, 'unit': 'msec'}, + {'metric_key': 'cpu|usage_average', 'unit': '%'} + ] + # set mocked function return values + m_get_alarm_defination_by_name.return_value = [] + m_create_symptom.return_value = 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804' + m_create_alarm_definition.return_value = \ + 'AlertDefinition-0f3cdcb3-4e1b-4a0b-86d0-66d4b3f65220' + m_get_vm_moref_id.return_value = vm_moref_id + m_get_vm_resource_id.return_value = None + m_save_alarm.assert_not_called() + + # Call configure_alarm method under test + return_value = self.mon_plugin.configure_alarm(config_dict) + + # Verify that mocked methods are called with correct parameters + self.assertEqual(m_get_default_Params.call_count, 2) + m_get_alarm_defination_by_name.assert_called_with(vrops_alarm_name) + m_create_symptom.assert_called_with(symptom_params) + m_create_alarm_definition.assert_called_with(alarm_params) + m_get_vm_moref_id.assert_called_with(config_dict['resource_uuid']) + m_get_vm_resource_id.assert_called_with(vm_moref_id) + m_create_alarm_notification_rule.assert_not_called() + + # Verify return value with expected value of alarm_def_uuid + self.assertEqual(return_value, alarm_def_uuid) + + @mock.patch.object(monPlugin.DatabaseManager, 'save_alarm') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_notification_rule') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') + @mock.patch.object(monPlugin.MonPlugin, 'create_alarm_definition') + @mock.patch.object(monPlugin.MonPlugin, 'create_symptom') + @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_by_name') + @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') + def test_configure_alarm_failed_to_create_alarm_notification_rule(self, m_get_default_Params, + m_get_alarm_defination_by_name, + m_create_symptom, + m_create_alarm_definition, + m_get_vm_moref_id, + m_get_vm_resource_id, + m_create_alarm_notification_rule, + m_save_alarm): + """Test configure alarm: failed to create alarm notification rule""" + + # Mock input configuration dictionary + config_dict = {'threshold_value': 0, 'severity': 'CRITICAL', + 'alarm_name': 'CPU_Utilization_Above_Threshold', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'statistic': 'AVERAGE', 'metric_name': 'CPU_UTILIZATION', + 'operation': 'GT', 'unit': '%', + 'description': 'CPU_Utilization_Above_Threshold'} + + # symptom parameters to be passed for symptom creation + symptom_params = {'threshold_value': 0, + 'cancel_cycles': 1, + 'adapter_kind_key': 'VMWARE', + 'resource_kind_key': 'VirtualMachine', + 'severity': 'CRITICAL', + 'symptom_name': \ + 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'operation': 'GT', + 'wait_cycles': 1, + 'metric_key': 'cpu|usage_average'} + + # alarm parameters to be passed for alarm creation + alarm_params = {'description': 'CPU_Utilization_Above_Threshold', + 'cancelCycles': 1, 'subType': 19, + 'waitCycles': 1, 'severity': 'CRITICAL', + 'impact': 'risk', 'adapterKindKey': 'VMWARE', + 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'resourceKindKey': 'VirtualMachine', + 'symptomDefinitionId': \ + 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804', + 'type': 16} + + vrops_alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + vm_moref_id = 'vm-6626' + alarm_def = 'AlertDefinition-0f3cdcb3-4e1b-4a0b-86d0-66d4b3f65220' + resource_id = 'ac87622f-b761-40a0-b151-00872a2a456e' + alarm_def_uuid = None + + # Mock default Parameters for alarm & metric configuration + m_get_default_Params.side_effect = [{'impact': 'risk', 'cancel_cycles': 1, + 'adapter_kind': 'VMWARE', 'repeat': False, + 'cancel_period': 300, 'alarm_type': 16, + 'vrops_alarm': 'CPU_Utilization_Above_Thr', + 'enabled': True, 'period': 300, + 'resource_kind': 'VirtualMachine', + 'alarm_subType': 19, 'action': 'acknowledge', + 'evaluation': 1, 'unit': 'msec'}, + {'metric_key': 'cpu|usage_average', 'unit': '%'} + ] + # set mocked function return values + m_get_alarm_defination_by_name.return_value = [] + m_create_symptom.return_value = 'SymptomDefinition-2e8f9ddc-9f7b-4cd6-b85d-7d7fe3a8a804' + m_create_alarm_definition.return_value = \ + 'AlertDefinition-0f3cdcb3-4e1b-4a0b-86d0-66d4b3f65220' + m_get_vm_moref_id.return_value = vm_moref_id + m_get_vm_resource_id.return_value = 'ac87622f-b761-40a0-b151-00872a2a456e' + m_create_alarm_notification_rule.return_value = None + + # Call configure_alarm method under test + return_value = self.mon_plugin.configure_alarm(config_dict) + + # Verify that mocked methods are called with correct parameters + self.assertEqual(m_get_default_Params.call_count, 2) + m_get_alarm_defination_by_name.assert_called_with(vrops_alarm_name) + m_create_symptom.assert_called_with(symptom_params) + m_create_alarm_definition.assert_called_with(alarm_params) + m_get_vm_moref_id.assert_called_with(config_dict['resource_uuid']) + m_get_vm_resource_id.assert_called_with(vm_moref_id) + m_create_alarm_notification_rule.assert_called_with(vrops_alarm_name, alarm_def, resource_id) + m_save_alarm.assert_not_called() + + # Verify return value with expected value of alarm_def_uuid + self.assertEqual(return_value, alarm_def_uuid) + + @mock.patch.object(monPlugin.requests, 'get') + def test_get_alarm_defination_details_valid_rest_req_response(self, m_get): + """Test get_alarm_defination_details: For a valid REST request response""" + + alarm_uuid = '9a6d8a14-9f25-4d81-bf91-4d773497444d' + + # Set mocked function's return values + m_get.return_value.status_code = 200 + m_get.return_value.content = '{"id":"AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d",\ + "name":"CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ + "description":"CPU_Utilization_Above_Threshold",\ + "adapterKindKey":"VMWARE","resourceKindKey":"VirtualMachine",\ + "waitCycles":1,"cancelCycles":1,"type":16,"subType":19,\ + "states":[{"severity":"CRITICAL","base-symptom-set":\ + {"type":"SYMPTOM_SET","relation":"SELF",\ + "aggregation":"ALL","symptomSetOperator":"AND","symptomDefinitionIds":\ + ["SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278"]},\ + "impact":{"impactType":"BADGE","detail":"risk"}}]}' + + expected_alarm_details = {'adapter_kind': 'VMWARE', 'symptom_definition_id': \ + 'SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278', + 'alarm_name': \ + 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'alarm_id': 'AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d', + 'resource_kind': 'VirtualMachine', 'type': 16, 'sub_type': 19} + + expected_alarm_details_json = {'states': + [{'impact': + {'impactType': 'BADGE', 'detail': 'risk'}, 'severity': 'CRITICAL', + 'base-symptom-set': {'symptomDefinitionIds': \ + [ + 'SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278'], + 'relation': 'SELF', 'type': 'SYMPTOM_SET', + 'aggregation': 'ALL', 'symptomSetOperator': 'AND'}}], + 'adapterKindKey': 'VMWARE', + 'description': 'CPU_Utilization_Above_Threshold', + 'type': 16, 'cancelCycles': 1, + 'resourceKindKey': 'VirtualMachine', + 'subType': 19, 'waitCycles': 1, + 'id': 'AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d', + 'name': \ + 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4'} + + # Call get_alarm_defination_details method under test + alarm_details_json, alarm_details = self.mon_plugin.get_alarm_defination_details(alarm_uuid) + + # Verify that mocked method is called + m_get.assert_called() + + # Verify return value with expected value + self.assertEqual(expected_alarm_details, alarm_details) + self.assertEqual(expected_alarm_details_json, alarm_details_json) + + @mock.patch.object(monPlugin.requests, 'get') + def test_get_alarm_defination_details_invalid_rest_req_response(self, m_get): + """Test get_alarm_defination_details: For an invalid REST request response""" + + alarm_uuid = '9a6d8a14-9f25-4d81-bf91-4d773497444d' + + # Set mocked function's return values + m_get.return_value.status_code = 404 + m_get.return_value.content = '{"message": "No such AlertDefinition - \ + AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444.",\ + "httpStatusCode": 404,"apiErrorCode": 404}' + + expected_alarm_details = None + expected_alarm_details_json = None + + # Call get_alarm_defination_details method under test + alarm_details_json, alarm_details = self.mon_plugin.get_alarm_defination_details(alarm_uuid) + + # verify that mocked method is called + m_get.assert_called() + + # Verify return value with expected value + self.assertEqual(expected_alarm_details, alarm_details) + self.assertEqual(expected_alarm_details_json, alarm_details_json) + + @mock.patch.object(monPlugin.requests, 'get') + def test_get_alarm_defination_by_name_valid_rest_req_response(self, m_get): + """Test get_alarm_defination_by_name: For a valid REST request response""" + + alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + + # Set mocked function's return values + m_get.return_value.status_code = 200 + m_get.return_value.content = '{"pageInfo": {"totalCount": 1,"page": 0,"pageSize": 1000},\ + "links": [\ + {"href": "/suite-api/api/alertdefinitions?page=0&pageSize=1000",\ + "rel": "SELF","name": "current"},\ + {"href": "/suite-api/api/alertdefinitions?page=0&pageSize=1000",\ + "rel": "RELATED","name": "first"},\ + {"href": "/suite-api/api/alertdefinitions?page=0&pageSize=1000",\ + "rel": "RELATED","name": "last"}],\ + "alertDefinitions": [{\ + "id": "AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d",\ + "name": "CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ + "description": "CPU_Utilization_Above_Threshold",\ + "adapterKindKey": "VMWARE","resourceKindKey": "VirtualMachine",\ + "waitCycles": 1,"cancelCycles": 1,"type": 16,"subType": 19,\ + "states": [{"impact": {"impactType": "BADGE","detail": "risk"},\ + "severity": "CRITICAL",\ + "base-symptom-set": {"type": "SYMPTOM_SET",\ + "relation": "SELF","aggregation": "ALL",\ + "symptomSetOperator": "AND",\ + "symptomDefinitionIds": [\ + "SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278"]}}]\ + }]}' + + # Expected return match list + Exp_alert_match_list = [{'states': + [{'impact': {'impactType': 'BADGE', 'detail': 'risk'}, + 'severity': 'CRITICAL', + 'base-symptom-set': { + 'symptomDefinitionIds': \ + ['SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278'], + 'relation': 'SELF', + 'type': 'SYMPTOM_SET', + 'aggregation': 'ALL', + 'symptomSetOperator': 'AND'} + }], + 'adapterKindKey': 'VMWARE', + 'description': 'CPU_Utilization_Above_Threshold', + 'type': 16, + 'cancelCycles': 1, + 'resourceKindKey': 'VirtualMachine', + 'subType': 19, 'waitCycles': 1, + 'id': 'AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d', + 'name': \ + 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + }] + + # Call get_alarm_defination_by_name method under test + alert_match_list = self.mon_plugin.get_alarm_defination_by_name(alarm_name) + + # Verify that mocked method is called + m_get.assert_called() + + # Verify return value with expected value + self.assertEqual(Exp_alert_match_list, alert_match_list) + + @mock.patch.object(monPlugin.requests, 'get') + def test_get_alarm_defination_by_name_no_valid_alarm_found(self, m_get): + """Test get_alarm_defination_by_name: With no valid alarm found in returned list""" + + alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda5' + + # Set mocked function's return values + m_get.return_value.status_code = 200 + m_get.return_value.content = '{"pageInfo": {"totalCount": 1,"page": 0,"pageSize": 1000},\ + "links": [\ + {"href": "/suite-api/api/alertdefinitions?page=0&pageSize=1000",\ + "rel": "SELF","name": "current"},\ + {"href": "/suite-api/api/alertdefinitions?page=0&pageSize=1000",\ + "rel": "RELATED","name": "first"},\ + {"href": "/suite-api/api/alertdefinitions?page=0&pageSize=1000",\ + "rel": "RELATED","name": "last"}],\ + "alertDefinitions": [{\ + "id": "AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d",\ + "name": "CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ + "description": "CPU_Utilization_Above_Threshold",\ + "adapterKindKey": "VMWARE","resourceKindKey": "VirtualMachine",\ + "waitCycles": 1,"cancelCycles": 1,"type": 16,"subType": 19,\ + "states": [{"impact": {"impactType": "BADGE","detail": "risk"},\ + "severity": "CRITICAL",\ + "base-symptom-set": {"type": "SYMPTOM_SET",\ + "relation": "SELF","aggregation": "ALL",\ + "symptomSetOperator": "AND",\ + "symptomDefinitionIds": [\ + "SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278"]}}]\ + }]}' + + # Expected return match list + Exp_alert_match_list = [] + + # Call get_alarm_defination_by_name method under test + alert_match_list = self.mon_plugin.get_alarm_defination_by_name(alarm_name) + + # Verify that mocked method is called + m_get.assert_called() + + # Verify return value with expected value + self.assertEqual(Exp_alert_match_list, alert_match_list) + + @mock.patch.object(monPlugin.requests, 'put') + @mock.patch.object(monPlugin.MonPlugin, 'get_symptom_defination_details') + def test_update_symptom_defination_valid_symptom_req_response(self, + m_get_symptom_defination_details, + m_put): + """Test update_symptom_defination: With valid REST response, update symptom""" + + # Expected symptom to be updated + symptom_defination_id = 'SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278' + new_alarm_config = {'severity': "CRITICAL", + 'operation': 'GT', + 'threshold_value': 5, + 'alarm_uuid': '9a6d8a14-9f25-4d81-bf91-4d773497444d' + } + + # Set mocked function's return values + m_get_symptom_defination_details.return_value = { + "id": "SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278", + "name": "CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4", + "adapterKindKey": "VMWARE", + "resourceKindKey": "VirtualMachine", + "waitCycles": 1, + "cancelCycles": 1, + "state": {"severity": "CRITICAL", + "condition": { + "type": "CONDITION_HT", + "key": "cpu|usage_average", "operator": "GT", "value": "0.0", + "valueType": "NUMERIC", "instanced": False, + "thresholdType": "STATIC"} + } + } + + m_put.return_value.status_code = 200 + m_put.return_value.content = '{\ + "id":"SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278",\ + "name":"CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ + "adapterKindKey":"VMWARE","resourceKindKey":"VirtualMachine","waitCycles":1,\ + "cancelCycles":1,\ + "state":{\ + "severity":"CRITICAL",\ + "condition":{\ + "type":"CONDITION_HT","key":"cpu|usage_average","operator":"GT","value":"5.0",\ + "valueType":"NUMERIC","instanced":False,"thresholdType":"STATIC"}}}' + + # Call update_symptom_defination method under test + symptom_uuid = self.mon_plugin.update_symptom_defination(symptom_defination_id, + new_alarm_config) + + # Verify that mocked method is called with required parameters + m_get_symptom_defination_details.assert_called_with(symptom_defination_id) + # m_put.assert_called_with(symptom_defination_id,new_alarm_config) + + # Verify return value with expected value + self.assertEqual(symptom_defination_id, symptom_uuid) + + @mock.patch.object(monPlugin.requests, 'put') + @mock.patch.object(monPlugin.MonPlugin, 'get_symptom_defination_details') + def test_update_symptom_defination_invalid_symptom_req_response(self, + m_get_symptom_defination_details, + m_put): + """Test update_symptom_defination: If invalid REST response received, return None""" + + # Expected symptom to be updated + symptom_defination_id = 'SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278' + new_alarm_config = {'severity': "CRITICAL", + 'operation': 'GT', + 'threshold_value': 5, + 'alarm_uuid': '9a6d8a14-9f25-4d81-bf91-4d773497444d' + } + + # Set mocked function's return values + m_get_symptom_defination_details.return_value = { + "id": "SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278", + "name": "CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4", + "adapterKindKey": "VMWARE", + "resourceKindKey": "VirtualMachine", + "waitCycles": 1, + "cancelCycles": 1, + "state": {"severity": "CRITICAL", + "condition": { + "type": "CONDITION_HT", + "key": "cpu|usage_average", "operator": "GT", "value": "0.0", + "valueType": "NUMERIC", "instanced": False, + "thresholdType": "STATIC"} + } + } + + m_put.return_value.status_code = 500 + m_put.return_value.content = '{\ + "message": "Internal Server error, cause unknown.",\ + "moreInformation": [\ + {"name": "errorMessage",\ + "value": "Symptom Definition CPU_Utilization_Above_Thr-e14b203c-\ + 6bf2-4e2f-a91c-8c19d240eda4 does not exist and hence cannot be updated."},\ + {"name": "localizedMessage",\ + "value": "Symptom Definition CPU_Utilization_Above_Thr-e14b203c-\ + 6bf2-4e2f-a91c-8c19d240eda4 does not exist and hence cannot be updated.;"}],\ + "httpStatusCode": 500,"apiErrorCode": 500}' + + # Call update_symptom_defination method under test + symptom_uuid = self.mon_plugin.update_symptom_defination(symptom_defination_id, + new_alarm_config) + + # Verify that mocked method is called with required parameters + m_get_symptom_defination_details.assert_called_with(symptom_defination_id) + m_put.assert_called() + + # Verify return value with expected value + self.assertEqual(symptom_uuid, None) + + @mock.patch.object(monPlugin.requests, 'put') + @mock.patch.object(monPlugin.MonPlugin, 'get_symptom_defination_details') + def test_update_symptom_defination_failed_to_get_symptom_defination(self, + m_get_symptom_defination_details, + m_put): + """Test update_symptom_defination: if fails to get symptom_defination returns None""" + + # Expected symptom to be updated + symptom_defination_id = 'SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278' + new_alarm_config = {'severity': "CRITICAL", + 'operation': 'GT', + 'threshold_value': 5, + 'alarm_uuid': '9a6d8a14-9f25-4d81-bf91-4d773497444d' + } + + # Set mocked function's return values + m_get_symptom_defination_details.return_value = None + + # Call update_symptom_defination method under test + symptom_uuid = self.mon_plugin.update_symptom_defination(symptom_defination_id, + new_alarm_config) + + # Verify that mocked method is called with required parameters + m_get_symptom_defination_details.assert_called_with(symptom_defination_id) + m_put.assert_not_called() + + # Verify return value with expected value + self.assertEqual(symptom_uuid, None) + + @mock.patch.object(monPlugin.requests, 'get') + def test_get_symptom_defination_details_valid_req_response(self, m_get): + """Test update_symptom_defination: With valid REST response symptom is created""" + + # Expected symptom to be updated + symptom_uuid = 'SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278' + + # Set mocked function's return values + m_get.return_value.status_code = 200 + m_get.return_value.content = '{\ + "id": "SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278",\ + "name": "CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ + "adapterKindKey": "VMWARE","resourceKindKey": "VirtualMachine","waitCycles": 1,\ + "cancelCycles": 1,"state": {"severity": "CRITICAL","condition": {"type": "CONDITION_HT",\ + "key": "cpu|usage_average","operator": "GT","value": "6.0","valueType": "NUMERIC",\ + "instanced": false,"thresholdType": "STATIC"}}}' + expected_symptom_details = { \ + "id": "SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278", + "name": "CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4", + "adapterKindKey": "VMWARE", "resourceKindKey": "VirtualMachine", "waitCycles": 1, + "cancelCycles": 1, "state": {"severity": "CRITICAL", "condition": {"type": "CONDITION_HT", + "key": "cpu|usage_average", + "operator": "GT", "value": "6.0", + "valueType": "NUMERIC", + "instanced": False, + "thresholdType": "STATIC"}}} + + # Call update_symptom_defination method under test + symptom_details = self.mon_plugin.get_symptom_defination_details(symptom_uuid) + + # Verify that mocked method is called with required parameters + m_get.assert_called() + + # Verify return value with expected value + self.assertEqual(expected_symptom_details, symptom_details) + + @mock.patch.object(monPlugin.requests, 'get') + def test_get_symptom_defination_details_invalid_req_response(self, m_get): + """Test update_symptom_defination: if invalid REST response received return None""" + + # Expected symptom to be updated + symptom_uuid = 'SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278' + + # Set mocked function's return values + m_get.return_value.status_code = 404 + m_get.return_value.content = '{"message": "No such SymptomDefinition\ + - SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278.",\ + "httpStatusCode": 404,"apiErrorCode": 404}' + + expected_symptom_details = None + + # Call update_symptom_defination method under test + symptom_details = self.mon_plugin.get_symptom_defination_details(symptom_uuid) + + # Verify that mocked method is called with required parameters + m_get.assert_called() + + # Verify return value with expected value + self.assertEqual(expected_symptom_details, symptom_details) + + @mock.patch.object(monPlugin.requests, 'get') + def test_get_symptom_defination_details_symptom_uuid_not_provided(self, m_get): + """Test update_symptom_defination: if required symptom uuid is not provided""" + + # Expected symptom to be updated + symptom_uuid = None + expected_symptom_details = None + + # Call update_symptom_defination method under test + symptom_details = self.mon_plugin.get_symptom_defination_details(symptom_uuid) + + # Verify that mocked method is called with required parameters + m_get.assert_not_called() + + # Verify return value with expected value + self.assertEqual(expected_symptom_details, symptom_details) + + @mock.patch.object(monPlugin.requests, 'put') + def test_reconfigure_alarm_valid_req_response(self, m_put): + """Test reconfigure_alarm: for valid REST response""" + + # Set input parameters to reconfigure_alarm + alarm_details_json = { + 'id': 'AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d', + 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'description': 'CPU_Utilization_Above_Threshold', 'adapterKindKey': 'VMWARE', + 'states': [{'impact': {'impactType': 'BADGE', 'detail': 'risk'}, 'severity': 'CRITICAL', + 'base-symptom-set': { + 'symptomDefinitionIds': ['SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278'], + 'relation': 'SELF', 'type': 'SYMPTOM_SET', 'aggregation': 'ALL', + 'symptomSetOperator': 'AND'}}], + 'type': 16, 'cancelCycles': 1, 'resourceKindKey': 'VirtualMachine', 'subType': 19, + 'waitCycles': 1} + + new_alarm_config = {'severity': 'WARNING', + 'description': 'CPU_Utilization_Above_Threshold_Warning'} + + # Set mocked function's return values + m_put.return_value.status_code = 200 + m_put.return_value.content = '{"id":"AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d",\ + "name":"CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ + "description":"CPU_Utilization_Above_Threshold_Warning","adapterKindKey":"VMWARE",\ + "resourceKindKey":"VirtualMachine","waitCycles":1,"cancelCycles":1,"type":16,\ + "subType":19,"states":[{"severity":"WARNING","base-symptom-set":{"type":"SYMPTOM_SET",\ + "relation":"SELF","aggregation":"ALL","symptomSetOperator":"AND",\ + "symptomDefinitionIds":["SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278"]},\ + "impact":{"impactType":"BADGE","detail":"risk"}}]}' + + # Expected alarm_def_uuid to be returned + expected_alarm_def_uuid = '9a6d8a14-9f25-4d81-bf91-4d773497444d' + + # Call reconfigure_alarm method under test + alarm_def_uuid = self.mon_plugin.reconfigure_alarm(alarm_details_json, new_alarm_config) + + # Verify that mocked method is called with required parameters + m_put.assert_called() + + # Verify return value with expected value + self.assertEqual(expected_alarm_def_uuid, alarm_def_uuid) + + @mock.patch.object(monPlugin.requests, 'put') + def test_reconfigure_alarm_invalid_req_response(self, m_put): + """Test reconfigure_alarm: for invalid REST response, return None""" + + # Set input parameters to reconfigure_alarm + alarm_details_json = { + 'id': 'AlertDefinition-9a6d8a14-9f25-4d81-bf91-4d773497444d', + 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'description': 'CPU_Utilization_Above_Threshold', 'adapterKindKey': 'VMWARE', + 'states': [{'impact': {'impactType': 'BADGE', 'detail': 'risk'}, 'severity': 'CRITICAL', + 'base-symptom-set': { + 'symptomDefinitionIds': ['SymptomDefinition-bcc2cb36-a67b-4deb-bcd3-9b5884973278'], + 'relation': 'SELF', 'type': 'SYMPTOM_SET', 'aggregation': 'ALL', + 'symptomSetOperator': 'AND'}}], + 'type': 16, 'cancelCycles': 1, 'resourceKindKey': 'VirtualMachine', 'subType': 19, + 'waitCycles': 1} + + new_alarm_config = {'severity': 'WARNING', + 'description': 'CPU_Utilization_Above_Threshold_Warning'} + + # Set mocked function's return values + m_put.return_value.status_code = 500 + m_put.return_value.content = '{"message": "Internal Server error, cause unknown.",\ + "moreInformation": [{"name": "errorMessage",\ + "value": "Cannot update Alert Definition CPU_Utilization_Above_Thr-\ + e14b203c-6bf2-4e2f-a91c-8c19d240eda4 since it does not exist"},\ + {"name": "localizedMessage",\ + "value": "Cannot update Alert Definition CPU_Utilization_Above_Thr-\ + e14b203c-6bf2-4e2f-a91c-8c19d240eda4 since it does not exist;"}],\ + "httpStatusCode": 500,"apiErrorCode": 500}' + + # Expected alarm_def_uuid to be returned + expected_alarm_def_uuid = None + + # Call reconfigure_alarm method under test + alarm_def_uuid = self.mon_plugin.reconfigure_alarm(alarm_details_json, new_alarm_config) + + # Verify that mocked method is called with required parameters + m_put.assert_called() + + # Verify return value with expected value + self.assertEqual(expected_alarm_def_uuid, alarm_def_uuid) + + @mock.patch.object(monPlugin.MonPlugin, 'delete_symptom_definition') + @mock.patch.object(monPlugin.MonPlugin, 'delete_alarm_defination') + @mock.patch.object(monPlugin.MonPlugin, 'delete_notification_rule') + @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_details') + def test_delete_alarm_configuration_successful_alarm_deletion(self, + m_get_alarm_defination_details, + m_delete_notification_rule, + m_delete_alarm_defination, + m_delete_symptom_definition): + """Test delete_alarm_configuration: for successful alarm deletion, return alarm uuid""" + + # Set input parameters to delete_alarm_configuration + delete_alarm_req_dict = {'alarm_uuid': '9a6d8a14-9f25-4d81-bf91-4d773497444d'} + + # Set mocked function's return values + alarm_details_json = { + 'id': 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d', + 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4', + 'symptomDefinitionIds': ['SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278']} + alarm_details = { + 'alarm_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4', + 'alarm_id': 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d', + 'symptom_definition_id': 'SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278'} + + m_get_alarm_defination_details.return_value = (alarm_details_json, alarm_details) + m_delete_notification_rule.return_value = '989e7293-d78d-4405-92e30ec4f247' + m_delete_alarm_defination.return_value = alarm_details['alarm_id'] + m_delete_symptom_definition.return_value = alarm_details['symptom_definition_id'] + + # Call reconfigure_alarm method under test + alarm_uuid = self.mon_plugin.delete_alarm_configuration(delete_alarm_req_dict) + + # Verify that mocked method is called with required parameters + m_get_alarm_defination_details.assert_called_with(delete_alarm_req_dict['alarm_uuid']) + m_delete_notification_rule.assert_called_with(alarm_details['alarm_name']) + m_delete_alarm_defination.assert_called_with(alarm_details['alarm_id']) + m_delete_symptom_definition.assert_called_with(alarm_details['symptom_definition_id']) + + # Verify return value with expected value + self.assertEqual(alarm_uuid, delete_alarm_req_dict['alarm_uuid']) + + @mock.patch.object(monPlugin.MonPlugin, 'delete_symptom_definition') + @mock.patch.object(monPlugin.MonPlugin, 'delete_alarm_defination') + @mock.patch.object(monPlugin.MonPlugin, 'delete_notification_rule') + @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_details') + def test_delete_alarm_configuration_failed_to_get_alarm_defination(self, + m_get_alarm_defination_details, + m_delete_notification_rule, + m_delete_alarm_defination, + m_delete_symptom_definition): + """Test delete_alarm_configuration: if failed to get alarm definition, return None""" + + # Set input parameters to delete_alarm_configuration + delete_alarm_req_dict = {'alarm_uuid': '9a6d8a14-9f25-4d81-bf91-4d773497444d'} + + # Set mocked function's return values + alarm_details_json = None + alarm_details = None + + m_get_alarm_defination_details.return_value = (alarm_details_json, alarm_details) + + # Call reconfigure_alarm method under test + alarm_uuid = self.mon_plugin.delete_alarm_configuration(delete_alarm_req_dict) + + # Verify that mocked method is called with required parameters + m_get_alarm_defination_details.assert_called_with(delete_alarm_req_dict['alarm_uuid']) + m_delete_notification_rule.assert_not_called() + m_delete_alarm_defination.assert_not_called() + m_delete_symptom_definition.assert_not_called() + + # Verify return value with expected value + self.assertEqual(alarm_uuid, None) + + @mock.patch.object(monPlugin.MonPlugin, 'delete_symptom_definition') + @mock.patch.object(monPlugin.MonPlugin, 'delete_alarm_defination') + @mock.patch.object(monPlugin.MonPlugin, 'delete_notification_rule') + @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_details') + def test_delete_alarm_configuration_failed_to_delete_notification_rule(self, + m_get_alarm_defination_details, + m_delete_notification_rule, + m_delete_alarm_defination, + m_delete_symptom_definition): + """Test delete_alarm_configuration: if failed to delete notification rule, return None""" + + # Set input parameters to delete_alarm_configuration + delete_alarm_req_dict = {'alarm_uuid': '9a6d8a14-9f25-4d81-bf91-4d773497444d'} + + # Set mocked function's return values + alarm_details_json = { + 'id': 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d', + 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4', + 'symptomDefinitionIds': ['SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278']} + alarm_details = { + 'alarm_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4', + 'alarm_id': 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d', + 'symptom_definition_id': 'SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278'} + + m_get_alarm_defination_details.return_value = (alarm_details_json, alarm_details) + m_delete_notification_rule.return_value = None + + # Call reconfigure_alarm method under test + alarm_uuid = self.mon_plugin.delete_alarm_configuration(delete_alarm_req_dict) + + # Verify that mocked method is called with required parameters + m_get_alarm_defination_details.assert_called_with(delete_alarm_req_dict['alarm_uuid']) + m_delete_notification_rule.assert_called_with(alarm_details['alarm_name']) + m_delete_alarm_defination.assert_not_called() + m_delete_symptom_definition.assert_not_called() + + # Verify return value with expected value + self.assertEqual(alarm_uuid, None) + + @mock.patch.object(monPlugin.MonPlugin, 'delete_symptom_definition') + @mock.patch.object(monPlugin.MonPlugin, 'delete_alarm_defination') + @mock.patch.object(monPlugin.MonPlugin, 'delete_notification_rule') + @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_details') + def test_delete_alarm_configuration_failed_to_delete_alarm_defination(self, + m_get_alarm_defination_details, + m_delete_notification_rule, + m_delete_alarm_defination, + m_delete_symptom_definition): + """Test delete_alarm_configuration: if failed to delete alarm definition, return None""" + + # Set input parameters to delete_alarm_configuration + delete_alarm_req_dict = {'alarm_uuid': '9a6d8a14-9f25-4d81-bf91-4d773497444d'} + + # Set mocked function's return values + alarm_details_json = { + 'id': 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d', + 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4', + 'symptomDefinitionIds': ['SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278']} + alarm_details = { + 'alarm_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4', + 'alarm_id': 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d', + 'symptom_definition_id': 'SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278'} + + m_get_alarm_defination_details.return_value = (alarm_details_json, alarm_details) + m_delete_notification_rule.return_value = '989e7293-d78d-4405-92e30ec4f247' + m_delete_alarm_defination.return_value = None + + # Call reconfigure_alarm method under test + alarm_uuid = self.mon_plugin.delete_alarm_configuration(delete_alarm_req_dict) + + # Verify that mocked method is called with required parameters + m_get_alarm_defination_details.assert_called_with(delete_alarm_req_dict['alarm_uuid']) + m_delete_notification_rule.assert_called_with(alarm_details['alarm_name']) + m_delete_alarm_defination.assert_called_with(alarm_details['alarm_id']) + m_delete_symptom_definition.assert_not_called() + + # Verify return value with expected value + self.assertEqual(alarm_uuid, None) + + @mock.patch.object(monPlugin.MonPlugin, 'delete_symptom_definition') + @mock.patch.object(monPlugin.MonPlugin, 'delete_alarm_defination') + @mock.patch.object(monPlugin.MonPlugin, 'delete_notification_rule') + @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_details') + def test_delete_alarm_configuration_failed_to_delete_symptom_definition(self, + m_get_alarm_defination_details, + m_delete_notification_rule, + m_delete_alarm_defination, + m_delete_symptom_definition): + """Test delete_alarm_configuration: if failed to delete symptom definition, return None""" + + # Set input parameters to delete_alarm_configuration + delete_alarm_req_dict = {'alarm_uuid': '9a6d8a14-9f25-4d81-bf91-4d773497444d'} + + # Set mocked function's return values + alarm_details_json = { + 'id': 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d', + 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4', + 'symptomDefinitionIds': ['SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278']} + alarm_details = { + 'alarm_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4', + 'alarm_id': 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d', + 'symptom_definition_id': 'SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278'} + + m_get_alarm_defination_details.return_value = (alarm_details_json, alarm_details) + m_delete_notification_rule.return_value = '989e7293-d78d-4405-92e30ec4f247' + m_delete_alarm_defination.return_value = alarm_details['alarm_id'] + m_delete_symptom_definition.return_value = None + + # Call reconfigure_alarm method under test + alarm_uuid = self.mon_plugin.delete_alarm_configuration(delete_alarm_req_dict) + + # Verify that mocked method is called with required parameters + m_get_alarm_defination_details.assert_called_with(delete_alarm_req_dict['alarm_uuid']) + m_delete_notification_rule.assert_called_with(alarm_details['alarm_name']) + m_delete_alarm_defination.assert_called_with(alarm_details['alarm_id']) + m_delete_symptom_definition.assert_called_with(alarm_details['symptom_definition_id']) + + # Verify return value with expected value + self.assertEqual(alarm_uuid, None) + + @mock.patch.object(monPlugin.requests, 'delete') + @mock.patch.object(monPlugin.MonPlugin, 'get_notification_rule_id_by_alarm_name') + def test_delete_notification_rule_successful_deletion_req_response(self, + m_get_notification_rule_id_by_alarm_name, + m_delete): + """Test delete_notification_rule: Valid notification rule is deleted & returns rule_id""" + + # Set input parameters to delete_notification_rule + alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4' + + # Set mocked function's return values + m_get_notification_rule_id_by_alarm_name.return_value = '8db86441-71d8-4830-9e1a-a90be3776d12' + m_delete.return_value.status_code = 204 + + # Call delete_notification_rule method under test + rule_id = self.mon_plugin.delete_notification_rule(alarm_name) + + # Verify that mocked method is called with required parameters + m_get_notification_rule_id_by_alarm_name.assert_called_with(alarm_name) + m_delete.assert_called() + + # Verify return value with expected value + self.assertEqual(rule_id, '8db86441-71d8-4830-9e1a-a90be3776d12') + + @mock.patch.object(monPlugin.requests, 'delete') + @mock.patch.object(monPlugin.MonPlugin, 'get_notification_rule_id_by_alarm_name') + def test_delete_notification_rule_failed_to_get_notification_rule_id(self, + m_get_notification_rule_id_by_alarm_name, + m_delete): + """Test delete_notification_rule: if notification rule is not found, returns None""" + + # Set input parameters to delete_notification_rule + alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4' + + # Set mocked function's return values + m_get_notification_rule_id_by_alarm_name.return_value = None + + # Call delete_notification_rule method under test + rule_id = self.mon_plugin.delete_notification_rule(alarm_name) + + # Verify that mocked method is called with required parameters + m_get_notification_rule_id_by_alarm_name.assert_called_with(alarm_name) + m_delete.assert_not_called() + + # verify return value with expected value + self.assertEqual(rule_id, None) + + @mock.patch.object(monPlugin.requests, 'delete') + @mock.patch.object(monPlugin.MonPlugin, 'get_notification_rule_id_by_alarm_name') + def test_delete_notification_rule_invalid_deletion_req_response(self, + m_get_notification_rule_id_by_alarm_name, + m_delete): + """Test delete_notification_rule: If an invalid response is received, returns None""" + + # Set input parameters to delete_notification_rule + alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-8c19d240eda4' + + # Set mocked function's return values + m_get_notification_rule_id_by_alarm_name.return_value = '8db86441-71d8-4830-9e1a-a90be3776d12' + m_delete.return_value.status_code = 404 + + # Call delete_notification_rule method under test + rule_id = self.mon_plugin.delete_notification_rule(alarm_name) + + # Verify that mocked method is called with required parameters + m_get_notification_rule_id_by_alarm_name.assert_called_with(alarm_name) + m_delete.assert_called() + + # Verify return value with expected value + self.assertEqual(rule_id, None) + + @mock.patch.object(monPlugin.requests, 'get') + def test_get_notification_rule_id_by_alarm_name_valid_req_response(self, m_get): + """Test get_notification_rule_id_by_alarm_name: A valid request response received, + returns notification_id + """ + + # Set input parameters to get_notification_rule_id_by_alarm_name + alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + + # Set mocked function's return values + m_get.return_value.status_code = 200 + m_get.return_value.content = '{\ + "pageInfo": {"totalCount": 0,"page": 0,"pageSize": 1000},\ + "links": [\ + {"href": "/suite-api/api/notifications/rules?page=0&pageSize=1000",\ + "rel": "SELF","name": "current"},\ + {"href": "/suite-api/api/notifications/rules?page=0&pageSize=1000",\ + "rel": "RELATED","name": "first"},\ + {"href": "/suite-api/api/notifications/rules?page=0&pageSize=1000",\ + "rel": "RELATED","name": "last"}],\ + "notification-rule": [{\ + "id": "2b86fa23-0c15-445c-a2b1-7bd725c46f59",\ + "name": "notify_CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ + "pluginId": "03053f51-f829-438d-993d-cc33a435d76a",\ + "links": [{"href": "/suite-api/api/notifications/rules/2b86fa23-0c15-445c-a2b1-7bd725c46f59",\ + "rel": "SELF","name": "linkToSelf"}]}]}' + + # Call get_notification_rule_id_by_alarm_name method under test + notification_id = self.mon_plugin.get_notification_rule_id_by_alarm_name(alarm_name) + + # Verify that mocked method is called with required parameters + m_get.assert_called() + + # Verify return value with expected value + self.assertEqual(notification_id, '2b86fa23-0c15-445c-a2b1-7bd725c46f59') + + @mock.patch.object(monPlugin.requests, 'get') + def test_get_notification_rule_id_by_alarm_name_invalid_req_response(self, m_get): + """Test get_notification_rule_id_by_alarm_name: If an invalid response received,\ + returns None + """ + + # Set input parameters to delete_alarm_configuration + alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + + # Set mocked function's return values + m_get.return_value.status_code = 404 + + # Call get_notification_rule_id_by_alarm_name method under test + notification_id = self.mon_plugin.get_notification_rule_id_by_alarm_name(alarm_name) + + # Verify that mocked method is called with required parameters + m_get.assert_called() + + # Verify return value with expected value + self.assertEqual(notification_id, None) + + @mock.patch.object(monPlugin.requests, 'get') + def test_get_notification_rule_id_by_alarm_name_rule_not_found(self, m_get): + """Test get_notification_rule_id_by_alarm_name: If a notification rule is not found, + returns None + """ + + # Set input parameters to delete_alarm_configuration + alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda' + + # Set mocked function's return values + m_get.return_value.status_code = 200 + m_get.return_value.content = '{\ + "pageInfo": {"totalCount": 0,"page": 0,"pageSize": 1000},\ + "links": [\ + {"href": "/suite-api/api/notifications/rules?page=0&pageSize=1000",\ + "rel": "SELF","name": "current"},\ + {"href": "/suite-api/api/notifications/rules?page=0&pageSize=1000",\ + "rel": "RELATED","name": "first"},\ + {"href": "/suite-api/api/notifications/rules?page=0&pageSize=1000",\ + "rel": "RELATED","name": "last"}],\ + "notification-rule": [{\ + "id": "2b86fa23-0c15-445c-a2b1-7bd725c46f59",\ + "name": "notify_CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4",\ + "pluginId": "03053f51-f829-438d-993d-cc33a435d76a",\ + "links": [{"href": "/suite-api/api/notifications/rules/2b86fa23-0c15-445c-a2b1-7bd725c46f59",\ + "rel": "SELF","name": "linkToSelf"}]}]}' + + # Call get_notification_rule_id_by_alarm_name method under test + notification_id = self.mon_plugin.get_notification_rule_id_by_alarm_name(alarm_name) + + # Verify that mocked method is called with required parameters + m_get.assert_called() + + # Verify return value with expected value + self.assertEqual(notification_id, None) + + @mock.patch.object(monPlugin.requests, 'delete') + def test_delete_alarm_defination_valid_req_response(self, m_delete): + """Test delete_alarm_defination: A valid request response received, + returns symptom_id + """ + + # Set input parameters to delete_alarm_definition + alarm_definition_id = 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d' + + # Set mocked function's return values + m_delete.return_value.status_code = 204 + + # Call delete_alarm_defination method under test + actual_alarm_id = self.mon_plugin.delete_alarm_defination(alarm_definition_id) + + # Verify that mocked method is called with required parameters + m_delete.assert_called() + + # Verify return value with expected value + self.assertEqual(actual_alarm_id, alarm_definition_id) + + @mock.patch.object(monPlugin.requests, 'delete') + def test_delete_alarm_defination_invalid_req_response(self, m_delete): + """Test delete_alarm_defination: If an invalid request response received, + returns None + """ + + # Set input parameters to delete_alarm_definition + alarm_definition_id = 'AlertDefinition-9a6d8a14-9f25-4d81-4d773497444d' + + # Set mocked function's return values + m_delete.return_value.status_code = 404 + + # Call delete_alarm_defination method under test + actual_alarm_id = self.mon_plugin.delete_alarm_defination(alarm_definition_id) + + # Verify that mocked method is called with required parameters + m_delete.assert_called() + + # Verify return value with expected value + self.assertEqual(actual_alarm_id, None) + + @mock.patch.object(monPlugin.requests, 'delete') + def test_delete_symptom_definition_valid_req_response(self, m_delete): + """Test delete_symptom_definition: A valid request response received, + returns symptom_id + """ + + # Set input parameters to delete_symptom_definition + symptom_definition_id = 'SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278' + + # Set mocked function's return values + m_delete.return_value.status_code = 204 + + # Call delete_symptom_definition method under test + actual_symptom_id = self.mon_plugin.delete_symptom_definition(symptom_definition_id) + + # Verify that mocked method is called with required parameters + m_delete.assert_called() + + # Verify return value with expected value + self.assertEqual(actual_symptom_id, symptom_definition_id) + + @mock.patch.object(monPlugin.requests, 'delete') + def test_delete_symptom_definition_invalid_req_response(self, m_delete): + """Test delete_symptom_definition: If an invalid request response received, + returns None + """ + + # Set input parameters to delete_symptom_definition + symptom_definition_id = 'SymptomDefinition-bcc2cb36-a67b-4deb-9b5884973278' + + # Set mocked function's return values + m_delete.return_value.status_code = 404 + + # Call delete_symptom_definition method under test + actual_symptom_id = self.mon_plugin.delete_symptom_definition(symptom_definition_id) + + # Verify that mocked method is called with required parameters + m_delete.assert_called() + + # Verify return value with expected value + self.assertEqual(actual_symptom_id, None) + + @mock.patch.object(monPlugin.requests, 'post') + @mock.patch.object(monPlugin.MonPlugin, 'check_if_plugin_configured') + def test_configure_rest_plugin_valid_plugin_id(self, m_check_if_plugin_configured, m_post): + """Test configure rest plugin method-valid plugin id""" + + # mock return values + expected_return = m_check_if_plugin_configured.return_value = "mock_pluginid" + + # call configure rest plugin method under test + actual_return = self.mon_plugin.configure_rest_plugin() + + # verify that mocked method is called + m_check_if_plugin_configured.assert_called() + m_post.assert_not_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.MonPlugin, 'enable_rest_plugin') + @mock.patch.object(monPlugin.requests, 'post') + @mock.patch.object(monPlugin.MonPlugin, 'check_if_plugin_configured') + def est_configure_rest_plugin_invalid_plugin_id(self, m_check_if_plugin_configured, m_post, m_enable_rest_plugin): + """Test configure rest plugin method-invalid plugin id""" + + # mock return values + m_check_if_plugin_configured.return_value = None # not configured + m_post.return_value.status_code = 201 # success + m_post.return_value.content = '{"pluginTypeId":"RestPlugin","pluginId":"1ef15663-9739-49fe-8c41-022bcc9f690c",\ + "name":"MON_module_REST_Plugin","version":1518693747871,"enabled":false,\ + "configValues":[{"name":"Url","value":"https://MON.lxd:8080/notify/"},\ + {"name":"Content-type","value":"application/json"},{"name":"Certificate",\ + "value":"AA:E7:3E:A5:34:E0:25:FB:28:84:3B:74:B2:18:74:C0:C3:E8:26:50"},\ + {"name":"ConnectionCount","value":"20"}]}' + + m_enable_rest_plugin.return_value = True # success + expected_return = '1ef15663-9739-49fe-8c41-022bcc9f690c' + + # call configure rest plugin method under test + actual_return = self.mon_plugin.configure_rest_plugin() + + # verify that mocked method is called + m_check_if_plugin_configured.assert_called() + m_post.assert_called() + m_enable_rest_plugin.assert_called_with('1ef15663-9739-49fe-8c41-022bcc9f690c', 'MON_module_REST_Plugin') + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.MonPlugin, 'enable_rest_plugin') + @mock.patch.object(monPlugin.requests, 'post') + @mock.patch.object(monPlugin.MonPlugin, 'check_if_plugin_configured') + def est_configure_rest_plugin_failed_to_enable_plugin(self, m_check_if_plugin_configured, m_post, + m_enable_rest_plugin): + """Test configure rest plugin method-failed to enable plugin case""" + + # mock return values + m_check_if_plugin_configured.return_value = None # not configured + m_post.return_value.status_code = 201 # success + m_post.return_value.content = '{"pluginTypeId":"RestPlugin","pluginId":"1ef15663-9739-49fe-8c41-022bcc9f690c",\ + "name":"MON_module_REST_Plugin","version":1518693747871,"enabled":false,\ + "configValues":[{"name":"Url","value":"https://MON.lxd:8080/notify/"},\ + {"name":"Content-type","value":"application/json"},{"name":"Certificate",\ + "value":"AA:E7:3E:A5:34:E0:25:FB:28:84:3B:74:B2:18:74:C0:C3:E8:26:50"},\ + {"name":"ConnectionCount","value":"20"}]}' + + m_enable_rest_plugin.return_value = False # return failure + expected_return = None + + # call configure rest plugin method under test + actual_return = self.mon_plugin.configure_rest_plugin() + + # verify that mocked method is called + m_check_if_plugin_configured.assert_called() + m_post.assert_called() + m_enable_rest_plugin.assert_called_with('1ef15663-9739-49fe-8c41-022bcc9f690c', 'MON_module_REST_Plugin') + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'get') + def test_check_if_plugin_configured_valid_req_response(self, m_get): + """Test check if plugin configured method-valid request response""" + + plugin_name = 'MON_module_REST_Plugin' + # mock return values + m_get.return_value.status_code = 200 + expected_return = '1ef15663-9739-49fe-8c41-022bcc9f690c' + m_get.return_value.content = '{"notificationPluginInstances":\ + [{"pluginTypeId":"RestPlugin",\ + "pluginId":"1ef15663-9739-49fe-8c41-022bcc9f690c",\ + "name":"MON_module_REST_Plugin","version":1518694966987,\ + "enabled":true,"configValues":[{"name":"Url",\ + "value":"https://MON.lxd:8080/notify/"},\ + {"name":"Content-type","value":"application/json"},\ + {"name":"Certificate",\ + "value":"AA:E7:3E:A5:34:E0:25:FB:28:84:3B:74:B2:18:74:C0"},\ + {"name":"ConnectionCount","value":"20"}]}]}' + + # call check if plugin configured method under test + actual_return = self.mon_plugin.check_if_plugin_configured(plugin_name) + + # verify that mocked method is called + m_get.assert_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'get') + def test_check_if_plugin_configured_invalid_req_response(self, m_get): + """Test check if plugin configured method-invalid request response""" + + plugin_name = 'MON_module_REST_Plugin' + # mock return values + m_get.return_value.status_code = 201 + expected_return = None + m_get.return_value.content = '{"notificationPluginInstances":\ + [{"pluginTypeId":"RestPlugin",\ + "pluginId":"1ef15663-9739-49fe-8c41-022bcc9f690c",\ + "name":"MON_module_REST_Plugin","version":1518694966987,\ + "enabled":true,"configValues":[{"name":"Url",\ + "value":"https://MON.lxd:8080/notify/"},\ + {"name":"Content-type","value":"application/json"},\ + {"name":"Certificate",\ + "value":"AA:E7:3E:A5:34:E0:25:FB:28:84:3B:74:B2:18:74:C0"},\ + {"name":"ConnectionCount","value":"20"}]}]}' + + # call check if plugin configured method under test + actual_return = self.mon_plugin.check_if_plugin_configured(plugin_name) + + # verify that mocked method is called + m_get.assert_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'put') + def test_enable_rest_plugin_valid_req_response(self, m_put): + """Test enable rest plugin method-valid request response""" + + plugin_name = 'MON_module_REST_Plugin' + plugin_id = '1ef15663-9739-49fe-8c41-022bcc9f690c' + # mock return values + m_put.return_value.status_code = 204 + expected_return = True + m_put.return_value.content = '' + + # call enable rest plugin configured method under test + actual_return = self.mon_plugin.enable_rest_plugin(plugin_id, plugin_name) + + # verify that mocked method is called + m_put.assert_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'put') + def test_enable_rest_plugin_invalid_req_response(self, m_put): + """Test enable rest plugin method-invalid request response""" + + plugin_name = 'MON_module_REST_Plugin' + plugin_id = '08018c0f-8879-4ca1-9b92-00e22d2ff81b' # invalid plugin id + # mock return values + m_put.return_value.status_code = 404 # api Error code + expected_return = False + m_put.return_value.content = '\ + No such Notification Plugin - 08018c0f-8879-4ca1-9b92-\ + 00e22d2ff81b.' + + # call enable rest plugin configured method under test + actual_return = self.mon_plugin.enable_rest_plugin(plugin_id, plugin_name) + + # verify that mocked method is called + m_put.assert_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'post') + @mock.patch.object(monPlugin.MonPlugin, 'check_if_plugin_configured') + def test_create_alarm_notification_rule_valid_req(self, m_check_if_plugin_configured, m_post): + """Test create alarm notification rule method valid request response""" + + alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + alarm_id = 'AlertDefinition-f1163767-6eac-438f-8e60-a7a867257e14' + res_id = 'ac87622f-b761-40a0-b151-00872a2a456e' + expected_return = "8db86441-71d8-4830-9e1a-a90be3776d12" + + # mock return values + m_check_if_plugin_configured.return_value = '03053f51-f829-438d-993d-cc33a435d76a' + m_post.return_value.status_code = 201 + m_post.return_value.content = '{"id":"8db86441-71d8-4830-9e1a-a90be3776d12",\ + "name":"notify_CPU_Utilization_Above_Thr-e14b203c",\ + "pluginId":"03053f51-f829-438d-993d-cc33a435d76a",\ + "alertControlStates":[],"alertStatuses":[],\ + "resourceFilter":{"matchResourceIdOnly":true,\ + "childrenResourceKindFilters":[],\ + "resourceId":"ac87622f-b761-40a0-b151-00872a2a456e"},\ + "alertTypeFilters":[],"alertDefinitionIdFilters":{"values":[\ + "AlertDefinition-f1163767-6eac-438f-8e60-a7a867257e14"]}}' + + # call enable rest plugin configured method under test + actual_return = self.mon_plugin.create_alarm_notification_rule(alarm_name, alarm_id, res_id) + + # verify that mocked method is called + m_check_if_plugin_configured.assert_called_with('MON_module_REST_Plugin') + m_post.assert_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'post') + @mock.patch.object(monPlugin.MonPlugin, 'check_if_plugin_configured') + def test_create_alarm_notification_rule_invalid_req(self, m_check_if_plugin_configured, m_post): + """Test create alarm notification rule method invalid request response""" + + alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + alarm_id = 'AlertDefinition-f1163767-6eac-438f-8e60-a7a867257e14' + res_id = 'ac87622f-b761-40a0-b151-00872a2a456e' + expected_return = None # invalid req should retrun none + + # mock return values + m_check_if_plugin_configured.return_value = '03053f51-f829-438d-993d-cc33a435d76a' + m_post.return_value.status_code = 500 + m_post.return_value.content = '{"message":"Internal Server error, cause unknown.",\ + "moreInformation":[{"name":"errorMessage","value":\ + "there is already a rule with the same rule name"},\ + {"name":"localizedMessage","value":"there is already \ + a rule with the same rule name;"}],"httpStatusCode":500,\ + "apiErrorCode":500}' + + # call enable rest plugin configured method under test + actual_return = self.mon_plugin.create_alarm_notification_rule(alarm_name, alarm_id, res_id) + + # verify that mocked method is called + m_check_if_plugin_configured.assert_called_with('MON_module_REST_Plugin') + m_post.assert_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'post') + @mock.patch.object(monPlugin.MonPlugin, 'check_if_plugin_configured') + def test_create_alarm_notification_rule_failed_to_get_plugin_id(self, + m_check_if_plugin_configured, m_post): + """Test create alarm notification rule method invalid plugin id""" + + alarm_name = 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + alarm_id = 'AlertDefinition-f1163767-6eac-438f-8e60-a7a867257e14' + res_id = 'ac87622f-b761-40a0-b151-00872a2a456e' + expected_return = None # invalid req should retrun none + + # mock return values + m_check_if_plugin_configured.return_value = None + + # call enable rest plugin configured method under test + actual_return = self.mon_plugin.create_alarm_notification_rule(alarm_name, alarm_id, res_id) + + # verify that mocked method is called + m_check_if_plugin_configured.assert_called_with('MON_module_REST_Plugin') + m_post.assert_not_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'get') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') + def test_get_metrics_data_valid_rest_req_response(self, m_get_default_Params, + m_get_vm_moref_id, + m_get_vm_resource_id, + m_get): + """Test get metrics data of resource method valid request response""" + + metrics = {'collection_period': 1, 'metric_name': 'CPU_UTILIZATION', 'metric_uuid': None, + 'schema_version': 1.0, 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'schema_type': 'read_metric_data_request', 'vim_type': 'VMware', + 'collection_unit': 'HR', 'vim_uuid': '1'} + + # mock return value + m_get_default_Params.return_value = {'metric_key': 'cpu|usage_average', 'unit': '%'} + vm_moref_id = m_get_vm_moref_id.return_value = 'vm-6626' + m_get_vm_resource_id.return_value = 'ac87622f-b761-40a0-b151-00872a2a456e' + m_get.return_value.status_code = 200 + m_get.return_value.content = '{"values":[{"resourceId":"ac87622f-b761-40a0-b151-\ + 00872a2a456e","stat-list":{"stat":[{"timestamps":\ + [1519716874297,1519717174294,1519717474295,1519717774298,\ + 1519718074300,1519718374299,1519718674314,1519718974325,\ + 1519719274304,1519719574298,1519719874298,1519720174301],\ + "statKey":{"key":"cpu|usage_average"},"intervalUnit":\ + {"quantifier":1},"data":[0.1120000034570694,\ + 0.11866666376590729,0.11599999666213989,0.11400000005960464,\ + 0.12066666781902313,0.11533333361148834,0.11800000071525574,\ + 0.11533333361148834,0.12200000137090683,0.11400000005960464,\ + 0.1459999978542328,0.12133333086967468]}]}}]}' + + # call get matrics data method under test + actual_return = self.mon_plugin.get_metrics_data(metrics) + + # verify that mocked method is called + m_get_default_Params.assert_called_with(metrics['metric_name']) + m_get_vm_moref_id.assert_called_with(metrics['resource_uuid']) + m_get_vm_resource_id.assert_called_with(vm_moref_id) + m_get.assert_called() + + # verify return value with expected value + # self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'get') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') + def test_get_metrics_data_invalid_rest_req_response(self, m_get_default_Params, + m_get_vm_moref_id, + m_get_vm_resource_id, + m_get): + """Test get metrics data of resource method invalid request response""" + + metrics = {'collection_period': 1, 'metric_name': 'CPU_UTILIZATION', 'metric_uuid': None, + 'schema_version': 1.0, 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'schema_type': 'read_metric_data_request', 'vim_type': 'VMware', + 'collection_unit': 'HR', 'vim_uuid': '1'} + + # mock return value + m_get_default_Params.return_value = {'metric_key': 'cpu|usage_average', 'unit': '%'} + vm_moref_id = m_get_vm_moref_id.return_value = 'vm-6626' + m_get_vm_resource_id.return_value = 'ac87622f-b761-40a0-b151-00872a2a456e' + m_get.return_value.status_code = 400 + expected_return = {'metric_name': 'CPU_UTILIZATION', 'metric_uuid': '0', + 'schema_version': '1.0', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'metrics_data': {'time_series': [], 'metrics_series': []}, + 'schema_type': 'read_metric_data_response', + 'unit': '%', 'vim_uuid': '1'} + + # call get metrics data method under test + actual_return = self.mon_plugin.get_metrics_data(metrics) + + # verify that mocked method is called + m_get_default_Params.assert_called_with(metrics['metric_name']) + m_get_vm_moref_id.assert_called_with(metrics['resource_uuid']) + m_get_vm_resource_id.assert_called_with(vm_moref_id) + m_get.assert_called() + + m_get.return_value.content = '{"message":"Invalid request... #1 violations found.",\ + "validationFailures":[{"failureMessage":"Invalid Parameter",\ + "violationPath":"end"}],"httpStatusCode":400,\ + "apiErrorCode":400}' + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'get') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') + def test_get_metrics_data_metric_not_supported(self, m_get_default_Params, + m_get_vm_moref_id, + m_get_vm_resource_id, + m_get): + """Test get metrics data of resource method invalid metric name""" + + metrics = {'collection_period': 1, 'metric_name': 'invalid_metric', 'metric_uuid': None, + 'schema_version': 1.0, + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'schema_type': 'read_metric_data_request', 'vim_type': 'VMware', + 'collection_unit': 'HR', 'vim_uuid': '1'} + + # mock return value + m_get_default_Params.return_value = {} # returns empty dict + + expected_return = {'metric_name': 'invalid_metric', 'metric_uuid': '0', 'vim_uuid': '1', + 'schema_version': '1.0', 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'metrics_data': {'time_series': [], 'metrics_series': []}, + 'schema_type': 'read_metric_data_response', 'unit': None} + + # call get matrics data method under test + actual_return = self.mon_plugin.get_metrics_data(metrics) + + # verify that mocked method is called/not called + m_get_default_Params.assert_called_with(metrics['metric_name']) + m_get_vm_moref_id.assert_not_called() + m_get_vm_resource_id.assert_not_called() + m_get.assert_not_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'get') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') + def test_get_metrics_data_failed_to_get_vm_moref_id(self, m_get_default_Params, + m_get_vm_moref_id, + m_get_vm_resource_id, + m_get): + """Test get metrics data method negative scenario- invalid resource id""" + + metrics = {'collection_period': 1, 'metric_name': 'cpu_utilization', 'metric_uuid': None, + 'schema_version': 1.0, 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'schema_type': 'read_metric_data_request', 'vim_type': 'VMware', + 'collection_unit': 'HR', 'vim_uuid': '1'} + + # mock return value + m_get_default_Params.return_value = {'metric_key': 'cpu|usage_average', 'unit': '%'} + m_get_vm_moref_id.return_value = None + expected_return = {'metric_name': 'cpu_utilization', 'metric_uuid': '0', + 'schema_version': '1.0', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'metrics_data': {'time_series': [], 'metrics_series': []}, + 'schema_type': 'read_metric_data_response', + 'unit': '%', 'vim_uuid': '1'} + + # call get matrics data method under test + actual_return = self.mon_plugin.get_metrics_data(metrics) + + # verify that mocked method is called/not called + m_get_default_Params.assert_called_with(metrics['metric_name']) + m_get_vm_moref_id.assert_called_with(metrics['resource_uuid']) + m_get_vm_resource_id.assert_not_called() + m_get.assert_not_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'get') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') + def test_get_metrics_data_failed_to_get_vm_resource_id(self, m_get_default_Params, + m_get_vm_moref_id, + m_get_vm_resource_id, + m_get): + """Test get metrics data method negative scenario- invalid moref id""" + + metrics = {'collection_period': 1, 'metric_name': 'CPU_UTILIZATION', 'metric_uuid': None, + 'schema_version': 1.0, 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'schema_type': 'read_metric_data_request', 'vim_type': 'VMware', + 'collection_unit': 'HR', 'vim_uuid': '1'} + + # mock return value + m_get_default_Params.return_value = {'metric_key': 'cpu|usage_average', 'unit': '%'} + m_get_vm_moref_id.return_value = 'Invalid-vm-6626' + m_get_vm_resource_id.return_value = None + expected_return = {'metric_name': 'CPU_UTILIZATION', 'metric_uuid': '0', + 'schema_version': '1.0', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 'e14b203c-6bf2-4e2f-a91c-8c19d2abcdef', + 'metrics_data': {'time_series': [], 'metrics_series': []}, + 'schema_type': 'read_metric_data_response', + 'unit': '%', 'vim_uuid': '1'} + + # call get matrics data method under test + actual_return = self.mon_plugin.get_metrics_data(metrics) + + # verify that mocked method is called/not called + m_get_default_Params.assert_called_with(metrics['metric_name']) + m_get_vm_moref_id.assert_called_with(metrics['resource_uuid']) + m_get_vm_resource_id.assert_called() + m_get_vm_resource_id.assert_called_with('Invalid-vm-6626') + m_get.assert_not_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.MonPlugin, 'reconfigure_alarm') + @mock.patch.object(monPlugin.MonPlugin, 'update_symptom_defination') + @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_details') + def test_update_alarm_configuration_successful_updation(self, m_get_alarm_defination_details, + m_update_symptom_defination, + m_reconfigure_alarm): + """Test update alarm configuration method""" + + alarm_config = {'alarm_uuid': 'f1163767-6eac-438f-8e60-a7a867257e14', + 'correlation_id': 14203, + 'description': 'CPU_Utilization_Above_Threshold_L', 'operation': 'GT'} + + # mock return value + alarm_details_json = {'states': [{'impact': {'impactType': 'BADGE', 'detail': 'risk'}, + 'severity': 'CRITICAL', 'base-symptom-set': {'symptomDefinitionIds': + [ + 'SymptomDefinition-47c88675-bea8-436a-bb41-8d2231428f44'], + 'relation': 'SELF', + 'type': 'SYMPTOM_SET', + 'aggregation': 'ALL'}}], + 'description': 'CPU_Utilization_Above_Threshold', 'type': 16, + 'id': 'AlertDefinition-f1163767-6eac-438f-8e60-a7a867257e14', + 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d2'} + alarm_details = {'symptom_definition_id': 'SymptomDefinition-47c88675-bea8-436a-bb41-\ + 8d2231428f44', 'alarm_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-\ + a91c-8c19d2', 'alarm_id': 'AlertDefinition-f1163767-6eac-438f-8e60-\ + a7a867257e14', 'resource_kind': 'VirtualMachine', 'type': 16} + m_get_alarm_defination_details.return_value = (alarm_details_json, alarm_details) + m_update_symptom_defination.return_value = 'SymptomDefinition-47c88675-bea8-436a-bb41-\ + 8d2231428f44' + expected_return = m_reconfigure_alarm.return_value = 'f1163767-6eac-438f-8e60-a7a867257e14' + + # call update alarm configuration method under test + actual_return = self.mon_plugin.update_alarm_configuration(alarm_config) + + # verify that mocked method is called + m_get_alarm_defination_details.assert_called_with(alarm_config['alarm_uuid']) + m_update_symptom_defination.assert_called_with(alarm_details['symptom_definition_id'], + alarm_config) + m_reconfigure_alarm.assert_called_with(alarm_details_json, alarm_config) + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.MonPlugin, 'reconfigure_alarm') + @mock.patch.object(monPlugin.MonPlugin, 'update_symptom_defination') + @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_details') + def test_update_alarm_configuration_failed_to_reconfigure_alarm(self, + m_get_alarm_defination_details, + m_update_symptom_defination, + m_reconfigure_alarm): + """Test update alarm configuration method- failed to reconfigure alarm""" + + alarm_config = {'alarm_uuid': 'f1163767-6eac-438f-8e60-a7a867257e14', + 'correlation_id': 14203, + 'description': 'CPU_Utilization_Above_Threshold_L', 'operation': 'GT'} + + # mock return value + alarm_details_json = {'states': [{'impact': {'impactType': 'BADGE', 'detail': 'risk'}, + 'severity': 'CRITICAL', 'base-symptom-set': {'symptomDefinitionIds': + [ + 'SymptomDefinition-47c88675-bea8-436a-bb41-8d2231428f44'], + 'relation': 'SELF', + 'type': 'SYMPTOM_SET', + 'aggregation': 'ALL'}}], + 'description': 'CPU_Utilization_Above_Threshold', 'type': 16, + 'id': 'AlertDefinition-f1163767-6eac-438f-8e60-a7a867257e14', + 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d2'} + alarm_details = {'symptom_definition_id': 'SymptomDefinition-47c88675-bea8-436a-bb41-\ + 8d2231428f44', 'alarm_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-\ + a91c-8c19d2', 'alarm_id': 'AlertDefinition-f1163767-6eac-438f-8e60-\ + a7a867257e14', 'resource_kind': 'VirtualMachine', 'type': 16} + m_get_alarm_defination_details.return_value = (alarm_details_json, alarm_details) + m_update_symptom_defination.return_value = 'SymptomDefinition-47c88675-bea8-436a-bb41-\ + 8d2231428f44' + expected_return = m_reconfigure_alarm.return_value = None # failed to reconfigure + + # call update alarm configuration method under test + actual_return = self.mon_plugin.update_alarm_configuration(alarm_config) + + # verify that mocked method is called + m_get_alarm_defination_details.assert_called_with(alarm_config['alarm_uuid']) + m_update_symptom_defination.assert_called_with(alarm_details['symptom_definition_id'], + alarm_config) + m_reconfigure_alarm.assert_called_with(alarm_details_json, alarm_config) + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.MonPlugin, 'reconfigure_alarm') + @mock.patch.object(monPlugin.MonPlugin, 'update_symptom_defination') + @mock.patch.object(monPlugin.MonPlugin, 'get_alarm_defination_details') + def test_update_alarm_configuration_failed_to_update_symptom(self, + m_get_alarm_defination_details, + m_update_symptom_defination, + m_reconfigure_alarm): + """Test update alarm configuration method- failed to update alarm""" + + alarm_config = {'alarm_uuid': 'f1163767-6eac-438f-8e60-a7a867257e14', + 'correlation_id': 14203, + 'description': 'CPU_Utilization_Above_Threshold_L', 'operation': 'GT'} + + # mock return value + alarm_details_json = {'states': [{'impact': {'impactType': 'BADGE', 'detail': 'risk'}, + 'severity': 'CRITICAL', 'base-symptom-set': {'symptomDefinitionIds': + [ + 'SymptomDefinition-47c88675-bea8-436a-bb41-8d2231428f44'], + 'relation': 'SELF', + 'type': 'SYMPTOM_SET', + 'aggregation': 'ALL'}}], + 'description': 'CPU_Utilization_Above_Threshold', 'type': 16, + 'id': 'AlertDefinition-f1163767-6eac-438f-8e60-a7a867257e14', + 'name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d2'} + alarm_details = {'symptom_definition_id': 'Invalid-47c88675-bea8-436a-bb41-\ + 8d2231428f44', 'alarm_name': 'CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-\ + a91c-8c19d2', 'alarm_id': 'AlertDefinition-f1163767-6eac-438f-8e60-\ + a7a867257e14', 'resource_kind': 'VirtualMachine', 'type': 16} + m_get_alarm_defination_details.return_value = (alarm_details_json, alarm_details) + expected_return = m_update_symptom_defination.return_value = None + + # call update alarm configuration method under test + actual_return = self.mon_plugin.update_alarm_configuration(alarm_config) + + # verify that mocked method is called + m_get_alarm_defination_details.assert_called_with(alarm_config['alarm_uuid']) + m_update_symptom_defination.assert_called_with(alarm_details['symptom_definition_id'], + alarm_config) + m_reconfigure_alarm.assert_not_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') + def test_verify_metric_support_metric_supported_with_unit(self, m_get_default_Params): + """Test verify metric support method for supported metric""" + + # mock return value + metric_info = {'metric_unit': '%', 'metric_name': 'cpu_utilization', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4'} + m_get_default_Params.return_value = {'metric_key': 'cpu|usage_average', 'unit': '%'} + expected_return = True # supported metric returns True + + # call verify metric support method under test + actual_return = self.mon_plugin.verify_metric_support(metric_info) + + # verify that mocked method is called + m_get_default_Params.assert_called_with(metric_info['metric_name']) + # m_get_default_Params.assert_called_with(metric_info) + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') + def test_verify_metric_support_metric_not_supported(self, m_get_default_Params): + """Test verify metric support method for un-supported metric""" + + # mock return value + metric_info = {'metric_unit': '%', 'metric_name': 'invalid_metric', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4'} + m_get_default_Params.return_value = {} + expected_return = False # supported metric returns True + + # call verify metric support method under test + actual_return = self.mon_plugin.verify_metric_support(metric_info) + + # verify that mocked method is called + m_get_default_Params.assert_called_with(metric_info['metric_name']) + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.MonPlugin, 'get_default_Params') + def test_verify_metric_support_metric_supported_with_mismatched_unit(self, + m_get_default_Params): + """Test verify metric support method for supported metric with mismatched unit""" + + # mock return value + metric_info = {'metric_unit': '', 'metric_name': 'invalid_metric', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4'} + m_get_default_Params.return_value = {'metric_key': 'cpu|usage_average', 'unit': '%'} + expected_return = True # supported metric returns True + + # call verify metric support method under test + actual_return = self.mon_plugin.verify_metric_support(metric_info) + + # verify that mocked method is called + m_get_default_Params.assert_called_with(metric_info['metric_name']) + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.MonPlugin, 'get_triggered_alarms_on_resource') + @mock.patch.object(monPlugin.MonPlugin, 'get_vrops_resourceid_from_ro_uuid') + def test_get_triggered_alarms_list_returns_triggered_alarms(self, + m_get_vrops_resourceid, + m_triggered_alarms): + """Test get triggered alarm list method valid input""" + + # Mock list alarm input + list_alarm_input = {'severity': 'CRITICAL', + 'correlation_id': 'e14b203c', + 'alarm_name': 'CPU_Utilization_Above_Threshold', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4'} + + resource_id = m_get_vrops_resourceid.return_value = 'ac87622f-b761-40a0-b151-00872a2a456e' + expected_return = m_triggered_alarms.return_value = [{'status': 'ACTIVE', + 'update_date': '2018-01-12T08:34:05', + 'severity': 'CRITICAL', 'resource_uuid': 'e14b203c', + 'cancel_date': '0000-00-00T00:00:00', + 'alarm_instance_uuid': 'd9e3bc84', + 'alarm_uuid': '5714977d', 'vim_type': 'VMware', + 'start_date': '2018-01-12T08:34:05'}, + {'status': 'CANCELED', + 'update_date': '2017-12-20T09:37:57', + 'severity': 'CRITICAL', 'resource_uuid': 'e14b203c', + 'cancel_date': '2018-01-12T06:49:19', + 'alarm_instance_uuid': 'd3bbeef6', + 'alarm_uuid': '7ba1bf3e', 'vim_type': 'VMware', + 'start_date': '2017-12-20T09:37:57'}] + + # call get triggered alarms list method under test + actual_return = self.mon_plugin.get_triggered_alarms_list(list_alarm_input) + + # verify that mocked method is called + m_get_vrops_resourceid.assert_called_with(list_alarm_input['resource_uuid']) + m_triggered_alarms.assert_called_with(list_alarm_input['resource_uuid'], resource_id) + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.MonPlugin, 'get_triggered_alarms_on_resource') + @mock.patch.object(monPlugin.MonPlugin, 'get_vrops_resourceid_from_ro_uuid') + def test_get_triggered_alarms_list_invalid_resource_uuid(self, + m_get_vrops_resourceid, + m_triggered_alarms): + """Test get triggered alarm list method invalid resource uuid""" + + # Mock list alarm input + list_alarm_input = {'severity': 'CRITICAL', + 'correlation_id': 'e14b203c', + 'alarm_name': 'CPU_Utilization_Above_Threshold', + 'resource_uuid': '12345'} # invalid resource uuid + + expected_return = m_get_vrops_resourceid.return_value = None # returns empty list + + # call get triggered alarms list method under test + actual_return = self.mon_plugin.get_triggered_alarms_list(list_alarm_input) + + # verify that mocked method is called + m_get_vrops_resourceid.assert_called_with(list_alarm_input['resource_uuid']) + m_triggered_alarms.assert_not_called() + + # verify return value with expected value + self.assertEqual([], actual_return) + + @mock.patch.object(monPlugin.MonPlugin, 'get_triggered_alarms_on_resource') + @mock.patch.object(monPlugin.MonPlugin, 'get_vrops_resourceid_from_ro_uuid') + def test_get_triggered_alarms_list_resource_uuid_not_present(self, + m_get_vrops_resourceid, + m_triggered_alarms): + """Test get triggered alarm list method resource not present""" + + # Mock list alarm input + list_alarm_input = {'severity': 'CRITICAL', + 'correlation_id': 'e14b203c', + 'alarm_name': 'CPU_Utilization_Above_Threshold'} + + # call get triggered alarms list method under test + actual_return = self.mon_plugin.get_triggered_alarms_list(list_alarm_input) + + # verify that mocked method is called + m_get_vrops_resourceid.assert_not_called() + m_triggered_alarms.assert_not_called() + + # verify return value with expected value + self.assertEqual([], actual_return) + + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') + def test_get_vrops_resourceid_from_ro_uuid(self, m_get_vm_moref_id, m_get_vm_resource_id): + """Test get vrops resourceid from ro uuid method""" + + # Mock the inputs + ro_resource_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + vm_moref_id = m_get_vm_moref_id.return_value = 'vm-6626' + expected_return = m_get_vm_resource_id.return_value = 'ac87622f-b761-40a0-b151-00872a2a456e' + + # call get_vrops_resourceid_from_ro_uuid method under test + actual_return = self.mon_plugin.get_vrops_resourceid_from_ro_uuid(ro_resource_uuid) + + # verify that mocked method is called + m_get_vm_moref_id.assert_called_with(ro_resource_uuid) + m_get_vm_resource_id.assert_called_with(vm_moref_id) + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') + def test_get_vrops_resourceid_from_ro_uuid_failed_to_get_vm_resource_id(self, + m_get_vm_moref_id, + m_get_vm_resource_id): + """Test get vrops resourceid from ro uuid method negative scenario""" + + # Mock the inputs + ro_resource_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + vm_moref_id = m_get_vm_moref_id.return_value = 'vm-6626' + expected_return = m_get_vm_resource_id.return_value = None + + # call get_vrops_resourceid_from_ro_uuid method under test + actual_return = self.mon_plugin.get_vrops_resourceid_from_ro_uuid(ro_resource_uuid) + + # verify that mocked method is called + m_get_vm_moref_id.assert_called_with(ro_resource_uuid) + m_get_vm_resource_id.assert_called_with(vm_moref_id) + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_resource_id') + @mock.patch.object(monPlugin.MonPlugin, 'get_vm_moref_id') + def test_get_vrops_resourceid_from_ro_uuid_failed_to_get_vm_moref_id(self, + m_get_vm_moref_id, + m_get_vm_resource_id): + """Test get vrops resourceid from ro uuid method negative scenario""" + + # Mock the inputs + ro_resource_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + expected_return = vm_moref_id = m_get_vm_moref_id.return_value = None + + # call get_vrops_resourceid_from_ro_uuid method under test + actual_return = self.mon_plugin.get_vrops_resourceid_from_ro_uuid(ro_resource_uuid) + + # verify that mocked method is called + m_get_vm_moref_id.assert_called_with(ro_resource_uuid) + m_get_vm_resource_id.assert_not_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'get') + def test_get_triggered_alarms_on_resource_valid_req_response(self, m_get): + """Test get triggered alarms on resource method for valid request""" + + # Mock the inputs + ro_resource_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + vrops_resource_id = 'ac87622f-b761-40a0-b151-00872a2a456e' + m_get.return_value.status_code = 200 + expected_return = [{'status': 'ACTIVE', 'update_date': '2018-01-12T08:34:05', + 'severity': 'CRITICAL', 'start_date': '2018-01-12T08:34:05', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'cancel_date': '2018-02-12T08:24:48', 'vim_type': 'VMware', + 'alarm_instance_uuid': 'd9e3bc84-dcb4-4905-b592-00a55f4cdaf1', + 'alarm_uuid': '5714977d-56f6-4222-adc7-43fa6c6e7e39'}] + + m_get.return_value.content = '{"alerts": [\ + {\ + "alertId": "d9e3bc84-dcb4-4905-b592-00a55f4cdaf1",\ + "resourceId": "ac87622f-b761-40a0-b151-00872a2a456e",\ + "alertLevel": "CRITICAL",\ + "status": "ACTIVE",\ + "startTimeUTC": 1515746045278,\ + "cancelTimeUTC": 1518423888708,\ + "updateTimeUTC": 1515746045278,\ + "alertDefinitionId": "AlertDefinition-5714977d-56f6-4222-adc7-43fa6c6e7e39",\ + "alertDefinitionName": "CPU_Utilization_Above_Thr-e14b203c-6bf2-4e2f-a91c-8c19d240eda4"\ + },\ + {\ + "alertId": "5fb5e940-e161-4253-a729-7255c6d6b1f5",\ + "resourceId": "ac87622f-b761-40a0-b151-00872a2a456e",\ + "alertLevel": "WARNING",\ + "status": "CANCELED",\ + "startTimeUTC": 1506684979154,\ + "cancelTimeUTC": 0,\ + "updateTimeUTC": 1520471975507,\ + "alertDefinitionId": "AlertDefinition-9ec5a921-1a54-411d-85ec-4c1c9b26dd02",\ + "alertDefinitionName": "VM_CPU_Usage_Alarm"\ + }]}' + + # call get_vrops_resourceid_from_ro_uuid method under test + actual_return = self.mon_plugin.get_triggered_alarms_on_resource(ro_resource_uuid, + vrops_resource_id) + + # verify that mocked method is called + m_get.assert_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'get') + def test_get_triggered_alarms_on_resource_invalid_req_response(self, m_get): + """Test get triggered alarms on resource method for invalid request""" + + # Mock the inputs + ro_resource_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + vrops_resource_id = 'ac87622f-b761-40a0-b151-00872a2a456e' + m_get.return_value.status_code = 204 + expected_return = None + + # call get_vrops_resourceid_from_ro_uuid method under test + actual_return = self.mon_plugin.get_triggered_alarms_on_resource(ro_resource_uuid, + vrops_resource_id) + + # verify that mocked method is called + m_get.assert_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'get') + def test_get_triggered_alarms_on_resource_no_alarms_present(self, m_get): + """Test get triggered alarms on resource method for no alarms present""" + + # Mock the inputs + ro_resource_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + vrops_resource_id = 'ac87622f-b761-40a0-b151-00872a2a456e' + m_get.return_value.status_code = 200 + expected_return = [] + m_get.return_value.content = '{"alerts": []}' + + # call get_vrops_resourceid_from_ro_uuid method under test + actual_return = self.mon_plugin.get_triggered_alarms_on_resource(ro_resource_uuid, + vrops_resource_id) + + # verify that mocked method is called + m_get.assert_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + def test_convert_date_time_valid_date_time(self): + """Test convert date time method valid input""" + + # Mock the inputs + date_time = 1515746045278 + expected_return = '2018-01-12T08:34:05' + + # call convert_date_time method under test + actual_return = self.mon_plugin.convert_date_time(date_time) + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + def test_convert_date_time_invalid_date_time(self): + """Test convert date time method invalid input""" + + # Mock the inputs + date_time = 0 + expected_return = '0000-00-00T00:00:00' + + # call convert_date_time method under test + actual_return = self.mon_plugin.convert_date_time(date_time) + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'get') + def test_get_vm_resource_id_rest_valid_req_response(self, m_get): + """Test get vms resource id valid request""" + + # Mock the inputs + vm_moref_id = 'vm-6626' + m_get.return_value.status_code = 200 + expected_return = "ac87622f-b761-40a0-b151-00872a2a456e" + m_get.return_value.content = \ + '{ \ + "resourceList": [\ + {\ + "creationTime": 1497770174130,\ + "resourceKey": {\ + "name": "OCInst2.ubuntu(4337d51f-1e65-4ab0-9c08-4897778d4fda)",\ + "adapterKindKey": "VMWARE",\ + "resourceKindKey": "VirtualMachine",\ + "resourceIdentifiers": [\ + {\ + "identifierType": {\ + "name": "VMEntityObjectID",\ + "dataType": "STRING",\ + "isPartOfUniqueness": true\ + },\ + "value": "vm-6626"\ + }\ + ]\ + },\ + "identifier": "ac87622f-b761-40a0-b151-00872a2a456e"\ + }\ + ]\ + }' + + # call get_vm_resource_id method under test + actual_return = self.mon_plugin.get_vm_resource_id(vm_moref_id) + + # verify that mocked method is called + m_get.assert_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'get') + def test_get_vm_resource_id_rest_invalid_req_response(self, m_get): + """Test get vms resource id invalid request""" + + # Mock the inputs + vm_moref_id = 'vm-6626' + m_get.return_value.status_code = 406 + expected_return = None + m_get.return_value.content = '406 Not Acceptable' + + # call get_vm_resource_id method under test + actual_return = self.mon_plugin.get_vm_resource_id(vm_moref_id) + + # verify that mocked method is called + m_get.assert_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'get') + def test_get_vm_resource_id_rest_invalid_response(self, m_get): + """Test get vms resource id invalid response""" + + # Mock the inputs + vm_moref_id = 'vm-6626' + m_get.return_value.status_code = 200 + expected_return = None + m_get.return_value.content = \ + '{ \ + "resourceList": \ + {\ + "creationTime": 1497770174130,\ + "resourceKey": {\ + "name": "OCInst2.ubuntu(4337d51f-1e65-4ab0-9c08-4897778d4fda)",\ + "adapterKindKey": "VMWARE",\ + "resourceKindKey": "VirtualMachine",\ + "resourceIdentifiers": [\ + {\ + "identifierType": {\ + "name": "VMEntityObjectID",\ + "dataType": "STRING",\ + "isPartOfUniqueness": true\ + },\ + "value": "vm-6626"\ + }\ + ]\ + },\ + "identifier": "ac87622f-b761-40a0-b151-00872a2a456e"\ + }\ + }' + + # call get_vm_resource_id method under test + actual_return = self.mon_plugin.get_vm_resource_id(vm_moref_id) + + # verify that mocked method is called + # m_get.assert_called + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.MonPlugin, 'get_vapp_details_rest') + def test_get_vm_moref_id_valid_id_found(self, m_get_vapp_details_rest): + """Test get vm moref id valid scenario""" + + # mock the inputs + vapp_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + m_get_vapp_details_rest.return_value = {'vm_vcenter_info': {'vm_moref_id': 'vm-6626'}} + expected_return = 'vm-6626' + + # call get_vm_resource_id method under test + actual_return = self.mon_plugin.get_vm_moref_id(vapp_uuid) + + # verify that mocked method is called + m_get_vapp_details_rest.assert_called_with(vapp_uuid) + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.MonPlugin, 'get_vapp_details_rest') + def test_get_vm_moref_id_valid_id_not_found(self, m_get_vapp_details_rest): + """Test get vm moref id invalid scenario""" + + # mock the inputs + vapp_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda' # invalid uuid + m_get_vapp_details_rest.return_value = {} + expected_return = None + + # call get_vm_resource_id method under test + actual_return = self.mon_plugin.get_vm_moref_id(vapp_uuid) + + # verify that mocked method is called + m_get_vapp_details_rest.assert_called_with(vapp_uuid) + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'get') + @mock.patch.object(monPlugin.MonPlugin, 'connect_as_admin') + def test_get_vapp_details_rest_valid_req_response(self, m_connect_as_admin, m_get): + """Test get vapp details rest method for valid request response""" + + # mock the inputs + vapp_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + m_connect_as_admin.return_value = self.vca + self.vca._session = self.session + self.vca._session.headers['x-vcloud-authorization'] = '2ec69b2cc6264ad0a47aaf4e3e280d16' + m_get.return_value.status_code = 200 + expected_return = {'vm_vcenter_info': {'vm_moref_id': 'vm-6626'}} + m_get.return_value.content = '\ + \ + \ + \ + \ + \ + \ + \ + vm-6626\ + VIRTUAL_MACHINE\ + \ + \ + \ + \ + \ + ' + + # call get_vapp_details_rest method under test + actual_return = self.mon_plugin.get_vapp_details_rest(vapp_uuid) + + # verify that mocked method is called + m_connect_as_admin.assert_called_with() + m_get.assert_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'get') + @mock.patch.object(monPlugin.MonPlugin, 'connect_as_admin') + def test_get_vapp_details_rest_invalid_req_response(self, m_connect_as_admin, m_get): + """Test get vapp details rest method for invalid request response""" + + # mock the inputs + vapp_uuid = 'Invalid-e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + m_connect_as_admin.return_value = self.vca + self.vca._session = self.session + self.vca._session.headers['x-vcloud-authorization'] = '2ec69b2cc6264ad0a47aaf4e3e280d16' + m_get.return_value.status_code = 400 + expected_return = {} + m_get.return_value.content = 'Bad Request' + + # call get_vapp_details_rest method under test + actual_return = self.mon_plugin.get_vapp_details_rest(vapp_uuid) + + # verify that mocked method is called + m_connect_as_admin.assert_called_with() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'get') + @mock.patch.object(monPlugin.MonPlugin, 'connect_as_admin') + def test_get_vapp_details_rest_failed_to_connect_vcd(self, m_connect_as_admin, m_get): + """Test get vapp details rest method for failed to connect to vcd""" + + # mock the inputs + vapp_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + m_connect_as_admin.return_value = None + expected_return = {} + + # call get_vapp_details_rest method under test + actual_return = self.mon_plugin.get_vapp_details_rest(vapp_uuid) + + # verify that mocked method is called + m_connect_as_admin.assert_called_with() + m_get.assert_not_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.requests, 'get') + @mock.patch.object(monPlugin.MonPlugin, 'connect_as_admin') + def test_get_vapp_details_rest_invalid_response(self, m_connect_as_admin, m_get): + """Test get vapp details rest method for invalid response""" + + # mock the inputs + vapp_uuid = 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4' + m_connect_as_admin.return_value = self.vca + self.vca._session = self.session + self.vca._session.headers['x-vcloud-authorization'] = '2ec69b2cc6264ad0a47aaf4e3e280d16' + m_get.return_value.status_code = 200 + expected_return = {} + m_get.return_value.content = '\ + \ + \ + \ + \ + \ + \ + \ + vm-6626\ + VIRTUAL_MACHINE\ + \ + \ + \ + \ + ' + + # call get_vapp_details_rest method under test + actual_return = self.mon_plugin.get_vapp_details_rest(vapp_uuid) + + # verify that mocked method is called + m_connect_as_admin.assert_called_with() + m_get.assert_called() + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + + @mock.patch.object(monPlugin.Client, 'set_credentials') + @mock.patch.object(monPlugin, 'Client') + def test_connect_as_admin(self, m_client, m_set_credentials): + """Test connect as admin to vCD method""" + + # mock the inputs and mocked returns + expected_return = m_client.return_value = self.vca + m_set_credentials.retrun_value = True + + # call connect_as_admin method under test + actual_return = self.mon_plugin.connect_as_admin() + + # verify that mocked method is called + m_client.assert_called_with(self.m_vim_access_config['vim_url'], + verify_ssl_certs=False) + + # verify return value with expected value + self.assertEqual(expected_return, actual_return) + +# For testing purpose +# if __name__ == '__main__': +# unittest.main() diff --git a/osm_mon/test/plugins/VMware/test_plugin_receiver.py b/osm_mon/test/plugins/VMware/test_plugin_receiver.py new file mode 100644 index 0000000..cc5dea9 --- /dev/null +++ b/osm_mon/test/plugins/VMware/test_plugin_receiver.py @@ -0,0 +1,927 @@ +# -*- coding: utf-8 -*- + +## +# Copyright 2017-2018 VMware Inc. +# This file is part of ETSI OSM +# 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. +# +# For those usages not covered by the Apache License, Version 2.0 please +# contact: osslegalrouting@vmware.com +## + +""" Mock tests for VMware vROPs plugin recevier """ + +import json +import logging +import os +import sys +import unittest +from io import UnsupportedOperation + +import mock + +# sys.path.append("/root/MON/") + +log = logging.getLogger(__name__) + +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..")) + +from osm_mon.plugins.vRealiseOps import plugin_receiver as monPluginRec +from osm_mon.core.database import VimCredentials + + +class Message(object): + """A class to mock a message object value for alarm and matric requests""" + + def __init__(self): + """Initialize a mocked message instance""" + self.topic = "alarm_or_metric_request" + self.key = None + self.value = json.dumps({"mock_value": "mock_details"}) + self.partition = 1 + self.offset = 100 + + +class TestPluginReceiver(unittest.TestCase): + """Test class for Plugin Receiver class methods""" + + def setUp(self): + """Setup the tests for plugin_receiver class methods""" + super(TestPluginReceiver, self).setUp() + self.plugin_receiver = monPluginRec.PluginReceiver() + + @mock.patch.object(monPluginRec.PluginReceiver, 'publish_create_alarm_status') + @mock.patch.object(monPluginRec.PluginReceiver, 'create_alarm') + def test_consume_create_alarm_request_key(self, m_create_alarm, m_publish_create_alarm_status): + """Test functionality of consume for create_alarm_request key""" + + vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" + + value = {"vim_uuid": vim_uuid, "alarm_create_request": "alarm_details"} + m_create_alarm.return_value = "test_alarm_id" + + # Call the consume method of plugin_receiver + self.plugin_receiver.handle_alarm_requests('create_alarm_request', value, vim_uuid) + + # verify if create_alarm and publish methods called with correct params + m_create_alarm.assert_called_with(value) + m_publish_create_alarm_status.assert_called_with("test_alarm_id", value) + + @mock.patch.object(monPluginRec.PluginReceiver, 'publish_update_alarm_status') + @mock.patch.object(monPluginRec.PluginReceiver, 'update_alarm') + def test_consume_update_alarm_request_key(self, m_update_alarm, + m_publish_update_alarm_status): + """Test functionality of consume for update_alarm_request key""" + + vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" + + value = {"vim_uuid": vim_uuid, "alarm_update_request": "alarm_details"} + + # set return value to mocked method + m_update_alarm.return_value = "test_alarm_id" + + # Call the consume method of plugin_receiver + self.plugin_receiver.handle_alarm_requests('update_alarm_request', value, vim_uuid) + + # verify update_alarm and publish method called with correct params + m_update_alarm.assert_called_with(value) + m_publish_update_alarm_status.assert_called_with("test_alarm_id", value) + + @mock.patch.object(monPluginRec.PluginReceiver, 'publish_delete_alarm_status') + @mock.patch.object(monPluginRec.PluginReceiver, 'delete_alarm') + def test_consume_delete_alarm_request_key(self, m_delete_alarm, + m_publish_delete_alarm_status): + """Test functionality of consume for delete_alarm_request key""" + + vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" + + value = {"vim_uuid": vim_uuid, "alarm_delete_request": "alarm_details"} + m_delete_alarm.return_value = "test_alarm_id" + + # Call the consume method of plugin_receiver and check delete_alarm request + self.plugin_receiver.handle_alarm_requests('delete_alarm_request', value, vim_uuid) + m_delete_alarm.assert_called_with(value) + + # Check if publish method called with correct parameters + m_publish_delete_alarm_status.assert_called_with("test_alarm_id", value) + + @mock.patch.object(monPluginRec.PluginReceiver, 'publish_list_alarm_response') + @mock.patch.object(monPluginRec.PluginReceiver, 'list_alarms') + def test_consume_list_alarm_request_key(self, m_list_alarms, + m_publish_list_alarm_response): + """ Test functionality of list alarm request key""" + + vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" + value = {"vim_uuid": vim_uuid, "alarm_list_request": "alarm_details"} + + test_alarm_list = [{"alarm_uuid": "alarm1_details"}, {"alarm_uuid": "alarm2_details"}] + + m_list_alarms.return_value = test_alarm_list + + # Call the consume method of plugin_receiver and check delete_alarm request + self.plugin_receiver.handle_alarm_requests('list_alarm_request', value, vim_uuid) + m_list_alarms.assert_called_with(value) + + # Check if publish method called with correct parameters + m_publish_list_alarm_response.assert_called_with(test_alarm_list, value) + + @mock.patch.object(monPluginRec.PluginReceiver, 'publish_create_alarm_status') + @mock.patch.object(monPluginRec.PluginReceiver, 'create_alarm') + def test_consume_invalid_alarm_request_key(self, m_create_alarm, + m_publish_create_alarm_status): + """Test functionality of consume for vim_access_credentials invalid request key""" + + vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" + + # Call the consume method of plugin_receiver + with self.assertRaises(UnsupportedOperation): + self.plugin_receiver.handle_alarm_requests('invalid_key', {}, vim_uuid) + + # verify that create_alarm and publish_create_alarm_status methods not called + m_create_alarm.assert_not_called() + m_publish_create_alarm_status.assert_not_called() + + @mock.patch.object(monPluginRec.PluginReceiver, 'publish_metrics_data_status') + @mock.patch.object(monPluginRec.MonPlugin, 'get_metrics_data') + def test_consume_invalid_metric_request_key(self, m_get_metrics_data, + m_publish_metric_data_status): + """Test functionality of invalid metric key request""" + + vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" + + # Call the consume method of plugin_receiver + with self.assertRaises(UnsupportedOperation): + self.plugin_receiver.handle_metric_requests('invalid_key', {}, vim_uuid) + + # verify that get metrics data and publish methods not called + m_get_metrics_data.assert_not_called() + m_publish_metric_data_status.assert_not_called() + + @mock.patch.object(monPluginRec.PluginReceiver, 'publish_metrics_data_status') + @mock.patch.object(monPluginRec.MonPlugin, 'get_metrics_data') + @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') + def test_consume_read_metric_data_request_key(self, m_get_vim_access_config, + m_get_metrics_data, + m_publish_metric_data_status): + """Test functionality of consume for read_metric_data_request key""" + + vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" + + value = {"vim_uuid": vim_uuid, "metric_name": "metric_details"} + m_get_metrics_data.return_value = {"metrics_data": "metrics_details"} + + m_get_vim_access_config.return_value = {'vrops_site': 'abc', + 'vrops_user': 'user', + 'vrops_password': 'passwd', + 'vim_url': 'vcd_url', + 'admin_username': 'admin', + 'admin_password': 'admin_passwd', + 'vim_uuid': '1', + 'tenant_id': 'org_vdc_1'} + + # Call the consume method of plugin_receiver + self.plugin_receiver.handle_metric_requests('read_metric_data_request', value, vim_uuid) + m_get_metrics_data.assert_called_with(value) + + # Check if publish method called with correct parameters + m_publish_metric_data_status.assert_called_with({"metrics_data": "metrics_details"}) + + @mock.patch.object(monPluginRec.PluginReceiver, 'publish_create_metric_response') + @mock.patch.object(monPluginRec.PluginReceiver, 'verify_metric') + def test_consume_create_metric_request_key(self, m_verify_metric, + m_publish_create_metric_response): + """Test functionality of consume for create_metric_request key""" + + vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" + value = {"vim_uuid": vim_uuid, "metric_create": "metric_details"} + + # set the return value + m_verify_metric.return_value = True + + # Call the consume method of plugin_receiver + self.plugin_receiver.handle_metric_requests('create_metric_request', value, vim_uuid) + m_verify_metric.assert_called_with(value) + + # Check if publish method called with correct parameters + m_publish_create_metric_response.assert_called_with(value, True) + + @mock.patch.object(monPluginRec.PluginReceiver, 'publish_update_metric_response') + @mock.patch.object(monPluginRec.PluginReceiver, 'verify_metric') + def test_consume_update_metric_request_key(self, m_verify_metric, + m_publish_update_metric_response): + """Test functionality of update metric request key""" + + vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" + + value = {"vim_uuid": vim_uuid, "metric_create": "metric_details"} + + # set the return value + m_verify_metric.return_value = True + + # Call the consume method of plugin_receiver + self.plugin_receiver.handle_metric_requests('update_metric_request', value, vim_uuid) + + # verify mocked methods called with correct parameters + m_verify_metric.assert_called_with(value) + m_publish_update_metric_response.assert_called_with(value, True) + + @mock.patch.object(monPluginRec.PluginReceiver, 'publish_delete_metric_response') + def test_consume_delete_metric_request_key(self, m_publish_delete_metric_response): + """Test functionality of consume for delete_metric_request key""" + + # Note: vROPS doesn't support deleting metric data + vim_uuid = "f85fc39e-723d-4172-979b-de28b36465bb" + + value = {"vim_uuid": vim_uuid, "metric_name": "metric_details"} + + # Call the consume method of plugin_receiver + self.plugin_receiver.handle_metric_requests('delete_metric_request', value, vim_uuid) + + # Check if publish method called with correct parameters + m_publish_delete_metric_response.assert_called_with(value) + + @mock.patch.object(monPluginRec.MonPlugin, 'configure_alarm') + @mock.patch.object(monPluginRec.MonPlugin, 'configure_rest_plugin') + @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') + def test_create_alarm_successful(self, m_get_vim_access_config, + m_configure_rest_plugin, + m_configure_alarm): + """ Test functionality of create alarm method-positive case""" + + # Mock config_alarm_info + config_alarm_info = {"schema_version": 1.0, + "schema_type": "create_alarm_request", + "vim_type": "VMware", + "vim_uuid": "1", + "alarm_create_request": {"correlation_id": 1, + "alarm_name": "CPU_Utilize_Threshold", + "metric_name": "CPU_UTILIZATION", + "tenant_uuid": "tenant_uuid", + "resource_uuid": "resource_uuid", + "description": "test_create_alarm", + "severity": "CRITICAL", + "operation": "GT", + "threshold_value": 10, + "unit": "%", + "statistic": "AVERAGE"}} + + # set return value to plugin uuid + m_get_vim_access_config.return_value = {'vrops_site': 'abc', + 'vrops_user': 'user', + 'vrops_password': 'passwd', + 'vim_url': 'vcd_url', + 'admin_username': 'admin', + 'admin_password': 'admin_passwd', + 'vim_uuid': '1', + 'tenant_id': 'org_vdc_1'} + + m_configure_rest_plugin.retrun_value = "plugin_uuid" + m_configure_alarm.return_value = "alarm_uuid" + + # call create alarm method under test + self.plugin_receiver.create_alarm(config_alarm_info) + + # verify mocked methods get called with correct params + m_get_vim_access_config.assert_called_with(config_alarm_info['vim_uuid']) + m_configure_rest_plugin.assert_called_with() + m_configure_alarm.assert_called_with(config_alarm_info["alarm_create_request"]) + + @mock.patch.object(monPluginRec.MonPlugin, 'configure_alarm') + @mock.patch.object(monPluginRec.MonPlugin, 'configure_rest_plugin') + @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') + def test_create_alarm_failed(self, m_get_vim_access_config, + m_configure_rest_plugin, + m_configure_alarm): + """ Test functionality of create alarm method negative case""" + + # Mock config_alarm_info + config_alarm_info = {"schema_version": 1.0, + "schema_type": "create_alarm_request", + "vim_type": "VMware", + "vim_uuid": "1", + "alarm_create_request": {"correlation_id": 1, + "alarm_name": "CPU_Utilize_Threshold", + "metric_name": "CPU_UTILIZATION", + "tenant_uuid": "tenant_uuid", + "resource_uuid": "resource_uuid", + "description": "test_create_alarm", + "severity": "CRITICAL", + "operation": "GT", + "threshold_value": 10, + "unit": "%", + "statistic": "AVERAGE"}} + + # set return value to plugin uuid and alarm_uuid to None + m_get_vim_access_config.return_value = {'vrops_site': 'abc', + 'vrops_user': 'user', + 'vrops_password': 'passwd', + 'vim_url': 'vcd_url', + 'admin_username': 'admin', + 'admin_password': 'admin_passwd', + 'vim_uuid': '1', + 'tenant_id': 'org_vdc_1'} + m_configure_rest_plugin.retrun_value = "plugin_uuid" + m_configure_alarm.return_value = None + + # call create alarm method under test + alarm_uuid = self.plugin_receiver.create_alarm(config_alarm_info) + + # verify mocked method called with correct params + m_get_vim_access_config.assert_called_with(config_alarm_info['vim_uuid']) + m_configure_rest_plugin.assert_called_with() + m_configure_alarm.assert_called_with(config_alarm_info["alarm_create_request"]) + + # verify create alarm method returns None when failed + self.assertEqual(alarm_uuid, None) + + @mock.patch.object(monPluginRec.MonPlugin, 'update_alarm_configuration') + @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') + def test_update_alarm_successful(self, m_get_vim_access_config, m_update_alarm_configuration): + """ Test functionality of update alarm method-positive case""" + + # Mock update_alarm_info + update_alarm_info = {"schema_version": 1.0, "schema_type": "update_alarm_request", + "vim_type": "VMware", "vim_uuid": "1", + "alarm_update_request": {'alarm_uuid': 'abc', 'correlation_id': 14203}} + + # set return value to mocked method + m_update_alarm_configuration.return_value = "alarm_uuid" + m_get_vim_access_config.return_value = {'vrops_site': 'abc', + 'vrops_user': 'user', + 'vrops_password': 'passwd', + 'vim_url': 'vcd_url', + 'admin_username': 'admin', + 'admin_password': 'admin_passwd', + 'vim_uuid': '1', + 'tenant_id': 'org_vdc_1'} + + # check update alarm gets called and returned correct value + ret_value = self.plugin_receiver.update_alarm(update_alarm_info) + + # check mocked method get called with correct param + m_get_vim_access_config.assert_called_with(update_alarm_info['vim_uuid']) + m_update_alarm_configuration.assert_called_with(update_alarm_info["alarm_update_request"]) + + # check return value and passed values are correct + self.assertEqual(ret_value, "alarm_uuid") + + @mock.patch.object(monPluginRec.MonPlugin, 'update_alarm_configuration') + @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') + def test_update_alarm_failed(self, m_get_vim_access_config, m_update_alarm_configuration): + """ Test functionality of update alarm method negative case""" + + # Mock update_alarm_info + update_alarm_info = {"schema_version": 1.0, "schema_type": "update_alarm_request", + "vim_type": "VMware", "vim_uuid": "1", + "alarm_update_request": {'alarm_uuid': 'abc', 'correlation_id': 14203}} + + # set return value to mocked method + m_update_alarm_configuration.return_value = None + m_get_vim_access_config.return_value = {'vrops_site': 'abc', + 'vrops_user': 'user', + 'vrops_password': 'passwd', + 'vim_url': 'vcd_url', + 'admin_username': 'admin', + 'admin_password': 'admin_passwd', + 'vim_uuid': '1', + 'tenant_id': 'org_vdc_1'} + + # check update alarm gets called and returned correct value + ret_value = self.plugin_receiver.update_alarm(update_alarm_info) + + # check mocked method get called with correct param + m_get_vim_access_config.assert_called_with(update_alarm_info['vim_uuid']) + m_update_alarm_configuration.assert_called_with(update_alarm_info["alarm_update_request"]) + + # check return value and passed values are correct + self.assertEqual(ret_value, None) + + @mock.patch.object(monPluginRec.MonPlugin, 'delete_alarm_configuration') + @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') + def test_delete_alarm_successful(self, m_get_vim_access_config, m_delete_alarm_configuration): + """ Test functionality of delete alarm method-positive case""" + + # Mock delete_alarm_info + delete_alarm_info = {"schema_version": 1.0, "schema_type": "delete_alarm_request", + "vim_type": "VMware", "vim_uuid": "1", + "alarm_delete_request": {'alarm_uuid': 'abc', 'correlation_id': 14203}} + + # set return value to mocked method + m_delete_alarm_configuration.return_value = "alarm_uuid" + m_get_vim_access_config.return_value = {'vrops_site': 'abc', + 'vrops_user': 'user', + 'vrops_password': 'passwd', + 'vim_url': 'vcd_url', + 'admin_username': 'admin', + 'admin_password': 'admin_passwd', + 'vim_uuid': '1', + 'tenant_id': 'org_vdc_1'} + + # check delete alarm gets called and returned correct value + ret_value = self.plugin_receiver.delete_alarm(delete_alarm_info) + + # check mocked method get called with correct param + m_get_vim_access_config.assert_called_with(delete_alarm_info['vim_uuid']) + m_delete_alarm_configuration.assert_called_with(delete_alarm_info["alarm_delete_request"]) + + # check return value and passed values are correct + self.assertEqual(ret_value, "alarm_uuid") + + @mock.patch.object(monPluginRec.MonPlugin, 'delete_alarm_configuration') + @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') + def test_delete_alarm_failed(self, m_get_vim_access_config, m_delete_alarm_configuration): + """ Test functionality of delete alarm method-negative case""" + + # Mock update_alarm_info + delete_alarm_info = {"schema_version": 1.0, "schema_type": "delete_alarm_request", + "vim_type": "VMware", "vim_uuid": "1", + "alarm_delete_request": {'alarm_uuid': 'abc', 'correlation_id': 14203}} + + # set return value to mocked method + m_delete_alarm_configuration.return_value = None + m_get_vim_access_config.return_value = {'vrops_site': 'abc', + 'vrops_user': 'user', + 'vrops_password': 'passwd', + 'vim_url': 'vcd_url', + 'admin_username': 'admin', + 'admin_password': 'admin_passwd', + 'vim_uuid': '1', + 'tenant_id': 'org_vdc_1'} + + # check delete alarm gets called and returned correct value + ret_value = self.plugin_receiver.delete_alarm(delete_alarm_info) + + # check mocked method get called with correct param + m_get_vim_access_config.assert_called_with(delete_alarm_info['vim_uuid']) + m_delete_alarm_configuration.assert_called_with(delete_alarm_info["alarm_delete_request"]) + + # check return value to check failed status + self.assertEqual(ret_value, None) + + def test_publish_create_alarm_status(self): + """ Test functionality of publish create alarm status method""" + + # Mock config_alarm_info + config_alarm_info = {'vim_type': 'VMware', "vim_uuid": "1", + 'alarm_create_request': { + 'threshold_value': 0, + 'severity': 'CRITICAL', + 'alarm_name': 'CPU_Utilization_Above_Threshold', + 'resource_uuid': 'e14b203c-6bf2-4e2f-a91c-8c19d240eda4', + 'correlation_id': 1234, + 'statistic': 'AVERAGE', + 'metric_name': 'CPU_UTILIZATION'} + } + + alarm_uuid = "xyz" + + # call publish create status method under test + self.plugin_receiver.publish_create_alarm_status(alarm_uuid, config_alarm_info) + + # verify mocked method called with correct params + # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) + + def test_publish_update_alarm_status(self): + """ Test functionality of publish update alarm status method""" + + # Mock update_alarm_info + update_alarm_info = {'vim_type': 'VMware', + 'vim_uuid': '1', + 'schema_type': 'update_alarm_request', + 'alarm_update_request': {'alarm_uuid': '6486e69', + 'correlation_id': 14203, + 'operation': 'GT' + } + } + + alarm_uuid = "xyz" + + # call publish update alarm status method under test + self.plugin_receiver.publish_update_alarm_status(alarm_uuid, update_alarm_info) + + # verify mocked method called with correct params + # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) + + def test_publish_delete_alarm_status(self): + """ Test functionality of publish delete alarm status method""" + + # Mock delete_alarm_info + delete_alarm_info = {'vim_type': 'VMware', + "vim_uuid": "1", + 'schema_type': 'delete_alarm_request', + 'alarm_delete_request': {'alarm_uuid': '6486e69', + 'correlation_id': 14203, + 'operation': 'GT' + } + } + + alarm_uuid = "xyz" + + # call publish delete alarm status method under test + self.plugin_receiver.publish_delete_alarm_status(alarm_uuid, delete_alarm_info) + + # verify mocked method called with correct params + # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) + + def test_publish_metrics_data_status(self): + """ Test functionality of publish metrics data status method""" + + # Mock metrics data + metrics_data = { + 'vim_uuid': '1', + 'metric_name': 'CPU_UTILIZATION', 'metric_uuid': '0', + 'resource_uuid': 'e14b20', 'correlation_id': 14203, + 'metrics_data': {'time_series': [15162011, 15162044], + 'metrics_series': [0.1166666671, 0.1266666650]}, + 'tenant_uuid': 123, 'unit': '%' + } + + # call publish metrics data status method under test + self.plugin_receiver.publish_metrics_data_status(metrics_data) + + # verify mocked method called with correct params + # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) + + @mock.patch.object(monPluginRec.MonPlugin, 'verify_metric_support') + @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') + def test_verify_metric_supported_metric(self, m_get_vim_access_config, + m_verify_metric_support): + """ Test functionality of verify metric method""" + + # mock metric_info + metric_info = {'vim_uuid': '1', + 'metric_create_request': {'metric_unit': '%', + 'metric_name': 'CPU_UTILIZATION', + 'resource_uuid': 'e14b203'}} + + # set mocked function return value to true + m_verify_metric_support.return_value = True + m_get_vim_access_config.return_value = {'vrops_site': 'abc', + 'vrops_user': 'user', + 'vrops_password': 'passwd', + 'vim_url': 'vcd_url', + 'admin_username': 'admin', + 'admin_password': 'admin_passwd', + 'vim_uuid': '1', + 'tenant_id': 'org_vdc_1'} + + # call verify_metric method under test + ret_value = self.plugin_receiver.verify_metric(metric_info) + + # verify mocked method called with correct params + m_get_vim_access_config.assert_called_with(metric_info['vim_uuid']) + m_verify_metric_support.assert_called_with(metric_info['metric_create_request']) + + # verify the return value + self.assertEqual(ret_value, True) + + @mock.patch.object(monPluginRec.MonPlugin, 'verify_metric_support') + @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') + def test_verify_metric_unsupported_metric(self, m_get_vim_access_config, + m_verify_metric_support): + """ Test functionality of verify metric method-negative case""" + + # mock metric_info with unsupported metrics name + metric_info = {'vim_uuid': '1', + 'metric_create_request': {'metric_unit': '%', + 'metric_name': 'Invalid', + 'resource_uuid': 'e14b203'}} + + # set mocked function return value to true + m_verify_metric_support.return_value = False + m_get_vim_access_config.return_value = {'vrops_site': 'abc', + 'vrops_user': 'user', + 'vrops_password': 'passwd', + 'vim_url': 'vcd_url', + 'admin_username': 'admin', + 'admin_password': 'admin_passwd', + 'vim_uuid': '1', + 'tenant_id': 'org_vdc_1'} + + # call verify_metric method under test + ret_value = self.plugin_receiver.verify_metric(metric_info) + + # verify mocked method called with correct params + m_get_vim_access_config.assert_called_with(metric_info['vim_uuid']) + m_verify_metric_support.assert_called_with(metric_info['metric_create_request']) + + # verify the return value + self.assertEqual(ret_value, False) + + def test_publish_create_metric_response(self): + """ Test functionality of publish create metric response method""" + + # Mock metric_info + metric_info = { + 'vim_uuid': '1', + 'vim_type': 'VMware', + 'correlation_id': 14203, + 'schema_type': 'create_metric_request', + 'metric_create_request': { + 'resource_uuid': '6486e69', + 'metric_name': 'CPU_UTILIZATION', + 'metric_unit': '%' + } + } + + metric_status = True + + # call publish create metric method under test + self.plugin_receiver.publish_create_metric_response(metric_info, metric_status) + + # verify mocked method called with correct params + # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) + + def test_publish_update_metric_response(self): + """ Test functionality of publish update metric response method""" + + # Mock metric_info + metric_info = { + 'vim_uuid': '1', + 'vim_type': 'VMware', + 'correlation_id': 14203, + 'schema_type': 'update_metric_request', + 'metric_create': { + 'resource_uuid': '6486e69', + 'metric_name': 'CPU_UTILIZATION', + 'metric_unit': '%' + } + } + + metric_status = True + + # call publish update metric method under test + self.plugin_receiver.publish_update_metric_response(metric_info, metric_status) + + # verify mocked method called with correct params + # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) + + def test_publish_delete_metric_response(self): + """ Test functionality of publish delete metric response method""" + + # Mock metric_info + metric_info = {'vim_uuid': '1', 'vim_type': 'VMware', 'correlation_id': 14203, + 'metric_uuid': 'e14b203c', 'resource_uuid': '6486e69', + 'metric_name': 'CPU_UTILIZATION', + 'schema_type': 'delete_metric_request'} + + # call publish delete metric method under test-vROPS doesn't support + # delete metric,just returns response with success + self.plugin_receiver.publish_delete_metric_response(metric_info) + + # verify mocked method called with correct params + # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) + + @mock.patch.object(monPluginRec.MonPlugin, 'get_triggered_alarms_list') + @mock.patch.object(monPluginRec.PluginReceiver, 'get_vim_access_config') + def test_list_alarms(self, m_get_vim_access_config, m_get_triggered_alarms_list): + """ Test functionality of list alarms method""" + + # Mock list alarm input + list_alarm_input = { + 'vim_uuid': '1', + 'vim_type': 'VMware', + 'alarm_list_request': { + 'severity': 'CRITICAL', + 'correlation_id': 14203, + 'alarm_name': 'CPU_Utilization_Above_Threshold', + 'resource_uuid': 'd14b203c'}} + + # set return value to mocked method + m_return = [{'status': 'ACTIVE', 'update_date': '2018-01-12T08:34:05', + 'severity': 'CRITICAL', 'resource_uuid': 'e14b203c', + 'cancel_date': '0000-00-00T00:00:00', 'alarm_instance_uuid': 'd9e3bc84', + 'alarm_uuid': '5714977d', 'vim_type': 'VMware', + 'start_date': '2018-01-12T08:34:05'}, + {'status': 'CANCELED', 'update_date': '2017-12-20T09:37:57', + 'severity': 'CRITICAL', 'resource_uuid': 'e14b203c', + 'cancel_date': '2018-01-12T06:49:19', 'alarm_instance_uuid': 'd3bbeef6', + 'alarm_uuid': '7ba1bf3e', 'vim_type': 'VMware', + 'start_date': '2017-12-20T09:37:57'}] + m_get_triggered_alarms_list.return_value = m_return + + m_get_vim_access_config.return_value = {'vrops_site': 'abc', + 'vrops_user': 'user', + 'vrops_password': 'passwd', + 'vim_url': 'vcd_url', + 'admin_username': 'admin', + 'admin_password': 'admin_passwd', + 'vim_uuid': '1', + 'tenant_id': 'org_vdc_1'} + + # call list alarms method under test + return_value = self.plugin_receiver.list_alarms(list_alarm_input) + + # verify mocked method called with correct params + m_get_vim_access_config.assert_called_with(list_alarm_input['vim_uuid']) + m_get_triggered_alarms_list.assert_called_with(list_alarm_input['alarm_list_request']) + + # verify list alarm method returns correct list + self.assertEqual(return_value, m_return) + + def test_publish_list_alarm_response(self): + """ Test functionality of publish list alarm response method""" + + # Mock list alarm input + msg_key = 'list_alarm_response' + topic = 'alarm_response' + list_alarm_input = {'vim_uuid': '1', + 'vim_type': 'VMware', + 'alarm_list_request': { + 'severity': 'CRITICAL', + 'correlation_id': 14203, + 'alarm_name': 'CPU_Utilization_Above_Threshold', + 'resource_uuid': 'd14b203c'}} + + triggered_alarm_list = [{'status': 'ACTIVE', 'update_date': '2018-01-12T08:34:05', + 'severity': 'CRITICAL', 'resource_uuid': 'e14b203c', + 'cancel_date': '0000-00-00T00:00:00', + 'start_date': '2018-01-12T08:34:05', + 'alarm_instance_uuid': 'd9e3bc84', + 'alarm_uuid': '5714977d', + 'vim_type': 'VMware' + }] + + # call publish list alarm response method under test + response = self.plugin_receiver.publish_list_alarm_response(triggered_alarm_list, list_alarm_input) + + # verify mocked method called with correct params + # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) + + def test_publish_access_update_response(self): + """ Test functionality of publish access update response method""" + + # Mock required inputs + access_update_status = True + access_info_req = {'vim_type': 'VMware', + 'vim_uuid': '1', + 'access_config': {'vrops_password': 'vmware', + 'vcloud-site': 'https://192.169.241.105', + 'vrops_user': 'Admin', 'correlation_id': 14203, + 'tenant_id': 'Org2'} + } + + # call publish access update response method under test + response = self.plugin_receiver.publish_access_update_response(access_update_status, access_info_req) + + # verify mocked method called with correct params + # TODO(diazb): Validate payload generation (self.assertEquals(response, expected_message)) + + @mock.patch.object(monPluginRec.PluginReceiver, 'write_access_config') + def test_update_access_credentials_successful(self, m_write_access_config): + """ Test functionality of update access credentials-positive case""" + + # Mock access_info + access_info = {'vrops_site': 'https://192.169.241.13', 'vrops_user': 'admin', + 'vrops_password': 'vmware', 'vcloud-site': 'https://192.169.241.15', + 'admin_username': 'admin', 'admin_password': 'vmware', + 'vcenter_ip': '192.169.241.13', 'vcenter_port': '443', + 'vcenter_user': 'admin', 'vcenter_password': 'vmware', + 'vim_tenant_name': 'Org2', 'orgname': 'Org2', 'tenant_id': 'Org2'} + + # Mock return values + expected_status = m_write_access_config.return_value = True + + # call publish update access credentials method under test + actual_status = self.plugin_receiver.update_access_credentials(access_info) + + # check write_access_config called with correct params + m_write_access_config.assert_called_with(access_info) + + # verify update access credentials returns correct status + self.assertEqual(expected_status, actual_status) + + @mock.patch.object(monPluginRec.PluginReceiver, 'write_access_config') + def test_update_access_credentials_less_config_params(self, m_write_access_config): + """ Test functionality of update access credentials-negative case""" + + # Mock access_info + access_info = {'vrops_site': 'https://192.169.241.13', 'vrops_user': 'admin', + 'vrops_password': 'vmware', 'vcloud-site': 'https://192.169.241.15', + 'admin_username': 'admin', 'admin_password': 'vmware', + 'vcenter_ip': '192.169.241.13', 'vcenter_port': '443', 'vcenter_user': 'admin', + 'vim_tenant_name': 'Org2', 'orgname': 'Org2', 'tenant_id': 'Org2'} + + # Mock return values + expected_status = m_write_access_config.return_value = False + + # call publish update access credentials method under test + actual_status = self.plugin_receiver.update_access_credentials(access_info) + + # check if mocked method not called + m_write_access_config.assert_not_called() + + # verify update access credentials returns correct status + self.assertEqual(expected_status, actual_status) + + @mock.patch.object(monPluginRec.PluginReceiver, 'write_access_config') + def test_update_access_credentials_failed(self, m_write_access_config): + """ Test functionality of update access credentials-failed case """ + + # Mock access_info + access_info = {'vrops_site': 'https://192.169.241.13', 'vrops_user': 'admin', + 'vrops_password': 'vmware', 'vcloud-site': 'https://192.169.241.15', + 'admin_username': 'admin', 'admin_password': 'vmware', + 'vcenter_ip': '192.169.241.13', 'vcenter_port': '443', + 'vcenter_user': 'admin', 'vcenter_password': 'vmware', + 'vim_tenant_name': 'Org2', 'orgname': 'Org2', 'tenant_id': 'Org2'} + + # Mock return values + expected_status = m_write_access_config.return_value = False + + # call publish update access credentials method under test + actual_status = self.plugin_receiver.update_access_credentials(access_info) + + # check write_access_config called with correct params + m_write_access_config.assert_called_with(access_info) + + # verify update access credentials returns correct status + self.assertEqual(expected_status, actual_status) + + def test_write_access_config_successful(self): + """ Test functionality of write access config method-positive case""" + + # Mock access_info + access_info = {'vrops_sit': 'https://192.169.241.13', 'vrops_user': 'admin', + 'vrops_password': 'vmware', 'vcloud-site': 'https://192.169.241.15', + 'admin_username': 'admin', 'admin_password': 'vmware', + 'vcenter_ip': '192.169.241.13', 'vcenter_port': '443', + 'vcenter_user': 'admin', 'vcenter_password': 'vmware', + 'vim_tenant_name': 'Org2', 'orgname': 'Org2', 'tenant_id': 'Org2'} + + # call write access config method under test + actual_status = self.plugin_receiver.write_access_config(access_info) + + # verify write access config returns correct status + self.assertEqual(True, actual_status) + + def test_write_access_config_failed(self): + """ Test functionality of write access config method-negative case""" + + # Mock access_info + access_info = [] # provided incorrect info to generate error + + # call write access config method under test + actual_status = self.plugin_receiver.write_access_config(access_info) + + # verify write access config returns correct status + self.assertEqual(False, actual_status) + + @mock.patch.object(monPluginRec.AuthManager, 'get_credentials') + def test_get_vim_access_config(self, m_get_credentials): + """ Test functionality of get_vim_access_config method-positive case""" + + # Mock vim_uuid & access_info + vim_uuid = '1' + vim_details = VimCredentials() + vim_details.name = "vrops_vcd82" + vim_details.password = "passwd" + vim_details.tenant_name = "MANO-VDC" + vim_details.type = "VMware" + vim_details.url = "https://10.10.1.1" + vim_details.user = "admin" + vim_details.uuid = "1" + vim_details.config = '{"orgname": "MANO-Org", "tenant_id": "MANO-VDC",\ + "admin_username": "administrator","admin_password": "vcd_pwd",\ + "vrops_user": "admin", "vrops_password": "vrops_pwd",\ + "vrops_site": "https://10.10.1.2","nsx_user": "admin",\ + "nsx_manager": "https://10.10.1.3", "nsx_password":"nsx_pwd",\ + "sdn_controller": "None", "sdn_port_mapping": "None",\ + "vcenter_ip": "10.10.1.4", "vcenter_user": "admin@vsphere.local",\ + "vcenter_password": "vcenter_pwd", "vcenter_port": "443"}' + m_get_credentials.return_value = vim_details + expected_config = {'vrops_password': 'vrops_pwd', 'vcenter_password': 'vcenter_pwd', + 'name': 'vrops_vcd82', 'org_user': 'admin', + 'org_password': 'passwd', 'nsx_user': 'admin', 'vim_tenant_name': 'MANO-VDC', + 'admin_username': 'administrator', 'vcenter_port': '443', + 'vim_url': 'https://10.10.1.1', 'orgname': 'MANO-Org', + 'admin_password': 'vcd_pwd', 'vrops_user': 'admin', 'vcenter_ip': '10.10.1.4', + 'vrops_site': 'https://10.10.1.2', 'nsx_manager': 'https://10.10.1.3', + 'nsx_password': 'nsx_pwd', 'vim_type': 'VMware', 'vim_uuid': '1', + 'vcenter_user': 'admin@vsphere.local'} + + # call get_vim_access_config method under test + actual_config = self.plugin_receiver.get_vim_access_config('1') + + # verify that mocked method is called + m_get_credentials.assert_called_with(vim_uuid) + + # Verify return value with expected value + self.assertEqual(expected_config, actual_config) + +# For testing purpose +# if __name__ == '__main__': + +# unittest.main() diff --git a/osm_mon/test/plugins/__init__.py b/osm_mon/test/plugins/__init__.py new file mode 100644 index 0000000..2d39b96 --- /dev/null +++ b/osm_mon/test/plugins/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- + +# Copyright 2018 Whitestack, LLC +# ************************************************************* + +# This file is part of OSM Monitoring module +# All Rights Reserved to Whitestack, LLC + +# 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. +# For those usages not covered by the Apache License, Version 2.0 please +# contact: bdiaz@whitestack.com or glavado@whitestack.com +## \ No newline at end of file diff --git a/setup.py b/setup.py index dc5812f..db7a715 100644 --- a/setup.py +++ b/setup.py @@ -73,7 +73,7 @@ setup( include_package_data=True, entry_points={ "console_scripts": [ - "osm-mon-exporter = osm_mon.cmd.exporter:main", + "osm-mon-prometheus-exporter = osm_mon.cmd.mon_prometheus_exporter:main", ] }, dependency_links=[