e1517f3a8da500fc5824117b873a9664789f7d65
[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  * ================================================================================
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
21 package org.onap.policy.models.simulators;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
25 import static org.assertj.core.api.Assertions.assertThatThrownBy;
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertTrue;
29 import static org.mockito.ArgumentMatchers.any;
30 import static org.mockito.Mockito.mock;
31 import static org.mockito.Mockito.when;
32
33 import java.io.FileNotFoundException;
34 import java.io.IOException;
35 import java.util.HashMap;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Map.Entry;
39 import java.util.Properties;
40 import java.util.concurrent.LinkedBlockingQueue;
41 import java.util.concurrent.TimeUnit;
42 import javax.ws.rs.core.Response;
43 import org.junit.After;
44 import org.junit.AfterClass;
45 import org.junit.BeforeClass;
46 import org.junit.Test;
47 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
48 import org.onap.policy.common.endpoints.http.client.HttpClient;
49 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
50 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
51 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
52 import org.onap.policy.common.endpoints.http.server.internal.JettyJerseyServer;
53 import org.onap.policy.common.utils.coder.Coder;
54 import org.onap.policy.common.utils.coder.CoderException;
55 import org.onap.policy.common.utils.network.NetworkUtil;
56 import org.onap.policy.common.utils.security.SelfSignedKeyStore;
57
58 public class MainTest {
59     private static final String PARAMETER_FILE = "simParameters.json";
60     private static final String HOST = "localhost";
61     private static final String EXPECTED_EXCEPTION = "expected exception";
62
63     private static Map<String, String> savedValues;
64
65     /**
66      * Saves system properties.
67      */
68     @BeforeClass
69     public static void setUpBeforeClass() throws IOException, InterruptedException {
70         savedValues = new HashMap<>();
71
72         for (String prop : List.of(JettyJerseyServer.SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME,
73                         JettyJerseyServer.SYSTEM_KEYSTORE_PROPERTY_NAME,
74                         JettyJerseyServer.SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME,
75                         JettyJerseyServer.SYSTEM_TRUSTSTORE_PROPERTY_NAME)) {
76
77             savedValues.put(prop, System.getProperty(prop));
78         }
79
80         System.setProperty(JettyJerseyServer.SYSTEM_KEYSTORE_PROPERTY_NAME, new SelfSignedKeyStore().getKeystoreName());
81         System.setProperty(JettyJerseyServer.SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME,
82                         SelfSignedKeyStore.KEYSTORE_PASSWORD);
83
84         System.setProperty(JettyJerseyServer.SYSTEM_TRUSTSTORE_PROPERTY_NAME,
85                         "src/main/resources/ssl/policy-truststore");
86         System.setProperty(JettyJerseyServer.SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME,
87                         SelfSignedKeyStore.KEYSTORE_PASSWORD);
88     }
89
90     /**
91      * Restores system properties.
92      */
93     @AfterClass
94     public static void tearDownAfterClass() {
95         for (Entry<String, String> ent : savedValues.entrySet()) {
96             if (ent.getValue() == null) {
97                 System.getProperties().remove(ent.getKey());
98             } else {
99                 System.setProperty(ent.getKey(), ent.getValue());
100             }
101         }
102     }
103
104     /**
105      * Shuts down the simulator instance.
106      */
107     @After
108     public void tearDown() {
109         Main main = Main.getInstance();
110         if (main != null && main.isAlive()) {
111             main.shutdown();
112         }
113     }
114
115     @Test
116     public void testConstructor() throws Exception {
117         assertThatIllegalArgumentException().isThrownBy(() -> new Main("invalidDmaapProvider.json"))
118                         .withMessage("invalid simulator parameters");
119     }
120
121     /**
122      * Verifies that all of the simulators are brought up and that HTTPS works with at
123      * least one of them.
124      */
125     @Test
126     public void testMain() throws Exception {
127         Main.main(new String[0]);
128         assertTrue(Main.getInstance() == null || !Main.getInstance().isAlive());
129
130         Main.main(new String[] {PARAMETER_FILE});
131
132         // don't need to wait long, because buildXxx() does the wait for us
133         for (int port : new int[] {6666, 6667, 6668, 6669, 6670, 6680}) {
134             assertTrue("simulator on port " + port, NetworkUtil.isTcpPortOpen(HOST, port, 1, 100));
135         }
136
137         // it's sufficient to verify that one of the simulators works
138         checkAai();
139     }
140
141     @Test
142     public void testMainMinimalParameters() {
143         Main.main(new String[] {"minParameters.json"});
144         assertNotNull(Main.getInstance());
145         assertTrue(Main.getInstance().isAlive());
146     }
147
148     private void checkAai() throws HttpClientConfigException {
149         BusTopicParams params = BusTopicParams.builder().clientName("client").hostname(HOST).port(6666).useHttps(true)
150                         .allowSelfSignedCerts(true).basePath("aai").build();
151         HttpClient client = HttpClientFactoryInstance.getClientFactory().build(params);
152
153         Response response = client.get("/v21/network/pnfs/pnf/demo-pnf");
154         assertEquals(200, response.getStatus());
155
156         String result = response.readEntity(String.class);
157         assertThat(result).contains("model-123456");
158     }
159
160     /**
161      * Tests readParameters() when the file cannot be found.
162      */
163     @Test
164     public void testReadParametersNoFile() {
165         assertThatIllegalArgumentException().isThrownBy(() -> new Main("missing-file.json"))
166                         .withCauseInstanceOf(FileNotFoundException.class);
167     }
168
169     /**
170      * Tests readParameters() when the json cannot be decoded.
171      */
172     @Test
173     public void testReadParametersInvalidJson() throws CoderException {
174         Coder coder = mock(Coder.class);
175         when(coder.decode(any(String.class), any())).thenThrow(new CoderException(EXPECTED_EXCEPTION));
176
177         assertThatIllegalArgumentException().isThrownBy(() -> new Main(PARAMETER_FILE) {
178             @Override
179             protected Coder makeCoder() {
180                 return coder;
181             }
182         }).withCauseInstanceOf(CoderException.class);
183     }
184
185     /**
186      * Tests buildRestServer() when the server port is not open.
187      */
188     @Test
189     public void testBuildRestServerNotOpen() {
190         HttpServletServer server = mock(HttpServletServer.class);
191
192         Main main = new Main(PARAMETER_FILE) {
193             @Override
194             protected HttpServletServer makeServer(Properties props) {
195                 return server;
196             }
197
198             @Override
199             protected boolean isTcpPortOpen(String hostName, int port) throws InterruptedException {
200                 return false;
201             }
202         };
203
204         assertThatThrownBy(main::start).hasCauseInstanceOf(IllegalStateException.class);
205     }
206
207     /**
208      * Tests buildRestServer() when the port checker is interrupted.
209      */
210     @Test
211     public void testBuildRestServerInterrupted() throws InterruptedException {
212         HttpServletServer server = mock(HttpServletServer.class);
213
214         Main main = new Main(PARAMETER_FILE) {
215             @Override
216             protected HttpServletServer makeServer(Properties props) {
217                 return server;
218             }
219
220             @Override
221             protected boolean isTcpPortOpen(String hostName, int port) throws InterruptedException {
222                 throw new InterruptedException(EXPECTED_EXCEPTION);
223             }
224         };
225
226         // run in another thread so we don't interrupt this thread
227         LinkedBlockingQueue<RuntimeException> queue = new LinkedBlockingQueue<>();
228         Thread thread = new Thread(() -> {
229             try {
230                 main.start();
231             } catch (RuntimeException e) {
232                 queue.add(e);
233             }
234         });
235
236         thread.setDaemon(true);
237         thread.start();
238
239         RuntimeException ex = queue.poll(5, TimeUnit.SECONDS);
240         assertNotNull(ex);
241         assertTrue(ex.getCause() instanceof IllegalStateException);
242         assertThat(ex.getCause()).hasMessageStartingWith("interrupted while building");
243     }
244
245     /**
246      * Tests buildTopicServer() when the provider class is invalid.
247      */
248     @Test
249     public void testBuildTopicServerInvalidProvider() {
250         assertThatThrownBy(() -> new Main("invalidTopicServer.json").start())
251                         .hasCauseInstanceOf(IllegalArgumentException.class);
252     }
253
254     /**
255      * Tests buildTopicServer() when the sink is missing.
256      */
257     @Test
258     public void testBuildTopicServerNoSink() {
259         assertThatThrownBy(() -> new Main("missingSink.json").start())
260                         .hasCauseInstanceOf(IllegalArgumentException.class);
261     }
262
263     /**
264      * Tests buildTopicServer() when the sink is missing.
265      */
266     @Test
267     public void testBuildTopicServerNoSource() {
268         assertThatThrownBy(() -> new Main("missingSource.json").start())
269                         .hasCauseInstanceOf(IllegalArgumentException.class);
270     }
271 }