Update poms to conform to merge job requirements
[aai/search-data-service.git] / search-data-service-app / src / test / java / org / onap / aai / sa / rest / IndexApiTest.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
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
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  */
21 package org.onap.aai.sa.rest;
22
23
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertTrue;
26 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
27 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
28
29 import java.io.File;
30 import java.io.FileNotFoundException;
31 import java.io.IOException;
32 import org.junit.Before;
33 // import org.glassfish.jersey.server.ResourceConfig;
34 // import org.glassfish.jersey.test.JerseyTest;
35 import org.junit.Test;
36 import org.junit.runner.RunWith;
37 import org.onap.aai.sa.searchdbabstraction.elasticsearch.exception.DocumentStoreOperationException;
38 import org.onap.aai.sa.searchdbabstraction.entity.OperationResult;
39 import org.springframework.beans.factory.annotation.Autowired;
40 import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
41 import org.springframework.boot.test.context.SpringBootTest;
42 import org.springframework.http.MediaType;
43 import org.springframework.http.ResponseEntity;
44 import org.springframework.test.context.junit4.SpringRunner;
45 import org.springframework.test.web.servlet.MockMvc;
46 import org.springframework.test.web.servlet.MvcResult;
47
48 //import javax.ws.rs.core.Application;
49 //import javax.ws.rs.core.Response;
50
51
52 /**
53  * This suite of tests is intended to exercise the set of REST endpoints associated with manipulating Indexes in the
54  * document store.
55  */
56 @RunWith(SpringRunner.class)
57 @SpringBootTest
58 @AutoConfigureMockMvc
59 public class IndexApiTest {
60
61     private final String TOP_URI = "/test/indexes/";
62     private final String SIMPLE_DOC_SCHEMA_JSON = "src/test/resources/json/simpleDocument.json";
63     private final String DYNAMIC_INDEX_PAYLOAD = "src/test/resources/json/dynamicIndex.json";
64
65     @Autowired
66     private MockMvc mockMvc;
67
68     //
69     // @Override
70     // protected Application configure() {
71     //
72     // // Make sure that our test endpoint is on the resource path
73     // // for Jersey Test.
74     // return new ResourceConfig(SearchServiceApiHarness.class);
75     // }
76     //
77     //
78
79     @Before
80     public void setup() throws Exception {
81         System.setProperty("CONFIG_HOME", System.getProperty("user.dir") + File.separator + "src/test/resources/json");
82     }
83
84     /**
85      * Tests the dynamic shcema creation flow that send the request JSON to the data store without any JSON validation
86      * against a schema
87      *
88      * @throws IOException
89      */
90     @Test
91     public void createDynamicIndexTest() throws Exception {
92         String indexName = "super-ultra-dynamic-mega-index";
93         String dynamicUri = TOP_URI + "dynamic/";
94         File indexFile = new File(DYNAMIC_INDEX_PAYLOAD);
95         String indexPayload = TestUtils.readFileToString(indexFile);
96
97         // String result = target(dynamicUri + indexName).request().put(Entity.json(indexPayload), String.class);
98         MvcResult result = this.mockMvc
99                 .perform(put(dynamicUri + indexName).contentType(MediaType.APPLICATION_JSON).content(indexPayload))
100                 .andReturn();
101
102         assertEquals(indexPayload, result.getResponse().getContentAsString());
103     }
104
105
106     /**
107      * This test validates that the {@link IndexApi} is able to convert {@link OperationResult} obects to standard REST
108      * {@link ResponseEntity} objects.
109      *
110      * @throws FileNotFoundException
111      * @throws IOException
112      * @throws DocumentStoreOperationException
113      */
114     @Test
115     public void responseFromOperationResultTest()
116             throws FileNotFoundException, IOException, DocumentStoreOperationException {
117
118         int SUCCESS_RESULT_CODE = 200;
119         String SUCCESS_RESULT_STRING = "Everything is ay-okay!";
120         int FAILURE_RESULT_CODE = 500;
121         String FAILURE_CAUSE_STRING = "Something went wrong!";
122
123
124         // Create an instance of the index API endpoint that we will test against.
125         // We will override the init() method because we don't want it to try to
126         // connect to a real document store.
127         IndexApi indexApi = new IndexApi(new SearchServiceApiHarness()) {
128             @Override
129             public void init() { /* do nothing */ }
130         };
131         //
132         // Construct an OperationResult instance with a success code and string.
133         OperationResult successResult = new OperationResult();
134         successResult.setResultCode(SUCCESS_RESULT_CODE);
135         successResult.setResult(SUCCESS_RESULT_STRING);
136
137         // Convert our success OperationResult to a standard REST Response...
138         ResponseEntity<?> successResponse = indexApi.responseFromOperationResult(successResult);
139
140         // ...and validate that the Response is correctly populated.
141         assertEquals("Unexpected result code", SUCCESS_RESULT_CODE, successResponse.getStatusCodeValue());
142         assertTrue("Incorrect result string", ((String) successResponse.getBody()).equals(SUCCESS_RESULT_STRING));
143
144         // Construct an OperationResult instance with an error code and failure
145         // cause.
146         OperationResult failureResult = new OperationResult();
147         failureResult.setResultCode(FAILURE_RESULT_CODE);
148         failureResult.setFailureCause(FAILURE_CAUSE_STRING);
149
150         // Convert our failure OperationResult to a standard REST Response...
151         ResponseEntity<?> failureResponse = indexApi.responseFromOperationResult(failureResult);
152
153         // ...and validate that the Response is correctly populated.
154         assertEquals("Unexpected result code", FAILURE_RESULT_CODE, failureResponse.getStatusCodeValue());
155         assertTrue("Incorrect result string", ((String) failureResponse.getBody()).equals(FAILURE_CAUSE_STRING));
156     }
157
158     //
159     //
160     // /**
161     // * This test validates the behaviour of the 'Create Index' POST request
162     // * endpoint.
163     // *
164     // * @throws IOException
165     // */
166     @Test
167     public void createIndexTest() throws Exception {
168
169         String INDEX_NAME = "test-index";
170         String EXPECTED_SETTINGS = "{\"analysis\": " + "{\"filter\": " + "{\"nGram_filter\": { "
171                 + "\"type\": \"nGram\", " + "\"min_gram\": 1, " + "\"max_gram\": 50, "
172                 + "\"token_chars\": [ \"letter\", \"digit\", \"punctuation\", \"symbol\" ]}}," + "\"analyzer\": {"
173                 + "\"nGram_analyzer\": " + "{\"type\": \"custom\"," + "\"tokenizer\": \"whitespace\","
174                 + "\"filter\": [\"lowercase\",\"asciifolding\",\"nGram_filter\"]}," + "\"whitespace_analyzer\": "
175                 + "{\"type\": \"custom\"," + "\"tokenizer\": \"whitespace\","
176                 + "\"filter\": [\"lowercase\",\"asciifolding\"]}}}}";
177         String EXPECTED_MAPPINGS =
178                 "{\"dynamic_templates\":[{\"strings\":{\"match_mapping_type\":\"string\",\"match\":\"*\",\"mapping\":{\"type\":\"text\",\"fielddata\":true}}}]"
179                         + ",\"properties\": {" + "\"serverName\": {" + "\"type\": \"string\", "
180                         + "\"index\": \"analyzed\", " + "\"search_analyzer\": \"whitespace\"}, "
181                         + "\"serverComplex\": {" + "\"type\": \"string\", " + "\"search_analyzer\": \"whitespace\"}}}";
182
183         // Read a valid document schema from a json file.
184         File schemaFile = new File(SIMPLE_DOC_SCHEMA_JSON);
185         String documentJson = TestUtils.readFileToString(schemaFile);
186
187         // Send a request to our 'create index' endpoint, using the schema
188         // which we just read.
189         // String result = target(TOP_URI + INDEX_NAME).request().put(Entity.json(documentJson), String.class);
190         MvcResult result = this.mockMvc
191                 .perform(put(TOP_URI + INDEX_NAME).contentType(MediaType.APPLICATION_JSON).content(documentJson))
192                 .andReturn();
193
194
195         // Our stub document store DAO returns the parameters that it was
196         // passed as the result string, so now we can validate that our
197         // endpoint invoked it with the correct parameters.
198         String[] tokenizedResult = result.getResponse().getContentAsString().split("@");
199         assertTrue("Unexpected Index Name '" + tokenizedResult[0] + "' passed to doc store DAO",
200                 tokenizedResult[0].equals(INDEX_NAME));
201         assertTrue("Unexpected settings string '" + tokenizedResult[1] + "' passed to doc store DAO",
202                 tokenizedResult[1].equals(EXPECTED_SETTINGS));
203         assertTrue("Unexpected mappings string '" + tokenizedResult[2] + "' passed to doc store DAO",
204                 tokenizedResult[2].equals(EXPECTED_MAPPINGS));
205     }
206
207     //
208     //
209     /**
210      * This test validates that a 'create index' request with an improperly formatted document schema as the payload
211      * will result in an appropriate error being returned from the endpoint.
212      */
213     @Test
214     public void createIndexWithMangledSchemaTest() throws Exception {
215
216         String INDEX_NAME = "test-index";
217         int BAD_REQUEST_CODE = 400;
218
219         String invalidSchemaString = "this is definitely not json!";
220
221         // ResponseEntity result = target(TOP_URI + INDEX_NAME).request().put(Entity.json(invalidSchemaString),
222         // ResponseEntity.class);
223         MvcResult result = this.mockMvc
224                 .perform(put(TOP_URI + INDEX_NAME).contentType(MediaType.APPLICATION_JSON).content(invalidSchemaString))
225                 .andReturn();
226
227         assertEquals("Invalid document schema should result in a 400 error", BAD_REQUEST_CODE,
228                 result.getResponse().getStatus());
229     }
230
231     //
232     //
233     /**
234      * This test validates the behaviour of the 'Delete Index' end point.
235      */
236     @Test
237     public void deleteIndexTest() throws Exception {
238
239         String INDEX_NAME = "test-index";
240
241         // Send a request to the 'delete index' endpoint.
242         // String result = target(TOP_URI + INDEX_NAME).request().delete(String.class);
243
244         MvcResult result = this.mockMvc.perform(delete(TOP_URI + INDEX_NAME).contentType(MediaType.APPLICATION_JSON)
245                 .header("If-Match", "1").content("Some Json")).andReturn();
246
247         // Validate that the expected parameters were passed to the document
248         // store DAO.
249         assertTrue("Unexpected index name '" + result.getResponse().getContentAsString() + "' passed to doc store DAO",
250                 result.getResponse().getContentAsString().equals(INDEX_NAME));
251     }
252
253     //
254     //
255     // /**
256     // * This test validates that attempting to delete an index which does not
257     // * exist results in a 404 error.
258     // */
259     @Test
260     public void deleteIndexDoesNotExistTest() throws Exception {
261
262         int NOT_FOUND_CODE = 404;
263
264         // Send a request to the 'delete index' endpoint, specifying a
265         // non-existent index.
266         // ResponseEntity result = target(TOP_URI +
267         // StubEsController.DOES_NOT_EXIST_INDEX).request().delete(ResponseEntity.class);
268
269         MvcResult result =
270                 this.mockMvc
271                         .perform(delete(TOP_URI + StubEsController.DOES_NOT_EXIST_INDEX)
272                                 .contentType(MediaType.APPLICATION_JSON).header("If-Match", "1").content("Some Json"))
273                         .andReturn();
274
275
276         // Validate that a 404 error code is returned from the end point.
277         assertEquals("Deleting an index which does not exist should result in a 404 error", NOT_FOUND_CODE,
278                 result.getResponse().getStatus());
279     }
280 }