View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2011-2026 Yegor Bugayenko
3    * SPDX-License-Identifier: MIT
4    */
5   package com.qulice.spi;
6   
7   import java.io.File;
8   import java.nio.file.Path;
9   import org.hamcrest.MatcherAssert;
10  import org.hamcrest.Matchers;
11  import org.junit.jupiter.api.Test;
12  import org.junit.jupiter.api.io.TempDir;
13  
14  /**
15   * Test case for {@link Relative}.
16   * @since 0.24
17   */
18  final class RelativeTest {
19  
20      @Test
21      void computesRelativePathForFileInsideBasedir(@TempDir final Path dir)
22          throws Exception {
23          MatcherAssert.assertThat(
24              "relative path under basedir must start with a forward slash",
25              new Relative(
26                  dir.toFile(), new File(dir.toFile(), "src/main/Foo.java")
27              ).path(),
28              Matchers.equalTo("/src/main/Foo.java")
29          );
30      }
31  
32      @Test
33      void returnsAbsolutePathWhenFileOutsideBasedir(@TempDir final Path dir)
34          throws Exception {
35          final File outside = new File(dir.toFile(), "sibling/Far.java");
36          MatcherAssert.assertThat(
37              "file outside basedir must not produce a truncated string",
38              new Relative(new File(dir.toFile(), "project"), outside).path(),
39              Matchers.equalTo(
40                  outside.getAbsoluteFile().toPath().normalize()
41                      .toString().replace(File.separatorChar, '/')
42              )
43          );
44      }
45  
46      @Test
47      void doesNotTruncateWhenBasedirIsStringPrefixButNotParent(
48          @TempDir final Path dir
49      ) throws Exception {
50          MatcherAssert.assertThat(
51              "sibling with shared string prefix cannot be treated as child",
52              new Relative(
53                  new File(dir.toFile(), "foo"),
54                  new File(dir.toFile(), "foobar/Baz.java")
55              ).path(),
56              Matchers.not(Matchers.startsWith("bar/"))
57          );
58      }
59  
60      @Test
61      void doesNotThrowWhenFilePathShorterThanBasedir(@TempDir final Path dir)
62          throws Exception {
63          MatcherAssert.assertThat(
64              "shallow file must not cause a substring-index exception",
65              new Relative(
66                  new File(dir.toFile(), "a/very/deep/basedir"),
67                  new File("x.java")
68              ).path(),
69              Matchers.notNullValue()
70          );
71      }
72  }