838489f18aa4cdd8d268a07769af5777396054ca
[aai/traversal.git] / aai-traversal / src / test / java / org / onap / aai / rest / search / OnapQueryTest.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 com.att.eelf.configuration.EELFLogger;
23 import com.att.eelf.configuration.EELFManager;
24 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
25 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
26 import org.apache.tinkerpop.gremlin.structure.Graph;
27 import org.apache.tinkerpop.gremlin.structure.Vertex;
28 import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
29 import org.junit.Before;
30 import org.junit.BeforeClass;
31 import org.junit.ClassRule;
32 import org.junit.Rule;
33 import org.junit.runner.RunWith;
34 import org.junit.runners.Parameterized;
35 import org.mockito.Mock;
36 import org.mockito.MockitoAnnotations;
37 import org.onap.aai.config.IntrospectionConfig;
38 import org.onap.aai.config.SearchConfiguration;
39 import org.onap.aai.config.SpringContextAware;
40 import org.onap.aai.edges.EdgeIngestor;
41 import org.onap.aai.edges.exceptions.AmbiguousRuleChoiceException;
42 import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
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.nodes.NodeIngestor;
48 import org.onap.aai.setup.AAIConfigTranslator;
49 import org.onap.aai.setup.SchemaLocationsBean;
50 import org.onap.aai.setup.SchemaVersion;
51 import org.onap.aai.setup.SchemaVersions;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.test.context.ContextConfiguration;
54 import org.springframework.test.context.TestPropertySource;
55 import org.springframework.test.context.junit4.rules.SpringClassRule;
56 import org.springframework.test.context.junit4.rules.SpringMethodRule;
57 import org.onap.aai.query.builder.GremlinTraversal;
58 import org.onap.aai.restcore.search.GremlinGroovyShell;
59 import org.onap.aai.restcore.search.GroovyQueryBuilder;
60 import org.onap.aai.serialization.db.EdgeSerializer;
61 import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
62 import org.onap.aai.serialization.engines.QueryStyle;
63 import org.onap.aai.serialization.engines.TransactionalGraphEngine;
64
65 import java.util.*;
66 import java.util.stream.Collectors;
67
68 import static org.junit.Assert.assertEquals;
69 import static org.mockito.Matchers.any;
70 import static org.mockito.Mockito.when;
71
72 @RunWith(Parameterized.class)
73 @ContextConfiguration(classes = {
74                 SchemaLocationsBean.class,
75         SchemaVersions.class,
76                 AAIConfigTranslator.class,
77         EdgeIngestor.class,
78         EdgeSerializer.class,
79         NodeIngestor.class,
80         SpringContextAware.class,
81                 SearchConfiguration.class,
82         IntrospectionConfig.class
83 })
84 @TestPropertySource(properties = {
85         "schema.uri.base.path = /aai",
86     "schema.ingest.file = src/test/resources/application-onap-test.properties"
87 })
88 public abstract class OnapQueryTest {
89
90         @ClassRule
91     public static final SpringClassRule springClassRule = new SpringClassRule();
92
93     @Rule
94     public final SpringMethodRule springMethodRule = new SpringMethodRule();
95
96         protected EELFLogger logger;
97         protected Graph graph;
98         protected GremlinGroovyShell shell;
99         @Mock protected TransactionalGraphEngine dbEngine;
100         protected final List<Vertex> expectedResult = new ArrayList<>();
101
102         @Autowired
103         protected EdgeIngestor edgeRules;
104
105         @Autowired
106         protected EdgeSerializer rules;
107
108         @Autowired
109         protected LoaderFactory loaderFactory;
110
111         @Autowired
112         protected SchemaVersions schemaVersions;
113
114         @Autowired
115         protected GremlinServerSingleton gremlinServerSingleton;
116
117         protected Loader loader;
118         protected GraphTraversalSource gts;
119
120         @Parameterized.Parameter(value = 0)
121         public SchemaVersion version;
122
123         @Parameterized.Parameters(name = "Version.{0}")
124         public static Collection<Object[]> data() {
125                 return Arrays.asList(new Object[][]{
126                                 {new SchemaVersion("v11")},
127                                 {new SchemaVersion("v12")},
128                                 {new SchemaVersion("v13")},
129                                 {new SchemaVersion("v14")}
130                 });
131         }
132
133         protected String query;
134
135         LinkedHashMap <String, Object> params;
136
137         @BeforeClass
138         public static void setupBundleconfig() {
139                 System.setProperty("AJSC_HOME", "./");
140                 System.setProperty("BUNDLECONFIG_DIR", "src/main/resources/");
141         }
142
143         @Before
144         public void setUp() throws AAIException, NoEdgeRuleFoundException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
145                 System.setProperty("AJSC_HOME", ".");
146                 System.setProperty("BUNDLECONFIG_DIR", "src/main/resources");
147                 logger = EELFManager.getInstance().getLogger(getClass());
148                 MockitoAnnotations.initMocks(this);
149                 graph = TinkerGraph.open();
150                 gts = graph.traversal();
151                 createGraph();
152                 shell = new GremlinGroovyShell();
153                 loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, version);
154                 setUpQuery();
155         }
156
157
158         protected void setUpQuery() {
159                 query = gremlinServerSingleton.getStoredQueryFromConfig(getQueryName());
160                 params = new LinkedHashMap <>();
161                 addParam(params);
162                 when(dbEngine.getQueryBuilder(any(QueryStyle.class))).thenReturn(new GremlinTraversal<>(loader, graph.traversal()));
163                 logger.info("Stored query in abstraction form {}", query);
164                 query = new GroovyQueryBuilder().executeTraversal(dbEngine, query, params);
165                 logger.info("After converting to gremlin query {}", query);
166                 query = "g" + query;
167                 GraphTraversal<Vertex, Vertex> g = graph.traversal().V();
168                 addStartNode(g);
169                 params.put("g", g);
170         }
171
172         public void run() {
173
174                 GraphTraversal<Vertex, Vertex> result = (GraphTraversal<Vertex, Vertex>)shell.executeTraversal(query, params);
175
176                 List<Vertex> vertices = result.toList();
177
178                 logger.info("Expected result set of vertexes [{}]", convert(expectedResult));
179                 logger.info("Actual Result set of vertexes [{}]", convert(vertices));
180
181                 List<Vertex> nonDuplicateExpectedResult = new ArrayList<>(new HashSet<>(expectedResult));
182                 vertices = new ArrayList<>(new HashSet<>(vertices));
183
184                 nonDuplicateExpectedResult.sort(Comparator.comparing(vertex -> vertex.id().toString()));
185                 vertices.sort(Comparator.comparing(vertex -> vertex.id().toString()));
186
187
188                 // Use this instead of the assertTrue as this provides more useful
189                 // debugging information such as this when expected and actual differ:
190                 // java.lang.AssertionError: Expected all the vertices to be found
191                 // Expected :[v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]]
192                 // 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]]
193                 assertEquals("Expected all the vertices to be found", nonDuplicateExpectedResult, vertices);
194
195         }
196
197         protected String convert(List<Vertex> vertices){
198                 return vertices
199                                 .stream()
200                                 .map(vertex -> vertex.property("aai-node-type").value().toString())
201                                 .collect(Collectors.joining(","));
202         }
203
204         protected abstract void createGraph() throws AAIException, NoEdgeRuleFoundException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException;
205
206         protected abstract String getQueryName();
207
208         protected abstract void addStartNode(GraphTraversal<Vertex, Vertex> g);
209
210         protected abstract void addParam(Map<String, Object> params);
211
212 }