How to test a function that needs to be run as root

I'm writing a small library that wraps a number of system functions (currently on Mac OS X) using FFI.

One of them calls proc_kmsgbuf() in libproc.c

I have it working, and wrote a small unit test for it. But as this function can only be called with root permissions it fails with "Operation not permitted" in errno.

If I run "sudo cargo test" it passes.

What is the correct way to go about testing such functions, if there is a recommended way?

thanks

1 Like

Here is my current attempt. It checks if the user is root and only really does the test if it is, and forces output of a message that the test was skipped if not run as root...

fn am_root() -> bool {
    match env::var("USER") {
        Ok(val) => val == "root",
        Err(e) => false,
    }

}
// Issue: Needs to be run as root! :-(
#[test]
fn kmessagebuffer_test() {
    if am_root() {
        match kmsgbuf() {
            Ok(buffer) => println!("Buffer: {:?}", buffer),
            Err(message) => assert!(false, message)
        }
    } else {
        writeln!(&mut io::stdout(), "The test 'kmessagebuffer_test' was skipped as it needs to be run as root").unwrap();
    }
}
1 Like

If possible, mock them. That is,

#[cfg(test)]
unsafe fn proc_kmsgbuf() {}

#[cfg(not(test))]
extern fn proc_kmsgbuf();

As much as I like mocking, you need to at least have integration tests for a few broad cases, just to make sure that you're using the real API correctly.

I think @andrewdavidmackenzie is doing the best possible thing, except that I'd use env_logger and error!, because the code is more descriptive.