我偶然发现Jimfs并想用它来测试文件系统交互的方法。 例如,如果写入文件列表成功,我写了一个非常长的方法来计算:
static boolean exportable(List<Path> paths, boolean force) {
List<Path> created = new LinkedList<>();
boolean success = true;
for (Path p : paths) {
if (Files.exists(p)) {
if (Files.isDirectory(p)) {
success = false;
log.error("Can't export results to file '{}': It's a directory!", p);
} else if (force) {
if (!Files.isWritable(p)) {
success = false;
log.error("Can't export to file '{}': No write access!", p);
}
} else {
success = false;
log.error("Can't export to file '{}': File does already exist and overwrite (-f) is not enabled!",
p);
}
} else { // does not exist
Path parent = p.toAbsolutePath().normalize().getParent();
if (Files.exists(parent)) {
try {
Files.createFile(p);
created.add(p);
log.debug("Created file '{}'", p);
} catch (AccessDeniedException e) {
success = false;
log.error("Can't export to file '{}': File could not be created. Access denied!", p);
} catch (IOException e) {
success = false;
log.error("Can't export to file '{}': File could not be created!", p, e);
}
} else if (force) {
List<Path> createdDirs = new ArrayList<>();
try {
createParentDirectories(parent, createdDirs);
} catch (IOException e) {
success = false;
log.error("Can't export to file '{}': Failed to create all parent directories!", p, e);
}
created.addAll(createdDirs);
try {
Files.createFile(p);
created.add(p);
log.debug("Created file '{}'.", p);
} catch (IOException e) {
success = false;
log.error("Can't export to file '{}': File could not be created!", p, e);
}
} else {
success = false;
log.error("Can't export to file '{}': File could not be created, because the parent directory '{}'"
+ " does not exist and automatic parent directory creation (-f) is not enabled!", p, parent);
}
}
}
if (!success && created.size() > 0) {
log.debug("Beginning to delete files and directories created while checking exportability.");
Collections.reverse(created); // delete created folders in reverse order
for (Path p : created) {
try {
Files.delete(p);
log.debug("Successfully deleted '{}'.", p);
} catch (IOException e) {
log.warn("Deleting file '{}' failed, which was created during exportability check!", p, e);
}
}
log.debug("Finished cleaning up created files and directories.");
}
}
我现在要做的就是写下这样的测试:
public void testExportToExistingFile_forceButNotWritable() throws Exception {
FileSystem fs = Jimfs.newFileSystem();
Path file = fs.getPath("file");
Files.createFile(file);
// How to deny writing to 'file' here???
assertFalse(exportable(ImmutableList.of(file), true));
}
我可以使用Jimfs这样做吗?如果没有,你会如何测试这种方法?
答案 0 :(得分:1)
不幸的是,Jimfs目前不支持任何类型的权限检查。它肯定是未来可能会很好的东西,它有点复杂(例如,根据POSIX和Windows文件系统之间的权限设置方式的差异)并且没有对于大多数用例来说似乎是必要的。