001/*
002 * Copyright (C) 2006-2018 Talend Inc. - www.talend.com
003 * <p>
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * http://www.apache.org/licenses/LICENSE-2.0
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.talend.sdk.component.junit;
017
018import static java.util.stream.Collectors.toList;
019import static java.util.stream.Collectors.toMap;
020
021import java.io.Serializable;
022import java.util.Collection;
023import java.util.HashMap;
024import java.util.HashSet;
025import java.util.List;
026import java.util.Map;
027import java.util.Objects;
028import java.util.function.Consumer;
029import java.util.function.Function;
030import java.util.stream.Stream;
031import java.util.stream.StreamSupport;
032
033public final class RecordAsserts implements Function<Iterable<Map<String, List<Serializable>>>, Void>, Serializable {
034
035    private final Map<String, SerializableConsumer<List<? extends Serializable>>> validators = new HashMap<>();
036
037    public <R extends Serializable> RecordAsserts withAsserts(final String outputName,
038            final SerializableConsumer<List<R>> validator) {
039        validators.put(outputName, SerializableConsumer.class.cast(validator));
040        return this;
041    }
042
043    @Override
044    public Void apply(final Iterable<Map<String, List<Serializable>>> input) {
045        final Map<String, List<Serializable>> outputs = StreamSupport
046                .stream(input.spliterator(), false)
047                .flatMap(m -> m.entrySet().stream())
048                .collect(toMap(Map.Entry::getKey, Map.Entry::getValue,
049                        (u1, u2) -> Stream.of(u1, u2).filter(Objects::nonNull).flatMap(Collection::stream).collect(
050                                toList())));
051
052        // if we want to validate some outputs which are not here it means the
053        // validation fails
054        // note: if we don't validate an output which is here it can means we don't care
055        // for current test so ignore the opposite
056        // validation
057        final Collection<String> missing = new HashSet<>(validators.keySet());
058        missing.removeAll(outputs.keySet());
059        if (!missing.isEmpty()) {
060            throw new IllegalArgumentException("Missing outputs: " + missing);
061        }
062
063        validators.forEach((k, v) -> v.accept(outputs.get(k)));
064
065        return null;
066    }
067
068    public interface SerializableConsumer<A> extends Consumer<A>, Serializable {
069    }
070
071}