Ver Fonte

Add tests for items tester validation.
Also create new test that proves out indexing of exceptions.

Sam Jaffe há 6 anos atrás
pai
commit
e377bd72ef

+ 35 - 0
src/main/lombok/org/leumasjaffe/json/schema/tester/ItemsTester.java

@@ -2,9 +2,13 @@ package org.leumasjaffe.json.schema.tester;
 
 import java.util.Arrays;
 import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
 
 import org.leumasjaffe.json.JsonHelper;
 import org.leumasjaffe.json.schema.Tester;
+import org.leumasjaffe.json.schema.ValidationException;
 import org.leumasjaffe.json.schema.ArrayTester;
 
 import com.fasterxml.jackson.databind.JsonNode;
@@ -21,6 +25,14 @@ public class ItemsTester implements ArrayTester {
 	public ItemsTester(Tester...testers) {
 		this(Arrays.asList(testers));
 	}
+	
+	@Override
+	public void validate(final JsonNode node) {
+		final List<ValidationException> exceptions = this.new Helper(node).validate();
+		if (!exceptions.isEmpty()) {
+			throw new ValidationException("items", "items did not match", exceptions);
+		}
+	}
 
 	@Override
 	public boolean accepts(JsonNode node) {
@@ -44,4 +56,27 @@ public class ItemsTester implements ArrayTester {
 		return out;
 	}
 	
+	@RequiredArgsConstructor
+	@FieldDefaults(makeFinal=true)
+	private class Helper {
+		JsonNode node;
+		
+		List<ValidationException> validate() {
+			final int elems = Math.min(schemas.size(), node.size());
+			return IntStream.range(0, elems).mapToObj(this::validate)
+					.filter(Optional::isPresent).map(Optional::get)
+					.collect(Collectors.toList());
+		}
+		
+		private Optional<ValidationException> validate(int i) {
+			try {
+				schemas.get(i).validate(node.get(i));
+			} catch (ValidationException ve) {
+				return Optional.of(new ValidationException(i,
+						"failed to match schema", ve));
+			}
+			return Optional.empty();
+		}
+	}
+	
 }

+ 15 - 0
src/test/java/org/leumasjaffe/json/schema/tester/ItemsTesterTest.java

@@ -1,6 +1,8 @@
 package org.leumasjaffe.json.schema.tester;
 
+import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
 import static org.hamcrest.collection.IsIterableWithSize.iterableWithSize;
+import static org.hamcrest.core.StringStartsWith.startsWith;
 import static org.junit.Assert.assertThat;
 import static org.leumasjaffe.json.schema.matcher.Accepts.accepts;
 import static org.leumasjaffe.json.schema.matcher.CausingExceptions.causedBy;
@@ -96,4 +98,17 @@ public class ItemsTesterTest {
 		new ItemsTester(isNull, isNull, isNull).validate(node);
 	}
 	
+
+	
+	@Test
+	public void testSubExceptionIsIndexed() {
+		thrown.expect(ValidationException.class);
+		thrown.expect(causedBy(contains(jsonPath(startsWith("#/items/1")))));
+		final ArrayNode node = new ArrayNode(JsonNodeFactory.instance);
+		node.addNull();
+		node.add(true);
+		Tester isNull = TypeTester.fromType("null");
+		new ItemsTester(isNull, isNull).validate(node);
+	}
+	
 }