Java 17 Upgrade
[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 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     @Test
117     public void testConstructor() throws Exception {
118         assertThatIllegalArgumentException().isThrownBy(() -> new Main("invalidDmaapProvider.json"))
119                         .withMessage("invalid simulator parameters");
120     }
121
122     /**
123      * Verifies that all of the simulators are brought up and that HTTPS works with at
124      * least one of them.
125      */
126     @Test
127     public void testMain() throws Exception {
128         Main.main(new String[0]);
129         assertTrue(Main.getInstance() == null || !Main.getInstance().isAlive());
130
131         Main.main(new String[] {PARAMETER_FILE});
132
133         // don't need to wait long, because buildXxx() does the wait for us
134         for (int port : new int[] {6666, 6667, 6668, 6669, 6670, 6680}) {
135             assertTrue("simulator on port " + port, NetworkUtil.isTcpPortOpen(HOST, port, 1, 100));
136         }
137
138         // it's sufficient to verify that one of the simulators works
139         checkAai();
140     }
141
142     @Test
143     public void testMainMinimalParameters() {
144         Main.main(new String[] {"minParameters.json"});
145         assertNotNull(Main.getInstance());
146         assertTrue(Main.getInstance().isAlive());
147     }
148
149     private void checkAai() throws HttpClientConfigException {
150         BusTopicParams params = BusTopicParams.builder().clientName("client").hostname(HOST).port(6666).useHttps(true)
151                         .allowSelfSignedCerts(true).basePath("aai").build();
152         HttpClient client = HttpClientFactoryInstance.getClientFactory().build(params);
153
154         Response response = client.get("/v21/network/pnfs/pnf/demo-pnf");
155         assertEquals(200, response.getStatus());
156
157         String result = response.readEntity(String.class);
158         assertThat(result).contains("model-123456");
159     }
160
161     /**
162      * Tests readParameters() when the file cannot be found.
163      */
164     @Test
165     public void testReadParametersNoFile() {
166         assertThatIllegalArgumentException().isThrownBy(() -> new Main("missing-file.json"))
167                         .withCauseInstanceOf(FileNotFoundException.class);
168     }
169
170     /**
171      * Tests readParameters() when the json cannot be decoded.
172      */
173     @Test
174     public void testReadParametersInvalidJson() throws CoderException {
175         Coder coder = mock(Coder.class);
176         when(coder.decode(any(String.class), any())).thenThrow(new CoderException(EXPECTED_EXCEPTION));
177
178         assertThatIllegalArgumentException().isThrownBy(() -> new Main(PARAMETER_FILE) {
179             @Override
180             protected Coder makeCoder() {
181                 return coder;
182             }
183         }).withCauseInstanceOf(CoderException.class);
184     }
185
186     /**
187      * Tests buildRestServer() when the server port is not open.
188      */
189     @Test
190     public void testBuildRestServerNotOpen() {
191         HttpServletServer server = mock(HttpServletServer.class);
192
193         Main main = new Main(PARAMETER_FILE) {
194             @Override
195             protected HttpServletServer makeServer(Properties props) {
196                 return server;
197             }
198
199             @Override
200             protected boolean isTcpPortOpen(String hostName, int port) throws InterruptedException {
201                 return false;
202             }
203         };
204
205         assertThatThrownBy(main::start).hasCauseInstanceOf(IllegalStateException.class);
206     }
207
208     /**
209      * Tests buildRestServer() when the port checker is interrupted.
210      */
211     @Test
212     public void testBuildRestServerInterrupted() throws InterruptedException {
213         HttpServletServer server = mock(HttpServletServer.class);
214
215         Main main = new Main(PARAMETER_FILE) {
216             @Override
217             protected HttpServletServer makeServer(Properties props) {
218                 return server;
219             }
220
221             @Override
222             protected boolean isTcpPortOpen(String hostName, int port) throws InterruptedException {
223                 throw new InterruptedException(EXPECTED_EXCEPTION);
224             }
225         };
226
227         // run in another thread so we don't interrupt this thread
228         LinkedBlockingQueue<RuntimeException> queue = new LinkedBlockingQueue<>();
229         Thread thread = new Thread(() -> {
230             try {
231                 main.start();
232             } catch (RuntimeException e) {
233                 queue.add(e);
234             }
235         });
236
237         thread.setDaemon(true);
238         thread.start();
239
240         RuntimeException ex = queue.poll(5, TimeUnit.SECONDS);
241         assertNotNull(ex);
242         assertTrue(ex.getCause() instanceof IllegalStateException);
243         assertThat(ex.getCause()).hasMessageStartingWith("interrupted while building");
244     }
245
246     /**
247      * Tests buildTopicServer() when the provider class is invalid.
248      */
249     @Test
250     public void testBuildTopicServerInvalidProvider() {
251         assertThatThrownBy(() -> new Main("invalidTopicServer.json").start())
252                         .hasCauseInstanceOf(IllegalArgumentException.class);
253     }
254
255     /**
256      * Tests buildTopicServer() when the sink is missing.
257      */
258     @Test
259     public void testBuildTopicServerNoSink() {
260         assertThatThrownBy(() -> new Main("missingSink.json").start())
261                         .hasCauseInstanceOf(IllegalArgumentException.class);
262     }
263
264     /**
265      * Tests buildTopicServer() when the sink is missing.
266      */
267     @Test
268     public void testBuildTopicServerNoSource() {
269         assertThatThrownBy(() -> new Main("missingSource.json").start())
270                         .hasCauseInstanceOf(IllegalArgumentException.class);
271     }
272 }