Merge "Add docker file for all simulators"
[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("invalidSimParameters.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 = 6666; port <= 6670; ++port) {
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     private void checkAai() throws HttpClientConfigException {
137         BusTopicParams params = BusTopicParams.builder().clientName("client").hostname(HOST).port(6666).useHttps(true)
138                         .allowSelfSignedCerts(true).basePath("aai").build();
139         HttpClient client = HttpClientFactoryInstance.getClientFactory().build(params);
140
141         Response response = client.get("/v8/network/generic-vnfs/generic-vnf/my-vnf");
142         assertEquals(200, response.getStatus());
143
144         String result = response.readEntity(String.class);
145         assertThat(result).contains("USUCP0PCOIL0110UJZZ01-vsrx");
146     }
147
148     /**
149      * Tests readParameters() when the file cannot be found.
150      */
151     @Test
152     public void testReadParametersNoFile() {
153         assertThatIllegalArgumentException().isThrownBy(() -> new Main("missing-file.json"))
154                         .withCauseInstanceOf(FileNotFoundException.class);
155     }
156
157     /**
158      * Tests readParameters() when the json cannot be decoded.
159      */
160     @Test
161     public void testReadParametersInvalidJson() throws CoderException {
162         Coder coder = mock(Coder.class);
163         when(coder.decode(any(String.class), any())).thenThrow(new CoderException(EXPECTED_EXCEPTION));
164
165         assertThatIllegalArgumentException().isThrownBy(() -> new Main(PARAMETER_FILE) {
166             @Override
167             protected Coder makeCoder() {
168                 return coder;
169             }
170         }).withCauseInstanceOf(CoderException.class);
171     }
172
173     /**
174      * Tests buildRestServer() when the server port is not open.
175      */
176     @Test
177     public void testBuildRestServerNotOpen() {
178         HttpServletServer server = mock(HttpServletServer.class);
179
180         Main main = new Main(PARAMETER_FILE) {
181             @Override
182             protected HttpServletServer makeServer(Properties props) {
183                 return server;
184             }
185
186             @Override
187             protected boolean isTcpPortOpen(String hostName, int port) throws InterruptedException {
188                 return false;
189             }
190         };
191
192         assertThatThrownBy(main::start).hasCauseInstanceOf(IllegalStateException.class);
193     }
194
195     /**
196      * Tests buildRestServer() when the port checker is interrupted.
197      */
198     @Test
199     public void testBuildRestServerInterrupted() throws InterruptedException {
200         HttpServletServer server = mock(HttpServletServer.class);
201
202         Main main = new Main(PARAMETER_FILE) {
203             @Override
204             protected HttpServletServer makeServer(Properties props) {
205                 return server;
206             }
207
208             @Override
209             protected boolean isTcpPortOpen(String hostName, int port) throws InterruptedException {
210                 throw new InterruptedException(EXPECTED_EXCEPTION);
211             }
212         };
213
214         // run in another thread so we don't interrupt this thread
215         LinkedBlockingQueue<RuntimeException> queue = new LinkedBlockingQueue<>();
216         Thread thread = new Thread(() -> {
217             try {
218                 main.start();
219             } catch (RuntimeException e) {
220                 queue.add(e);
221             }
222         });
223
224         thread.setDaemon(true);
225         thread.start();
226
227         RuntimeException ex = queue.poll(5, TimeUnit.SECONDS);
228         assertNotNull(ex);
229         assertTrue(ex.getCause() instanceof IllegalStateException);
230         assertThat(ex.getCause()).hasMessageStartingWith("interrupted while building");
231     }
232
233     /**
234      * Tests buildTopicServer() when the provider class is invalid.
235      */
236     @Test
237     public void testBuildTopicServerInvalidProvider() {
238         assertThatThrownBy(() -> new Main("invalidTopicServer.json").start());
239     }
240
241     /**
242      * Tests buildTopicServer() when the sink is missing.
243      */
244     @Test
245     public void testBuildTopicServerNoSink() {
246         assertThatThrownBy(() -> new Main("missingSink.json").start());
247     }
248
249     /**
250      * Tests buildTopicServer() when the sink is missing.
251      */
252     @Test
253     public void testBuildTopicServerNoSource() {
254         assertThatThrownBy(() -> new Main("missingSource.json").start());
255     }
256 }