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