-
Notifications
You must be signed in to change notification settings - Fork 12
/
GraphQLCoreTestSupport.java
320 lines (284 loc) · 14.5 KB
/
GraphQLCoreTestSupport.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.graphql.core.it;
import java.io.Reader;
import java.io.StringReader;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import javax.inject.Inject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.johnzon.mapper.Mapper;
import org.apache.johnzon.mapper.MapperBuilder;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.builder.Builders;
import org.apache.sling.api.request.builder.SlingHttpServletResponseResult;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ResourceWrapper;
import org.apache.sling.engine.SlingRequestProcessor;
import org.apache.sling.graphql.core.mocks.QueryDataFetcherComponent;
import org.apache.sling.graphql.core.mocks.TestDataFetcherComponent;
import org.apache.sling.testing.paxexam.SlingOptions;
import org.apache.sling.testing.paxexam.SlingVersionResolver;
import org.apache.sling.testing.paxexam.TestSupport;
import org.jetbrains.annotations.NotNull;
import org.junit.Before;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.ProbeBuilder;
import org.ops4j.pax.exam.TestProbeBuilder;
import org.ops4j.pax.exam.options.ModifiableCompositeOption;
import org.ops4j.pax.exam.options.extra.VMOption;
import org.ops4j.pax.tinybundles.core.TinyBundle;
import org.osgi.framework.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.sling.testing.paxexam.SlingOptions.slingCommonsMetrics;
import static org.apache.sling.testing.paxexam.SlingOptions.slingQuickstartOakTar;
import static org.apache.sling.testing.paxexam.SlingOptions.slingResourcePresence;
import static org.apache.sling.testing.paxexam.SlingOptions.slingScripting;
import static org.apache.sling.testing.paxexam.SlingOptions.slingScriptingJsp;
import static org.junit.Assert.fail;
import static org.ops4j.pax.exam.CoreOptions.composite;
import static org.ops4j.pax.exam.CoreOptions.junitBundles;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.streamBundle;
import static org.ops4j.pax.exam.CoreOptions.when;
import static org.ops4j.pax.exam.cm.ConfigurationAdminOptions.newConfiguration;
public abstract class GraphQLCoreTestSupport extends TestSupport {
private static final Logger LOGGER = LoggerFactory.getLogger(GraphQLCoreTestSupport.class);
private final static int STARTUP_WAIT_SECONDS = 30;
@Inject
protected ResourceResolverFactory resourceResolverFactory;
@Inject
protected SlingRequestProcessor requestProcessor;
public ModifiableCompositeOption baseConfiguration() {
final String vmOpt = System.getProperty("pax.vm.options");
VMOption vmOption = null;
if (StringUtils.isNotEmpty(vmOpt)) {
vmOption = new VMOption(vmOpt);
}
final String jacocoOpt = System.getProperty("jacoco.command");
VMOption jacocoCommand = null;
if (StringUtils.isNotEmpty(jacocoOpt)) {
jacocoCommand = new VMOption(jacocoOpt);
}
SlingOptions.versionResolver.setVersionFromProject(SlingVersionResolver.SLING_GROUP_ID, "org.apache.sling.api");
SlingOptions.versionResolver.setVersionFromProject(SlingVersionResolver.SLING_GROUP_ID, "org.apache.sling.servlets.resolver");
SlingOptions.versionResolver.setVersionFromProject(SlingVersionResolver.SLING_GROUP_ID, "org.apache.sling.engine");
SlingOptions.versionResolver.setVersionFromProject(SlingVersionResolver.SLING_GROUP_ID, "org.apache.sling.resourceresolver");
SlingOptions.versionResolver.setVersionFromProject(SlingVersionResolver.SLING_GROUP_ID, "org.apache.sling.scripting.api");
SlingOptions.versionResolver.setVersionFromProject(SlingVersionResolver.SLING_GROUP_ID, "org.apache.sling.scripting.core");
SlingOptions.versionResolver.setVersionFromProject(SlingVersionResolver.SLING_GROUP_ID, "org.apache.sling.commons.compiler");
SlingOptions.versionResolver.setVersionFromProject(SlingVersionResolver.SLING_GROUP_ID, "org.apache.sling.jcr.jackrabbit.usermanager");
return composite(
when(vmOption != null).useOptions(vmOption),
when(jacocoCommand != null).useOptions(jacocoCommand),
super.baseConfiguration(),
slingQuickstart(),
graphQLJava(),
testBundle("bundle.filename"),
newConfiguration("org.apache.sling.jcr.base.internal.LoginAdminWhitelist")
.put("whitelist.bundles.regexp", "^PAXEXAM.*$")
.asOption(),
mavenBundle().groupId("org.apache.sling").artifactId("org.apache.sling.servlet-helpers").versionAsInProject(),
mavenBundle().groupId("org.apache.sling").artifactId("org.apache.sling.commons.johnzon").versionAsInProject(),
mavenBundle().groupId("org.osgi").artifactId("org.osgi.util.converter").versionAsInProject(), // required for the newer Sling API
mavenBundle().groupId(SlingVersionResolver.SLING_GROUP_ID).artifactId("org.apache.sling.scripting.spi").versionAsInProject(),
mavenBundle().groupId("org.apache.johnzon").artifactId("johnzon-mapper").versionAsInProject(),
slingResourcePresence(),
slingCommonsMetrics(),
jsonPath(),
junitBundles()
);
}
@ProbeBuilder
public TestProbeBuilder probeConfiguration(final TestProbeBuilder testProbeBuilder) {
testProbeBuilder.setHeader("Sling-Initial-Content", "initial-content");
return testProbeBuilder;
}
protected Option testDataFetchers() {
return buildBundleWithBnd(TestDataFetcherComponent.class, QueryDataFetcherComponent.class);
}
protected Option slingQuickstart() {
final int httpPort = findFreePort();
final String workingDirectory = workingDirectory();
return composite(
slingQuickstartOakTar(workingDirectory, httpPort),
slingScripting(),
slingScriptingJsp()
);
}
protected Option jsonPath() {
return composite(
mavenBundle().groupId("com.jayway.jsonpath").artifactId("json-path").versionAsInProject(),
mavenBundle().groupId("net.minidev").artifactId("json-smart").versionAsInProject(),
mavenBundle().groupId("net.minidev").artifactId("accessors-smart").versionAsInProject(),
mavenBundle().groupId("org.ow2.asm").artifactId("asm").versionAsInProject(),
mavenBundle().groupId("com.jayway.jsonpath").artifactId("json-path-assert").versionAsInProject(),
mavenBundle().groupId("org.apache.servicemix.bundles").artifactId("org.apache.servicemix.bundles.hamcrest").versionAsInProject()
);
}
protected Option graphQLJava() {
return composite(
mavenBundle().groupId("com.graphql-java").artifactId("graphql-java").versionAsInProject(),
mavenBundle().groupId("org.antlr").artifactId("antlr4-runtime").versionAsInProject(),
mavenBundle().groupId("com.graphql-java").artifactId("java-dataloader").versionAsInProject(),
mavenBundle().groupId("org.reactivestreams").artifactId("reactive-streams").versionAsInProject()
);
}
/**
* Injecting the appropriate services to wait for would be more elegant but this is very reliable..
*/
@Before
public void waitForSling() throws Exception {
final int expectedStatus = 200;
final List<Integer> statuses = new ArrayList<>();
final String path = "/.json";
final Instant endTime = Instant.now().plus(Duration.ofSeconds(STARTUP_WAIT_SECONDS));
while(Instant.now().isBefore(endTime)) {
final int status = executeRequest("GET", path, null, null, null, -1).getStatus();
statuses.add(status);
if (status == expectedStatus) {
return;
}
Thread.sleep(250);
}
fail("Did not get a " + expectedStatus + " status at " + path + " got " + statuses);
}
protected SlingHttpServletResponseResult executeRequest(final String method,
final String path, Map<String, String[]> params, String contentType,
Reader body, final int expectedStatus) throws Exception {
// Admin resolver is fine for testing
@SuppressWarnings("deprecation")
final ResourceResolver resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null);
final int [] statusParam = expectedStatus == -1 ? null : new int[] { expectedStatus };
Resource resource = resourceResolver.resolve(path);
String selectorsExtensionSuffix = resource.getResourceMetadata().getResolutionPathInfo();
String[] selectors = new String[0];
String extension = null;
String suffix = null;
int firstSlash = selectorsExtensionSuffix.indexOf('/');
if (firstSlash != -1) {
suffix = selectorsExtensionSuffix.substring(firstSlash);
selectorsExtensionSuffix = selectorsExtensionSuffix.substring(0, selectorsExtensionSuffix.length() - suffix.length());
}
if (selectorsExtensionSuffix.startsWith(".")) {
selectorsExtensionSuffix = selectorsExtensionSuffix.substring(1);
}
if (selectorsExtensionSuffix.length() > 0) {
String[] parts = selectorsExtensionSuffix.split("\\.");
if (parts.length > 1) {
selectors = Arrays.copyOfRange(parts, 0, parts.length - 1);
}
extension = parts[parts.length - 1];
}
String resolvedPath = resource.getPath();
if (selectors.length > 0) {
resolvedPath += "." + String.join(".", selectors);
}
if (extension != null) {
resolvedPath += "." + extension;
}
if (suffix != null) {
resolvedPath += suffix;
}
if (!path.equals(resolvedPath) && suffix != null) {
resource = new ResourceWrapper(resource) {
@Override
public @NotNull String getPath() {
return path;
}
};
}
final SlingHttpServletRequest request = Builders.newRequestBuilder(Objects.requireNonNull(resource))
.withRequestMethod(method)
.withParameters(params)
.withContentType(contentType)
.withBody(body == null ? null : IOUtils.toString(body))
.withSelectors(resource instanceof ResourceWrapper ? null : selectors)
.withExtension(resource instanceof ResourceWrapper ? null : extension)
.withSuffix(resource instanceof ResourceWrapper ? null : suffix)
.build();
final SlingHttpServletResponseResult response = Builders.newResponseBuilder().build();
requestProcessor.processRequest(request, response, resourceResolver);
return response;
}
protected String getContent(String path) throws Exception {
return executeRequest("GET", path, null, null, null, 200).getOutputAsString();
}
protected String getContent(String path, String ... params) throws Exception {
return executeRequest("GET", path, toMap(params), null, null, 200).getOutputAsString();
}
protected String getContentWithPost(String path, String query, Map<String, Object> variables) throws Exception {
Map<String, Object> body = new HashMap<>();
if (query != null) {
String queryEncoded = query.replace("\n", "\\n");
body.put("query", queryEncoded);
}
if (variables != null) {
body.put("variables", variables);
}
return executeRequest("POST", path, null, "application/json", new StringReader(toJSON(body)), 200).getOutputAsString();
}
protected SlingHttpServletResponseResult persistQuery(String path, String query, Map<String, Object> variables) throws Exception {
Map<String, Object> body = new HashMap<>();
if (query != null) {
String queryEncoded = query.replace("\n", "\\n");
body.put("query", queryEncoded);
}
if (variables != null) {
body.put("variables", variables);
}
return executeRequest("POST", path + "/persisted", null, "application/json", new StringReader(toJSON(body)), -1);
}
protected String toJSON(Object source) {
Mapper mapper = new MapperBuilder().build();
return mapper.toStructure(source).toString();
}
protected Map<String, String[]> toMap(String ...keyValuePairs) {
final Map<String, String[]> result = new HashMap<>();
for(int i=0 ; i < keyValuePairs.length; i+=2) {
result.put(keyValuePairs[i], new String[] {keyValuePairs[i+1]});
}
return result;
}
protected Option buildBundleWithExportedPackages(final Class<?>... classes) {
final TinyBundle bundle = org.ops4j.pax.tinybundles.core.TinyBundles.bundle();
bundle.set(Constants.BUNDLE_SYMBOLICNAME, getClass().getSimpleName() + UUID.randomUUID());
final StringBuilder exports = new StringBuilder();
for (final Class<?> clazz : classes) {
bundle.add(clazz);
if(exports.length() != 0) {
exports.append(",");
}
exports.append(clazz.getPackage().getName());
}
bundle.set(Constants.EXPORT_PACKAGE, exports.toString());
return streamBundle(bundle.build()).start();
}
}