Skip to content

Instantly share code, notes, and snippets.

@JohnScience
Last active August 3, 2024 07:12
Show Gist options
  • Save JohnScience/8586357fb1a6fdd36380cf4b552b52ca to your computer and use it in GitHub Desktop.
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.
// 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