f63ddbda4236dfed6476c94bd37b39da1ca2f6ae
[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.onap.aai.sa.rest.IndexApi;
28 import org.onap.aai.sa.searchdbabstraction.elasticsearch.exception.DocumentStoreOperationException;
29 import org.onap.aai.sa.searchdbabstraction.entity.OperationResult;
30
31 import javax.ws.rs.client.Entity;
32 import javax.ws.rs.core.Application;
33 import javax.ws.rs.core.Response;
34 import java.io.*;
35
36 import static org.junit.Assert.assertEquals;
37 import static org.junit.Assert.assertTrue;
38
39
40 /**
41  * This suite of tests is intended to exercise the set of REST endpoints
42  * associated with manipulating Indexes in the document store.
43  */
44 public class IndexApiTest extends JerseyTest {
45
46   private final String TOP_URI = "/test/indexes/";
47   private final String SIMPLE_DOC_SCHEMA_JSON = "src/test/resources/json/simpleDocument.json";
48   private final String DYNAMIC_INDEX_PAYLOAD = "src/test/resources/json/dynamicIndex.json";
49
50   @Override
51   protected Application configure() {
52
53     // Make sure that our test endpoint is on the resource path
54     // for Jersey Test.
55     return new ResourceConfig(SearchServiceApiHarness.class);
56   }
57
58
59   /**
60    * This test validates that the {@link IndexApi} is able to convert {@link OperationResult}
61    * obects to standard REST {@link Response} objects.
62    *
63    * @throws FileNotFoundException
64    * @throws IOException
65    * @throws DocumentStoreOperationException
66    */
67   @Test
68   public void responseFromOperationResultTest() throws FileNotFoundException, IOException, DocumentStoreOperationException {
69
70     int SUCCESS_RESULT_CODE = 200;
71     String SUCCESS_RESULT_STRING = "Everything is ay-okay!";
72     int FAILURE_RESULT_CODE = 500;
73     String FAILURE_CAUSE_STRING = "Something went wrong!";
74
75
76     // Create an instance of the index API endpoint that we will test against.
77     // We will override the init() method because we don't want it to try to
78     // connect to a real document store.
79     IndexApi indexApi = new IndexApi(new SearchServiceApiHarness()) {
80       @Override
81       public void init() { /* do nothing */ }
82     };
83
84     //Construct an OperationResult instance with a success code and string.
85     OperationResult successResult = new OperationResult();
86     successResult.setResultCode(SUCCESS_RESULT_CODE);
87     successResult.setResult(SUCCESS_RESULT_STRING);
88
89     // Convert our success OperationResult to a standard REST Response...
90     Response successResponse = indexApi.responseFromOperationResult(successResult);
91
92     // ...and validate that the Response is correctly populated.
93     assertEquals("Unexpected result code", SUCCESS_RESULT_CODE, successResponse.getStatus());
94     assertTrue("Incorrect result string", ((String) successResponse.getEntity()).equals(SUCCESS_RESULT_STRING));
95
96     // Construct an OperationResult instance with an error code and failure
97     // cause.
98     OperationResult failureResult = new OperationResult();
99     failureResult.setResultCode(FAILURE_RESULT_CODE);
100     failureResult.setFailureCause(FAILURE_CAUSE_STRING);
101
102     // Convert our failure OperationResult to a standard REST Response...
103     Response failureResponse = indexApi.responseFromOperationResult(failureResult);
104
105     // ...and validate that the Response is correctly populated.
106     assertEquals("Unexpected result code", FAILURE_RESULT_CODE, failureResponse.getStatus());
107     assertTrue("Incorrect result string", ((String) failureResponse.getEntity()).equals(FAILURE_CAUSE_STRING));
108   }
109
110
111   /**
112    * This test validates the behaviour of the 'Create Index' POST request
113    * endpoint.
114    *
115    * @throws IOException
116    */
117   @Test
118   public void createIndexTest() throws IOException {
119
120     String INDEX_NAME = "test-index";
121     String EXPECTED_SETTINGS =
122         "{\"analysis\": "
123             + "{\"filter\": "
124             + "{\"nGram_filter\": { "
125             + "\"type\": \"nGram\", "
126             + "\"min_gram\": 1, "
127             + "\"max_gram\": 50, "
128             + "\"token_chars\": [ \"letter\", \"digit\", \"punctuation\", \"symbol\" ]}},"
129             + "\"analyzer\": {"
130             + "\"nGram_analyzer\": "
131             + "{\"type\": \"custom\","
132             + "\"tokenizer\": \"whitespace\","
133             + "\"filter\": [\"lowercase\",\"asciifolding\",\"nGram_filter\"]},"
134             + "\"whitespace_analyzer\": "
135             + "{\"type\": \"custom\","
136             + "\"tokenizer\": \"whitespace\","
137             + "\"filter\": [\"lowercase\",\"asciifolding\"]}}}}";
138     String EXPECTED_MAPPINGS =
139         "{\"properties\": {"
140             + "\"serverName\": {"
141             + "\"type\": \"string\", "
142             + "\"index\": \"analyzed\", "
143             + "\"search_analyzer\": \"whitespace\"}, "
144             + "\"serverComplex\": {"
145             + "\"type\": \"string\", "
146             + "\"search_analyzer\": \"whitespace\"}}}";
147
148     // Read a valid document schema from a json file.
149     File schemaFile = new File(SIMPLE_DOC_SCHEMA_JSON);
150     String documentJson = TestUtils.readFileToString(schemaFile);
151
152     // Send a request to our 'create index' endpoint, using the schema
153     // which we just read.
154     String result = target(TOP_URI + INDEX_NAME).request().put(Entity.json(documentJson), String.class);
155
156
157     // Our stub document store DAO returns the parameters that it was
158     // passed as the result string, so now we can validate that our
159     // endpoint invoked it with the correct parameters.
160     String[] tokenizedResult = result.split("@");
161     assertTrue("Unexpected Index Name '" + tokenizedResult[0] + "' passed to doc store DAO",
162         tokenizedResult[0].equals(INDEX_NAME));
163     assertTrue("Unexpected settings string '" + tokenizedResult[1] + "' passed to doc store DAO",
164         tokenizedResult[1].equals(EXPECTED_SETTINGS));
165     assertTrue("Unexpected mappings string '" + tokenizedResult[2] + "' passed to doc store DAO",
166         tokenizedResult[2].equals(EXPECTED_MAPPINGS));
167   }
168
169   /**
170    * Tests the dynamic shcema creation flow that send the request
171    * JSON to the data store without any JSON validation against a schema
172    * 
173    * @throws IOException
174    */
175   @Test
176   public void createDynamicIndexTest() throws IOException {
177     String indexName = "super-ultra-dynamic-mega-index";
178     String dynamicUri = TOP_URI + "dynamic/";
179     File indexFile = new File(DYNAMIC_INDEX_PAYLOAD);
180     String indexPayload = TestUtils.readFileToString(indexFile);
181     
182     String result = target(dynamicUri + indexName).request().put(Entity.json(indexPayload), String.class);
183
184     assertEquals(indexPayload, result);
185   }
186
187   /**
188    * This test validates that a 'create index' request with an improperly
189    * formatted document schema as the payload will result in an
190    * appropriate error being returned from the endpoint.
191    */
192   @Test
193   public void createIndexWithMangledSchemaTest() {
194
195     String INDEX_NAME = "test-index";
196     int BAD_REQUEST_CODE = 400;
197
198     String invalidSchemaString = "this is definitely not json!";
199
200     Response result = target(TOP_URI + INDEX_NAME).request().put(Entity.json(invalidSchemaString), Response.class);
201
202     assertEquals("Invalid document schema should result in a 400 error",
203         BAD_REQUEST_CODE, result.getStatus());
204   }
205
206
207   /**
208    * This test validates the behaviour of the 'Delete Index' end point.
209    */
210   @Test
211   public void deleteIndexTest() {
212
213     String INDEX_NAME = "test-index";
214
215     // Send a request to the 'delete index' endpoint.
216     String result = target(TOP_URI + INDEX_NAME).request().delete(String.class);
217
218     // Validate that the expected parameters were passed to the document
219     // store DAO.
220     assertTrue("Unexpected index name '" + result + "' passed to doc store DAO",
221         result.equals(INDEX_NAME));
222   }
223
224
225   /**
226    * This test validates that attempting to delete an index which does not
227    * exist results in a 404 error.
228    */
229   @Test
230   public void deleteIndexDoesNotExistTest() {
231
232     int NOT_FOUND_CODE = 404;
233
234     // Send a request to the 'delete index' endpoint, specifying a
235     // non-existent index.
236     Response result = target(TOP_URI + StubEsController.DOES_NOT_EXIST_INDEX).request().delete(Response.class);
237
238     // Validate that a 404 error code is returned from the end point.
239     assertEquals("Deleting an index which does not exist should result in a 404 error",
240         NOT_FOUND_CODE, result.getStatus());
241   }
242 }