Mocking a File for unit testing

Is there a lib that handles mocking File?

I'm not aware of anything, but ...

  • Unless you're creating something very low level: at which point you probably want to mock the underlying syscalls/OS function calls
  • or creating an extension trait for File: at which point you can easily create a struct tailored to your test needs and impl your trait for that
  • or working with reading and manipulating metadata: I've always stuck to integration tests for this, with dedicated test assets and leveraged tempfile to create copies in a temp directory for any writes. With the compiler & clippy covering so many potential regression cases that you need to guard against with tests in other languages, integration testing ends up earlier to read, faster to write, safer to maintain, lower bloat and without the usual "visibility gaps & speed" concerns (IMHO as someone who really cares about testing, and had a tendency to "over-mock" when not writing rust)

Then you probably have an API which could be better taking a generic Reader / Writer than being tied to File API Guidelines - C-RW-VALUE: and test it with an &[u8] or anything custom made to better fit your needs

If you just need it for tests, could something like

help ?

 #[test]
    fn test_sandbox_init() {

        // doesn't exist
        let files = sandbox::mock::File::new(
            &vec![
                "README.md",
                "src/main.rs",
                "src/lib.rs",
            ],
        );

        let directory = TempDir::new_in(".")
            .unwrap_or_else(|e| panic!("{}", e));

        let sandbox = Sandbox::new(
            files,
            &vec![
                "README.md:r",
                "src/main.rs:rw"
            ],
            directory
        );

        // doesn't exist
        let files = sandbox::mock::File::new(
            &vec![
                "README.md",
                "mock/main.rs"
            ],
        );
        // to get the idea
        assert_eq!(files, sandbox.tmpdir)
    }

something like this?

i'll try memoryFS if it don't work ill have to be creative ahah

more like:

- src
| ...
- tests
| - assets
| | - test_file1
| | - test_file2
...
use std::fs::File;

use tempfile::tempdir;
use dircpy::copy_dir;

let tmp = tempdir().expect("couldn't create temp dir for test");
copy_dir("tests/assets", tmp.path()).expect("couldn't copy test files");

let file1 = File::open(tmp.path().join("test_file1").unwrap();
// do some tests on file1

let dont_splat = File::create_new(tmp.path().join("test_file2").unwrap_err();
// check the error was correct

Tip: There's no value in unwrap_or_else(|e| panic!(...)) just use unwrap which will debug-print the error or expect() for a custom message.

Strictly speaking, there might be, if it's not panic!("literal string"), but panic!("formatter string using {e}") - this can't always be reproduced with unwrap/expect.