2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.policy.models.simulators;
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;
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;
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;
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";
64 private static Map<String, String> savedValues;
67 * Saves system properties.
70 public static void setUpBeforeClass() throws IOException, InterruptedException {
71 savedValues = new HashMap<>();
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)) {
78 savedValues.put(prop, System.getProperty(prop));
81 System.setProperty(JettyJerseyServer.SYSTEM_KEYSTORE_PROPERTY_NAME, new SelfSignedKeyStore().getKeystoreName());
82 System.setProperty(JettyJerseyServer.SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME,
83 SelfSignedKeyStore.KEYSTORE_PASSWORD);
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);
92 * Restores system properties.
95 public static void tearDownAfterClass() {
96 for (Entry<String, String> ent : savedValues.entrySet()) {
97 if (ent.getValue() == null) {
98 System.getProperties().remove(ent.getKey());
100 System.setProperty(ent.getKey(), ent.getValue());
106 * Shuts down the simulator instance.
109 public void tearDown() {
110 Main main = Main.getInstance();
111 if (main != null && main.isAlive()) {
117 public void testConstructor() throws Exception {
118 assertThatIllegalArgumentException().isThrownBy(() -> new Main("invalidDmaapProvider.json"))
119 .withMessage("invalid simulator parameters");
123 * Verifies that all the simulators are brought up and that HTTPS works with at
127 public void testMain() throws Exception {
128 Main.main(new String[0]);
129 assertTrue(Main.getInstance() == null || !Main.getInstance().isAlive());
131 Main.main(new String[] {PARAMETER_FILE});
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));
138 // it's sufficient to verify that one of the simulators works
143 public void testMainMinimalParameters() {
144 Main.main(new String[] {"minParameters.json"});
145 assertNotNull(Main.getInstance());
146 assertTrue(Main.getInstance().isAlive());
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);
154 Response response = client.get("/v21/network/pnfs/pnf/demo-pnf");
155 assertEquals(200, response.getStatus());
157 String result = response.readEntity(String.class);
158 assertThat(result).contains("model-123456");
162 * Tests readParameters() when the file cannot be found.
165 public void testReadParametersNoFile() {
166 assertThatIllegalArgumentException().isThrownBy(() -> new Main("missing-file.json"))
167 .withCauseInstanceOf(FileNotFoundException.class);
171 * Tests readParameters() when the json cannot be decoded.
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));
178 assertThatIllegalArgumentException().isThrownBy(() -> new Main(PARAMETER_FILE) {
180 protected Coder makeCoder() {
183 }).withCauseInstanceOf(CoderException.class);
187 * Tests buildRestServer() when the server port is not open.
190 public void testBuildRestServerNotOpen() {
191 HttpServletServer server = mock(HttpServletServer.class);
193 Main main = new Main(PARAMETER_FILE) {
195 protected HttpServletServer makeServer(Properties props) {
200 protected boolean isTcpPortOpen(String hostName, int port) throws InterruptedException {
205 assertThatThrownBy(main::start).hasCauseInstanceOf(IllegalStateException.class);
209 * Tests buildRestServer() when the port checker is interrupted.
212 public void testBuildRestServerInterrupted() throws InterruptedException {
213 HttpServletServer server = mock(HttpServletServer.class);
215 Main main = new Main(PARAMETER_FILE) {
217 protected HttpServletServer makeServer(Properties props) {
222 protected boolean isTcpPortOpen(String hostName, int port) throws InterruptedException {
223 throw new InterruptedException(EXPECTED_EXCEPTION);
227 // run in another thread, so we don't interrupt this thread
228 LinkedBlockingQueue<RuntimeException> queue = new LinkedBlockingQueue<>();
229 Thread thread = new Thread(() -> {
232 } catch (RuntimeException e) {
237 thread.setDaemon(true);
240 RuntimeException ex = queue.poll(5, TimeUnit.SECONDS);
242 assertTrue(ex.getCause() instanceof IllegalStateException);
243 assertThat(ex.getCause()).hasMessageStartingWith("interrupted while building");
247 * Tests buildTopicServer() when the provider class is invalid.
250 public void testBuildTopicServerInvalidProvider() {
251 assertThatThrownBy(() -> new Main("invalidTopicServer.json").start())
252 .hasCauseInstanceOf(IllegalArgumentException.class);
256 * Tests buildTopicServer() when the sink is missing.
259 public void testBuildTopicServerNoSink() {
260 assertThatThrownBy(() -> new Main("missingSink.json").start())
261 .hasCauseInstanceOf(IllegalArgumentException.class);
265 * Tests buildTopicServer() when the sink is missing.
268 public void testBuildTopicServerNoSource() {
269 assertThatThrownBy(() -> new Main("missingSource.json").start())
270 .hasCauseInstanceOf(IllegalArgumentException.class);