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