aboutsummaryrefslogtreecommitdiffstats
path: root/aai-traversal/src/test/java/org/onap/aai/rest/GfpVserverDataStoredQueryTest.java
blob: c96540721016f619f2e82efa5e1d419be57be4bb (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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017-2018 AT&T Intellectual Property. 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 at
 *
 *    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=========================================================
 */
package org.onap.aai.rest;

import org.onap.aai.config.PropertyPasswordConfiguration;
import org.onap.aai.transforms.XmlFormatTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.att.eelf.configuration.EELFManager;
import com.jayway.jsonpath.JsonPath;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphTransaction;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.onap.aai.AAISetup;
import org.onap.aai.HttpTestUtil;
import org.onap.aai.PayloadUtil;
import org.onap.aai.dbmap.AAIGraph;
import org.onap.aai.setup.SchemaVersion;
import org.springframework.test.context.ContextConfiguration;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.*;
import java.util.*;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@ContextConfiguration(initializers = PropertyPasswordConfiguration.class)
public class GfpVserverDataStoredQueryTest extends AAISetup{

    private static final Logger logger = LoggerFactory.getLogger(GfpVserverDataStoredQueryTest.class);

    protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");

    private HttpHeaders httpHeaders;

    private MultivaluedMap<String, String> headersMultiMap;
    private MultivaluedMap<String, String> queryParameters;

    private List<String> aaiRequestContextList;

    private List<MediaType> outputMediaTypes;

    private HttpTestUtil httpTestUtil;

    private QueryConsumer queryConsumer;

    private SchemaVersion version;
    private String cloudRegionUri;

    @Before
    public void setup() throws Exception {

        version = schemaVersions.getDefaultVersion();

        cloudRegionUri = "/aai/" + version.toString()
                                   + "/cloud-infrastructure/cloud-regions/"
                                   + "cloud-region/testOwner1/testRegion1";
        httpTestUtil = new HttpTestUtil();

        Map<String, String> templateValues = new HashMap<>();

        templateValues.put("cloud-owner", "testOwner1");
        templateValues.put("cloud-region-id", "testRegion1");
        templateValues.put("tenant-id", "testTenant1");
        templateValues.put("tenant-name", "testTenantName1");
        templateValues.put("vserver-id", "testVserver1");
        templateValues.put("vserver-name", "junit-vservers");
        templateValues.put("interface-name", "testlInterfaceName1");
        templateValues.put("ipv4-address", "192.33.233.233");
        templateValues.put("ipv6-address", "2001:0db8:85a3:0000:0000:8a2e:0370:7334");
        templateValues.put("vlan-interface", "vlan-interface1");

        String cloudRegionPayload = PayloadUtil.
                getTemplatePayload("cloud-region-with-linterface.json", templateValues);

        Response response = httpTestUtil.doPut(cloudRegionUri, cloudRegionPayload);
        logger.info("Response status received {}", response.getEntity());

        assertNotNull("Expected the response to be not null", response);
        assertEquals("Expecting the cloud region to be created", 201, response.getStatus());
        logger.info("Successfully created the cloud region with linterface");

        queryConsumer = new QueryConsumer(traversalUriHttpEntry, schemaVersions, gremlinServerSingleton, new XmlFormatTransformer(), basePath);

        httpHeaders         = mock(HttpHeaders.class);

        headersMultiMap     = new MultivaluedHashMap<>();
        queryParameters     = Mockito.spy(new MultivaluedHashMap<>());

        headersMultiMap.add("X-FromAppId", "JUNIT");
        headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
        headersMultiMap.add("Real-Time", "true");
        headersMultiMap.add("Accept", "application/json");
        headersMultiMap.add("aai-request-context", "");

        outputMediaTypes = new ArrayList<>();
        outputMediaTypes.add(APPLICATION_JSON);

        aaiRequestContextList = new ArrayList<>();
        aaiRequestContextList.add("");

        when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
        when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
        when(httpHeaders.getRequestHeader("X-FromAppId")).thenReturn(Arrays.asList("JUNIT"));
        when(httpHeaders.getRequestHeader("X-TransactionId")).thenReturn(Arrays.asList("JUNIT"));
        when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList);

        Mockito.doReturn(null).when(queryParameters).remove(anyObject());

        when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON);
    }

    @Test
    public void testStoredQueryVerifyDoesNotThrowMethodTooLargeWhenLargeNumberOfStartingVertexes() throws Exception {

        // Add hundred thousand vserver vertexes to properly
        // test the scenario where the application was
        // failing with method too large
        String vservers = System.getProperty("perf.vservers.count", "1000");
        addVservers(Integer.parseInt(vservers));

        Map<String, String> templateValues = new HashMap<>();

        // Purposefully putting the filter to the testVserver1 as
        // since this is a junit test other junit tests could put
        // vserver and not properly clean up after the test
        // so doing this to ensure that this is testing against the particular vserver
        // as not to fail when another unit test decide to put vserver and not clean up
        templateValues.put("start", "nodes/vservers?vserver-name=junit-vservers");
        templateValues.put("query", "gfp-vserver-data");

        String payload = PayloadUtil.getTemplatePayload("custom-query.json", templateValues);
        String query = String.format("/aai/%s/query?format=resource_and_url", version.toString());

        UriInfo uriInfo = Mockito.mock(UriInfo.class);
        HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);

        queryParameters.add("format", "resource_and_url");
        Mockito.when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
        when(uriInfo.getPath()).thenReturn(query);

        Response response = queryConsumer.executeQuery(
            payload,
            version.toString(),
            "resource_and_url", "" +
            "no_op",
            httpHeaders,
            uriInfo,
            "-1",
            "-1"
        );

        String entity = response.getEntity().toString();
        assertEquals("Expected the response to be 200 but got this returned: " + response.getEntity().toString(),
                200, response.getStatus());
        List<String> urls = JsonPath.read(entity, "$.results[*].url");
        assertEquals("Expected the urls to be 3", 3, urls.size());
        removeVertexes();
    }

    @Test
    public void testStoredQueryWhenQueryDoesNotExistShouldReturnBadRequest() throws Exception {

        Map<String, String> templateValues = new HashMap<>();

        templateValues.put("start", "nodes/vservers");
        templateValues.put("query", "fake-query");

        String payload = PayloadUtil.getTemplatePayload("custom-query.json", templateValues);
        String query = String.format("/aai/%s/query?format=resource_and_url", version.toString());

        UriInfo uriInfo = Mockito.mock(UriInfo.class);
        HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);

        queryParameters.add("format", "resource_and_url");
        Mockito.when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
        when(uriInfo.getPath()).thenReturn(query);

        Response response = queryConsumer.executeQuery(
                payload,
                version.toString(),
                "resource_and_url", "" +
                        "no_op",
                httpHeaders,
                uriInfo,
                "-1",
                "-1"
        );

        String entity = response.getEntity().toString();

        assertEquals("Expected the response to be 400 but got this returned: " + entity,
                400, response.getStatus());

        assertThat("Expecting error message since query doesn't exist", entity,
                containsString("Query payload is invalid"));
    }

    @Test
    public void testStoredQueryWhenStartFilterReturnsZeroVertexesItShouldHandleProperly() throws Exception {

        Map<String, String> templateValues = new HashMap<>();

        templateValues.put("start", "nodes/vservers?vserver-name=nonexistent-filter");
        templateValues.put("query", "gfp-vserver-data");

        String payload = PayloadUtil.getTemplatePayload("custom-query.json", templateValues);
        String query = String.format("/aai/%s/query?format=resource_and_url", version.toString());

        UriInfo uriInfo = Mockito.mock(UriInfo.class);
        HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);

        queryParameters.add("format", "resource_and_url");
        Mockito.when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
        when(uriInfo.getPath()).thenReturn(query);

        Response response = queryConsumer.executeQuery(
                payload,
                version.toString(),
                "resource_and_url", "" +
                        "no_op",
                httpHeaders,
                uriInfo,
                "-1",
                "-1"
        );

        String entity = response.getEntity().toString();

        assertEquals("Expected the response to be 404 but got this returned: " + entity,
                404, response.getStatus());

        assertThat(entity, containsString("Start URI returned no vertexes, please check the start URI"));
    }

    @After
    public void tearDown(){
        removeVertexes();
    }

    private void removeVertexes(){

        JanusGraph JanusGraph = AAIGraph.getInstance().getGraph();
        JanusGraphTransaction transaction = JanusGraph.newTransaction();

        boolean success = true;

        try {
            GraphTraversalSource g = transaction.traversal();
            g.V().has("source-of-truth", "JUNIT").toList().stream()
                    .forEach((vertex) -> vertex.remove());
        } catch(Exception ex){
            success = false;
            logger.error("Unable to remove all of the junit vservers due to {}", ex);
        } finally {
            if(success){
                transaction.commit();
            } else {
                transaction.rollback();
            }
        }

    }

    private void addVservers(int vserversCount){

        JanusGraph JanusGraph = AAIGraph.getInstance().getGraph();
        JanusGraphTransaction transaction = JanusGraph.newTransaction();

        boolean success = true;

        try {

            GraphTraversalSource g = transaction.traversal();
            for(int index = 0; index < vserversCount; index++){
                String randomVserverId = UUID.randomUUID().toString();
                g.addV().property("aai-node-type", "vserver")
                        .property( "vserver-id", "random-" + randomVserverId)
                        .property( "vserver-name", "junit-vservers")
                        .property( "source-of-truth", "JUNIT")
                        .next();
            }

        } catch(Exception ex){
            success = false;
            logger.error("Unable to add all of the vservers due to {}", ex);
        } finally {
            if(success){
                transaction.commit();
            } else {
                transaction.rollback();
            }
        }
    }
}