65f1850d28498e3db0e0ce937d9c15ab49354aea
[portal/ric-dashboard.git] / dashboard / webapp-backend / src / test / java / org / oransc / ric / portal / dashboard / config / AppManagerMockConfiguration.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 AT&T Intellectual Property
6  * %%
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20 package org.oransc.ric.portal.dashboard.config;
21
22 import static org.mockito.ArgumentMatchers.any;
23 import static org.mockito.Mockito.doAnswer;
24 import static org.mockito.Mockito.mock;
25 import static org.mockito.Mockito.when;
26
27 import java.lang.invoke.MethodHandles;
28
29 import org.oransc.ric.portal.dashboard.exception.InvalidArgumentException;
30 import org.oransc.ric.portal.dashboard.model.RicRegionList;
31 import org.oransc.ricplt.appmgr.client.api.HealthApi;
32 import org.oransc.ricplt.appmgr.client.api.XappApi;
33 import org.oransc.ricplt.appmgr.client.invoker.ApiClient;
34 import org.oransc.ricplt.appmgr.client.model.AllDeployableXapps;
35 import org.oransc.ricplt.appmgr.client.model.AllDeployedXapps;
36 import org.oransc.ricplt.appmgr.client.model.AllXappConfig;
37 import org.oransc.ricplt.appmgr.client.model.ConfigMetadata;
38 import org.oransc.ricplt.appmgr.client.model.ConfigValidationError;
39 import org.oransc.ricplt.appmgr.client.model.ConfigValidationErrors;
40 import org.oransc.ricplt.appmgr.client.model.EventType;
41 import org.oransc.ricplt.appmgr.client.model.SubscriptionRequest;
42 import org.oransc.ricplt.appmgr.client.model.SubscriptionResponse;
43 import org.oransc.ricplt.appmgr.client.model.XAppConfig;
44 import org.oransc.ricplt.appmgr.client.model.Xapp;
45 import org.oransc.ricplt.appmgr.client.model.Xapp.StatusEnum;
46 import org.oransc.ricplt.appmgr.client.model.XappDescriptor;
47 import org.oransc.ricplt.appmgr.client.model.XappInstance;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.beans.factory.annotation.Value;
52 import org.springframework.context.annotation.Bean;
53 import org.springframework.context.annotation.Configuration;
54 import org.springframework.context.annotation.Profile;
55 import org.springframework.http.HttpStatus;
56
57 /**
58  * Creates an implementation of the xApp manager client that answers requests
59  * with mock data.
60  */
61 @Configuration
62 @Profile("test")
63 public class AppManagerMockConfiguration {
64
65         private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
66
67         // Simulate remote method delay for UI testing
68         private int delayMs;
69
70         // Autowire all the properties required by the real class
71         // (even tho not used here) as a test of the properties.
72         @Autowired
73         public AppManagerMockConfiguration(@Value("${appmgr.url.suffix}") final String urlSuffix, //
74                         final RicRegionList instanceConfig, //
75                         @Value("${mock.config.delay:0}") int delayMs) {
76                 logger.info("ctor: configured with suffix {}, instances {}, delay {}", urlSuffix, instanceConfig, delayMs);
77                 this.delayMs = delayMs;
78         }
79
80         /**
81          * Builds a mock HealthApi object. Does not accept an instance key because this
82          * API answers no text.
83          * 
84          * @return mock HealthApi
85          */
86         private HealthApi healthApi() {
87                 ApiClient mockClient = mock(ApiClient.class);
88                 when(mockClient.getStatusCode()).thenReturn(HttpStatus.OK);
89                 HealthApi mockApi = mock(HealthApi.class);
90                 when(mockApi.getApiClient()).thenReturn(mockClient);
91                 doAnswer(i -> null).when(mockApi).getHealthAlive();
92                 doAnswer(i -> null).when(mockApi).getHealthReady();
93                 return mockApi;
94         }
95
96         /**
97          * Builds a mock XappApi object.
98          * 
99          * @param instanceKey
100          *                        RIC instance
101          * @return Object that returns instance-specific results
102          */
103         private XappApi xappApi(String instanceKey) {
104                 logger.debug("Creating XappApi for instance {}", instanceKey);
105                 // Create instance-specific objects
106                 String[] appNames = { "Measurement Campaign " + instanceKey, "UE Event Collector " + instanceKey };
107                 final String configJson = " { \"config\" : \"example-" + instanceKey + "\"}";
108                 final ConfigValidationErrors configValErrs = new ConfigValidationErrors();
109                 configValErrs.add(new ConfigValidationError().field("mock error"));
110                 final AllXappConfig allXappConfigs = new AllXappConfig();
111                 final AllDeployableXapps deployableApps = new AllDeployableXapps();
112                 final AllDeployedXapps deployedXapps = new AllDeployedXapps();
113                 for (String n : appNames) {
114                         ConfigMetadata metadata = new ConfigMetadata().xappName(n).namespace("namespace");
115                         XAppConfig config = new XAppConfig().config(configJson).metadata(metadata);
116                         allXappConfigs.add(config);
117                         deployableApps.add(n);
118                         Xapp xapp = new Xapp().name(n).version("version").status(StatusEnum.UNKNOWN);
119                         xapp.addInstancesItem(new XappInstance().name("abcd-1234").ip("127.0.0.1").port(200)
120                                         .status(XappInstance.StatusEnum.RUNNING));
121                         deployedXapps.add(xapp);
122                 }
123                 final SubscriptionResponse subRes = new SubscriptionResponse().eventType(EventType.ALL).id("subid").version(1);
124                 // Mock the methods to return the instance-specific objects
125                 ApiClient mockClient = mock(ApiClient.class);
126                 when(mockClient.getStatusCode()).thenReturn(HttpStatus.OK);
127                 XappApi mockApi = mock(XappApi.class);
128                 when(mockApi.getApiClient()).thenReturn(mockClient);
129                 doAnswer(inv -> {
130                         if (delayMs > 0) {
131                                 logger.debug("getAllXappConfig sleeping {}", delayMs);
132                                 Thread.sleep(delayMs);
133                         }
134                         return allXappConfigs;
135                 }).when(mockApi).getAllXappConfig();
136                 doAnswer(inv -> {
137                         if (delayMs > 0) {
138                                 logger.debug("modifyXappConfig sleeping {}", delayMs);
139                                 Thread.sleep(delayMs);
140                         }
141                         return configValErrs;
142                 }).when(mockApi).modifyXappConfig(any(XAppConfig.class));
143                 doAnswer(inv -> {
144                         if (delayMs > 0) {
145                                 logger.debug("deployXapp of {} sleeping {}", inv.getArgument(0), delayMs);
146                                 Thread.sleep(delayMs);
147                         }
148                         XappDescriptor descr = inv.<XappDescriptor>getArgument(0);
149                         if (descr == null || descr.getXappName() == null)
150                                 throw new InvalidArgumentException("Name is required");
151                         return deployedXapps.get(0);
152                 }).when(mockApi).deployXapp(any(XappDescriptor.class));
153                 doAnswer(inv -> {
154                         if (delayMs > 0) {
155                                 logger.debug("listAllDeployableXapps sleeping {}", delayMs);
156                                 Thread.sleep(delayMs);
157                         }
158                         return deployableApps;
159                 }).when(mockApi).listAllXapps();
160                 doAnswer(inv -> {
161                         if (delayMs > 0) {
162                                 logger.debug("getAllXapps sleeping {}", delayMs);
163                                 Thread.sleep(delayMs);
164                         }
165                         return deployedXapps;
166                 }).when(mockApi).getAllXapps();
167                 doAnswer(inv -> {
168                         if (delayMs > 0) {
169                                 logger.debug("getXappByName of {} sleeping {}", inv.getArgument(0), delayMs);
170                                 Thread.sleep(delayMs);
171                         }
172                         return deployedXapps.get(0);
173                 }).when(mockApi).getXappByName(any(String.class));
174                 doAnswer(inv -> {
175                         if (delayMs > 0) {
176                                 logger.debug("undeployXapp of {} sleeping {}", inv.getArgument(0), delayMs);
177                                 Thread.sleep(delayMs);
178                         }
179                         return null;
180                 }).when(mockApi).undeployXapp(any(String.class));
181                 doAnswer(inv -> {
182                         if (delayMs > 0) {
183                                 logger.debug("addSubscription sleeping {}", delayMs);
184                                 Thread.sleep(delayMs);
185                         }
186                         return subRes;
187                 }).when(mockApi).addSubscription(any(SubscriptionRequest.class));
188                 doAnswer(inv -> {
189                         if (delayMs > 0) {
190                                 logger.debug("deleteSubscription sleeping {}", delayMs);
191                                 Thread.sleep(delayMs);
192                         }
193                         return null;
194                 }).when(mockApi).deleteSubscription(any(String.class));
195                 return mockApi;
196         }
197
198         @Bean
199         // Must use the same name as the non-mock configuration
200         public AppManagerApiBuilder appManagerApiBuilder() {
201                 final AppManagerApiBuilder mockBuilder = mock(AppManagerApiBuilder.class);
202                 final HealthApi mockHealthApi = healthApi();
203                 when(mockBuilder.getHealthApi(any(String.class))).thenReturn(mockHealthApi);
204                 for (final String key : RICInstanceMockConfiguration.INSTANCE_KEYS) {
205                         final XappApi mockXappApi = xappApi(key);
206                         when(mockBuilder.getXappApi(key)).thenReturn(mockXappApi);
207                 }
208                 return mockBuilder;
209         }
210
211 }