aboutsummaryrefslogtreecommitdiffstats
path: root/src/test/java/org/openecomp/sa/rest/IndexApiTest.java
blob: b969ab611e2a96c47d5f143de9eb231ebd4a51d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/**
 * ============LICENSE_START=======================================================
 * Search Data Service
 * ================================================================================
 * Copyright © 2017 AT&T Intellectual Property.
 * Copyright © 2017 Amdocs
 * All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License ati
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 *
 * ECOMP and OpenECOMP are trademarks
 * and service marks of AT&T Intellectual Property.
 */
package org.openecomp.sa.rest;


import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import org.openecomp.sa.searchdbabstraction.elasticsearch.exception.DocumentStoreOperationException;
import org.openecomp.sa.searchdbabstraction.entity.OperationResult;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import java.io.*;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;


/**
 * This suite of tests is intended to exercise the set of REST endpoints
 * associated with manipulating Indexes in the document store.
 */
public class IndexApiTest extends JerseyTest {

  private final String TOP_URI = "/test/indexes/";
  private final String SIMPLE_DOC_SCHEMA_JSON = "src/test/resources/json/simpleDocument.json";


  @Override
  protected Application configure() {

    // Make sure that our test endpoint is on the resource path
    // for Jersey Test.
    return new ResourceConfig(SearchServiceApiHarness.class);
  }


  /**
   * This test validates that the {@link IndexApi} is able to convert {@link OperationResult}
   * obects to standard REST {@link Response} objects.
   *
   * @throws FileNotFoundException
   * @throws IOException
   * @throws DocumentStoreOperationException
   */
  @Test
  public void responseFromOperationResultTest() throws FileNotFoundException, IOException, DocumentStoreOperationException {

    int SUCCESS_RESULT_CODE = 200;
    String SUCCESS_RESULT_STRING = "Everything is ay-okay!";
    int FAILURE_RESULT_CODE = 500;
    String FAILURE_CAUSE_STRING = "Something went wrong!";


    // Create an instance of the index API endpoint that we will test against.
    // We will override the init() method because we don't want it to try to
    // connect to a real document store.
    IndexApi indexApi = new IndexApi(new SearchServiceApiHarness()) {
      @Override
      public void init() { /* do nothing */ }
    };

    //Construct an OperationResult instance with a success code and string.
    OperationResult successResult = new OperationResult();
    successResult.setResultCode(SUCCESS_RESULT_CODE);
    successResult.setResult(SUCCESS_RESULT_STRING);

    // Convert our success OperationResult to a standard REST Response...
    Response successResponse = indexApi.responseFromOperationResult(successResult);

    // ...and validate that the Response is correctly populated.
    assertEquals("Unexpected result code", SUCCESS_RESULT_CODE, successResponse.getStatus());
    assertTrue("Incorrect result string", ((String) successResponse.getEntity()).equals(SUCCESS_RESULT_STRING));

    // Construct an OperationResult instance with an error code and failure
    // cause.
    OperationResult failureResult = new OperationResult();
    failureResult.setResultCode(FAILURE_RESULT_CODE);
    failureResult.setFailureCause(FAILURE_CAUSE_STRING);

    // Convert our failure OperationResult to a standard REST Response...
    Response failureResponse = indexApi.responseFromOperationResult(failureResult);

    // ...and validate that the Response is correctly populated.
    assertEquals("Unexpected result code", FAILURE_RESULT_CODE, failureResponse.getStatus());
    assertTrue("Incorrect result string", ((String) failureResponse.getEntity()).equals(FAILURE_CAUSE_STRING));
  }


  /**
   * This test validates the behaviour of the 'Create Index' POST request
   * endpoint.
   *
   * @throws IOException
   */
  @Test
  public void createIndexTest() throws IOException {

    String INDEX_NAME = "test-index";
    String EXPECTED_SETTINGS =
        "{\"analysis\": "
            + "{\"filter\": "
            + "{\"nGram_filter\": { "
            + "\"type\": \"nGram\", "
            + "\"min_gram\": 1, "
            + "\"max_gram\": 50, "
            + "\"token_chars\": [ \"letter\", \"digit\", \"punctuation\", \"symbol\" ]}},"
            + "\"analyzer\": {"
            + "\"nGram_analyzer\": "
            + "{\"type\": \"custom\","
            + "\"tokenizer\": \"whitespace\","
            + "\"filter\": [\"lowercase\",\"asciifolding\",\"nGram_filter\"]},"
            + "\"whitespace_analyzer\": "
            + "{\"type\": \"custom\","
            + "\"tokenizer\": \"whitespace\","
            + "\"filter\": [\"lowercase\",\"asciifolding\"]}}}}";
    String EXPECTED_MAPPINGS =
        "{\"properties\": {"
            + "\"serverName\": {"
            + "\"type\": \"string\", "
            + "\"index\": \"analyzed\", "
            + "\"search_analyzer\": \"whitespace\"}, "
            + "\"serverComplex\": {"
            + "\"type\": \"string\", "
            + "\"search_analyzer\": \"whitespace\"}}}";

    // Read a valid document schema from a json file.
    File schemaFile = new File(SIMPLE_DOC_SCHEMA_JSON);
    String documentJson = TestUtils.readFileToString(schemaFile);

    // Send a request to our 'create index' endpoint, using the schema
    // which we just read.
    String result = target(TOP_URI + INDEX_NAME).request().put(Entity.json(documentJson), String.class);


    // Our stub document store DAO returns the parameters that it was
    // passed as the result string, so now we can validate that our
    // endpoint invoked it with the correct parameters.
    String[] tokenizedResult = result.split("@");
    assertTrue("Unexpected Index Name '" + tokenizedResult[0] + "' passed to doc store DAO",
        tokenizedResult[0].equals(INDEX_NAME));
    assertTrue("Unexpected settings string '" + tokenizedResult[1] + "' passed to doc store DAO",
        tokenizedResult[1].equals(EXPECTED_SETTINGS));
    assertTrue("Unexpected mappings string '" + tokenizedResult[2] + "' passed to doc store DAO",
        tokenizedResult[2].equals(EXPECTED_MAPPINGS));
  }


  /**
   * This test validates that a 'create index' request with an improperly
   * formatted document schema as the payload will result in an
   * appropriate error being returned from the endpoint.
   */
  @Test
  public void createIndexWithMangledSchemaTest() {

    String INDEX_NAME = "test-index";
    int BAD_REQUEST_CODE = 400;

    String invalidSchemaString = "this is definitely not json!";

    Response result = target(TOP_URI + INDEX_NAME).request().put(Entity.json(invalidSchemaString), Response.class);

    assertEquals("Invalid document schema should result in a 400 error",
        BAD_REQUEST_CODE, result.getStatus());
  }


  /**
   * This test validates the behaviour of the 'Delete Index' end point.
   */
  @Test
  public void deleteIndexTest() {

    String INDEX_NAME = "test-index";

    // Send a request to the 'delete index' endpoint.
    String result = target(TOP_URI + INDEX_NAME).request().delete(String.class);

    // Validate that the expected parameters were passed to the document
    // store DAO.
    assertTrue("Unexpected index name '" + result + "' passed to doc store DAO",
        result.equals(INDEX_NAME));
  }


  /**
   * This test validates that attempting to delete an index which does not
   * exist results in a 404 error.
   */
  @Test
  public void deleteIndexDoesNotExistTest() {

    int NOT_FOUND_CODE = 404;

    // Send a request to the 'delete index' endpoint, specifying a
    // non-existent index.
    Response result = target(TOP_URI + StubEsController.DOES_NOT_EXIST_INDEX).request().delete(Response.class);

    // Validate that a 404 error code is returned from the end point.
    assertEquals("Deleting an index which does not exist should result in a 404 error",
        NOT_FOUND_CODE, result.getStatus());
  }
}