Merge "Fixed broken unittest in policy agent"
[nonrtric.git] / enrichment-coordinator-service / src / test / java / org / oransc / enrichment / ApplicationTest.java
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2019-2020 Nordix Foundation. 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.oransc.enrichment;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.junit.jupiter.api.Assertions.assertTrue;
25
26 import com.google.gson.Gson;
27 import com.google.gson.GsonBuilder;
28 import com.google.gson.JsonElement;
29 import com.google.gson.JsonObject;
30 import com.google.gson.JsonPrimitive;
31
32 import org.junit.jupiter.api.BeforeEach;
33 import org.junit.jupiter.api.Test;
34 import org.junit.jupiter.api.extension.ExtendWith;
35 import org.oransc.enrichment.clients.AsyncRestClient;
36 import org.oransc.enrichment.configuration.ApplicationConfig;
37 import org.oransc.enrichment.configuration.ImmutableWebClientConfig;
38 import org.oransc.enrichment.configuration.WebClientConfig;
39 import org.oransc.enrichment.controllers.consumer.ConsumerConsts;
40 import org.oransc.enrichment.controllers.consumer.ConsumerEiJobInfo;
41 import org.oransc.enrichment.repository.EiJob;
42 import org.oransc.enrichment.repository.EiJobs;
43 import org.oransc.enrichment.repository.EiType;
44 import org.oransc.enrichment.repository.EiTypes;
45 import org.oransc.enrichment.repository.ImmutableEiJob;
46 import org.oransc.enrichment.repository.ImmutableEiType;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.boot.test.context.SpringBootTest;
51 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
52 import org.springframework.boot.test.context.TestConfiguration;
53 import org.springframework.boot.web.server.LocalServerPort;
54 import org.springframework.context.ApplicationContext;
55 import org.springframework.http.HttpStatus;
56 import org.springframework.http.MediaType;
57 import org.springframework.http.ResponseEntity;
58 import org.springframework.test.context.TestPropertySource;
59 import org.springframework.test.context.junit.jupiter.SpringExtension;
60 import org.springframework.web.reactive.function.client.WebClientResponseException;
61
62 import reactor.core.publisher.Mono;
63 import reactor.test.StepVerifier;
64
65 @ExtendWith(SpringExtension.class)
66 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
67 @TestPropertySource(
68     properties = { //
69         "server.ssl.key-store=./config/keystore.jks", //
70         "app.webclient.trust-store=./config/truststore.jks"})
71 class ApplicationTest {
72     private static final Logger logger = LoggerFactory.getLogger(ApplicationTest.class);
73
74     @Autowired
75     ApplicationContext context;
76
77     @Autowired
78     EiJobs eiJobs;
79
80     @Autowired
81     EiTypes eiTypes;
82
83     @Autowired
84     ApplicationConfig applicationConfig;
85
86     private static Gson gson = new GsonBuilder() //
87         .serializeNulls() //
88         .create(); //
89
90     /**
91      * Overrides the BeanFactory.
92      */
93     @TestConfiguration
94     static class TestBeanFactory {
95
96     }
97
98     @LocalServerPort
99     private int port;
100
101     @BeforeEach
102     void reset() {
103         this.eiJobs.clear();
104         this.eiTypes.clear();
105     }
106
107     @Test
108     void getEiTypes() throws Exception {
109         addEiType("test");
110         String url = "/eitypes";
111         String rsp = restClient().get(url).block();
112         assertThat(rsp).isEqualTo("[\"test\"]");
113     }
114
115     @Test
116     void getEiType() throws Exception {
117         addEiType("test");
118         String url = "/eitypes/test";
119         String rsp = restClient().get(url).block();
120         assertThat(rsp).contains("job_data_schema");
121     }
122
123     @Test
124     void getEiTypeNotFound() throws Exception {
125         String url = "/eitypes/junk";
126         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND, "Could not find EI Job: junk");
127     }
128
129     @Test
130     void getEiJobsIds() throws Exception {
131         addEiJob("typeId", "jobId");
132         String url = "/eitypes/typeId/eijobs";
133         String rsp = restClient().get(url).block();
134         assertThat(rsp).isEqualTo("[\"jobId\"]");
135     }
136
137     @Test
138     void getEiJobTypeNotFound() throws Exception {
139         String url = "/eitypes/junk/eijobs";
140         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND, "Could not find EI Job: junk");
141     }
142
143     @Test
144     void getEiJob() throws Exception {
145         addEiJob("typeId", "jobId");
146         String url = "/eitypes/typeId/eijobs/jobId";
147         String rsp = restClient().get(url).block();
148         assertThat(rsp).contains("job_data");
149     }
150
151     @Test
152     void getEiJobStatus() throws Exception {
153         addEiJob("typeId", "jobId");
154         String url = "/eitypes/typeId/eijobs/jobId/status";
155         String rsp = restClient().get(url).block();
156         assertThat(rsp).contains("ENABLED");
157     }
158
159     // Status TBD
160
161     @Test
162     void deleteEiJob() throws Exception {
163         addEiJob("typeId", "jobId");
164         assertThat(this.eiJobs.size()).isEqualTo(1);
165         String url = "/eitypes/typeId/eijobs/jobId";
166         restClient().delete(url).block();
167         assertThat(this.eiJobs.size()).isEqualTo(0);
168     }
169
170     @Test
171     void putEiJob() throws Exception {
172         addEiType("typeId");
173
174         String url = "/eitypes/typeId/eijobs/jobId";
175         String body = gson.toJson(eiJobInfo());
176         ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
177         assertThat(this.eiJobs.size()).isEqualTo(1);
178         assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.CREATED);
179
180         resp = restClient().putForEntity(url, body).block();
181         assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
182         EiJob job = this.eiJobs.getJob("jobId");
183         assertThat(job.owner()).isEqualTo("owner");
184     }
185
186     ConsumerEiJobInfo eiJobInfo() {
187         return new ConsumerEiJobInfo(jsonObject(), "owner");
188     }
189
190     // @Test
191     @SuppressWarnings("squid:S2699")
192     void runMock() throws Exception {
193         logger.info("Keeping server alive! " + this.port);
194         synchronized (this) {
195             this.wait();
196         }
197     }
198
199     JsonObject jsonObject() {
200         JsonObject jsonObj = new JsonObject();
201         JsonElement e = new JsonPrimitive(111);
202         jsonObj.add("param", e);
203         return jsonObj;
204     }
205
206     private EiJob addEiJob(String typeId, String jobId) {
207         addEiType(typeId);
208         EiJob job = ImmutableEiJob.builder() //
209             .id(jobId) //
210             .typeId(typeId) //
211             .owner("owner") //
212             .jobData(jsonObject()) //
213             .build();
214         this.eiJobs.put(job);
215         return job;
216     }
217
218     private EiType addEiType(String typeId) {
219         EiType t = ImmutableEiType.builder() //
220             .id(typeId) //
221             .jobDataSchema(jsonObject()) //
222             .build();
223         this.eiTypes.put(t);
224         return t;
225     }
226
227     private String baseUrl() {
228         return "https://localhost:" + this.port + ConsumerConsts.A1E_API_ROOT;
229     }
230
231     private AsyncRestClient restClient(boolean useTrustValidation) {
232         WebClientConfig config = this.applicationConfig.getWebClientConfig();
233         config = ImmutableWebClientConfig.builder() //
234             .keyStoreType(config.keyStoreType()) //
235             .keyStorePassword(config.keyStorePassword()) //
236             .keyStore(config.keyStore()) //
237             .keyPassword(config.keyPassword()) //
238             .isTrustStoreUsed(useTrustValidation) //
239             .trustStore(config.trustStore()) //
240             .trustStorePassword(config.trustStorePassword()) //
241             .build();
242
243         return new AsyncRestClient(baseUrl(), config);
244     }
245
246     private AsyncRestClient restClient() {
247         return restClient(false);
248     }
249
250     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
251         testErrorCode(request, expStatus, responseContains, true);
252     }
253
254     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
255         boolean expectApplicationProblemJsonMediaType) {
256         StepVerifier.create(request) //
257             .expectSubscription() //
258             .expectErrorMatches(
259                 t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType)) //
260             .verify();
261     }
262
263     private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
264         boolean expectApplicationProblemJsonMediaType) {
265         assertTrue(throwable instanceof WebClientResponseException);
266         WebClientResponseException responseException = (WebClientResponseException) throwable;
267         assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
268         assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
269         if (expectApplicationProblemJsonMediaType) {
270             assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
271         }
272         return true;
273     }
274
275 }