Update the license for 2017-2018 license
[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-2018 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 package org.onap.aai.rest.search;
21
22 import static org.hamcrest.MatcherAssert.assertThat;
23 import static org.hamcrest.Matchers.contains;
24 import static org.hamcrest.Matchers.containsInAnyOrder;
25 import static org.junit.Assert.assertArrayEquals;
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertTrue;
28 import static org.mockito.Matchers.any;
29 import static org.mockito.Mockito.when;
30
31 import java.util.*;
32 import java.util.stream.Collector;
33 import java.util.stream.Collectors;
34
35 import com.att.eelf.configuration.EELFLogger;
36 import com.att.eelf.configuration.EELFManager;
37 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
38 import org.apache.tinkerpop.gremlin.structure.Graph;
39 import org.apache.tinkerpop.gremlin.structure.Vertex;
40 import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
41 import org.mockito.Mock;
42 import org.mockito.MockitoAnnotations;
43 import org.onap.aai.exceptions.AAIException;
44 import org.onap.aai.introspection.Loader;
45 import org.onap.aai.introspection.LoaderFactory;
46 import org.onap.aai.introspection.ModelType;
47 import org.onap.aai.introspection.Version;
48 import org.onap.aai.query.builder.GremlinTraversal;
49 import org.onap.aai.serialization.db.EdgeRules;
50 import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
51 import org.onap.aai.serialization.engines.QueryStyle;
52 import org.onap.aai.serialization.engines.TransactionalGraphEngine;
53
54 public abstract class QueryTest {
55
56         private EELFLogger logger;
57         protected Graph graph;
58         private GremlinServerSingleton gremlinServerSingleton;
59         private GremlinGroovyShellSingleton shell;
60         @Mock private TransactionalGraphEngine dbEngine;
61         protected final List<Vertex> expectedResult = new ArrayList<>();
62         //expectedResultForMaps is for when the query returns a HashMap, not a Vertex
63         protected String expectedResultForMaps = new String();
64         protected final EdgeRules rules = EdgeRules.getInstance();
65         protected Loader loader;
66         
67         public QueryTest() throws AAIException, NoEdgeRuleFoundException {
68                 setUp();
69                 logger = EELFManager.getInstance().getLogger(getClass());
70         }
71
72         public void setUp() throws AAIException, NoEdgeRuleFoundException {
73                 System.setProperty("AJSC_HOME", ".");
74                 System.setProperty("BUNDLECONFIG_DIR", "src/main/resources");
75                 MockitoAnnotations.initMocks(this);
76                 graph = TinkerGraph.open();
77                 createGraph();
78                 gremlinServerSingleton = GremlinServerSingleton.getInstance();
79                 shell = GremlinGroovyShellSingleton.getInstance();
80                 loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest());
81         }
82         
83         public void run() {
84                 this.run(false);
85         }
86         
87         public void run(boolean isHashMap) {
88                 
89                 String query = gremlinServerSingleton.getStoredQueryFromConfig(getQueryName());
90                 Map<String, Object> params = new HashMap<>();
91                 addParam(params);
92                 when(dbEngine.getQueryBuilder(any(QueryStyle.class))).thenReturn(new GremlinTraversal<>(loader, graph.traversal()));
93                 logger.info("Stored query in abstraction form {}", query);
94                 query = GroovyQueryBuilderSingleton.getInstance().executeTraversal(dbEngine, query, params);
95                 logger.info("After converting to gremlin query {}", query);
96                 query = "g" + query;
97                 GraphTraversal<Vertex, Vertex> g = graph.traversal().V();
98                 addStartNode(g);
99                 params.put("g", g);
100                 
101                 //Certain custom queries return HashMaps instead of Vertex; different code must used for both cases to avoid a ClassCastException
102                 if(!isHashMap) {
103                         GraphTraversal<Vertex, Vertex> result = (GraphTraversal<Vertex, Vertex>)shell.executeTraversal(query, params);
104                         
105                         List<Vertex> vertices = result.toList();
106
107                         logger.info("Expected result set of vertexes [{}]", convert(expectedResult));
108                         logger.info("Actual Result set of vertexes [{}]", convert(vertices));
109
110                         List<Vertex> nonDuplicateExpectedResult = new ArrayList<>(new HashSet<>(expectedResult));
111                         vertices = new ArrayList<>(new HashSet<>(vertices));
112
113                         nonDuplicateExpectedResult.sort(Comparator.comparing(vertex -> vertex.id().toString()));
114                         vertices.sort(Comparator.comparing(vertex -> vertex.id().toString()));
115
116                         // Use this instead of the assertTrue as this provides more useful
117                         // debugging information such as this when expected and actual differ:
118                         // java.lang.AssertionError: Expected all the vertices to be found
119                         // Expected :[v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]]
120                         // 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]]
121                         assertEquals("Expected all the vertices to be found", nonDuplicateExpectedResult, vertices);
122                 }
123                 else {
124                         GraphTraversal<HashMap<String,Long>, HashMap<String,Long>> result = (GraphTraversal<HashMap<String,Long>, HashMap<String,Long>>)shell.executeTraversal(query, params);
125                         
126                         String map = result.toList().toString();
127                         System.out.println(map);
128                         assertTrue("all hash maps found", map.equals(expectedResultForMaps) && expectedResultForMaps.equals(map));                      
129                 }
130         }
131
132         private String convert(List<Vertex> vertices){
133                 return vertices
134                                 .stream()
135                                 .map(vertex -> vertex.property("aai-node-type").value().toString())
136                                 .collect(Collectors.joining(","));
137         }
138
139         protected abstract void createGraph() throws AAIException, NoEdgeRuleFoundException;
140                 
141         protected abstract String getQueryName();
142         
143         protected abstract void addStartNode(GraphTraversal<Vertex, Vertex> g);
144         
145         protected abstract void addParam(Map<String, Object> params);
146 }