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.apiguardian.api.API;
025import org.apiguardian.api.API.Status;
026import org.assertj.core.api.AbstractAssert;
027import org.assertj.core.api.AbstractListAssert;
028import org.assertj.core.api.AssertFactory;
029import org.jspecify.annotations.Nullable;
030
031/**
032 * An implementation of {@link AbstractListAssert} that can perform type-specific assertions on the
033 * members of the container being asserted upon.
034 *
035 * <p>This acts as a bridge with AssertJ now that
036 * {@link org.assertj.core.api.FactoryBasedNavigableListAssert} has been deprecated. Users should
037 * treat this object like any other kind of {@link AbstractListAssert} for all purposes.
038 *
039 * @author Ashley Scopes
040 * @since 3.1.0
041 */
042@API(since = "3.1.0", status = Status.STABLE)
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
046  private final AssertFactory<@Nullable E, A> assertFactory;
047
048  TypeAwareListAssert(@Nullable List<? extends E> list, AssertFactory<E, A> assertFactory) {
049    super(list, TypeAwareListAssert.class);
050    this.assertFactory = assertFactory;
051  }
052
053  @Override
054  protected A toAssert(@Nullable E value, String description) {
055    return assertFactory.createAssert(value).describedAs(description);
056  }
057
058  @Override
059  protected TypeAwareListAssert<@Nullable E, A> newAbstractIterableAssert(
060      Iterable<? extends @Nullable E> iterable
061  ) {
062    return StreamSupport
063        .stream(iterable.spliterator(), false)
064        .collect(collectingAndThen(toList(), curry()));
065  }
066
067  private Function<@Nullable List<@Nullable E>, TypeAwareListAssert<@Nullable E, A>> curry() {
068    return list -> new TypeAwareListAssert<>(list, assertFactory);
069  }
070}