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

net.jqwik.engine.properties.RandomizedParameterGenerator Maven / Gradle / Ivy

The newest version!
package net.jqwik.engine.properties;

import java.util.*;

import net.jqwik.api.*;
import net.jqwik.api.providers.*;
import net.jqwik.engine.support.*;
import net.jqwik.engine.support.types.*;

class RandomizedParameterGenerator {
	private final TypeUsage typeUsage;
	private final List> arbitraries;
	private final int genSize;
	private final boolean withEdgeCases;

	RandomizedParameterGenerator(MethodParameter parameter, Set> arbitraries, int genSize, boolean withEdgeCases) {
		this.typeUsage = TypeUsageImpl.forParameter(parameter);
		this.arbitraries = new ArrayList<>(arbitraries);
		this.genSize = genSize;
		this.withEdgeCases = withEdgeCases;
	}

	Shrinkable next(Random random, Map> arbitrariesCache) {
		RandomGenerator selectedGenerator = selectGenerator(random, arbitrariesCache);
		return selectedGenerator.next(random);
	}

	private RandomGenerator selectGenerator(Random random, Map> arbitrariesCache) {
		if (arbitrariesCache.containsKey(typeUsage)) {
			Arbitrary arbitrary = arbitrariesCache.get(typeUsage);
			return getGenerator(arbitrary);
		}
		int index = arbitraries.size() == 1 ? 0 : random.nextInt(arbitraries.size());
		Arbitrary selectedArbitrary = arbitraries.get(index);
		arbitrariesCache.put(typeUsage, selectedArbitrary);
		return getGenerator(selectedArbitrary);
	}

	private RandomGenerator getGenerator(Arbitrary arbitrary) {
		return arbitrary.generator(genSize, withEdgeCases);
	}
}