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

com.github.tomakehurst.wiremock.verification.NearMissCalculator Maven / Gradle / Ivy

package com.github.tomakehurst.wiremock.verification;

import com.github.tomakehurst.wiremock.matching.MatchResult;
import com.github.tomakehurst.wiremock.matching.RequestPattern;
import com.github.tomakehurst.wiremock.stubbing.ServedStub;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
import com.github.tomakehurst.wiremock.stubbing.StubMappings;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;

import java.util.Comparator;
import java.util.List;

import static com.google.common.collect.FluentIterable.from;
import static java.lang.Math.min;

public class NearMissCalculator {

    public static final int NEAR_MISS_COUNT = 3;

    public static final Comparator NEAR_MISS_ASCENDING_COMPARATOR = new Comparator() {
        public int compare(NearMiss o1, NearMiss o2) {
            return o1.compareTo(o2);
        }
    };

    private final StubMappings stubMappings;
    private final RequestJournal requestJournal;

    public NearMissCalculator(StubMappings stubMappings, RequestJournal requestJournal) {
        this.stubMappings = stubMappings;
        this.requestJournal = requestJournal;
    }

    public List findNearestTo(final LoggedRequest request) {
        List allMappings = stubMappings.getAll();

        return sortAndTruncate(from(allMappings).transform(new Function() {
            public NearMiss apply(StubMapping stubMapping) {
                MatchResult matchResult = stubMapping.getRequest().match(request);
                return new NearMiss(request, stubMapping, matchResult);
            }
        }), allMappings.size());
    }

    public List findNearestTo(final RequestPattern requestPattern) {
        List servedStubs = requestJournal.getAllServedStubs();
        return sortAndTruncate(from(servedStubs).transform(new Function() {
            public NearMiss apply(ServedStub servedStub) {
                MatchResult matchResult = requestPattern.match(servedStub.getRequest());
                return new NearMiss(servedStub.getRequest(), requestPattern, matchResult);
            }
        }), servedStubs.size());
    }

    private static List sortAndTruncate(FluentIterable nearMisses, int originalSize) {
        return nearMisses
            .toSortedList(NEAR_MISS_ASCENDING_COMPARATOR)
            .subList(0, min(NEAR_MISS_COUNT, originalSize));
    }


}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy