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