testresult-0.4.1/.cargo_vcs_info.json0000644000000001360000000000100132540ustar { "git": { "sha1": "1502e5c7821e6d0c22ecb0d3ca17625e9b66ea30" }, "path_in_vcs": "" }testresult-0.4.1/.codespellrc000064400000000000000000000001171046102023000143430ustar 00000000000000[codespell] skip = .cargo,.git,target,Cargo.lock ignore-words-list = crate,ser testresult-0.4.1/.env000064400000000000000000000001511046102023000126320ustar 00000000000000# Ubuntu packages UBUNTU_PACKAGES= # Windows packages WINDOWS_PACKAGES= # macOS packages MACOS_PACKAGES= testresult-0.4.1/.gitattributes000064400000000000000000000000161046102023000147340ustar 00000000000000* text eol=lf testresult-0.4.1/.gitignore000064400000000000000000000000101046102023000140230ustar 00000000000000/target testresult-0.4.1/.justfile000075500000000000000000000050771046102023000137060ustar 00000000000000#!/usr/bin/env -S just --working-directory . --justfile # Load project-specific properties from the `.env` file set dotenv-load := true # Since this is a first recipe it's being run by default. # Faster checks need to be executed first for better UX. For example # codespell is very fast. cargo fmt does not need to download crates etc. # Perform all checks check: spelling formatting docs lints dependencies tests # Checks common spelling mistakes spelling: codespell # Checks source code formatting formatting: just --unstable --fmt --check # We're using nightly to properly group imports, see .rustfmt.toml cargo +nightly fmt --all -- --check # Lints the source code lints: cargo clippy --workspace --no-deps --all-targets -- -D warnings # Checks for issues with dependencies dependencies: cargo deny check # Runs all unit tests. By default ignored tests are not run. Run with `ignored=true` to run only ignored tests tests: cargo test --all # Build docs for this crate only docs: cargo doc --no-deps # Installs packages required to build [linux] install-packages: sudo apt-get install --assume-yes --no-install-recommends $UBUNTU_PACKAGES [macos] [windows] install-packages: echo no-op # Checks for commit messages check-commits REFS='main..': #!/usr/bin/env bash set -euo pipefail for commit in $(git rev-list "{{ REFS }}"); do MSG="$(git show -s --format=%B "$commit")" CODESPELL_RC="$(mktemp)" git show "$commit:.codespellrc" > "$CODESPELL_RC" if ! grep -q "Signed-off-by: " <<< "$MSG"; then printf "Commit %s lacks \"Signed-off-by\" line.\n" "$commit" printf "%s\n" \ " Please use:" \ " git rebase --signoff main && git push --force-with-lease" \ " See https://developercertificate.org/ for more details." exit 1; elif ! codespell --config "$CODESPELL_RC" - <<< "$MSG"; then printf "The spelling in commit %s needs improvement.\n" "$commit" exit 1; else printf "Commit %s is good.\n" "$commit" fi done # Fixes common issues. Files need to be git add'ed fix: #!/usr/bin/env bash set -euo pipefail if ! git diff-files --quiet ; then echo "Working tree has changes. Please stage them: git add ." exit 1 fi codespell --write-changes just --unstable --fmt # try to fix rustc issues cargo fix --allow-staged # try to fix clippy issues cargo clippy --fix --allow-staged # fmt must be last as clippy's changes may break formatting cargo +nightly fmt --all testresult-0.4.1/.rustfmt.toml000064400000000000000000000001061046102023000145200ustar 00000000000000group_imports = "StdExternalCrate" format_code_in_doc_comments = true testresult-0.4.1/CHANGELOG.md000064400000000000000000000010621046102023000136540ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. ## [Unreleased] ## v0.4.1 - Expose `TestError` and make a couple of doc improvements. Thanks to @ijackson for implementing this change ([#14](https://github.com/wiktor-k/testresult/pull/14)). ## v0.4.0 - Make `TestResult` generic to be more flexible. - Print the error message using "alternate" format (`{:#}`) for better anyhow messages. ## v0.3.0 - Modified hidden error type name. - Cleaned up documentation. ## v0.2.0 - API cleanup ## v0.1.0 - First public release testresult-0.4.1/CONTRIBUTING.md000064400000000000000000000051561046102023000143040ustar 00000000000000# Contributing Thanks for taking the time to contribute to this project! All changes need to: - pass basic checks, including tests, formatting and lints, - be signed-off. ## Basic checks We are using standard Rust ecosystem tools including `rustfmt` and `clippy` with one minor difference. Due to a couple of `rustfmt` features being available only in nightly (see the `.rustfmt.toml` file) nightly `rustfmt` is necessary. All of these details are captured in a `.justfile` and can be checked by running [`just`'](https://just.systems/). To run all checks locally before sending them to CI you can set your git hooks directory: ```sh git config core.hooksPath scripts/hooks/ ``` ## Developer Certificate of Origin The sign-off is a simple line at the end of the git commit message, which certifies that you wrote it or otherwise have the right to pass it on as a open-source patch. The rules are pretty simple: if you can [certify the below][DCO]: ``` Developer's Certificate of Origin 1.1 By making a contribution to this project, I certify that: (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. ``` then you just add a line saying Signed-off-by: Random J Developer using your name. If you set your `user.name` and `user.email`, you can sign your commit automatically with [`git commit --signoff`][GSO]. To sign-off your last commit: git commit --amend --signoff [DCO]: https://developercertificate.org [GSO]: https://git-scm.com/docs/git-commit#git-commit---signoff If you want to fix multiple commits use: git rebase --signoff main To check if your commits are correctly signed-off locally use `just check-commits`. testresult-0.4.1/Cargo.toml0000644000000022300000000000100112470ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "testresult" version = "0.4.1" authors = ["Wiktor Kwapisiewicz "] build = false exclude = [".github"] autobins = false autoexamples = false autotests = false autobenches = false description = "Provides TestResult type for concise and precise test failures" readme = "README.md" keywords = [ "testing", "error", "error-handling", ] categories = [ "development-tools::testing", "rust-patterns", ] license = "MIT OR Apache-2.0" repository = "https://github.com/wiktor-k/testresult" [lib] name = "testresult" path = "src/lib.rs" [dependencies] [dev-dependencies.anyhow] version = "1.0.86" [dev-dependencies.rstest] version = "0.21.0" testresult-0.4.1/Cargo.toml.orig000064400000000000000000000007511046102023000147360ustar 00000000000000[package] name = "testresult" version = "0.4.1" edition = "2021" authors = ["Wiktor Kwapisiewicz "] description = "Provides TestResult type for concise and precise test failures" repository = "https://github.com/wiktor-k/testresult" license = "MIT OR Apache-2.0" keywords = ["testing", "error", "error-handling"] categories = ["development-tools::testing", "rust-patterns"] exclude = [".github"] [dependencies] [dev-dependencies] anyhow = "1.0.86" rstest = "0.21.0" testresult-0.4.1/LICENSE-APACHE000064400000000000000000000251371046102023000140000ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. testresult-0.4.1/LICENSE-MIT000064400000000000000000000017771046102023000135140ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. testresult-0.4.1/README.md000064400000000000000000000066541046102023000133360ustar 00000000000000# Test result [![CI](https://github.com/wiktor-k/testresult/actions/workflows/rust.yml/badge.svg)](https://github.com/wiktor-k/testresult/actions/workflows/rust.yml) [![Crates.io](https://img.shields.io/crates/v/testresult)](https://crates.io/crates/testresult) [![Codecov](https://img.shields.io/codecov/c/gh/wiktor-k/testresult)](https://app.codecov.io/gh/wiktor-k/testresult) Provides `TestResult` type that can be used in tests to avoid `unwrap`s but at the same time to have precise stacktraces with the point of failure clearly written. It's like a lean [`anyhow`](https://crates.io/crates/anyhow) for tests! ## Details Consider the following code. It uses `unwrap` so the test failure stacktrace will informative. Unfortunately it's not as concise as it could be: ```rust #[test] fn it_works() { // ... std::fs::File::open("this-file-does-not-exist").unwrap(); // ... } ``` Improved version of this code uses `Result` and the `?` operator: ```rust #[test] fn it_works() -> Result<(), Box> { // ... std::fs::File::open("this-file-does-not-exist")?; // ... Ok(()) } ``` Running the following code with `RUST_BACKTRACE=1 cargo test` shows the following stacktrace: ```text ---- tests::it_works stdout ---- thread 'tests::it_works' panicked at 'assertion failed: `(left == right)` left: `1`, ... 4: test::assert_test_result at /rustc/4b91a6ea7258a947e59c6522cd5898e7c0a6a88f/library/test/src/lib.rs:184:5 5: testresult::tests::it_works::{{closure}} at ./src/lib.rs:52:5 6: core::ops::function::FnOnce::call_once at /rustc/4b91a6ea7258a947e59c6522cd5898e7c0a6a88f/library/core/src/ops/function.rs:248:5 ... note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace. ``` Unfortunately even though the test function location is recorded, the exact line where the test failure occurred is not present in the backtrace. Let's adjust the test result type to use `TestResult`. This is the only change compared to previous example: ```rust #[test] fn it_works() -> TestResult { // ... std::fs::File::open("this-file-does-not-exist")?; // ... Ok(()) } ``` Running it again with `cargo test` shows more details: ```text ---- tests::it_works stdout ---- thread 'tests::it_works' panicked at 'error: std::io::error::Error - No such file or directory (os error 2)', src/lib.rs:53:9 ``` Note that the error location is now in the backtrace and also in the test failure message. This means that we don't even need the backtrace to know where the error happened. The advantages of using `TestResult`: - exact failure line is present in the test failure and the backtrace, - the underlying error type and message are present in the test failure, - the signature of the test result is simpler. For a more elaborate description see ["Improving failure messages in Rust tests returning a Result"][IMPROV]. [IMPROV]: https://bluxte.net/musings/2023/01/08/improving_failure_messages_rust_tests/ ## License This project is licensed under either of: - [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0), - [MIT license](https://opensource.org/licenses/MIT). at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. testresult-0.4.1/SECURITY.md000064400000000000000000000017551046102023000136450ustar 00000000000000# Security policy If you have discovered a security vulnerability in this project, please report it privately. Do not disclose it as a public issue. This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released. This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure. We will contact you back within 2 business days after reporting the issue. Thanks for helping make the project safe for everyone! ## Reporting a vulnerability Please, report the vulnerability either through [new security advisory form][ADV] or by directly contacting our security contacts. [ADV]: https://github.com/wiktor-k/testresult/security/advisories/new Security contacts: - [Wiktor Kwapisiewicz][WK]. [WK]: https://github.com/wiktor-k ## Supported Versions Security updates are applied only to the most recent release. testresult-0.4.1/deny.toml000064400000000000000000000002421046102023000136760ustar 00000000000000[advisories] version = 2 yanked = "deny" ignore = [ ] [bans] deny = [ ] multiple-versions = "allow" [licenses] version = 2 allow = [ "Apache-2.0", "MIT", ] testresult-0.4.1/scripts/hooks/pre-commit000075500000000000000000000050771046102023000166710ustar 00000000000000#!/usr/bin/env -S just --working-directory . --justfile # Load project-specific properties from the `.env` file set dotenv-load := true # Since this is a first recipe it's being run by default. # Faster checks need to be executed first for better UX. For example # codespell is very fast. cargo fmt does not need to download crates etc. # Perform all checks check: spelling formatting docs lints dependencies tests # Checks common spelling mistakes spelling: codespell # Checks source code formatting formatting: just --unstable --fmt --check # We're using nightly to properly group imports, see .rustfmt.toml cargo +nightly fmt --all -- --check # Lints the source code lints: cargo clippy --workspace --no-deps --all-targets -- -D warnings # Checks for issues with dependencies dependencies: cargo deny check # Runs all unit tests. By default ignored tests are not run. Run with `ignored=true` to run only ignored tests tests: cargo test --all # Build docs for this crate only docs: cargo doc --no-deps # Installs packages required to build [linux] install-packages: sudo apt-get install --assume-yes --no-install-recommends $UBUNTU_PACKAGES [macos] [windows] install-packages: echo no-op # Checks for commit messages check-commits REFS='main..': #!/usr/bin/env bash set -euo pipefail for commit in $(git rev-list "{{ REFS }}"); do MSG="$(git show -s --format=%B "$commit")" CODESPELL_RC="$(mktemp)" git show "$commit:.codespellrc" > "$CODESPELL_RC" if ! grep -q "Signed-off-by: " <<< "$MSG"; then printf "Commit %s lacks \"Signed-off-by\" line.\n" "$commit" printf "%s\n" \ " Please use:" \ " git rebase --signoff main && git push --force-with-lease" \ " See https://developercertificate.org/ for more details." exit 1; elif ! codespell --config "$CODESPELL_RC" - <<< "$MSG"; then printf "The spelling in commit %s needs improvement.\n" "$commit" exit 1; else printf "Commit %s is good.\n" "$commit" fi done # Fixes common issues. Files need to be git add'ed fix: #!/usr/bin/env bash set -euo pipefail if ! git diff-files --quiet ; then echo "Working tree has changes. Please stage them: git add ." exit 1 fi codespell --write-changes just --unstable --fmt # try to fix rustc issues cargo fix --allow-staged # try to fix clippy issues cargo clippy --fix --allow-staged # fmt must be last as clippy's changes may break formatting cargo +nightly fmt --all testresult-0.4.1/scripts/hooks/pre-push000075500000000000000000000000711046102023000163450ustar 00000000000000#!/usr/bin/env sh set -euo pipefail just check-commits testresult-0.4.1/src/lib.rs000064400000000000000000000077651046102023000137660ustar 00000000000000#![doc = include_str!("../README.md")] #![deny(missing_debug_implementations)] #![deny(missing_docs)] // the docs illustrate the usage in test functions #![allow(clippy::test_attr_in_doctest)] /// Error, but one which immediately panics with a stacktrace. /// /// Usually used via [`TestResult`]. /// /// Any other type of error can be converted to this one but the /// conversion will always panic. /// /// This type is useful only in unit tests. /// It cannot be instantiated: no values of this type can ever exist. #[derive(Debug)] pub enum TestError {} impl From for TestError { #[track_caller] // Will show the location of the caller in test failure messages fn from(error: T) -> Self { // Use alternate format for rich error message for anyhow // See: https://docs.rs/anyhow/latest/anyhow/struct.Error.html#display-representations panic!("error: {} - {:#}", std::any::type_name::(), error); } } /// Unit test result - always panics when an error occurs. /// /// This type allows panicking when encountering any type of /// failure. Thus it allows using the `?` operator in unit tests but still /// getting the complete stacktrace and the exact place of a failure during /// tests. /// /// # Examples /// /// Using [`TestResult`] as a result of a test function: /// /// ``` /// use testresult::TestResult; /// /// #[test] /// fn it_works() -> TestResult { /// // ... /// std::fs::File::open("this-file-does-not-exist")?; /// // ... /// Ok(()) /// } /// ``` /// /// 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 std::fs::File; /// /// use rstest::{fixture, rstest}; /// use testresult::TestResult; /// /// #[fixture] /// fn a_file() -> TestResult { /// let file = File::open("this-file-does-not-exist")?; /// // ... /// Ok(file) /// } /// /// #[rstest] /// fn it_works(file: File) -> TestResult { /// // ... /// Ok(()) /// } /// ``` pub type TestResult = std::result::Result; #[cfg(test)] mod tests { use anyhow::Context as _; use super::*; #[test] #[ignore] // ignored test must still compile // this checks whether conversion from all errors is accomplished fn compilation_works() -> TestResult { std::fs::File::open("this-file-does-not-exist")?; Ok(()) } // helper function which always fails fn test_fn() -> TestResult { let string = String::from_utf8(vec![0, 159, 146, 150])?; Ok(string) } #[test] fn check_if_panics() -> TestResult { let result = std::panic::catch_unwind(|| { let _ = test_fn(); }); assert!(result.is_err()); let err = result.unwrap_err(); assert_eq!( Some( &"error: alloc::string::FromUtf8Error - invalid utf-8 sequence of 1 bytes from index 1" .to_string() ), err.downcast_ref::() ); Ok(()) } fn anyhow_a() -> anyhow::Result { let string = String::from_utf8(vec![0, 159, 146, 150])?; Ok(string) } fn anyhow_b() -> anyhow::Result { let file = anyhow_a().context("Parsing a string")?; Ok(file) } fn anyhow_c() -> TestResult { let file = anyhow_b()?; Ok(file) } #[test] fn check_if_anyhow_panics() -> TestResult { let result = std::panic::catch_unwind(|| { let _ = anyhow_c(); }); assert!(result.is_err()); let err = result.unwrap_err(); assert_eq!( Some( &"error: anyhow::Error - Parsing a string: invalid utf-8 sequence of 1 bytes from index 1" .to_string() ), err.downcast_ref::() ); Ok(()) } }