Last active
August 3, 2024 07:12
-
-
Save JohnScience/8586357fb1a6fdd36380cf4b552b52ca to your computer and use it in GitHub Desktop.
An example of a test that behaves differently depending on whether it is called directly or indirectly.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I work in VS Code. It has a Run Test button above every test. | |
// I have a test that renders an HTML page with Handlebars. | |
// I'd like to open the page in the browser if the test is called directly. | |
// If the test is called indirectly (but rather as a result of `cargo test`), I don't want the test to open the browser. | |
// The code below demonstrates how it can be achieved. | |
#[cfg(test)] | |
mod tests { | |
#[test] | |
fn direct_test() { | |
let called_directly = { | |
let path = format!("{}::{}", module_path!().split_once("::").map(|(_crate_name, mod_path)| mod_path).unwrap(), stringify!(direct_test)); | |
std::env::args().any(|arg| arg == path) | |
}; | |
if called_directly { | |
println!("Called directly"); | |
} else { | |
println!("Called indirectly"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment