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