Skip to content

Commit

Permalink
Make TestResult generic
Browse files Browse the repository at this point in the history
  • Loading branch information
wiktor-k committed Mar 11, 2024
1 parent cf69828 commit 2b0a570
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,6 @@ categories = ["development-tools::testing"]
exclude = [".github"]

[dependencies]

[dev-dependencies]
rstest = "0.18.2"
38 changes: 33 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ impl<T: std::fmt::Display> From<T> for TestError {
///
/// # Examples
///
/// Using [`TestResult`] as a result of the test function:
///
/// ```
/// use testresult::TestResult;
///
Expand All @@ -40,7 +42,31 @@ impl<T: std::fmt::Display> From<T> for TestError {
/// Ok(())
/// }
/// ```
pub type TestResult = std::result::Result<(), TestError>;
///
/// As [`TestResult`] is generic one can use it in test helper functions to return
/// objects to test functions.
/// For example [`TestResult`] used in `rstest` fixture returns a [`std::fs::File`] object that
/// can be used by the test:
///
/// ```
/// use rstest::{fixture, rstest};
/// use std::fs::File;
/// use testresult::TestResult;
///
/// #[fixture]
/// fn a_file() -> TestResult<File> {
/// let file = File::open("this-file-does-not-exist")?;
/// // ...
/// Ok(file)
/// }
///
/// #[rstest]
/// fn it_works(file: File) -> TestResult {
/// // ...
/// Ok(())
/// }
/// ```
pub type TestResult<T = ()> = std::result::Result<T, TestError>;

#[cfg(test)]
mod tests {
Expand All @@ -54,13 +80,15 @@ mod tests {
Ok(())
}

// helper function which always fails
fn test_fn() -> TestResult<std::fs::File> {
let file = std::fs::File::open("this-file-does-not-exist")?;
Ok(file)
}

#[test]
fn check_if_panics() -> TestResult {
let result = std::panic::catch_unwind(|| {
fn test_fn() -> TestResult {
std::fs::File::open("this-file-does-not-exist")?;
Ok(())
}
let _ = test_fn();
});
assert!(result.is_err());
Expand Down

0 comments on commit 2b0a570

Please sign in to comment.