### Stdout Prefix Example Source: https://docs.rs/goldentests/latest/goldentests/config/struct.TestConfig.html?search= Example usage of test_line_prefix and test_stdout_prefix for parsing expected output. ```text // expected stdout: // first line of stdout // second line of stdout // Normal comment, expected stdout is done being read. ``` -------------------------------- ### Example test file structure Source: https://docs.rs/goldentests/latest/goldentests/config/struct.TestConfig.html?search= Demonstrates how test keywords are embedded within comments in a source file. ```text std::cout << "Hello, World!\n"; std::cerr << "Goodbye, World!\n"; // These are args to your program, so this: // args: --run // Gets translated to: target/debug/my-compiler --run testfile // The expected exit status is optional, by default it is not checked. // expected exit status: 0 // The expected stdout output however is mandatory. If it is omitted, it // is assumed that stdout should be empty after invoking the program. // expected stdout: // Hello, World! // The expected stderr output is also mandatory. If it is omitted it is // likewise assumed stderr should be empty. // expected stderr: // Goodbye, World! ``` -------------------------------- ### Stderr Prefix Example Source: https://docs.rs/goldentests/latest/goldentests/config/struct.TestConfig.html?search= Example usage of test_line_prefix and test_stderr_prefix for parsing expected error output. ```text -- expected stderr: -- first line of stderr -- second line of stderr -- Normal comment, expected stderr is done being read. ``` -------------------------------- ### Exit Status Prefix Example Source: https://docs.rs/goldentests/latest/goldentests/config/struct.TestConfig.html?search= Example usage of test_line_prefix and test_exit_status_prefix for defining expected exit codes. ```text // expected exit status: 0 ``` -------------------------------- ### Define a golden test file Source: https://docs.rs/goldentests/latest/goldentests/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example of a test file using keywords to specify expected stdout, stderr, and exit status for the command under test. ```python import sys print("hello!\nfriend!") print("error!", file=sys.stderr) sys.exit(3) # Assuming 'python' is the command passed to TestConfig::new: # args: -B # expected exit status: 3 # expected stdout: # hello! # friend! # expected stderr: error! ``` -------------------------------- ### Initialize TestConfig with default keywords Source: https://docs.rs/goldentests/latest/goldentests/config/struct.TestConfig.html?search= Construct a new TestConfig instance by specifying the binary path, test directory, and comment prefix. ```rust use goldentests::TestConfig; let config = TestConfig::new("target/debug/my-compiler", "examples/goldentests", "// "); ``` -------------------------------- ### TestConfig::new Source: https://docs.rs/goldentests/latest/goldentests/config/struct.TestConfig.html Creates a new TestConfig instance with default keywords for parsing test files. ```APIDOC ## pub fn new(binary_path: Binary, test_path: Tests, test_line_prefix: &str) -> TestConfig ### Description Creates a new TestConfig for the given binary path, test path, and prefix. This uses default keywords for parsing test files. ### Parameters - **binary_path** (Binary: Into) - Required - Path to the binary to be tested. - **test_path** (Tests: Into) - Required - Path to the directory containing test files. - **test_line_prefix** (&str) - Required - The prefix used to identify test lines in the source files. ``` -------------------------------- ### TestConfig::new Source: https://docs.rs/goldentests/latest/goldentests/config/struct.TestConfig.html?search=u32+-%3E+bool Creates a new TestConfig instance with default keywords for parsing test files. ```APIDOC ## pub fn new(binary_path: Binary, test_path: Tests, test_line_prefix: &str) -> TestConfig ### Description Creates a new TestConfig for the given binary path, test path, and prefix. This uses default keywords for parsing test files. ### Parameters - **binary_path** (Binary) - Required - Path to the binary to be tested. - **test_path** (Tests) - Required - Path to the directory containing test files. - **test_line_prefix** (&str) - Required - The prefix used to identify test lines in source files. ``` -------------------------------- ### TestConfig::new Source: https://docs.rs/goldentests/latest/goldentests/config/struct.TestConfig.html?search=std%3A%3Avec Creates a new TestConfig instance with default keywords for parsing test files. ```APIDOC ## pub fn new(binary_path: Binary, test_path: Tests, test_line_prefix: &str) -> TestConfig ### Description Creates a new TestConfig for the given binary path, test path, and prefix. This uses default keywords for parsing test files. ### Parameters - **binary_path** (Binary: Into) - Required - Path to the binary being tested. - **test_path** (Tests: Into) - Required - Path to the directory containing test files. - **test_line_prefix** (&str) - Required - The prefix used to identify test configuration lines in source files. ``` -------------------------------- ### TestConfig::new Source: https://docs.rs/goldentests/latest/goldentests/index.html?search= Initializes a new configuration for running golden tests, specifying the binary to test, the directory containing test files, and the comment syntax used for test metadata. ```APIDOC ## TestConfig::new ### Description Creates a new TestConfig instance to manage the execution of golden tests. ### Signature `pub fn new(binary_path: &str, test_directory: &str, comment_syntax: &str) -> TestResult` ### Parameters - **binary_path** (str) - The path to the binary or command to be tested. - **test_directory** (str) - The directory containing the test files. - **comment_syntax** (str) - The comment prefix used in test files to define golden test metadata. ``` -------------------------------- ### TestConfig::new Source: https://docs.rs/goldentests/latest/goldentests/index.html Initializes a new configuration for running golden tests, specifying the binary to test, the directory containing test files, and the comment syntax used for test metadata. ```APIDOC ## TestConfig::new ### Description Creates a new TestConfig instance to manage golden test execution. ### Signature `pub fn new(command: &str, test_directory: &str, comment_syntax: &str) -> TestResult` ### Parameters - **command** (str) - The path to the binary or command to be tested. - **test_directory** (str) - The directory path containing the golden test files. - **comment_syntax** (str) - The comment prefix used in test files to embed golden test keywords. ``` -------------------------------- ### into_ok Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the contained Ok value without panicking. ```APIDOC ## pub const fn into_ok(self) -> T ### Description Returns the contained `Ok` value, but never panics. This is a nightly-only experimental API. ``` -------------------------------- ### TestConfig::new_from_config_file Source: https://docs.rs/goldentests/latest/goldentests/config/struct.TestConfig.html Creates a TestConfig by reading settings from a goldentests.toml file. ```APIDOC ## pub fn new_from_config_file(path: Option) -> TestConfig ### Description Creates a TestConfig from reading a goldentests.toml configuration file. If no path is provided, it searches the current and parent directories. ### Parameters - **path** (Option) - Optional - Path to the configuration file. ``` -------------------------------- ### TestConfig::new_from_config_file Source: https://docs.rs/goldentests/latest/goldentests/config/struct.TestConfig.html?search=std%3A%3Avec Creates a TestConfig by reading a goldentests.toml configuration file. ```APIDOC ## pub fn new_from_config_file(path: Option) -> TestConfig ### Description Creates a TestConfig from reading a `goldentests.toml` configuration file. If no path is provided, it searches the current and parent directories. ### Parameters - **path** (Option) - Optional - Path to the configuration file. ``` -------------------------------- ### TestConfig::with_custom_keywords Source: https://docs.rs/goldentests/latest/goldentests/config/struct.TestConfig.html?search=u32+-%3E+bool Creates a TestConfig with custom keywords for parsing test files. ```APIDOC ## pub fn with_custom_keywords(...) -> TestConfig ### Description Allows customization of the keywords used when searching through test files, such as changing the prefixes for arguments, stdout, stderr, and exit status. ``` -------------------------------- ### TestConfig::with_custom_keywords Source: https://docs.rs/goldentests/latest/goldentests/config/struct.TestConfig.html?search=std%3A%3Avec Creates a TestConfig with fully customizable keywords for test parsing. ```APIDOC ## pub fn with_custom_keywords(...) -> TestConfig ### Description Allows customization of all keywords and prefixes used when searching through test files. ### Parameters - **binary_path** (Binary: Into) - Required - **test_path** (Tests: Into) - Required - **glob** (Vec) - Required - **test_line_prefix** (&str) - Required - **test_args_prefix** (&str) - Required - **test_args_after_prefix** (&str) - Required - **test_stdout_prefix** (&str) - Required - **test_stderr_prefix** (&str) - Required - **test_exit_status_prefix** (&str) - Required - **overwrite_tests** (bool) - Required ``` -------------------------------- ### TestConfig::with_custom_keywords Source: https://docs.rs/goldentests/latest/goldentests/config/struct.TestConfig.html Creates a TestConfig with fully customizable keywords for test parsing. ```APIDOC ## pub fn with_custom_keywords(binary_path: Binary, test_path: Tests, glob: Vec, test_line_prefix: &str, test_args_prefix: &str, test_args_after_prefix: &str, test_stdout_prefix: &str, test_stderr_prefix: &str, test_exit_status_prefix: &str, overwrite_tests: bool) -> TestConfig ### Description Allows full customization of the keywords used when searching through test files. ``` -------------------------------- ### Globs::new Source: https://docs.rs/goldentests/latest/goldentests/glob/struct.Globs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new instance of Globs from a slice of glob pattern strings. ```APIDOC ## pub fn new(glob_strings: &[String]) -> TestResult ### Description Creates a new Globs instance initialized with the provided slice of glob strings. ### Parameters - **glob_strings** (&[String]) - Required - A slice of strings representing the glob patterns to match against. ``` -------------------------------- ### TestConfig::run_tests Source: https://docs.rs/goldentests/latest/goldentests/config/struct.TestConfig.html?search=std%3A%3Avec Executes the tests configured in the TestConfig instance. ```APIDOC ## pub fn run_tests(&self) -> TestResult<()> ### Description Recurses through all files in the configured path, parses them, and runs the target program with the arguments specified in the file. ``` -------------------------------- ### Configure goldentests in a Rust test function Source: https://docs.rs/goldentests/latest/goldentests/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initialize the TestConfig with the binary path, test directory, and comment syntax to enable automated golden testing. ```rust use goldentests::{ TestConfig, TestResult }; #[test] fn run_goldentests() -> TestResult<()> { // Replace "// " with your language's/parser's comment syntax. // This tells golden tests to embed its keywords in lines beginning with "// " let config = TestConfig::new("target/debug/my-binary", "directory/with/tests", "// ")?; config.run_tests() } ``` -------------------------------- ### Chain Results with And Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Returns the provided result if the current result is Ok, otherwise returns the Err. ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` -------------------------------- ### Providing default values with unwrap_or Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Returns the contained Ok value or a provided default value if the result is Err. ```rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### TestConfig::run_tests Source: https://docs.rs/goldentests/latest/goldentests/index.html Executes the golden tests based on the provided configuration. ```APIDOC ## TestConfig::run_tests ### Description Runs all golden tests found in the configured directory and compares the actual output against the expected output defined in the test files. ### Signature `pub fn run_tests(&self) -> TestResult<()>` ``` -------------------------------- ### unwrap Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the contained Ok value, consuming the self value. Panics if the value is an Err. ```APIDOC ## pub fn unwrap(self) -> T ### Description Returns the contained `Ok` value, consuming the `self` value. Panics if the value is an `Err`. ### Parameters - **self** (Result) - The result instance to unwrap. ``` -------------------------------- ### Using or to provide fallback Results Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Returns the current result if it is Ok, otherwise returns the provided alternative result. Arguments are evaluated eagerly. ```rust let x: Result = Ok(2); let y: Result = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("early error"); let y: Result = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("not a 2"); let y: Result = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result = Ok(2); let y: Result = Ok(100); assert_eq!(x.or(y), Ok(2)); ``` -------------------------------- ### TestConfig Struct Definition Source: https://docs.rs/goldentests/latest/goldentests/config/struct.TestConfig.html?search= The primary configuration structure for defining test behavior and file parsing rules. ```rust pub struct TestConfig {Show 13 fields pub binary_path: PathBuf, pub test_path: PathBuf, pub glob: Vec, pub test_line_prefix: String, pub test_args_prefix: String, pub test_args_after_prefix: String, pub test_stdout_prefix: String, pub test_stderr_prefix: String, pub test_exit_status_prefix: String, pub overwrite_tests: bool, pub interactive: bool, pub base_args: String, pub base_args_after: String, } ``` -------------------------------- ### Calculate Product of Result Items Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Demonstrates using the Product trait to multiply values within a Result iterator, returning Err if any parsing fails. ```rust let nums = vec!["5", "10", "1", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert_eq!(total, Ok(100)); let nums = vec!["5", "10", "one", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert!(total.is_err()); ``` -------------------------------- ### Provide Default Values with unwrap_or and unwrap_or_else Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html Use unwrap_or to return a default value on Err, or unwrap_or_else to compute a default value using a closure. ```rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` ```rust fn count(x: &str) -> usize { x.len() } assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` -------------------------------- ### Check Result with Predicate Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search= Using is_ok_and to check if a Result is Ok and matches a predicate. ```rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Collect Results with FromIterator Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Demonstrates how FromIterator short-circuits on the first Err encountered when collecting a sequence of Results. ```rust let v = vec![1, 2]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3])); ``` ```rust let v = vec![1, 2, 0]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!")); ``` ```rust let v = vec![3, 2, 1, 10]; let mut shared = 0; let res: Result, &'static str> = v.iter().map(|x: &u32| { shared += x; x.checked_sub(2).ok_or("Underflow!") }).collect(); assert_eq!(res, Err("Underflow!")); assert_eq!(shared, 6); ``` -------------------------------- ### unwrap_or_default Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the contained Ok value or the default value for the type if the result is Err. ```APIDOC ## pub fn unwrap_or_default(self) -> T ### Description Consumes the `self` argument then, if `Ok`, returns the contained value, otherwise if `Err`, returns the default value for that type. ``` -------------------------------- ### Convert Result to Option Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Methods to convert Result into Option by either keeping the Ok value or the Err value. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` ```rust let x: Result = Ok(2); assert_eq!(x.err(), None); let x: Result = Err("Nothing here"); assert_eq!(x.err(), Some("Nothing here")); ``` -------------------------------- ### and Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the provided result if the current result is Ok, otherwise returns the Err value. ```APIDOC ## pub fn and(self, res: Result) -> Result ### Description Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`. ``` -------------------------------- ### Map Result to Default or Fallback Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Methods to handle Result by providing default values or fallback functions when an Err is encountered. ```rust let x: Result<_, &str> = Ok("foo"); assert_eq!(x.map_or(42, |v| v.len()), 3); let x: Result<&str, _> = Err("bar"); assert_eq!(x.map_or(42, |v| v.len()), 42); ``` ```rust let k = 21; let x : Result<_, &str> = Ok("foo"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3); let x : Result<&str, _> = Err("bar"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42); ``` ```rust let x: Result<_, &str> = Ok("foo"); let y: Result<&str, _> = Err("bar"); assert_eq!(x.map_or_default(|x| x.len()), 3); assert_eq!(y.map_or_default(|y| y.len()), 0); ``` -------------------------------- ### into_err Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the contained Err value without panicking. ```APIDOC ## pub const fn into_err(self) -> E ### Description Returns the contained `Err` value, but never panics. This is a nightly-only experimental API. ``` -------------------------------- ### Unwrap Result with Default Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Returns the Ok value or the default value of the type if the result is Err. ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### and_then Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Calls the provided function if the result is Ok, otherwise returns the Err value. ```APIDOC ## pub fn and_then(self, op: F) -> Result ### Description Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`. ``` -------------------------------- ### Into Ok Value Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Extracts the Ok value without risk of panicking, requiring the error type to be Infallible. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Reference Conversion for Result Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Methods to obtain references or mutable references to the contents of a Result. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### Computing default values with unwrap_or_else Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Returns the contained Ok value or computes a default value using a closure if the result is Err. ```rust fn count(x: &str) -> usize { x.len() } assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` -------------------------------- ### Copy Result Contents Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Copies the contents of an Ok variant for types that implement Copy. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` -------------------------------- ### Consume Result with IntoIterator Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Shows how IntoIterator treats Ok as a single-element collection and Err as an empty collection. ```rust let x: Result = Ok(5); let v: Vec = x.into_iter().collect(); assert_eq!(v, [5]); let x: Result = Err("nothing!"); let v: Vec = x.into_iter().collect(); assert_eq!(v, []); ``` -------------------------------- ### Unwrap Result Values Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Extracts the Ok value or panics if the result is Err. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### Fallback to Alternative Results with or and or_else Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html Use or to return an alternative Result if the current one is Err, or or_else to compute an alternative Result lazily. ```rust let x: Result = Ok(2); let y: Result = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("early error"); let y: Result = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("not a 2"); let y: Result = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result = Ok(2); let y: Result = Ok(100); assert_eq!(x.or(y), Ok(2)); ``` ```rust fn sq(x: u32) -> Result { Ok(x * x) } fn err(x: u32) -> Result { Err(x) } assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2)); assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2)); assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9)); assert_eq!(Err(3).or_else(err).or_else(err), Err(3)); ``` -------------------------------- ### Expect Result Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Returns the contained Ok value or panics with a provided message if the result is Err. ```rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### Check Result Status Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Methods to verify if a Result is Ok or Err. ```rust let x: Result = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` ```rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` ```rust let x: Result = Ok(-3); assert_eq!(x.is_err(), false); let x: Result = Err("Some error message"); assert_eq!(x.is_err(), true); ``` -------------------------------- ### Chain Results with And Then Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Calls a function if the result is Ok, allowing for lazy evaluation and control flow. ```rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } ``` -------------------------------- ### expect_err Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the contained Err value, panicking if the result is Ok. ```APIDOC ## pub fn expect_err(self, msg: &str) -> E ### Description Returns the contained `Err` value, consuming the `self` value. Panics if the value is an `Ok`, with a panic message including the passed message. ``` -------------------------------- ### unwrap_err Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the contained Err value, panicking if the result is Ok. ```APIDOC ## pub fn unwrap_err(self) -> E ### Description Returns the contained `Err` value, consuming the `self` value. Panics if the value is an `Ok`. ``` -------------------------------- ### Clone Result Contents Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Clones the contents of an Ok variant for types that implement Clone. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### Unwrapping Ok values without checks Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Unwraps the Ok value without checking for Err. Calling this on Err is undefined behavior. ```rust let x: Result = Ok(2); assert_eq!(unsafe { x.unwrap_unchecked() }, 2); ``` ```rust let x: Result = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior! ``` -------------------------------- ### Expect Error from Result Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Returns the Err value or panics if the result is Ok. ```rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### Inspect Result Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Executes a closure with a reference to the contained value if the result is Ok, returning the original result. ```rust let x: u8 = "4" .parse::() .inspect(|x| println!("original: {x}")) .map(|x| x.pow(3)) .expect("failed to parse number"); ``` -------------------------------- ### Map Result Values Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Transform the Ok value of a Result using a mapping function. ```rust let line = "1\n2\n3\n4\n"; for num in line.lines() { match num.parse::().map(|i| i * 2) { Ok(n) => println!("{n}"), Err(..) => {} } } ``` -------------------------------- ### Transpose Result and Option Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Transposes a Result of an Option into an Option of a Result. ```rust #[derive(Debug, Eq, PartialEq)] struct SomeErr; let x: Result, SomeErr> = Ok(Some(5)); let y: Option> = Some(Ok(5)); assert_eq!(x.transpose(), y); ``` -------------------------------- ### Unwrap Error from Result Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Returns the Err value or panics if the result is Ok. ```rust let x: Result = Ok(2); x.unwrap_err(); // panics with `2` ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### Globs::is_match Source: https://docs.rs/goldentests/latest/goldentests/glob/struct.Globs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Checks if a given file path matches any of the glob patterns stored in the Globs instance. ```APIDOC ## pub fn is_match(&self, path: &Path) -> bool ### Description Determines whether the specified path matches any of the glob patterns defined in this instance. ### Parameters - **path** (&Path) - Required - The file path to check against the glob patterns. ### Returns - **bool** - Returns true if the path matches, false otherwise. ``` -------------------------------- ### Calculate Sum of Result Items Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Demonstrates using the Sum trait to add values within a Result iterator, returning Err if a negative element is encountered. ```rust let f = |&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) }; let v = vec![1, 2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Ok(3)); let v = vec![1, -2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Err("Negative element found")); ``` -------------------------------- ### Globs struct definition Source: https://docs.rs/goldentests/latest/goldentests/glob/struct.Globs.html?search= The internal structure definition for Globs. ```rust pub struct Globs { /* private fields */ } ``` -------------------------------- ### Check Result with is_err_and Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Returns true if the result is Err and the contained value matches the provided predicate. ```rust use std::io::{Error, ErrorKind}; let x: Result = Err(Error::new(ErrorKind::NotFound, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true); let x: Result = Err(Error::new(ErrorKind::PermissionDenied, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Ok(123); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Err("ownership".to_string()); assert_eq!(x.as_ref().is_err_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Chaining Result operations with and_then Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Use and_then to chain fallible operations that return a Result. The closure is only executed if the previous result is Ok. ```rust assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string())); assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed")); assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number")); ``` ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Into Error Value Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Extracts the Err value without risk of panicking, requiring the ok type to be Infallible. ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### Represent TestResult Enum Structure Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search= The underlying enum structure for TestResult. ```rust pub enum TestResult { Ok(T), Err(()), } ``` -------------------------------- ### Iterate Result Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Returns an iterator over the contained value if the result is Ok, otherwise returns an empty iterator. ```rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Inspect Error Result Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Executes a closure with a reference to the contained error if the result is Err, returning the original result. ```rust use std::{fs, io}; fn read() -> io::Result { fs::read_to_string("address.txt") .inspect_err(|e| eprintln!("failed to read file: {e}")) } ``` -------------------------------- ### Using or_else for lazy fallback Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Calls a closure to compute a fallback result if the current result is Err. Useful for lazy evaluation. ```rust fn sq(x: u32) -> Result { Ok(x * x) } fn err(x: u32) -> Result { Err(x) } assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2)); assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2)); assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9)); assert_eq!(Err(3).or_else(err).or_else(err), Err(3)); ``` -------------------------------- ### Unwrapping Err values without checks Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Unwraps the Err value without checking for Ok. Calling this on Ok is undefined behavior. ```rust let x: Result = Ok(2); unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); ``` -------------------------------- ### Flatten Nested Results Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Converts a nested Result into a single-level Result. ```rust let x: Result, u32> = Ok(Ok("hello")); assert_eq!(Ok("hello"), x.flatten()); let x: Result, u32> = Ok(Err(6)); assert_eq!(Err(6), x.flatten()); let x: Result, u32> = Err(6); assert_eq!(Err(6), x.flatten()); ``` ```rust let x: Result, u32>, u32> = Ok(Ok(Ok("hello"))); assert_eq!(Ok(Ok("hello")), x.flatten()); assert_eq!(Ok("hello"), x.flatten().flatten()); ``` -------------------------------- ### Into Error Infallible Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search= Extracts the Err value from a Result known to be infallible. ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### Iterate Mut Result Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Returns a mutable iterator over the contained value if the result is Ok, otherwise returns an empty iterator. ```rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### Map Error Result Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Transforms the error variant of a Result while leaving the Ok variant unchanged. ```rust fn stringify(x: u32) -> String { format!("error code: {x}") } let x: Result = Ok(2); assert_eq!(x.map_err(stringify), Ok(2)); let x: Result = Err(13); assert_eq!(x.map_err(stringify), Err("error code: 13".to_string())); ``` -------------------------------- ### Deref Result Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Converts a Result containing a dereferenceable type into a Result containing a reference to the target type. ```rust let x: Result = Ok("hello".to_string()); let y: Result<&str, &u32> = Ok("hello"); assert_eq!(x.as_deref(), y); let x: Result = Err(42); let y: Result<&str, &u32> = Err(&42); assert_eq!(x.as_deref(), y); ``` -------------------------------- ### Define TestResult Type Alias Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool The TestResult type alias simplifies Result usage by fixing the error type to unit. ```rust pub type TestResult = Result; ``` ```rust pub enum TestResult { Ok(T), Err(()), } ``` -------------------------------- ### Deref Mut Result Source: https://docs.rs/goldentests/latest/goldentests/error/type.TestResult.html?search=u32+-%3E+bool Converts a Result containing a mutable dereferenceable type into a Result containing a mutable reference to the target type. ```rust let mut s = "HELLO".to_string(); let mut x: Result = Ok("hello".to_string()); let y: Result<&mut str, &mut u32> = Ok(&mut s); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); let mut i = 42; let mut x: Result = Err(42); let y: Result<&mut str, &mut u32> = Err(&mut i); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.