jio.test.stub.StubBuilder Maven / Gradle / Ivy
Show all versions of jio-test Show documentation
package jio.test.stub;
import fun.gen.Gen;
import jio.IO;
import jio.Lambda;
import java.time.Duration;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import static java.util.Objects.requireNonNull;
/**
* A builder for building `IO` stubs instances using generators of IO effects. class, where delays and failures can be
* produced based on the call number to the generator. Generators are composable using the `Combinators` class.
*
* Example of generating `IO` instances with generators and composition:
*
* {@code
* var gen1 = Gen.seq(IO::succeed);
* var gen2 = Gen.cons(IO.fail(new RuntimeException("bad luck!")));
* var gen = Combinators.oneOf(gen1, gen2);
* }
*
*
* This class allows you to generate `IO` instances with various generators and customize their behavior. You can also
* specify an executor using the {@link #withExecutor(Executor)} method for handling asynchronous IO operations.
*
* @param The type of value generated by the stub.
* @see Gen
* @see fun.gen.Combinators
*/
public final class StubBuilder implements Supplier> {
private final Gen> gen;
private Executor executor;
private Gen delayGen;
private StubBuilder(final Gen> gen) {
this.gen = gen;
}
/**
* Creates a new stub using the provided generator of IO effects.
*
* @param gen The generator for creating `IO` instances.
* @param The type of value to generate.
* @return A new stub instance.
*/
public static StubBuilder ofGen(final Gen> gen) {
return new StubBuilder<>(requireNonNull(gen));
}
/**
* Creates a new stub using the provided generator of values.
*
* @param gen The generator for creating values of type O
* @param The type of value to generate.
* @return A new stub instance.
*/
public static StubBuilder ofSucGen(final Gen gen) {
return new StubBuilder<>(requireNonNull(gen).map(IO::succeed));
}
/**
* Sets the executor for this stub. The executor is used for asynchronous IO operations. Use this method when you want
* to customize the executor used by the generated `IO` instances.
*
* @param executor The executor to be used for asynchronous operations.
* @return This stub instance with the executor set.
*/
public StubBuilder withExecutor(Executor executor) {
this.executor = requireNonNull(executor);
return this;
}
/**
* Sets the generator of delays
*
* @param delaysGen the generator of delays
* @return this stub builder with a delay generator
*/
public StubBuilder withDelays(final Gen delaysGen) {
this.delayGen = requireNonNull(delaysGen);
return this;
}
/**
* Generates an `IO` stub using the specified generator and settings.
*
* @return The generated `IO` stub instance.
*/
@Override
public IO get() {
Lambda, GenValue> delay = it -> delayGen == null ? it : IO.lazy(delayGen.sample())
.then(it::sleep);
return executor == null ?
IO.lazy(gen.sample())
.then(delay) :
IO.lazy(gen.sample(),
executor)
.then(delay);
}
}