Skip to content

Commit 2bd97ae

Browse files
committed
updating IssueTest resource loading to work in both envs (vanilla and android)
1 parent c1a799e commit 2bd97ae

File tree

1 file changed

+49
-48
lines changed

1 file changed

+49
-48
lines changed

tests/vanilla/src/main/java/org/everit/json/schema/IssueTest.java

Lines changed: 49 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,23 @@
55
import static java.util.stream.Collectors.joining;
66
import static org.everit.json.schema.loader.OrgJsonUtil.toMap;
77

8-
import java.io.File;
9-
import java.io.FileInputStream;
10-
import java.io.FileNotFoundException;
118
import java.io.IOException;
9+
import java.io.InputStream;
1210
import java.io.UncheckedIOException;
1311
import java.lang.reflect.Constructor;
14-
import java.net.URISyntaxException;
1512
import java.util.ArrayList;
16-
import java.util.Arrays;
1713
import java.util.HashMap;
1814
import java.util.HashSet;
1915
import java.util.List;
2016
import java.util.Map;
2117
import java.util.Objects;
2218
import java.util.Optional;
19+
import java.util.Set;
2320
import java.util.function.Consumer;
21+
import java.util.regex.Pattern;
22+
import java.util.stream.Collectors;
2423

24+
import org.apache.commons.io.IOUtils;
2525
import org.everit.json.schema.loader.SchemaLoader;
2626
import org.everit.json.schema.regexp.RE2JRegexpFactory;
2727
import org.json.JSONArray;
@@ -34,26 +34,29 @@
3434
import org.junit.runner.RunWith;
3535
import org.junit.runners.Parameterized;
3636
import org.junit.runners.Parameterized.Parameters;
37+
import org.reflections.Reflections;
38+
import org.reflections.scanners.ResourcesScanner;
3739

3840
@RunWith(Parameterized.class)
3941
public class IssueTest {
4042

4143
@Parameters(name = "{1}")
4244
public static List<Object[]> params() {
4345
List<Object[]> rval = new ArrayList<>();
44-
try {
45-
File issuesDir = new File(
46-
IssueTest.class.getResource("/org/everit/json/schema/issues").toURI());
47-
for (File issue : issuesDir.listFiles()) {
48-
rval.add(new Object[] { issue, issue.getName() });
49-
}
50-
} catch (URISyntaxException e) {
51-
throw new RuntimeException(e);
46+
Reflections refs = new Reflections("org.everit.json.schema.issues",
47+
new ResourcesScanner());
48+
Set<String> paths = refs.getResources(Pattern.compile("schema.json"))
49+
.stream().map(path -> path.substring(0, path.lastIndexOf('/')))
50+
.collect(Collectors.toSet());
51+
for (String path : paths) {
52+
rval.add(new Object[] { path, path.substring(path.lastIndexOf('/') + 1) });
5253
}
5354
return rval;
5455
}
5556

56-
private final File issueDir;
57+
private final String issueDir;
58+
59+
private final String testCaseName;
5760

5861
private JettyWrapper servletSupport;
5962

@@ -65,46 +68,44 @@ public static List<Object[]> params() {
6568

6669
private Validator.ValidatorBuilder validatorBuilder = Validator.builder();
6770

68-
public IssueTest(final File issueDir, final String ignored) {
69-
this.issueDir = requireNonNull(issueDir, "issueDir cannot be null");
71+
public IssueTest(String issueDir, String testCaseName) {
72+
this.issueDir = "/" + requireNonNull(issueDir, "issueDir cannot be null");
73+
this.testCaseName = testCaseName;
7074
}
7175

72-
private Optional<File> fileByName(final String fileName) {
73-
return Arrays.stream(issueDir.listFiles())
74-
.filter(file -> file.getName().equals(fileName))
75-
.findFirst();
76+
private Optional<InputStream> fileByName(final String fileName) {
77+
return Optional.ofNullable(getClass().getResourceAsStream(issueDir + "/" + fileName));
78+
// return Arrays.stream(issueDir.listFiles())
79+
// .filter(file -> file.getName().equals(fileName))
80+
// .findFirst();
7681
}
7782

78-
private void initJetty(final File documentRoot) {
83+
private void initJetty() {
7984
try {
80-
servletSupport = new JettyWrapper(documentRoot.getAbsolutePath());
85+
servletSupport = new JettyWrapper(issueDir + "/" + "remotes");
8186
servletSupport.start();
8287
} catch (Exception e) {
8388
throw new RuntimeException(e);
8489
}
8590
}
8691

87-
private static JSONObject fileAsJson(File file) {
92+
private static JSONObject streamAsJson(InputStream file) {
8893
try {
89-
return new JSONObject(new JSONTokener(new FileInputStream(file)));
90-
} catch (FileNotFoundException e) {
94+
return new JSONObject(new JSONTokener(IOUtils.toString(file)));
95+
} catch (java.io.IOException e) {
9196
throw new UncheckedIOException(e);
9297
}
9398
}
9499

95100
private Schema loadSchema() {
96-
Optional<File> schemaFile = fileByName("schema.json");
97-
try {
98-
if (schemaFile.isPresent()) {
99-
JSONObject schemaObj = fileAsJson(schemaFile.get());
100-
loaderBuilder = SchemaLoader.builder().schemaJson(schemaObj);
101-
consumeValidatorConfig();
102-
return loaderBuilder.build().load().build();
103-
}
104-
throw new RuntimeException(issueDir.getCanonicalPath() + "/schema.json is not found");
105-
} catch (IOException e) {
106-
throw new UncheckedIOException(e);
101+
Optional<InputStream> schemaFile = fileByName("schema.json");
102+
if (schemaFile.isPresent()) {
103+
JSONObject schemaObj = streamAsJson(schemaFile.get());
104+
loaderBuilder = SchemaLoader.builder().schemaJson(schemaObj);
105+
consumeValidatorConfig();
106+
return loaderBuilder.build().load().build();
107107
}
108+
throw new RuntimeException(issueDir + "/schema.json is not found");
108109
}
109110

110111
private void consumeValidatorConfig() {
@@ -138,7 +139,7 @@ private void consumeValidatorConfig() {
138139
loaderBuilder.draftV7Support();
139140
}
140141
});
141-
fileByName("validator-config.json").map(file -> fileAsJson(file)).ifPresent(configJson -> {
142+
fileByName("validator-config.json").map(file -> streamAsJson(file)).ifPresent(configJson -> {
142143
configKeyHandlers.entrySet()
143144
.stream()
144145
.filter(entry -> configJson.has(entry.getKey()))
@@ -165,8 +166,8 @@ private void stopJetty() {
165166

166167
@Test
167168
public void test() {
168-
Assume.assumeFalse("issue dir starts with 'x' - ignoring", issueDir.getName().startsWith("x"));
169-
fileByName("remotes").ifPresent(this::initJetty);
169+
Assume.assumeFalse("issue dir starts with 'x' - ignoring", testCaseName.startsWith("x"));
170+
fileByName("remotes").ifPresent(unused -> initJetty());
170171
try {
171172
Schema schema = loadSchema();
172173
fileByName("subject-valid.json").ifPresent(file -> validate(file, schema, true));
@@ -176,7 +177,7 @@ public void test() {
176177
}
177178
}
178179

179-
private void validate(final File file, final Schema schema, final boolean shouldBeValid) {
180+
private void validate(InputStream file, Schema schema, boolean shouldBeValid) {
180181
ValidationException thrown = null;
181182

182183
Object subject = loadJsonFile(file);
@@ -197,7 +198,7 @@ private void validate(final File file, final Schema schema, final boolean should
197198
Assert.fail(failureBuilder.toString());
198199
}
199200
if (!shouldBeValid && thrown != null) {
200-
Optional<File> expectedFile = fileByName("expectedException.json");
201+
Optional<InputStream> expectedFile = fileByName("expectedException.json");
201202
if (expectedFile.isPresent()) {
202203
if (!checkExpectedValues(expectedFile.get(), thrown)) {
203204
expectedFailureList.stream()
@@ -220,12 +221,12 @@ private void validate(final File file, final Schema schema, final boolean should
220221

221222
// TODO - it would be nice to see this moved out of tests to the main
222223
// source so that it can be used as a convenience method by users also...
223-
private Object loadJsonFile(final File file) {
224+
private Object loadJsonFile(InputStream file) {
224225

225226
Object subject = null;
226227

227228
try {
228-
JSONTokener jsonTok = new JSONTokener(new FileInputStream(file));
229+
JSONTokener jsonTok = new JSONTokener(IOUtils.toString(file));
229230

230231
// Determine if we have a single JSON object or an array of them
231232
Object jsonTest = jsonTok.nextValue();
@@ -238,7 +239,7 @@ private Object loadJsonFile(final File file) {
238239
}
239240
} catch (JSONException e) {
240241
throw new RuntimeException("failed to parse subject json file", e);
241-
} catch (FileNotFoundException e) {
242+
} catch (IOException e) {
242243
throw new UncheckedIOException(e);
243244
}
244245
return subject;
@@ -255,8 +256,8 @@ private Object loadJsonFile(final File file) {
255256
* The expected contents are then compared against the actual validation failures reported in the
256257
* ValidationException and nested causingExceptions.
257258
*/
258-
private boolean checkExpectedValues(final File expectedExceptionsFile,
259-
final ValidationException ve) {
259+
private boolean checkExpectedValues(InputStream expectedExceptionsFile,
260+
ValidationException ve) {
260261
// Read the expected values from user supplied file
261262
Object expected = loadJsonFile(expectedExceptionsFile);
262263
expectedFailureList = new ArrayList<String>();
@@ -297,8 +298,8 @@ private void readExpectedValues(final JSONObject expected) {
297298
expectedFailureList.add((String) expected.get("message"));
298299
if (expected.has("causingExceptions")) {
299300
JSONArray causingEx = expected.getJSONArray("causingExceptions");
300-
for (Object subJson : causingEx) {
301-
readExpectedValues((JSONObject) subJson);
301+
for (int i = 0; i < causingEx.length(); ++i) {
302+
readExpectedValues(causingEx.getJSONObject(i));
302303
}
303304
}
304305
}

0 commit comments

Comments
 (0)