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