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

ru.yandex.qatools.matchers.collection.HasSameItemsAsCollectionMatcher Maven / Gradle / Ivy

package ru.yandex.qatools.matchers.collection;

import ch.lambdaj.collection.LambdaCollection;
import org.hamcrest.*;

import java.util.Collection;

import static ch.lambdaj.collection.LambdaCollections.with;
import static java.util.Collections.frequency;
import static org.hamcrest.Matchers.is;
import static ru.yandex.qatools.matchers.collection.MismatchHelper.appendMismatch;
import static ru.yandex.qatools.matchers.collection.MismatchHelper.asStringWithFrequency;

/**
 * Created with IntelliJ IDEA.
 * User: lanwen
 * Date: 09.05.13
 * Time: 14:21
 */
public class HasSameItemsAsCollectionMatcher extends TypeSafeDiagnosingMatcher> {

    private Collection expect;
    @SuppressWarnings("unchecked")
    private WrapperFactory wrapperFactory = (WrapperFactory) ObjectMethodsWrapper.standardMethods();


    public HasSameItemsAsCollectionMatcher(Collection expected) {
        this.expect = expected;
    }


    @Override
    protected boolean matchesSafely(Collection actual, Description mismatchDescription) {
        LambdaCollection> wrappedActual = with(actual).convert(WrapperConverter.wrapWith(wrapperFactory));
        LambdaCollection> wrappedExpected = with(expect).convert(WrapperConverter.wrapWith(wrapperFactory));

        LambdaCollection> frequencyNotEqual = wrappedExpected.clone()
                .remove(occurrCountEqual(wrappedActual, wrappedExpected));
        frequencyNotEqual.addAll(wrappedActual.clone().remove(occurrCountEqual(wrappedActual, wrappedExpected)));

        appendMismatch(mismatchDescription, "Not equal frequency",
                frequencyNotEqual.distinct().convert(asStringWithFrequency(wrappedActual, wrappedExpected)));
        return frequencyNotEqual.isEmpty();
    }


    @Override
    public void describeTo(Description description) {
        description.appendText("collections contains same items");
    }


    @Factory
    public static  Matcher> hasSameItemsAsCollection(Collection correctList) {
        return new HasSameItemsAsCollectionMatcher<>(correctList);
    }


    private  Matcher> occurrCountEqual(final Collection> actualList,
                                                           final Collection> expectedList) {
        return new FeatureMatcher, Boolean>(is(true), "", "") {
            @Override
            protected Boolean featureValueOf(Wrapper actual) {
                return frequency(expectedList, actual) == frequency(actualList, actual);
            }
        };
    }


}





© 2015 - 2025 Weber Informatics LLC | Privacy Policy