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 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;
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;
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 public void setup() throws Exception {
81 System.setProperty("CONFIG_HOME", System.getProperty("user.dir")+ File.separator + "src/test/resources/json");
85 * Tests the dynamic shcema creation flow that send the request
86 * JSON to the data store without any JSON validation against a schema
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);
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 ();
101 assertEquals(indexPayload, result.getResponse ().getContentAsString ());
106 * This test validates that the {@link IndexApi} is able to convert {@link OperationResult}
107 * obects to standard REST {@link ResponseEntity} objects.
109 * @throws FileNotFoundException
110 * @throws IOException
111 * @throws DocumentStoreOperationException
114 public void responseFromOperationResultTest() throws FileNotFoundException, IOException, DocumentStoreOperationException {
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!";
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()) {
127 public void init() { /* do nothing */ }
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);
135 // Convert our success OperationResult to a standard REST Response...
136 ResponseEntity successResponse = indexApi.responseFromOperationResult(successResult);
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));
142 // Construct an OperationResult instance with an error code and failure
144 OperationResult failureResult = new OperationResult();
145 failureResult.setResultCode(FAILURE_RESULT_CODE);
146 failureResult.setFailureCause(FAILURE_CAUSE_STRING);
148 // Convert our failure OperationResult to a standard REST Response...
149 ResponseEntity failureResponse = indexApi.responseFromOperationResult(failureResult);
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));
158 // * This test validates the behaviour of the 'Create Index' POST request
161 // * @throws IOException
164 public void createIndexTest() throws Exception {
166 String INDEX_NAME = "test-index";
167 String EXPECTED_SETTINGS =
170 + "{\"nGram_filter\": { "
171 + "\"type\": \"nGram\", "
172 + "\"min_gram\": 1, "
173 + "\"max_gram\": 50, "
174 + "\"token_chars\": [ \"letter\", \"digit\", \"punctuation\", \"symbol\" ]}},"
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\"}}}";
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);
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 ();
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));
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.
225 public void createIndexWithMangledSchemaTest() throws Exception {
227 String INDEX_NAME = "test-index";
228 int BAD_REQUEST_CODE = 400;
230 String invalidSchemaString = "this is definitely not json!";
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 ();
236 assertEquals("Invalid document schema should result in a 400 error",
237 BAD_REQUEST_CODE, result.getResponse ().getStatus ());
242 * This test validates the behaviour of the 'Delete Index' end point.
245 public void deleteIndexTest() throws Exception {
247 String INDEX_NAME = "test-index";
249 // Send a request to the 'delete index' endpoint.
250 // String result = target(TOP_URI + INDEX_NAME).request().delete(String.class);
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 ( );
257 // Validate that the expected parameters were passed to the document
259 assertTrue("Unexpected index name '" + result.getResponse ().getContentAsString () + "' passed to doc store DAO",
260 result.getResponse ().getContentAsString ().equals(INDEX_NAME));
265 // * This test validates that attempting to delete an index which does not
266 // * exist results in a 404 error.
269 public void deleteIndexDoesNotExistTest() throws Exception {
271 int NOT_FOUND_CODE = 404;
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);
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 ( );
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 ());