Add new tests to validate O1
[it/dep.git] / smo-install / test / pythonsdk / src / orantests / test_o1.py
1 #!/usr/bin/env python3
2 ###
3 # ============LICENSE_START=======================================================
4 # ORAN SMO PACKAGE - PYTHONSDK TESTS
5 # ================================================================================
6 # Copyright (C) 2021-2022 AT&T Intellectual Property. All rights
7 #                             reserved.
8 # ================================================================================
9 # Licensed under the Apache License, Version 2.0 (the "License");
10 # you may not use this file except in compliance with the License.
11 # You may obtain a copy of the License at
12 #
13 # http://www.apache.org/licenses/LICENSE-2.0
14 #
15 # Unless required by applicable law or agreed to in writing, software
16 # distributed under the License is distributed on an "AS IS" BASIS,
17 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 # See the License for the specific language governing permissions and
19 # limitations under the License.
20 # ============LICENSE_END============================================
21 # ===================================================================
22 #
23 ###
24 """O1 tests module."""
25 import datetime
26 import logging
27 import json
28 import os
29 import time
30 import pytest
31 from onapsdk.configuration import settings
32 from smo.network_simulators import NetworkSimulators
33 from oransdk.dmaap.dmaap import OranDmaap
34 from oransdk.sdnc.sdnc import OranSdnc
35 from waiting import wait
36
37 # Set working dir as python script location
38 abspath = os.path.abspath(__file__)
39 dname = os.path.dirname(abspath)
40 os.chdir(dname)
41
42 logging.config.dictConfig(settings.LOG_CONFIG)
43 logger = logging.getLogger("Test O1")
44
45 network_simulators = NetworkSimulators("./resources")
46 dmaap = OranDmaap()
47 test_session_timestamp = datetime.datetime.now()
48
49 @pytest.fixture(scope="module", autouse=True)
50 def setup_simulators():
51     """Setup the simulators before the executing the tests."""
52     logger.info("Test class setup for O1 tests")
53
54     # Do a first get to register the o1test/o1test user in DMAAP
55     # all registration messages will then be stored for the registration tests.
56     # If it exists already it clears all cached events.
57     wait(lambda: (dmaap.get_message_from_topic("unauthenticated.VES_PNFREG_OUTPUT", 5000, settings.DMAAP_GROUP, settings.DMAAP_USER).json() == []), sleep_seconds=10, timeout_seconds=60, waiting_for="DMaap topic unauthenticated.VES_PNFREG_OUTPUT to be empty")
58     wait(lambda: (dmaap.get_message_from_topic("unauthenticated.SEC_FAULT_OUTPUT", 5000, settings.DMAAP_GROUP, settings.DMAAP_USER).json() == []), sleep_seconds=10, timeout_seconds=60, waiting_for="DMaap topic unauthenticated.SEC_FAULT_OUTPUT to be empty")
59     network_simulators.start_network_simulators()
60     network_simulators.wait_for_network_simulators_to_be_running()
61   # ADD DU RESTART just in case
62     # Wait enough time to have at least the SDNR notifications sent
63     logger.info("Waiting 20s that SDNR sends all registration events to VES...")
64     time.sleep(10)
65     logger.info("Enabling faults/events reporting on SDNR")
66     network_simulators.enable_events_for_all_simulators()
67 #    logger.info("Waiting 20s that the Dmaap faults topic is created...")
68 #    time.sleep(20)
69     # Preparing the DMaap to cache all the events for the fault topics.
70     # If it exists already it clears all cached events.
71     logger.info("Waiting 120s to have registration and faults events in DMaap")
72     time.sleep(120)
73     logger.info("Test Session setup completed successfully")
74
75     ### Cleanup code
76     yield
77     network_simulators.stop_network_simulators()
78     logger.info("Test Session cleanup done")
79
80 def create_registration_structure(events):
81     """Decode the registration events list."""
82     devices_found_in_events = dict()
83     for event in events:
84         event_json = json.loads(event)
85         logger.info("Registration json decoded: %s", str(event_json))
86         devices_found_in_events[event_json["event"]["commonEventHeader"]["sourceName"]] = event_json["event"]["commonEventHeader"]["reportingEntityName"]
87
88     logger.info("Devices found in events:%s", devices_found_in_events)
89     return devices_found_in_events
90
91 def create_faults_structure(events):
92     """Decode the fault events list."""
93     faults_found_in_events = dict()
94     for event in events:
95         event_json = json.loads(event)
96         logger.info("Fault json decoded: %s", str(event_json))
97         if event_json["event"]["commonEventHeader"]["sourceName"] in faults_found_in_events:
98             faults_found_in_events[event_json["event"]["commonEventHeader"]["sourceName"]] += 1
99         else:
100             faults_found_in_events[event_json["event"]["commonEventHeader"]["sourceName"]] = 1
101     logger.info("Faults found in events: %s", faults_found_in_events)
102     return faults_found_in_events
103
104 def test_devices_in_sdnc():
105     """Verify that the devices are well defined in SDNC."""
106     logger.info("Verify if devices are well in SDNC")
107     for device in settings.NETWORK_SIMULATORS_LIST:
108         logger.info("Verify if %s is well in SDNR", device)
109         assert OranSdnc.get_devices(device, settings.SDNC_BASICAUTH) == 200
110
111 def validate_faults_timestamp(faults):
112     """Extract only the faults returned by SDNC that have been raised during this test."""
113     valid_faults = []
114     for fault in faults['data-provider:output']['data']:
115         converted_fault_timestamp = datetime.datetime.strptime(fault['timestamp'], "%Y-%m-%dT%H:%M:%S.%fZ")
116         logger.info("Comparing fault timestamp %s (%s) to session test timestamp %s", converted_fault_timestamp, fault['timestamp'], test_session_timestamp)
117         if converted_fault_timestamp > test_session_timestamp:
118             valid_faults.append(fault)
119     logger.info("Valid faults array: %s", valid_faults)
120     return valid_faults
121
122 def test_device_faults_in_sdnc():
123     """Verify that the device faults are well defined in SDNC."""
124     logger.info("Verify is there is any events")
125     for device in settings.NETWORK_SIMULATORS_DU_RU_LIST:
126         faults = OranSdnc.get_events(settings.SDNC_BASICAUTH, device).json()
127         logger.info("Verify if %s has events", device)
128         assert len(validate_faults_timestamp(faults)) >= 3
129
130 def test_network_devices_registration_in_dmaap():
131     """Validate that the devices are well registered in SDNR and forwarded to VES."""
132     logger.info("Verify if SDNR sends well the RU registration to VES by checking in DMAAP")
133     # As the user has been registered in DMAAP during test session init,
134     # that call should return all sims registered by SDNR
135     all_registrations = []
136     events = []
137
138     while (events := dmaap.get_message_from_topic("unauthenticated.VES_PNFREG_OUTPUT", 30000, settings.DMAAP_GROUP, settings.DMAAP_USER).json()) != []:
139         logger.info("Getting a first set of event: %s", events)
140         all_registrations += events
141
142     logger.info("ALl registration events received: %s", all_registrations)
143     # events should be a list of messages
144     logger.info("Verify if the number of events is well >= to the number of expected devices")
145     # The DU can send multiple times message to VES and SDNR can send multiple time event for RU
146     assert len(all_registrations) >= (len(settings.NETWORK_SIMULATORS_DU_RU_LIST))
147     devices_registered = create_registration_structure(all_registrations)
148
149     # Each device must be at least one time in the event list
150     for sim_name in settings.NETWORK_SIMULATORS_DU_RU_LIST:
151         logger.info("Checking if %s is in events list", sim_name)
152         assert sim_name in devices_registered
153         if "o-ru" in sim_name:
154             logger.info("RU event detected checking SDNR has well registered it")
155             assert "ONAP SDN-R" in devices_registered[sim_name]
156         elif "o-du" in sim_name:
157             logger.info("DU detected checking it has well registered itself")
158             assert "o-du" in devices_registered[sim_name]
159
160 def test_device_faults_in_dmaap():
161     """Verify that device faults are well sent to DMAAP by SDNR."""
162     logger.info("Verify if SDNR forwards well the faults sent by the simulators to DMAAP")
163     events = dmaap.get_message_from_topic("unauthenticated.SEC_FAULT_OUTPUT", 30000, settings.DMAAP_GROUP, settings.DMAAP_USER).json()
164     logger.info("Verify if faults have well been received for each device")
165     assert len(events) > 0
166     faults_received = create_faults_structure(events)
167
168     # Each device must have some faults
169     for sim_name in settings.NETWORK_SIMULATORS_DU_RU_LIST:
170         logger.info("Check if %s has at least >=3 faults", sim_name)
171         assert sim_name in faults_received and faults_received[sim_name] >= 3