001/*
002 * Copyright (C) 2022 - 2023, 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 io.github.ascopes.jct.containers.PackageContainerGroup;
019import io.github.ascopes.jct.repr.LocationRepresentation;
020import io.github.ascopes.jct.utils.StringUtils;
021import org.apiguardian.api.API;
022import org.apiguardian.api.API.Status;
023import org.assertj.core.api.AbstractPathAssert;
024import org.jspecify.annotations.Nullable;
025import java.nio.file.Path;
026import java.util.Objects;
027import java.util.Set;
028import java.util.stream.Collectors;
029import java.util.stream.StreamSupport;
030
031import static io.github.ascopes.jct.utils.IoExceptionUtils.uncheckedIo;
032import static io.github.ascopes.jct.utils.IterableUtils.combineOneOrMore;
033import static io.github.ascopes.jct.utils.IterableUtils.requireNonNullValues;
034import static io.github.ascopes.jct.utils.StringUtils.quoted;
035import static io.github.ascopes.jct.utils.StringUtils.quotedIterable;
036import static java.util.Objects.requireNonNull;
037import static org.assertj.core.api.Assertions.assertThat;
038
039/**
040 * Assertions for package container groups.
041 *
042 * @author Ashley Scopes
043 * @since 0.0.1
044 */
045@API(since = "0.0.1", status = Status.STABLE)
046public final class PackageContainerGroupAssert
047    extends AbstractContainerGroupAssert<PackageContainerGroupAssert, PackageContainerGroup> {
048
049  /**
050   * Initialize the container group assertions.
051   *
052   * @param containerGroup the container group to assert upon.
053   */
054  public PackageContainerGroupAssert(@Nullable PackageContainerGroup containerGroup) {
055    super(containerGroup, PackageContainerGroupAssert.class);
056  }
057
058  /**
059   * Assert that all given files exist.
060   *
061   * @param path  the first path to check for
062   * @param paths additional paths to check for.
063   * @return this object for further call chaining.
064   * @throws AssertionError       if the container group is null, or if any of the files do not
065   *                              exist.
066   * @throws NullPointerException if any of the paths are null.
067   */
068  public PackageContainerGroupAssert allFilesExist(String path, String... paths) {
069    requireNonNull(path, "path");
070    requireNonNullValues(paths, "paths");
071
072    allFilesExist(combineOneOrMore(path, paths));
073    return this;
074  }
075
076  /**
077   * Assert that all given files exist.
078   *
079   * @param paths paths to check for.
080   * @return this object for further call chaining.
081   * @throws AssertionError       if the container group is null, or if any of the files do not
082   *                              exist.
083   * @throws NullPointerException if any of the paths are null.
084   */
085  public PackageContainerGroupAssert allFilesExist(Iterable<String> paths) {
086    requireNonNullValues(paths, "paths");
087
088    isNotNull();
089
090    assertThat(paths)
091        .withFailMessage(
092            "Expected all paths in %s to exist but one or more did not",
093            quotedIterable(paths)
094        )
095        .allSatisfy(this::fileExists);
096    return this;
097  }
098
099  /**
100   * Get assertions to perform on the class loader associated with this container group.
101   *
102   * @return the assertions to perform.
103   * @throws AssertionError if the container group is null.
104   */
105  public ClassLoaderAssert classLoader() {
106    isNotNull();
107
108    return new ClassLoaderAssert(actual.getClassLoader());
109  }
110
111  /**
112   * Assert that the given file does not exist.
113   *
114   * <pre><code>
115   *   // Using platform-specific separators.
116   *   assertions.fileDoesNotExist("foo/bar/baz.txt")...;
117   *
118   *   // Letting JCT infer the correct path separators to use (recommended).
119   *   assertions.fileDoesNotExist("foo", "bar", "baz.txt");
120   * </code></pre>
121   *
122   * @param fragment  the first part of the path.
123   * @param fragments any additional parts of the path.
124   * @return this assertion object for further assertions.
125   * @throws AssertionError       if the file exists, or if the container group is null.
126   * @throws NullPointerException if any of the fragments are null.
127   */
128  public PackageContainerGroupAssert fileDoesNotExist(String fragment, String... fragments) {
129    requireNonNull(fragment, "fragment");
130    requireNonNullValues(fragments, "fragments");
131
132    isNotNull();
133
134    var actualFile = actual.getFile(fragment, fragments);
135
136    if (actualFile == null) {
137      return this;
138    }
139
140    throw failure(
141        "Expected path %s to not exist in %s but it was found at %s",
142        quotedUserProvidedPath(combineOneOrMore(fragment, fragments)),
143        LocationRepresentation.getInstance().toStringOf(actual.getLocation()),
144        quoted(actualFile)
145    );
146  }
147
148  /**
149   * Assert that the given file exists.
150   *
151   * <pre><code>
152   *   // Letting JCT infer the correct path separators to use (recommended).
153   *   assertions.fileExists("foo", "bar", "baz.txt");
154   *
155   *   // Using platform-specific separators (more likely to produce unexpected results).
156   *   assertions.fileExists("foo/bar/baz.txt")...;
157   * </code></pre>
158   *
159   * <p>If the file does not exist, then this object will attempt to find the
160   * closest matches and list them in an error message along with the assertion error.
161   *
162   * @param fragment  the first part of the path.
163   * @param fragments any additional parts of the path.
164   * @return assertions to perform on the path of the file that exists.
165   * @throws AssertionError       if the file does not exist, or if the container group is null.
166   * @throws NullPointerException if any of the fragments are null.
167   */
168
169  public AbstractPathAssert<?> fileExists(String fragment, String... fragments) {
170    requireNonNull(fragment, "fragment");
171    requireNonNullValues(fragments, "fragments");
172
173    isNotNull();
174
175    var actualFile = actual.getFile(fragment, fragments);
176
177    if (actualFile != null) {
178      // File exists with this path. Hooray, lets return assertions on it.
179      return assertThat(actualFile);
180    }
181
182    var expected = combineOneOrMore(fragment, fragments);
183    var message = StringUtils.resultNotFoundWithFuzzySuggestions(
184        fuzzySafePath(expected),
185        quotedUserProvidedPath(expected),
186        listAllUniqueFilesForAllContainers(),
187        this::fuzzySafePath,
188        this::quotedUserProvidedPath,
189        "file with relative path"
190    );
191    throw failure(message);
192  }
193
194  private Set<Path> listAllUniqueFilesForAllContainers() {
195    return uncheckedIo(actual::listAllFiles)
196        .keySet()
197        .stream()
198        // Make all the files relative to their roots.
199        .flatMap(container -> uncheckedIo(container::listAllFiles)
200            .stream()
201            .map(container.getInnerPathRoot().getPath()::relativize))
202        // Filter out the inner path root itself, preventing few confusing issues with zero-length
203        // file names. In ZIP paths this can also be null, so we have to check for both "" and null
204        // here.
205        .filter(this::fileNameIsPresent)
206        // Remove duplicates (don't think this can ever happen but this is just to be safe).
207        .collect(Collectors.toSet());
208  }
209
210  private <T> String quotedUserProvidedPath(Iterable<T> parts) {
211    return StreamSupport
212        .stream(parts.spliterator(), false)
213        .map(Objects::toString)
214        .collect(Collectors.collectingAndThen(
215            Collectors.joining("/"),
216            StringUtils::quoted
217        ));
218  }
219
220  private <T> String fuzzySafePath(Iterable<T> parts) {
221    // Join on null bytes as we don't ever use those in normal path names. This way, we ignore
222    // file-system and OS-specific path separators creating ambiguities (like how Windows uses
223    // backslashes rather than forward slashes to delimit paths).
224    return StreamSupport
225        .stream(parts.spliterator(), false)
226        .map(Objects::toString)
227        .collect(Collectors.joining("\0"));
228  }
229
230  private boolean fileNameIsPresent(@Nullable Path path) {
231    // Path can be null if no path elements exist in ZipPath impls.
232    return path == null || !Objects.toString(path.getFileName(), "").isBlank();
233  }
234}