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

net.jqwik.engine.properties.shrinking.ShrinkAndGrowShrinker Maven / Gradle / Ivy

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

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

import net.jqwik.api.*;
import net.jqwik.api.lifecycle.*;
import net.jqwik.engine.support.*;

class ShrinkAndGrowShrinker extends AbstractSampleShrinker {

	public ShrinkAndGrowShrinker(Map, TryExecutionResult> falsificationCache) {
		super(falsificationCache);
	}

	@Override
	public FalsifiedSample shrink(
		Falsifier> falsifier,
		FalsifiedSample sample,
		Consumer sampleShrunkConsumer,
		Consumer shrinkAttemptConsumer
	) {
		FalsifiedSample current = sample;
		List> allPairs =
			Combinatorics.distinctPairs(sample.shrinkables().size()).collect(Collectors.toList());
		for (Tuple.Tuple2 pair : allPairs) {
			current = shrinkAndGrow(falsifier, current, sampleShrunkConsumer, shrinkAttemptConsumer, pair.get1(), pair.get2());
		}
		return current;
	}

	private FalsifiedSample shrinkAndGrow(
		Falsifier> falsifier,
		FalsifiedSample sample,
		Consumer sampleShrunkConsumer,
		Consumer shrinkAttemptConsumer,
		int index1,
		int index2
	) {
		Function>, Stream>>> shrinker =
			shrinkables -> {
				Shrinkable before = shrinkables.get(index1);
				Stream> afterStream = before.shrink();
				return afterStream.flatMap(after -> {
					Optional> optionalShrink2 = shrinkables.get(index2).grow(before, after);
					if (optionalShrink2.isPresent()) {
						ArrayList> newShrinkables = new ArrayList<>(sample.shrinkables());
						newShrinkables.set(index1, after);
						newShrinkables.set(index2, optionalShrink2.get());
						return Stream.of(newShrinkables);
					} else {
						return Stream.empty();
					}
				});
			};

		return shrink(
			falsifier,
			sample,
			sampleShrunkConsumer,
			shrinkAttemptConsumer,
			shrinker
		);
	}

}