2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.aai.sa.rest;
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;
40 import java.io.FileNotFoundException;
41 import java.io.IOException;
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;
48 //import javax.ws.rs.core.Application;
49 //import javax.ws.rs.core.Response;
53 * This suite of tests is intended to exercise the set of REST endpoints
54 * associated with manipulating Indexes in the document store.
56 @RunWith(SpringRunner.class)
59 public class IndexApiTest {
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";
66 private MockMvc mockMvc;
70 // protected Application configure() {
72 // // Make sure that our test endpoint is on the resource path
73 // // for Jersey Test.
74 // return new ResourceConfig(SearchServiceApiHarness.class);
80 * Tests the dynamic shcema creation flow that send the request
81 * JSON to the data store without any JSON validation against a schema
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);
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 ();
96 assertEquals(indexPayload, result.getResponse ().getContentAsString ());
101 * This test validates that the {@link IndexApi} is able to convert {@link OperationResult}
102 * obects to standard REST {@link ResponseEntity} objects.
104 * @throws FileNotFoundException
105 * @throws IOException
106 * @throws DocumentStoreOperationException
109 public void responseFromOperationResultTest() throws FileNotFoundException, IOException, DocumentStoreOperationException {
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!";
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()) {
122 public void init() { /* do nothing */ }
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);
130 // Convert our success OperationResult to a standard REST Response...
131 ResponseEntity successResponse = indexApi.responseFromOperationResult(successResult);
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));
137 // Construct an OperationResult instance with an error code and failure
139 OperationResult failureResult = new OperationResult();
140 failureResult.setResultCode(FAILURE_RESULT_CODE);
141 failureResult.setFailureCause(FAILURE_CAUSE_STRING);
143 // Convert our failure OperationResult to a standard REST Response...
144 ResponseEntity failureResponse = indexApi.responseFromOperationResult(failureResult);
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));
153 // * This test validates the behaviour of the 'Create Index' POST request
156 // * @throws IOException
159 public void createIndexTest() throws Exception {
161 String INDEX_NAME = "test-index";
162 String EXPECTED_SETTINGS =
165 + "{\"nGram_filter\": { "
166 + "\"type\": \"nGram\", "
167 + "\"min_gram\": 1, "
168 + "\"max_gram\": 50, "
169 + "\"token_chars\": [ \"letter\", \"digit\", \"punctuation\", \"symbol\" ]}},"
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 =
181 + "\"serverName\": {"
182 + "\"type\": \"string\", "
183 + "\"index\": \"analyzed\", "
184 + "\"search_analyzer\": \"whitespace\"}, "
185 + "\"serverComplex\": {"
186 + "\"type\": \"string\", "
187 + "\"search_analyzer\": \"whitespace\"}}}";
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);
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 ();
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));
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.
219 public void createIndexWithMangledSchemaTest() throws Exception {
221 String INDEX_NAME = "test-index";
222 int BAD_REQUEST_CODE = 400;
224 String invalidSchemaString = "this is definitely not json!";
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 ();
230 assertEquals("Invalid document schema should result in a 400 error",
231 BAD_REQUEST_CODE, result.getResponse ().getStatus ());
236 * This test validates the behaviour of the 'Delete Index' end point.
239 public void deleteIndexTest() throws Exception {
241 String INDEX_NAME = "test-index";
243 // Send a request to the 'delete index' endpoint.
244 // String result = target(TOP_URI + INDEX_NAME).request().delete(String.class);
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 ( );
251 // Validate that the expected parameters were passed to the document
253 assertTrue("Unexpected index name '" + result.getResponse ().getContentAsString () + "' passed to doc store DAO",
254 result.getResponse ().getContentAsString ().equals(INDEX_NAME));
259 // * This test validates that attempting to delete an index which does not
260 // * exist results in a 404 error.
263 public void deleteIndexDoesNotExistTest() throws Exception {
265 int NOT_FOUND_CODE = 404;
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);
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 ( );
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 ());