![JAR search and dependency download from the Maven repository](/logo.png)
javaslang.test.Gen Maven / Gradle / Ivy
Show all versions of javaslang-test Show documentation
/* / \____ _ _ ____ ______ / \ ____ __ _______
* / / \/ \ / \/ \ / /\__\/ // \/ \ // /\__\ JΛVΛSLΛNG
* _/ / /\ \ \/ / /\ \\__\\ \ // /\ \ /\\/ \ /__\ \ Copyright 2014-2017 Javaslang, http://javaslang.io
* /___/\_/ \_/\____/\_/ \_/\__\/__/\__\_/ \_// \__/\_____/ Licensed under the Apache License, Version 2.0
*/
package javaslang.test;
import javaslang.Tuple2;
import javaslang.collection.Iterator;
import javaslang.collection.List;
import javaslang.collection.Stream;
import javaslang.collection.Vector;
import java.util.Objects;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* Generators are the building blocks for providing arbitrary objects.
*
* To ease the creation of Arbitraries, Gen is a FunctionalInterface which extends {@code Function}.
*
* Gen objects are obtained via one of the methods {@code choose}, {@code fail}, {@code frequency}, {@code of} and
* {@code oneOf}.
*
* Given Gen objects may be transformed using one of the methods {@code filter}, {@code map} and {@code flatMap}.
*
* A simple way to obtain an Arbitrary of a Gen is to call {@linkplain javaslang.test.Gen#arbitrary()}.
* This will ignore the size hint of Arbitrary.
*
* @param type of generated objects
* @author Daniel Dietrich
* @see javaslang.test.Arbitrary
* @since 1.2.0
*/
@FunctionalInterface
public interface Gen {
int FILTER_THRESHOLD = Integer.MAX_VALUE;
/**
* Functional interface of this generator.
*
* @param random a random number generator
* @return A generated value of type T.
*/
T apply(Random random);
/**
* A generator which constantly returns t.
*
* @param t A value.
* @param Type of t.
* @return A new T generator
*/
static Gen of(T t) {
return ignored -> t;
}
static Gen of(T seed, Function super T, ? extends T> next) {
Objects.requireNonNull(next, "next is null");
final Iterator iterator = Iterator.iterate(seed, next);
return ignored -> iterator.next();
}
/**
* Chooses an int between min and max, bounds inclusive and numbers distributed according to the distribution of
* the underlying random number generator.
*
* Note: min and max are internally swapped if min > max.
*
* @param min lower bound
* @param max upper bound
* @return A new int generator
*/
static Gen choose(int min, int max) {
if (min == max) {
return ignored -> min;
} else {
final int _min = Math.min(min, max);
final int _max = Math.max(min, max);
return rng -> rng.nextInt(Math.abs(_max - _min) + 1) + _min;
}
}
/**
* Chooses a long between min and max, bounds inclusive and numbers distributed according to the distribution of
* the underlying random number generator.
*
* Note: min and max are internally swapped if min > max.
*
* @param min lower bound
* @param max upper bound
* @return A new long generator
*/
static Gen choose(long min, long max) {
if (min == max) {
return ignored -> min;
} else {
return random -> {
final double d = random.nextDouble();
final long _min = Math.min(min, max);
final long _max = Math.max(min, max);
return (long) ((d * _max) + ((1.0 - d) * _min) + d);
};
}
}
/**
* Chooses a double between min and max, bounds inclusive and numbers distributed according to the distribution
* of the underlying random number generator.
*
* Note: min and max are internally swapped if min > max.
*
* @param min lower bound
* @param max upper bound
* @return A new double generator
* @throws IllegalArgumentException if min or max is infinite, min or max is not a number (NaN)
*/
static Gen choose(double min, double max) {
if (Double.isInfinite(min)) {
throw new IllegalArgumentException("min is infinite");
}
if (Double.isInfinite(max)) {
throw new IllegalArgumentException("max is infinite");
}
if (Double.isNaN(min)) {
throw new IllegalArgumentException("min is not a number (NaN)");
}
if (Double.isNaN(max)) {
throw new IllegalArgumentException("max is not a number (NaN)");
}
if (min == max) {
return ignored -> min;
} else {
return random -> {
final double d = random.nextDouble();
final double _min = Math.min(min, max);
final double _max = Math.max(min, max);
return d * _max + (1.0 - d) * _min;
};
}
}
/**
* Chooses a char between min and max, bounds inclusive and chars distributed according to the underlying random
* number generator.
*
* Note: min and max are internally swapped if min > max.
*
* @param min lower bound
* @param max upper bound
* @return A new char generator
*/
static Gen choose(char min, char max) {
if (min == max) {
return ignored -> min;
} else {
return random -> (char) (int) Gen.choose((int) min, (int) max).apply(random);
}
}
/**
* Chooses an enum value from all the enum constants defined in the enumerated type.
*
* @param clazz Enum class
* @param type of enum constants
* @return A new enum generator
*/
static > Gen choose(Class clazz) {
Objects.requireNonNull(clazz, "clazz is null");
return random -> Gen.choose(clazz.getEnumConstants()).apply(random);
}
/**
* Chooses a value from all values in the array.
*
* @param values array with the values to choose from
* @param value type
* @return A new array generator
*/
static Gen choose(T[] values) {
Objects.requireNonNull(values, "values is null");
if (values.length == 0) {
return Gen.fail("Empty array");
} else {
return random -> Gen.choose(0, values.length - 1).map(i -> values[i]).apply(random);
}
}
/**
* Chooses a value from all values in the iterable
*
* @param values iterable with the values to choose from.
* @param value type
* @return A new iterable generator
*/
static Gen choose(Iterable values) {
Objects.requireNonNull(values, "values is null");
final Iterator iterator = Iterator.ofAll(values);
if (!iterator.hasNext()) {
throw new IllegalArgumentException("Empty iterable");
}
@SuppressWarnings("unchecked")
final T[] array = (T[]) iterator.toJavaArray();
return choose(array);
}
/**
* A failing generator which throws a RuntimeException("failed").
*
* @param Type of values theoretically generated.
* @return A new generator which always fails with the message "failed"
*/
static Gen fail() {
return fail("failed");
}
/**
* A failing generator which throws a RuntimeException.
*
* @param message Message thrown.
* @param Type of values theoretically generated.
* @return A new generator which always fails with the given message
*/
static Gen fail(String message) {
return ignored -> {
throw new RuntimeException(message);
};
}
/**
* Chooses one of the given generators according to their frequency.
* Only generators with positive frequencies are used in returned
* generator.
*
* @param generators A non-empty array of Tuples (frequency, generator)
* @param Type to be generated
* @return A new T generator
* @throws java.lang.NullPointerException if generators is null
* @throws java.lang.IllegalArgumentException if generators doesn't contain any generator with positive frequency
*/
@SuppressWarnings("varargs")
@SafeVarargs
static Gen frequency(Tuple2>... generators) {
Objects.requireNonNull(generators, "generators is null");
if (generators.length == 0) {
throw new IllegalArgumentException("generators is empty");
}
final Iterable>> iterable = Stream.of(generators);
return frequency(iterable);
}
/**
* Chooses one of the given generators according to their frequency.
* Only generators with positive frequencies ares used in returned
* generator.
*
* @param generators A non-empty traversable of Tuples (frequency, generator)
* @param Type to be generated
* @return A new T generator
* @throws java.lang.NullPointerException if generators is null
* @throws java.lang.IllegalArgumentException if generators doesn't contain any generator with positive frequency
*/
static Gen frequency(Iterable>> generators) {
Objects.requireNonNull(generators, "generators is null");
final Vector>> filtered = Iterator.ofAll(generators)
.filter(t -> t._1() > 0).toVector();
if (filtered.isEmpty()) {
throw new IllegalArgumentException("no generator with positive weight");
}
final int size = filtered.map(t -> {
final int frequency = t._1;
return frequency;
}).sum().intValue();
return choose(1, size).flatMap(n -> GenModule.frequency(n, filtered.iterator()));
}
/**
* Randomly chooses one of the given generators.
*
* @param generators A non-empty array of generators
* @param Type to be generated
* @return A new T generator
* @throws java.lang.NullPointerException if generators is null
* @throws java.lang.IllegalArgumentException if generators is empty
*/
@SafeVarargs
static Gen oneOf(Gen... generators) {
Objects.requireNonNull(generators, "generators is null");
if (generators.length == 0) {
throw new IllegalArgumentException("generators is empty");
}
return choose(0, generators.length - 1).flatMap(i -> generators[i]);
}
/**
* Randomly chooses one of the given generators.
*
* @param generators A non-empty Iterable of generators
* @param Type to be generated
* @return A new T generator
* @throws java.lang.NullPointerException if generators is null
* @throws java.lang.IllegalArgumentException if generators is empty
*/
static Gen oneOf(Iterable> generators) {
Objects.requireNonNull(generators, "generators is null");
final Stream> stream = Stream.ofAll(generators);
if (stream.isEmpty()) {
throw new IllegalArgumentException("generators is empty");
}
@SuppressWarnings("unchecked")
final Gen[] array = stream.toJavaArray((Class>) (Object) Gen.class);
return oneOf(array);
}
/**
* Converts this Gen to an Arbitrary
*
* @return An arbitrary which returns this generator regardless of the provided size hint n
*/
default Arbitrary arbitrary() {
return n -> this;
}
/**
* Returns a generator based on this generator which produces values that fulfill the given predicate.
*
* @param predicate A predicate
* @return A new generator
*/
default Gen filter(Predicate super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return random -> {
int count = 0;
T t;
while (!predicate.test(t = apply(random))) {
// it may take a looooooong time to hit this condition!
if (++count == FILTER_THRESHOLD) {
throw new IllegalStateException("empty filter");
}
}
return t;
};
}
/**
* Maps generated Ts to Us.
*
* @param mapper A function that maps a generated T to a new generator which generates objects of type U.
* @param Type of generated objects of the new generator
* @return A new generator
*/
default Gen flatMap(Function super T, ? extends Gen extends U>> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
return random -> mapper.apply(apply(random)).apply(random);
}
/**
* Maps generated Ts to Us.
*
* @param mapper A function that maps a generated T to an object of type U.
* @param Type of the mapped object
* @return A new generator
*/
default Gen map(Function super T, ? extends U> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
return random -> mapper.apply(apply(random));
}
default Gen peek(Consumer super T> action) {
return random -> {
final T t = apply(random);
action.accept(t);
return t;
};
}
/**
* Transforms this {@code Gen}.
*
* @param f A transformation
* @param Type of transformation result
* @return An instance of type {@code U}
* @throws NullPointerException if {@code f} is null
*/
default U transform(Function super Gen, ? extends U> f) {
Objects.requireNonNull(f, "f is null");
return f.apply(this);
}
}
interface GenModule {
/**
* Chooses a Gen according to the given frequencies.
*
* @param n a random value between 0 and sum(frequencies) - 1
* @param iter a non-empty Iterator of (frequency, Gen) pairs
* @param type of generated values
* @return A value generator, choosen according to the given frequencies and the underlying n
*/
static Gen frequency(int n, java.util.Iterator>> iter) {
do {
final Tuple2> freqGen = iter.next();
final int k = freqGen._1;
if (n <= k) {
return freqGen._2;
} else {
n = n - k;
}
} while(true);
}
}