78 lines
2.5 KiB
Java
78 lines
2.5 KiB
Java
package com.sftp.manager.service;
|
|
|
|
import org.junit.jupiter.api.Assertions;
|
|
import org.junit.jupiter.api.Test;
|
|
import org.junit.jupiter.api.io.TempDir;
|
|
|
|
import java.io.File;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.nio.file.Files;
|
|
import java.nio.file.Path;
|
|
|
|
public class LocalFileServiceTest {
|
|
|
|
private final LocalFileService localFileService = new LocalFileService();
|
|
|
|
@TempDir
|
|
Path tempDir;
|
|
|
|
@Test
|
|
public void createDirectory_shouldRejectParentTraversalPath() {
|
|
String badPath = tempDir.resolve("../escape-dir").toString();
|
|
|
|
Exception ex = Assertions.assertThrows(Exception.class,
|
|
() -> localFileService.createDirectory(badPath));
|
|
|
|
Assertions.assertTrue(ex.getMessage().contains("上级目录引用"));
|
|
}
|
|
|
|
@Test
|
|
public void deleteFile_shouldRejectRootPath() {
|
|
File[] roots = File.listRoots();
|
|
Assertions.assertNotNull(roots);
|
|
Assertions.assertTrue(roots.length > 0);
|
|
|
|
String rootPath = roots[0].getPath();
|
|
|
|
Exception ex = Assertions.assertThrows(Exception.class,
|
|
() -> localFileService.deleteFile(rootPath));
|
|
|
|
Assertions.assertTrue(ex.getMessage().contains("根目录禁止删除"));
|
|
}
|
|
|
|
@Test
|
|
public void renameFile_shouldRejectCrossDirectoryRename() throws Exception {
|
|
Path source = tempDir.resolve("source.txt");
|
|
Files.write(source, "data".getBytes(StandardCharsets.UTF_8));
|
|
|
|
Path subDir = tempDir.resolve("sub");
|
|
Files.createDirectories(subDir);
|
|
Path target = subDir.resolve("target.txt");
|
|
|
|
Exception ex = Assertions.assertThrows(Exception.class,
|
|
() -> localFileService.renameFile(source.toString(), target.toString()));
|
|
|
|
Assertions.assertTrue(ex.getMessage().contains("仅支持同目录重命名"));
|
|
}
|
|
|
|
@Test
|
|
public void renameFile_shouldAllowRenameInSameDirectory() throws Exception {
|
|
Path source = tempDir.resolve("old-name.txt");
|
|
Files.write(source, "data".getBytes(StandardCharsets.UTF_8));
|
|
Path target = tempDir.resolve("new-name.txt");
|
|
|
|
boolean result = localFileService.renameFile(source.toString(), target.toString());
|
|
|
|
Assertions.assertTrue(result);
|
|
Assertions.assertFalse(Files.exists(source));
|
|
Assertions.assertTrue(Files.exists(target));
|
|
}
|
|
|
|
@Test
|
|
public void fileExists_shouldReturnFalseWhenPathContainsTraversal() {
|
|
boolean exists = localFileService.fileExists("../sensitive-path");
|
|
|
|
Assertions.assertFalse(exists);
|
|
}
|
|
}
|