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