Organise imports to ONAP Java standards
[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 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
54  * associated with manipulating Indexes in the 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
86    * JSON to the data store without any JSON validation 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.perform ( put (dynamicUri + indexName)
99             .contentType ( MediaType.APPLICATION_JSON ).content ( indexPayload )).andReturn ();
100
101     assertEquals(indexPayload, result.getResponse ().getContentAsString ());
102   }
103
104
105   /**
106    * This test validates that the {@link IndexApi} is able to convert {@link OperationResult}
107    * obects to standard REST {@link ResponseEntity} objects.
108    *
109    * @throws FileNotFoundException
110    * @throws IOException
111    * @throws DocumentStoreOperationException
112    */
113   @Test
114   public void responseFromOperationResultTest() throws FileNotFoundException, IOException, DocumentStoreOperationException {
115
116     int SUCCESS_RESULT_CODE = 200;
117     String SUCCESS_RESULT_STRING = "Everything is ay-okay!";
118     int FAILURE_RESULT_CODE = 500;
119     String FAILURE_CAUSE_STRING = "Something went wrong!";
120
121
122     // Create an instance of the index API endpoint that we will test against.
123     // We will override the init() method because we don't want it to try to
124     // connect to a real document store.
125     IndexApi indexApi = new IndexApi(new SearchServiceApiHarness()) {
126       @Override
127       public void init() { /* do nothing */ }
128     };
129 //
130     //Construct an OperationResult instance with a success code and string.
131     OperationResult successResult = new OperationResult();
132     successResult.setResultCode(SUCCESS_RESULT_CODE);
133     successResult.setResult(SUCCESS_RESULT_STRING);
134
135     // Convert our success OperationResult to a standard REST Response...
136     ResponseEntity successResponse = indexApi.responseFromOperationResult(successResult);
137
138     // ...and validate that the Response is correctly populated.
139     assertEquals("Unexpected result code", SUCCESS_RESULT_CODE, successResponse.getStatusCodeValue ());
140     assertTrue("Incorrect result string", ((String) successResponse.getBody ()).equals(SUCCESS_RESULT_STRING));
141
142     // Construct an OperationResult instance with an error code and failure
143     // cause.
144     OperationResult failureResult = new OperationResult();
145     failureResult.setResultCode(FAILURE_RESULT_CODE);
146     failureResult.setFailureCause(FAILURE_CAUSE_STRING);
147
148     // Convert our failure OperationResult to a standard REST Response...
149     ResponseEntity failureResponse = indexApi.responseFromOperationResult(failureResult);
150
151     // ...and validate that the Response is correctly populated.
152     assertEquals("Unexpected result code", FAILURE_RESULT_CODE, failureResponse.getStatusCodeValue ());
153     assertTrue("Incorrect result string", ((String) failureResponse.getBody ()).equals(FAILURE_CAUSE_STRING));
154   }
155 //
156 //
157 //  /**
158 //   * This test validates the behaviour of the 'Create Index' POST request
159 //   * endpoint.
160 //   *
161 //   * @throws IOException
162 //   */
163   @Test
164   public void createIndexTest() throws Exception {
165
166     String INDEX_NAME = "test-index";
167     String EXPECTED_SETTINGS =
168         "{\"analysis\": "
169             + "{\"filter\": "
170             + "{\"nGram_filter\": { "
171             + "\"type\": \"nGram\", "
172             + "\"min_gram\": 1, "
173             + "\"max_gram\": 50, "
174             + "\"token_chars\": [ \"letter\", \"digit\", \"punctuation\", \"symbol\" ]}},"
175             + "\"analyzer\": {"
176             + "\"nGram_analyzer\": "
177             + "{\"type\": \"custom\","
178             + "\"tokenizer\": \"whitespace\","
179             + "\"filter\": [\"lowercase\",\"asciifolding\",\"nGram_filter\"]},"
180             + "\"whitespace_analyzer\": "
181             + "{\"type\": \"custom\","
182             + "\"tokenizer\": \"whitespace\","
183             + "\"filter\": [\"lowercase\",\"asciifolding\"]}}}}";
184     String EXPECTED_MAPPINGS =
185         "{\"dynamic_templates\":[{\"strings\":{\"match_mapping_type\":\"string\",\"match\":\"*\",\"mapping\":{\"type\":\"text\",\"fielddata\":true}}}]"
186         + ",\"properties\": {"
187             + "\"serverName\": {"
188             + "\"type\": \"string\", "
189             + "\"index\": \"analyzed\", "
190             + "\"search_analyzer\": \"whitespace\"}, "
191             + "\"serverComplex\": {"
192             + "\"type\": \"string\", "
193             + "\"search_analyzer\": \"whitespace\"}}}";
194
195     // Read a valid document schema from a json file.
196     File schemaFile = new File(SIMPLE_DOC_SCHEMA_JSON);
197     String documentJson = TestUtils.readFileToString(schemaFile);
198
199     // Send a request to our 'create index' endpoint, using the schema
200     // which we just read.
201     // String result = target(TOP_URI + INDEX_NAME).request().put(Entity.json(documentJson), String.class);
202     MvcResult result = this.mockMvc.perform ( put ( TOP_URI + INDEX_NAME ).contentType ( MediaType.APPLICATION_JSON )
203             .content ( documentJson) ).andReturn ();
204
205
206     // Our stub document store DAO returns the parameters that it was
207     // passed as the result string, so now we can validate that our
208     // endpoint invoked it with the correct parameters.
209     String[] tokenizedResult = result.getResponse ().getContentAsString ().split("@");
210     assertTrue("Unexpected Index Name '" + tokenizedResult[0] + "' passed to doc store DAO",
211         tokenizedResult[0].equals(INDEX_NAME));
212     assertTrue("Unexpected settings string '" + tokenizedResult[1] + "' passed to doc store DAO",
213         tokenizedResult[1].equals(EXPECTED_SETTINGS));
214     assertTrue("Unexpected mappings string '" + tokenizedResult[2] + "' passed to doc store DAO",
215         tokenizedResult[2].equals(EXPECTED_MAPPINGS));
216   }
217 //
218 //
219   /**
220    * This test validates that a 'create index' request with an improperly
221    * formatted document schema as the payload will result in an
222    * appropriate error being returned from the endpoint.
223    */
224   @Test
225   public void createIndexWithMangledSchemaTest() throws Exception {
226
227     String INDEX_NAME = "test-index";
228     int BAD_REQUEST_CODE = 400;
229
230     String invalidSchemaString = "this is definitely not json!";
231
232     // ResponseEntity result = target(TOP_URI + INDEX_NAME).request().put(Entity.json(invalidSchemaString), ResponseEntity.class);
233     MvcResult result = this.mockMvc.perform ( put ( TOP_URI + INDEX_NAME ).contentType ( MediaType.APPLICATION_JSON )
234             .content ( invalidSchemaString) ).andReturn ();
235
236     assertEquals("Invalid document schema should result in a 400 error",
237         BAD_REQUEST_CODE, result.getResponse ().getStatus ());
238   }
239 //
240 //
241   /**
242    * This test validates the behaviour of the 'Delete Index' end point.
243    */
244   @Test
245   public void deleteIndexTest() throws Exception {
246
247     String INDEX_NAME = "test-index";
248
249     // Send a request to the 'delete index' endpoint.
250     // String result = target(TOP_URI + INDEX_NAME).request().delete(String.class);
251
252     MvcResult result = this.mockMvc.perform ( delete ( TOP_URI + INDEX_NAME )
253             .contentType ( MediaType.APPLICATION_JSON )
254             .header ( "If-Match", "1" )
255             .content ( "Some Json" ) ).andReturn ( );
256
257     // Validate that the expected parameters were passed to the document
258     // store DAO.
259     assertTrue("Unexpected index name '" + result.getResponse ().getContentAsString () + "' passed to doc store DAO",
260         result.getResponse ().getContentAsString ().equals(INDEX_NAME));
261   }
262 //
263 //
264 //  /**
265 //   * This test validates that attempting to delete an index which does not
266 //   * exist results in a 404 error.
267 //   */
268   @Test
269   public void deleteIndexDoesNotExistTest() throws Exception {
270
271     int NOT_FOUND_CODE = 404;
272
273     // Send a request to the 'delete index' endpoint, specifying a
274     // non-existent index.
275     // ResponseEntity result = target(TOP_URI + StubEsController.DOES_NOT_EXIST_INDEX).request().delete(ResponseEntity.class);
276
277     MvcResult result = this.mockMvc.perform ( delete ( TOP_URI + StubEsController.DOES_NOT_EXIST_INDEX )
278             .contentType ( MediaType.APPLICATION_JSON )
279             .header ( "If-Match", "1" )
280             .content ( "Some Json" ) ).andReturn ( );
281
282
283     // Validate that a 404 error code is returned from the end point.
284     assertEquals("Deleting an index which does not exist should result in a 404 error",
285         NOT_FOUND_CODE, result.getResponse ().getStatus ());
286   }
287 }