001/*
002 * Copyright (C) 2022 - 2024, the original author or authors.
003 *
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 *
008 *    http://www.apache.org/licenses/LICENSE-2.0
009 *
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 io.github.ascopes.jct.assertions;
017
018import static java.util.stream.Collectors.collectingAndThen;
019import static java.util.stream.Collectors.toList;
020
021import java.util.List;
022import java.util.function.Function;
023import java.util.stream.StreamSupport;
024import org.assertj.core.api.AbstractAssert;
025import org.assertj.core.api.AbstractListAssert;
026import org.assertj.core.api.AssertFactory;
027import org.jspecify.annotations.Nullable;
028
029//@formatter:off
030/**
031 * An implementation of {@link AbstractListAssert} that can perform type-specific assertions on the
032 * members of the container being asserted upon.
033 *
034 * <p>This acts as a bridge with AssertJ now that
035 * {@link org.assertj.core.api.FactoryBasedNavigableListAssert} has been deprecated. Users should
036 * treat this object like any other kind of {@link AbstractListAssert} for all purposes.
037 *
038 * @param <E> the element type to assert upon.
039 * @param <A> the assertion type for the element.
040 * @author Ashley Scopes
041 * @since 3.1.0
042 */
043public final class TypeAwareListAssert<E, A extends AbstractAssert<A, @Nullable E>>
044    extends AbstractListAssert<TypeAwareListAssert<@Nullable E, A>, @Nullable List<? extends @Nullable E>, @Nullable E, A> {
045  //@formatter:on
046
047  private final AssertFactory<@Nullable E, A> assertFactory;
048
049  TypeAwareListAssert(@Nullable List<? extends E> list, AssertFactory<E, A> assertFactory) {
050    super(list, TypeAwareListAssert.class);
051    this.assertFactory = assertFactory;
052  }
053
054  @Override
055  protected A toAssert(@Nullable E value, String description) {
056    return assertFactory.createAssert(value).describedAs(description);
057  }
058
059  @Override
060  protected TypeAwareListAssert<@Nullable E, A> newAbstractIterableAssert(
061      Iterable<? extends @Nullable E> iterable
062  ) {
063    return StreamSupport
064        .stream(iterable.spliterator(), false)
065        .collect(collectingAndThen(toList(), curry()));
066  }
067
068  private Function<@Nullable List<@Nullable E>, TypeAwareListAssert<@Nullable E, A>> curry() {
069    return list -> new TypeAwareListAssert<>(list, assertFactory);
070  }
071}