Merge "rename controller.controllerName to controller.name"
[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 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.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Map.Entry;
38 import java.util.Properties;
39 import java.util.concurrent.LinkedBlockingQueue;
40 import java.util.concurrent.TimeUnit;
41 import javax.ws.rs.core.Response;
42 import org.junit.After;
43 import org.junit.AfterClass;
44 import org.junit.BeforeClass;
45 import org.junit.Test;
46 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
47 import org.onap.policy.common.endpoints.http.client.HttpClient;
48 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
49 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
50 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
51 import org.onap.policy.common.endpoints.http.server.internal.JettyJerseyServer;
52 import org.onap.policy.common.utils.coder.Coder;
53 import org.onap.policy.common.utils.coder.CoderException;
54 import org.onap.policy.common.utils.network.NetworkUtil;
55
56 public class MainTest {
57     private static final String PARAMETER_FILE = "simParameters.json";
58     private static final String HOST = "localhost";
59     private static final String EXPECTED_EXCEPTION = "expected exception";
60
61     private static Map<String, String> savedValues;
62
63     /**
64      * Saves system properties.
65      */
66     @BeforeClass
67     public static void setUpBeforeClass() {
68         savedValues = new HashMap<>();
69
70         for (String prop : List.of(JettyJerseyServer.SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME,
71                         JettyJerseyServer.SYSTEM_KEYSTORE_PROPERTY_NAME,
72                         JettyJerseyServer.SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME,
73                         JettyJerseyServer.SYSTEM_TRUSTSTORE_PROPERTY_NAME)) {
74
75             savedValues.put(prop, System.getProperty(prop));
76         }
77
78         System.setProperty(JettyJerseyServer.SYSTEM_KEYSTORE_PROPERTY_NAME, "src/test/resources/keystore-test");
79         System.setProperty(JettyJerseyServer.SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME, "kstest");
80
81         System.setProperty(JettyJerseyServer.SYSTEM_TRUSTSTORE_PROPERTY_NAME, "src/test/resources/keystore-test");
82         System.setProperty(JettyJerseyServer.SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME, "kstest");
83     }
84
85     /**
86      * Restores system properties.
87      */
88     @AfterClass
89     public static void tearDownAfterClass() {
90         for (Entry<String, String> ent : savedValues.entrySet()) {
91             if (ent.getValue() == null) {
92                 System.getProperties().remove(ent.getKey());
93             } else {
94                 System.setProperty(ent.getKey(), ent.getValue());
95             }
96         }
97     }
98
99     /**
100      * Shuts down the simulator instance.
101      */
102     @After
103     public void tearDown() {
104         Main main = Main.getInstance();
105         if (main != null && main.isAlive()) {
106             main.shutdown();
107         }
108     }
109
110     @Test
111     public void testConstructor() throws Exception {
112         assertThatIllegalArgumentException().isThrownBy(() -> new Main("invalidDmaapProvider.json"))
113                         .withMessage("invalid simulator parameters");
114     }
115
116     /**
117      * Verifies that all of 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("/v8/network/generic-vnfs/generic-vnf/my-vnf");
149         assertEquals(200, response.getStatus());
150
151         String result = response.readEntity(String.class);
152         assertThat(result).contains("USUCP0PCOIL0110UJZZ01-vsrx");
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      * Tests buildTopicServer() when the provider class is invalid.
242      */
243     @Test
244     public void testBuildTopicServerInvalidProvider() {
245         assertThatThrownBy(() -> new Main("invalidTopicServer.json").start());
246     }
247
248     /**
249      * Tests buildTopicServer() when the sink is missing.
250      */
251     @Test
252     public void testBuildTopicServerNoSink() {
253         assertThatThrownBy(() -> new Main("missingSink.json").start());
254     }
255
256     /**
257      * Tests buildTopicServer() when the sink is missing.
258      */
259     @Test
260     public void testBuildTopicServerNoSource() {
261         assertThatThrownBy(() -> new Main("missingSource.json").start());
262     }
263 }