Crate stdio_override

Source
Expand description

§Stdio-Override

This crate provides a library for overriding Stdio file descriptors.
It provides a Guard for the replacement so that when the guard is dropped the file descriptors are switched back and the replacement File Descriptor will be closed.

Trying to replace an std File Descriptor twice without dropping the guard will result in a panic

Notice: When trying to use this in tests you must run with cargo test -- --nocapture otherwise it will redirect stdout/stderr again.

This library is made to be intuitive and easy to use.

§Examples

Stdout:

use stdio_override::StdoutOverride;
use std::fs;
let file_name = "./test.txt";
let guard = StdoutOverride::override_file(file_name)?;
println!("Isan to Stdout!");

let contents = fs::read_to_string(file_name)?;
assert_eq!("Isan to Stdout!\n", contents);
drop(guard);
println!("Outside!");

Stderr:

use stdio_override::StderrOverride;
use std::fs;
let file_name = "./testerr.txt";
let guard = StderrOverride::override_file(file_name)?;
eprintln!("Failure to stderr");

let contents = fs::read_to_string(file_name)?;
assert_eq!("Failure to stderr\n", contents);
drop(guard);
eprintln!("Stderr is back!");

Stdin:

use stdio_override::StdinOverride;
let file_name = "./inputs.txt";

{
    let mut file = File::create(&file_name)?;
    file.write_all(b"Inputs to stdin")?;
}
let guard = StdinOverride::override_file(file_name)?;
let mut user_input = String::new();
io::stdin().read_line(&mut user_input)?;

drop(guard);

assert_eq!("Inputs to stdin", user_input);
// Stdin is working as usual again, because the guard is dropped.

Structs§