*/
package org.sonar.api.utils;
-import org.apache.commons.io.FilenameUtils;
-
-import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
+import javax.annotation.CheckForNull;
+import javax.annotation.Nullable;
+import org.apache.commons.io.FilenameUtils;
/**
* @since 4.0
*/
public class PathUtils {
- PathUtils() {
+ private PathUtils() {
// only static methods
}
/**
* Normalize path and replace file separators by forward slash
*/
+ @CheckForNull
public static String sanitize(@Nullable String path) {
return FilenameUtils.normalize(path, true);
}
* Get canonical path and replace file separators by forward slash. This
* method does not throw boring checked exception.
*/
+ @CheckForNull
public static String canonicalPath(@Nullable File file) {
+ if (file == null) {
+ return null;
+ }
try {
- return file != null ? FilenameUtils.separatorsToUnix(file.getCanonicalPath()) : null;
+ return FilenameUtils.separatorsToUnix(file.getCanonicalPath());
} catch (IOException e) {
throw new IllegalStateException("Fail to get the canonical path of " + file.getAbsolutePath(), e);
}
import java.io.File;
import java.io.IOException;
+import org.sonar.test.TestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public void testSanitize() throws Exception {
assertThat(PathUtils.sanitize("foo/bar/..")).isEqualTo("foo/");
assertThat(PathUtils.sanitize("C:\\foo\\..\\bar")).isEqualTo("C:/bar");
+ assertThat(PathUtils.sanitize(null)).isNull();
}
@Test
- public void testCanonicalPath_unchecked_exception() throws Exception {
+ public void test_canonicalPath() throws Exception {
+ File file = temp.newFile();
+ String path = PathUtils.canonicalPath(file);
+ assertThat(path).isEqualTo(FilenameUtils.separatorsToUnix(file.getCanonicalPath()));
+ }
+
+ @Test
+ public void canonicalPath_returns_null_if_null_input() {
+ assertThat(PathUtils.canonicalPath(null)).isNull();
+ }
+
+ @Test
+ public void canonicalPath_fails_to_get_canonical_path() throws Exception {
File file = mock(File.class);
when(file.getCanonicalPath()).thenThrow(new IOException());
}
@Test
- public void testCanonicalPath() throws Exception {
- File file = temp.newFile();
- String path = PathUtils.canonicalPath(file);
- assertThat(path).isEqualTo(FilenameUtils.separatorsToUnix(file.getCanonicalPath()));
- assertThat(PathUtils.canonicalPath(null)).isNull();
- }
-
- @Test
- public void haveFunGetCoverage() {
- // does not fail
- new PathUtils();
+ public void only_statics() {
+ assertThat(TestUtils.hasOnlyPrivateConstructors(PathUtils.class)).isTrue();
}
}