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

io.github.olib963.javatest.matchers.internal.EntryMatcher Maven / Gradle / Ivy

There is a newer version: 0.2.0
Show newest version
package io.github.olib963.javatest.matchers.internal;

import io.github.olib963.javatest.matchers.MatchResult;
import io.github.olib963.javatest.matchers.Matcher;

import java.util.Map;
import java.util.Optional;

public class EntryMatcher implements Matcher> {
    private final Matcher keyMatcher;
    private final Matcher valueMatcher;

    public EntryMatcher(Matcher keyMatcher, Matcher valueMatcher) {
        this.keyMatcher = keyMatcher;
        this.valueMatcher = valueMatcher;
    }

    @Override
    public MatchResult matches(Map.Entry entry) {
        var key = entry.getKey();
        var keyResult = keyMatcher.matches(key);
        var keyMismatch = keyResult.mismatch.map(m -> "Key " + key + " " + m);

        var value = entry.getValue();
        var valueResult = valueMatcher.matches(value);
        var valueMismatch = valueResult.mismatch.map(m -> "value " + key + " " + m);
        boolean matches = keyResult.matches && valueResult.matches;
        return MatchResult.of(matches, combine(keyMismatch, valueMismatch));
    }

    @Override
    public String describeExpected() {
        return "have key that was expected to " + keyMatcher.describeExpected()
                + " and value that was expected to " + valueMatcher.describeExpected();
    }

    private Optional combine(Optional a, Optional b) {
        if (a.isPresent()) {
            var aStr = a.get();
            String withB = b.map(bStr -> aStr + " " + bStr).orElse(aStr);
            return Optional.of(withB);
        }
        return b;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy