All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.jqwik.vavr.arbitraries.base.SingleValueArbitrary Maven / Gradle / Ivy

package net.jqwik.vavr.arbitraries.base;

import net.jqwik.api.Arbitrary;
import net.jqwik.api.Tuple;
import net.jqwik.api.arbitraries.ArbitraryDecorator;
import net.jqwik.api.configurators.ArbitraryConfigurator;
import net.jqwik.api.configurators.SelfConfiguringArbitrary;
import net.jqwik.api.providers.TypeUsage;

import java.util.ArrayList;
import java.util.List;

public abstract class SingleValueArbitrary extends ArbitraryDecorator implements Arbitrary, SelfConfiguringArbitrary {

    private final Arbitrary innerArbitrary;
    private final List> configurations = new ArrayList<>();
    private Arbitrary configuredInnerArbitrary;

    public SingleValueArbitrary(final Arbitrary innerArbitrary) {
        this.innerArbitrary = innerArbitrary;
    }

    protected abstract U mapValue(T value);

    @Override
    protected Arbitrary arbitrary() {
        return getConfiguredInnerArbitrary().map(this::mapValue);
    }

    @Override
    public Arbitrary configure(final ArbitraryConfigurator configurator, final TypeUsage targetType) {
        this.configurations.add(Tuple.of(configurator, targetType));
        return this;
    }

    private Arbitrary getConfiguredInnerArbitrary() {
        if (this.configuredInnerArbitrary == null) {
            this.configuredInnerArbitrary = this.innerArbitrary;
            for (final Tuple.Tuple2 configuration : this.configurations) {
                final ArbitraryConfigurator configurator = configuration.get1();
                final TypeUsage targetType = configuration.get2();
                this.configuredInnerArbitrary = SelfConfiguringArbitrary
                        .configure(this.configuredInnerArbitrary, configurator, targetType);
            }
        }
        return this.configuredInnerArbitrary;
    }

}