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   *
17   * @since 0.24
18   */
19  final class RelativeTest {
20  
21      @Test
22      void computesRelativePathForFileInsideBasedir(@TempDir final Path dir)
23          throws Exception {
24          MatcherAssert.assertThat(
25              "relative path under basedir must start with a forward slash",
26              new Relative(
27                  dir.toFile(), new File(dir.toFile(), "src/main/Foo.java")
28              ).path(),
29              Matchers.equalTo("/src/main/Foo.java")
30          );
31      }
32  
33      @Test
34      void returnsAbsolutePathWhenFileOutsideBasedir(@TempDir final Path dir)
35          throws Exception {
36          final File outside = new File(dir.toFile(), "sibling/Far.java");
37          MatcherAssert.assertThat(
38              "file outside basedir must not produce a truncated string",
39              new Relative(new File(dir.toFile(), "project"), outside).path(),
40              Matchers.equalTo(
41                  outside.getAbsoluteFile().toPath().normalize()
42                      .toString().replace(File.separatorChar, '/')
43              )
44          );
45      }
46  
47      @Test
48      void doesNotTruncateWhenBasedirIsStringPrefixButNotParent(
49          @TempDir final Path dir
50      ) throws Exception {
51          MatcherAssert.assertThat(
52              "sibling with shared string prefix cannot be treated as child",
53              new Relative(
54                  new File(dir.toFile(), "foo"),
55                  new File(dir.toFile(), "foobar/Baz.java")
56              ).path(),
57              Matchers.not(Matchers.startsWith("bar/"))
58          );
59      }
60  
61      @Test
62      void doesNotThrowWhenFilePathShorterThanBasedir(@TempDir final Path dir)
63          throws Exception {
64          MatcherAssert.assertThat(
65              "shallow file must not cause a substring-index exception",
66              new Relative(
67                  new File(dir.toFile(), "a/very/deep/basedir"),
68                  new File("x.java")
69              ).path(),
70              Matchers.notNullValue()
71          );
72      }
73  }