ca9041097c47557ea11bf4007de1457cfce39631
[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 smo.dmaap import DmaapUtils
34 from oransdk.dmaap.dmaap import OranDmaap
35 from oransdk.sdnc.sdnc import OranSdnc
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 dmaap_utils = DmaapUtils()
48 test_session_timestamp = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
49
50
51 @pytest.fixture(scope="module", autouse=True)
52 def setup_simulators():
53     """Setup the simulators before the executing the tests."""
54     logger.info("Test class setup for O1 tests")
55
56     # Do a first get to register the o1test/o1test user in DMAAP
57     # all registration messages will then be stored for the registration tests.
58     # If it exists already it clears all cached events.
59
60     dmaap_utils.clean_dmaap(settings.DMAAP_GROUP, settings.DMAAP_USER)
61
62     network_simulators.start_and_wait_network_simulators()
63   # ADD DU RESTART just in case
64     # Wait enough time to have at least the SDNR notifications sent
65     logger.info("Waiting 20s that SDNR sends all registration events to VES...")
66     time.sleep(20)
67     logger.info("Enabling faults/events reporting on SDNR")
68     network_simulators.enable_events_for_all_simulators()
69 #    logger.info("Waiting 20s that the Dmaap faults topic is created...")
70 #    time.sleep(20)
71     # Preparing the DMaap to cache all the events for the fault topics.
72     # If it exists already it clears all cached events.
73     logger.info("Waiting 300s to have registration and faults events in DMaap")
74     time.sleep(300)
75     logger.info("Test Session setup completed successfully")
76
77     ### Cleanup code
78     yield
79     network_simulators.stop_network_simulators()
80     time.sleep(10)
81     logger.info("Test Session cleanup done")
82
83 def create_registration_structure(events):
84     """Decode the registration events list."""
85     devices_found_in_events = dict()
86     for event in events:
87         event_json = json.loads(event)
88         logger.info("Registration json decoded: %s", str(event_json))
89         devices_found_in_events[event_json["event"]["commonEventHeader"]["sourceName"]] = event_json["event"]["commonEventHeader"]["reportingEntityName"]
90
91     logger.info("Devices found in events:%s", devices_found_in_events)
92     return devices_found_in_events
93
94 def create_faults_structure(events):
95     """Decode the fault events list."""
96     faults_found_in_events = dict()
97     for event in events:
98         event_json = json.loads(event)
99         logger.info("Fault json decoded: %s", str(event_json))
100         if event_json["event"]["commonEventHeader"]["sourceName"] in faults_found_in_events:
101             faults_found_in_events[event_json["event"]["commonEventHeader"]["sourceName"]] += 1
102         else:
103             faults_found_in_events[event_json["event"]["commonEventHeader"]["sourceName"]] = 1
104     logger.info("Faults found in events: %s", faults_found_in_events)
105     return faults_found_in_events
106
107 def test_devices_in_sdnc():
108     """Verify that the devices are well defined in SDNC."""
109     logger.info("Verify if devices are well in SDNC")
110     for device in settings.NETWORK_SIMULATORS_LIST:
111         logger.info("Verify if %s is well in SDNR", device)
112         assert OranSdnc.get_devices(device, settings.SDNC_BASICAUTH) == 200
113
114 def validate_faults_timestamp(faults):
115     """Extract only the faults returned by SDNC that have been raised during this test."""
116     valid_faults = []
117     for fault in faults['data-provider:output']['data']:
118         try:
119             converted_fault_timestamp = datetime.datetime.strptime(fault['timestamp'], "%Y-%m-%dT%H:%M:%S.%f%z")
120         except ValueError:
121             converted_fault_timestamp = datetime.datetime.strptime(fault['timestamp'], "%Y-%m-%dT%H:%M:%S%z")
122         logger.info("Comparing fault timestamp %s (%s) to session test timestamp %s", converted_fault_timestamp, fault['timestamp'], test_session_timestamp)
123         if converted_fault_timestamp > test_session_timestamp:
124             valid_faults.append(fault)
125     logger.info("Valid faults array: %s", valid_faults)
126     return valid_faults
127
128 def test_device_faults_in_sdnc():
129     """Verify that the device faults are well defined in SDNC."""
130     logger.info("Verify is there is any events")
131     for device in settings.NETWORK_SIMULATORS_DU_RU_LIST:
132         faults = OranSdnc.get_events(settings.SDNC_BASICAUTH, device).json()
133         logger.info("Verify if %s has events", device)
134         assert len(validate_faults_timestamp(faults)) >= 3
135
136 def test_network_devices_registration_in_dmaap():
137     """Validate that the devices are well registered in SDNR and forwarded to VES."""
138     logger.info("Verify if SDNR sends well the RU registration to VES by checking in DMAAP")
139     # As the user has been registered in DMAAP during test session init,
140     # that call should return all sims registered by SDNR
141     all_registrations = []
142     events = []
143
144     while (events := dmaap.get_message_from_topic(settings.DMAAP_TOPIC_PNFREG, 30000, settings.DMAAP_GROUP, settings.DMAAP_USER).json()) != []:
145         logger.info("Getting a first set of event: %s", events)
146         all_registrations += events
147
148     logger.info("ALl registration events received: %s", all_registrations)
149     # events should be a list of messages
150     logger.info("Verify if the number of events is well >= to the number of expected devices")
151     # The DU can send multiple times message to VES and SDNR can send multiple time event for RU
152     assert len(all_registrations) >= (len(settings.NETWORK_SIMULATORS_DU_RU_LIST))
153     devices_registered = create_registration_structure(all_registrations)
154
155     # Each device must be at least one time in the event list
156     for sim_name in settings.NETWORK_SIMULATORS_DU_RU_LIST:
157         logger.info("Checking if %s is in events list", sim_name)
158         assert sim_name in devices_registered
159         if "o-ru" in sim_name:
160             logger.info("RU event detected checking SDNR has well registered it")
161             assert "ONAP SDN-R" in devices_registered[sim_name]
162         elif "o-du" in sim_name:
163             logger.info("DU detected checking it has well registered itself")
164             assert "o-du" in devices_registered[sim_name]
165
166 def test_device_faults_in_dmaap():
167     """Verify that device faults are well sent to DMAAP by SDNR."""
168     logger.info("Verify if SDNR forwards well the faults sent by the simulators to DMAAP")
169     events = dmaap.get_message_from_topic(settings.DMAAP_TOPIC_FAULT, 30000, settings.DMAAP_GROUP, settings.DMAAP_USER).json()
170     logger.info("Verify if faults have well been received for each device")
171     assert len(events) > 0
172     faults_received = create_faults_structure(events)
173
174     # Each device must have some faults
175     for sim_name in settings.NETWORK_SIMULATORS_DU_RU_LIST:
176         logger.info("Check if %s has at least >=3 faults", sim_name)
177         assert sim_name in faults_received and faults_received[sim_name] >= 3