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