ae54449cda82227b89c075390b9b47bd73e5671a
[aai/traversal.git] / aai-traversal / src / test / java / org / onap / aai / rest / search / QueryTest.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *    http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  *
20  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  */
22 package org.onap.aai.rest.search;
23
24 import static org.hamcrest.MatcherAssert.assertThat;
25 import static org.hamcrest.Matchers.contains;
26 import static org.hamcrest.Matchers.containsInAnyOrder;
27 import static org.junit.Assert.assertArrayEquals;
28 import static org.junit.Assert.assertEquals;
29 import static org.junit.Assert.assertTrue;
30 import static org.mockito.Matchers.any;
31 import static org.mockito.Mockito.when;
32
33 import java.util.*;
34 import java.util.stream.Collector;
35 import java.util.stream.Collectors;
36
37 import com.att.eelf.configuration.EELFLogger;
38 import com.att.eelf.configuration.EELFManager;
39 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
40 import org.apache.tinkerpop.gremlin.structure.Graph;
41 import org.apache.tinkerpop.gremlin.structure.Vertex;
42 import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
43 import org.mockito.Mock;
44 import org.mockito.MockitoAnnotations;
45 import org.onap.aai.exceptions.AAIException;
46 import org.onap.aai.introspection.Loader;
47 import org.onap.aai.introspection.LoaderFactory;
48 import org.onap.aai.introspection.ModelType;
49 import org.onap.aai.introspection.Version;
50 import org.onap.aai.query.builder.GremlinTraversal;
51 import org.onap.aai.serialization.db.EdgeRules;
52 import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
53 import org.onap.aai.serialization.engines.QueryStyle;
54 import org.onap.aai.serialization.engines.TransactionalGraphEngine;
55
56 public abstract class QueryTest {
57
58         private EELFLogger logger;
59         protected Graph graph;
60         private GremlinServerSingleton gremlinServerSingleton;
61         private GremlinGroovyShellSingleton shell;
62         @Mock private TransactionalGraphEngine dbEngine;
63         protected final List<Vertex> expectedResult = new ArrayList<>();
64         //expectedResultForMaps is for when the query returns a HashMap, not a Vertex
65         protected String expectedResultForMaps = new String();
66         protected final EdgeRules rules = EdgeRules.getInstance();
67         protected Loader loader;
68         
69         public QueryTest() throws AAIException, NoEdgeRuleFoundException {
70                 setUp();
71                 logger = EELFManager.getInstance().getLogger(getClass());
72         }
73
74         public void setUp() throws AAIException, NoEdgeRuleFoundException {
75                 System.setProperty("AJSC_HOME", ".");
76                 System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local");
77                 MockitoAnnotations.initMocks(this);
78                 graph = TinkerGraph.open();
79                 createGraph();
80                 gremlinServerSingleton = GremlinServerSingleton.getInstance();
81                 shell = GremlinGroovyShellSingleton.getInstance();
82                 loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest());
83         }
84         
85         public void run() {
86                 this.run(false);
87         }
88         
89         public void run(boolean isHashMap) {
90                 
91                 String query = gremlinServerSingleton.getStoredQueryFromConfig(getQueryName());
92                 Map<String, Object> params = new HashMap<>();
93                 addParam(params);
94                 when(dbEngine.getQueryBuilder(any(QueryStyle.class))).thenReturn(new GremlinTraversal<>(loader, graph.traversal()));
95                 logger.info("Stored query in abstraction form {}", query);
96                 query = GroovyQueryBuilderSingleton.getInstance().executeTraversal(dbEngine, query, params);
97                 logger.info("After converting to gremlin query {}", query);
98                 query = "g" + query;
99                 GraphTraversal<Vertex, Vertex> g = graph.traversal().V();
100                 addStartNode(g);
101                 params.put("g", g);
102                 
103                 //Certain custom queries return HashMaps instead of Vertex; different code must used for both cases to avoid a ClassCastException
104                 if(!isHashMap) {
105                         GraphTraversal<Vertex, Vertex> result = (GraphTraversal<Vertex, Vertex>)shell.executeTraversal(query, params);
106                         
107                         List<Vertex> vertices = result.toList();
108
109                         logger.info("Expected result set of vertexes [{}]", convert(expectedResult));
110                         logger.info("Actual Result set of vertexes [{}]", convert(vertices));
111
112                         List<Vertex> nonDuplicateExpectedResult = new ArrayList<>(new HashSet<>(expectedResult));
113                         vertices = new ArrayList<>(new HashSet<>(vertices));
114
115                         nonDuplicateExpectedResult.sort(Comparator.comparing(vertex -> vertex.id().toString()));
116                         vertices.sort(Comparator.comparing(vertex -> vertex.id().toString()));
117
118                         // Use this instead of the assertTrue as this provides more useful
119                         // debugging information such as this when expected and actual differ:
120                         // java.lang.AssertionError: Expected all the vertices to be found
121                         // Expected :[v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]]
122                         // Actual   :[v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]]
123                         assertEquals("Expected all the vertices to be found", nonDuplicateExpectedResult, vertices);
124                 }
125                 else {
126                         GraphTraversal<HashMap<String,Long>, HashMap<String,Long>> result = (GraphTraversal<HashMap<String,Long>, HashMap<String,Long>>)shell.executeTraversal(query, params);
127                         
128                         String map = result.toList().toString();
129                         System.out.println(map);
130                         assertTrue("all hash maps found", map.equals(expectedResultForMaps) && expectedResultForMaps.equals(map));                      
131                 }
132         }
133
134         private String convert(List<Vertex> vertices){
135                 return vertices
136                                 .stream()
137                                 .map(vertex -> vertex.property("aai-node-type").value().toString())
138                                 .collect(Collectors.joining(","));
139         }
140
141         protected abstract void createGraph() throws AAIException, NoEdgeRuleFoundException;
142                 
143         protected abstract String getQueryName();
144         
145         protected abstract void addStartNode(GraphTraversal<Vertex, Vertex> g);
146         
147         protected abstract void addParam(Map<String, Object> params);
148 }