Remove dmaap from models
[policy/models.git] / models-sim / policy-models-simulators / src / test / java / org / onap / policy / models / simulators / MainTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2023-2024 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.models.simulators;
23
24 import static org.assertj.core.api.Assertions.assertThat;
25 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
26 import static org.assertj.core.api.Assertions.assertThatThrownBy;
27 import static org.junit.Assert.assertEquals;
28 import static org.junit.Assert.assertNotNull;
29 import static org.junit.Assert.assertTrue;
30 import static org.mockito.ArgumentMatchers.any;
31 import static org.mockito.Mockito.mock;
32 import static org.mockito.Mockito.when;
33
34 import jakarta.ws.rs.core.Response;
35 import java.io.FileNotFoundException;
36 import java.io.IOException;
37 import java.util.HashMap;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Map.Entry;
41 import java.util.Properties;
42 import java.util.concurrent.LinkedBlockingQueue;
43 import java.util.concurrent.TimeUnit;
44 import org.junit.After;
45 import org.junit.AfterClass;
46 import org.junit.BeforeClass;
47 import org.junit.Test;
48 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
49 import org.onap.policy.common.endpoints.http.client.HttpClient;
50 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
51 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
52 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
53 import org.onap.policy.common.endpoints.http.server.internal.JettyJerseyServer;
54 import org.onap.policy.common.utils.coder.Coder;
55 import org.onap.policy.common.utils.coder.CoderException;
56 import org.onap.policy.common.utils.network.NetworkUtil;
57 import org.onap.policy.common.utils.security.SelfSignedKeyStore;
58
59 public class MainTest {
60     private static final String PARAMETER_FILE = "simParameters.json";
61     private static final String HOST = "localhost";
62     private static final String EXPECTED_EXCEPTION = "expected exception";
63
64     private static Map<String, String> savedValues;
65
66     /**
67      * Saves system properties.
68      */
69     @BeforeClass
70     public static void setUpBeforeClass() throws IOException, InterruptedException {
71         savedValues = new HashMap<>();
72
73         for (String prop : List.of(JettyJerseyServer.SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME,
74                         JettyJerseyServer.SYSTEM_KEYSTORE_PROPERTY_NAME,
75                         JettyJerseyServer.SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME,
76                         JettyJerseyServer.SYSTEM_TRUSTSTORE_PROPERTY_NAME)) {
77
78             savedValues.put(prop, System.getProperty(prop));
79         }
80
81         System.setProperty(JettyJerseyServer.SYSTEM_KEYSTORE_PROPERTY_NAME, new SelfSignedKeyStore().getKeystoreName());
82         System.setProperty(JettyJerseyServer.SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME,
83                         SelfSignedKeyStore.KEYSTORE_PASSWORD);
84
85         System.setProperty(JettyJerseyServer.SYSTEM_TRUSTSTORE_PROPERTY_NAME,
86                         "src/main/resources/ssl/policy-truststore");
87         System.setProperty(JettyJerseyServer.SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME,
88                         SelfSignedKeyStore.KEYSTORE_PASSWORD);
89     }
90
91     /**
92      * Restores system properties.
93      */
94     @AfterClass
95     public static void tearDownAfterClass() {
96         for (Entry<String, String> ent : savedValues.entrySet()) {
97             if (ent.getValue() == null) {
98                 System.getProperties().remove(ent.getKey());
99             } else {
100                 System.setProperty(ent.getKey(), ent.getValue());
101             }
102         }
103     }
104
105     /**
106      * Shuts down the simulator instance.
107      */
108     @After
109     public void tearDown() {
110         Main main = Main.getInstance();
111         if (main != null && main.isAlive()) {
112             main.shutdown();
113         }
114     }
115
116     /**
117      * Verifies that all the simulators are brought up and that HTTPS works with at
118      * least one of them.
119      */
120     @Test
121     public void testMain() throws Exception {
122         Main.main(new String[0]);
123         assertTrue(Main.getInstance() == null || !Main.getInstance().isAlive());
124
125         Main.main(new String[] {PARAMETER_FILE});
126
127         // don't need to wait long, because buildXxx() does the wait for us
128         for (int port : new int[] {6666, 6667, 6668, 6669, 6670, 6680}) {
129             assertTrue("simulator on port " + port, NetworkUtil.isTcpPortOpen(HOST, port, 1, 100));
130         }
131
132         // it's sufficient to verify that one of the simulators works
133         checkAai();
134     }
135
136     @Test
137     public void testMainMinimalParameters() {
138         Main.main(new String[] {"minParameters.json"});
139         assertNotNull(Main.getInstance());
140         assertTrue(Main.getInstance().isAlive());
141     }
142
143     private void checkAai() throws HttpClientConfigException {
144         BusTopicParams params = BusTopicParams.builder().clientName("client").hostname(HOST).port(6666).useHttps(true)
145                         .allowSelfSignedCerts(true).basePath("aai").build();
146         HttpClient client = HttpClientFactoryInstance.getClientFactory().build(params);
147
148         Response response = client.get("/v21/network/pnfs/pnf/demo-pnf");
149         assertEquals(200, response.getStatus());
150
151         String result = response.readEntity(String.class);
152         assertThat(result).contains("model-123456");
153     }
154
155     /**
156      * Tests readParameters() when the file cannot be found.
157      */
158     @Test
159     public void testReadParametersNoFile() {
160         assertThatIllegalArgumentException().isThrownBy(() -> new Main("missing-file.json"))
161                         .withCauseInstanceOf(FileNotFoundException.class);
162     }
163
164     /**
165      * Tests readParameters() when the json cannot be decoded.
166      */
167     @Test
168     public void testReadParametersInvalidJson() throws CoderException {
169         Coder coder = mock(Coder.class);
170         when(coder.decode(any(String.class), any())).thenThrow(new CoderException(EXPECTED_EXCEPTION));
171
172         assertThatIllegalArgumentException().isThrownBy(() -> new Main(PARAMETER_FILE) {
173             @Override
174             protected Coder makeCoder() {
175                 return coder;
176             }
177         }).withCauseInstanceOf(CoderException.class);
178     }
179
180     /**
181      * Tests buildRestServer() when the server port is not open.
182      */
183     @Test
184     public void testBuildRestServerNotOpen() {
185         HttpServletServer server = mock(HttpServletServer.class);
186
187         Main main = new Main(PARAMETER_FILE) {
188             @Override
189             protected HttpServletServer makeServer(Properties props) {
190                 return server;
191             }
192
193             @Override
194             protected boolean isTcpPortOpen(String hostName, int port) throws InterruptedException {
195                 return false;
196             }
197         };
198
199         assertThatThrownBy(main::start).hasCauseInstanceOf(IllegalStateException.class);
200     }
201
202     /**
203      * Tests buildRestServer() when the port checker is interrupted.
204      */
205     @Test
206     public void testBuildRestServerInterrupted() throws InterruptedException {
207         HttpServletServer server = mock(HttpServletServer.class);
208
209         Main main = new Main(PARAMETER_FILE) {
210             @Override
211             protected HttpServletServer makeServer(Properties props) {
212                 return server;
213             }
214
215             @Override
216             protected boolean isTcpPortOpen(String hostName, int port) throws InterruptedException {
217                 throw new InterruptedException(EXPECTED_EXCEPTION);
218             }
219         };
220
221         // run in another thread, so we don't interrupt this thread
222         LinkedBlockingQueue<RuntimeException> queue = new LinkedBlockingQueue<>();
223         Thread thread = new Thread(() -> {
224             try {
225                 main.start();
226             } catch (RuntimeException e) {
227                 queue.add(e);
228             }
229         });
230
231         thread.setDaemon(true);
232         thread.start();
233
234         RuntimeException ex = queue.poll(5, TimeUnit.SECONDS);
235         assertNotNull(ex);
236         assertTrue(ex.getCause() instanceof IllegalStateException);
237         assertThat(ex.getCause()).hasMessageStartingWith("interrupted while building");
238     }
239
240
241 }