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

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

There is a newer version: 1.9.1
Show newest version
package net.jqwik.engine.properties.shrinking;

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

import net.jqwik.api.*;

public class DeepSearchShrinkingSequence implements ShrinkingSequence {
	private final Function, Set>> candidatesFor;
	private final Falsifier falsifier;
	private FalsificationResult currentBest;
	private FalsificationResult searchBase;
	private boolean lastStepSuccessful = true;

	public DeepSearchShrinkingSequence(Shrinkable startingShrinkable, Function, Set>> candidatesFor, Falsifier falsifier) {
		this.currentBest = FalsificationResult.falsified(startingShrinkable);
		this.searchBase = currentBest;
		this.candidatesFor = candidatesFor;
		this.falsifier = falsifier;
	}

	@Override
	public boolean next(Runnable count, Consumer> falsifiedReporter) {
		if (!lastStepSuccessful)
			return false;

		lastStepSuccessful = false;

		Set> candidates = getShrinkableCandidates();

		List> nextBase = candidates
			.stream()
			.sorted()
			.map(this::falsify)
			.filter(result -> result.status() != FalsificationResult.Status.VERIFIED)
			.collect(Collectors.toList());

		nextBase
			.stream()
			.filter(result -> result.status() == FalsificationResult.Status.FALSIFIED)
			.findFirst()
			.ifPresent(result -> {
				count.run();
				lastStepSuccessful = true;
				this.currentBest = result;
				falsifiedReporter.accept(this.currentBest);
				this.searchBase = this.currentBest;
			});

		nextBase
			.stream()
			.filter(result -> result.status() == FalsificationResult.Status.FILTERED_OUT)
			.filter(result -> result.shrinkable().isSmallerThan(currentBest.shrinkable())).filter(result -> result.shrinkable().isSmallerThan(searchBase.shrinkable()))
			.findFirst()
			.ifPresent(result -> {
				count.run();
				lastStepSuccessful = true;
				searchBase = result;
			});

		return lastStepSuccessful;
	}

	private Set> getShrinkableCandidates() {
		Set> candidates = new HashSet<>(candidatesFor.apply(searchBase.shrinkable()));
		if (searchBase != currentBest) {
			candidates.addAll(candidatesFor.apply(currentBest.shrinkable()));
		}
		return candidates;
	}

	private FalsificationResult falsify(Shrinkable candidate) {
		return falsifier.falsify(candidate);
	}

	@Override
	public FalsificationResult current() {
		return currentBest;
	}

	@Override
	public void init(FalsificationResult initialCurrent) {
		currentBest = FalsificationResult.falsified(currentBest.shrinkable(), initialCurrent.throwable().orElse(null));
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy