From dd9f72b94eb7b2c37061c80457e74e8d7ac3e18f Mon Sep 17 00:00:00 2001 From: Carlo Zancanaro Date: Tue, 9 Jun 2015 17:33:56 +1000 Subject: Add an ObjectGenerator<>, and related machinery (also a mapOf generator) --- .../java/au/id/zancanaro/javacheck/Generators.java | 29 ++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'src/main/java/au/id/zancanaro/javacheck/Generators.java') diff --git a/src/main/java/au/id/zancanaro/javacheck/Generators.java b/src/main/java/au/id/zancanaro/javacheck/Generators.java index f4ac025..63d4ece 100644 --- a/src/main/java/au/id/zancanaro/javacheck/Generators.java +++ b/src/main/java/au/id/zancanaro/javacheck/Generators.java @@ -1,8 +1,12 @@ package au.id.zancanaro.javacheck; +import au.id.zancanaro.javacheck.object.GeneratorProvider; +import au.id.zancanaro.javacheck.object.ObjectGenerator; + import java.util.*; import java.util.function.Consumer; import java.util.function.Function; +import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; @@ -75,6 +79,7 @@ public final class Generators { private static ShrinkStrategy longShrinkStrategy(final long bound) { return value -> StreamSupport.stream(new Spliterators.AbstractSpliterator(Long.MAX_VALUE, Spliterator.ORDERED) { long curr = value - bound; + @Override public boolean tryAdvance(Consumer action) { if (curr == 0) { @@ -173,6 +178,22 @@ public final class Generators { }; } + @SuppressWarnings("unchecked") + public static Generator> mapOf(Generator keyGen, Generator valueGen) { + return (random, size) -> { + Generator countGen = sized(s -> integer(0, s)); + int count = countGen.generate(random, size).getValue(); + return Generator.list(count, Generator.tuple(keyGen, valueGen)) + .generate(random, size) + .map(pairs -> pairs.stream() + .collect(Collectors.toMap( + pair -> (K) pair.get(0), + pair -> (V) pair.get(1), + (first, second) -> second))) + .map(Collections::unmodifiableMap); + }; + } + public static Generator character() { return integer(0, 256).map(i -> (char) i.intValue()); } @@ -216,4 +237,12 @@ public final class Generators { return String.valueOf(chars); }); } + + public static Generator ofType(Class type) { + return new ObjectGenerator<>(type); + } + + public static Generator ofType(Class type, GeneratorProvider provider) { + return new ObjectGenerator<>(type, provider); + } } -- cgit v1.2.3