EzDevInfo.com

jimfs

An in-memory file system for Java 7+

Set DefaultFileSystemProvider for testing

How can I set the DefaultFileSystemProvider to use, for example, JimfsFileSystemProvider? The javadoc for FileSystems.getDefault() says I need to set a system property, but when I try to do that I get a NoSuchMethodException:

System.setProperty("java.nio.file.spi.DefaultFileSystemProvider",
                   "com.google.common.jimfs.JimfsFileSystemProvider");
FileSystems.getDefault();

Stack Trace:

java.lang.Error: java.lang.NoSuchMethodException: com.google.common.jimfs.JimfsFileSystemProvider.<init>(java.nio.file.spi.FileSystemProvider)
at java.nio.file.FileSystems$DefaultFileSystemHolder.getDefaultProvider(FileSystems.java:128)
....

Do I need to set up something else or is this a bug in jimfs?


Source: (StackOverflow)

How to force an IOException in jimfs

I have file related code to test where I would like to test my error handling for an existing file that I cannot read.

class SomeClass {
    //...
    public void load(Path path) {
       if (!Files.isRegularFile(path)) {
           return null;
       }
       //...
       try {
           // ...
       catch (IOException e) {
           // cleanup
       }
    }
}

I am using jimfs to isolate the tests from the real file system.

So how would I create a file on jimfs that is not readable?

I have already tried assigning posix permissions and a different user to the path through Files.setAttribute on the desired path, both of which seem to have been ignored when attempting to read or write to the path.


Source: (StackOverflow)

Advertisements

creating a virtual file system with JIMFS

I'd like to use Google's JIMFS for creating a virtual file system for testing purposes. I have trouble getting started, though.

I looked at this tutorial: http://www.hascode.com/2015/03/creating-in-memory-file-systems-with-googles-jimfs/

However, when I create the file system, it actually gets created in the existing file system, i. e. I cannot do:

Files.createDirectory("/virtualfolder");` because I am denied access.

Am I missing something?

Currently, my code looks something like this:

Test Class:

    FileSystem fs = Jimfs.newFileSystem(Configuration.unix());
    Path vTargetFolder = fs.getPath("/Store/homes/linux/abc/virtual");

TestedClass test = new TestedClass(vTargetFolder.toAbsolutePath().toString());

Java class somewhere:

targetPath = Paths.get(targetName);
Files.createDirectory(targetPath);

// etc., creating files and writing them to the target directory

However, I created a separate class just to test JIMFS and here the creation of the directory doesnt fail, but I cannot create a new file like this:

FileSystem fs = Jimfs.newFileSystem(Configuration.unix());
Path data = fs.getPath("/virtual");
Path dir = Files.createDirectory(data);


Path file = Files.createFile(Paths.get(dir + "/abc.txt")); // throws NoSuchFileException

What am I doing wrong?


Source: (StackOverflow)

Do I have to clean my Jimfs FileSystem after each test?

I'm using Jimfs in my tests like this:

public class FooTest {
  private FileSystem fs = Jimfs.newFileSystem(Configuration.unix());
  private List<Path> paths = new ArrayList<>();
  private Path getPath(String first, String... more) {
    Path path = fs.getPath(first, more);
    paths.add(path);
    return path;
  }
  @After public void cleanPaths() {
    for (Path path: paths) {
      Files.walkFileTree(path, FileVisitors.DELETE);
    }
  }
  @Test public void bar() {
    Path baz = getPath("baz");
    // test using baz
  }
}

Now, we know that Jimfs is in memory. Do I really need to clean up the paths I created or can I just remove the @After method (and its associated mechanism)?

I clearly think it's the basic need why jimfs was created, but well... I'm adapting existing code and I suddenly became confused about this.


Source: (StackOverflow)

Testing file system interaction: Setting file permissions

I stumbled upon Jimfs and wanted to use it for testing methods with file system interaction. For example, I wrote a pretty long method that figures out, if writing to a list of files could succeed:

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.");
    }
}

What I want to do now is to write tests like this one:

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));
}

Can I use Jimfs to do this? If not, how would you test this method?


Source: (StackOverflow)

JimFS: what is the purpose of /work directory

I started to use google jimfs and doing ls I found there work directory in the root of FS. What is the purpose of this folder?


Source: (StackOverflow)

JimFS: how to get File from Path

I started using google jimfs and I can't understand how I can get file from path. In source code I see that Path.toFile throws UnsupportedOperationException. But how then can I use it without files? For example if my application need to know if some path is folder or file.


Source: (StackOverflow)