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