summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDaniel Mueller <deso@posteo.net>2019-01-08 20:55:33 -0800
committerDaniel Mueller <deso@posteo.net>2019-01-08 20:55:33 -0800
commit17203a1a5d91a1749adeca0f108aad8efa979ff3 (patch)
tree23de871a4e76802de0568304b667f21493bcfa1f
parentf01d63d978505badf3400df54b592e51dc0f7654 (diff)
downloadnitrocli-17203a1a5d91a1749adeca0f108aad8efa979ff3.tar.gz
nitrocli-17203a1a5d91a1749adeca0f108aad8efa979ff3.tar.bz2
Introduce UnwrapError trait to simplify error testing
For testing purposes it is beneficial to be able to check for expected errors with the least amount of boiler plate code possible. This change attempts to be a first step into this direction. It introduces a test-only trait that can be used to directly unwrap a specific error from a Result<T, crate::error::Error>.
-rw-r--r--nitrocli/src/tests/mod.rs20
-rw-r--r--nitrocli/src/tests/status.rs13
2 files changed, 22 insertions, 11 deletions
diff --git a/nitrocli/src/tests/mod.rs b/nitrocli/src/tests/mod.rs
index 474b43c..cb0d09e 100644
--- a/nitrocli/src/tests/mod.rs
+++ b/nitrocli/src/tests/mod.rs
@@ -17,6 +17,8 @@
// * along with this program. If not, see <http://www.gnu.org/licenses/>. *
// *************************************************************************
+use std::fmt;
+
use nitrokey_test::test as test_device;
// TODO: This is a hack to make the nitrokey-test crate work across
@@ -63,6 +65,24 @@ impl IntoArg for nitrokey::DeviceWrapper {
}
}
+/// A trait simplifying checking for expected errors.
+pub trait UnwrapError {
+ /// Unwrap an Error::Error variant.
+ fn unwrap_str_err(self) -> String;
+}
+
+impl<T> UnwrapError for crate::Result<T>
+where
+ T: fmt::Debug,
+{
+ fn unwrap_str_err(self) -> String {
+ match self.unwrap_err() {
+ crate::Error::Error(err) => err,
+ err => panic!("Unexpected error variant found: {:?}", err),
+ }
+ }
+}
+
mod nitrocli {
use super::*;
diff --git a/nitrocli/src/tests/status.rs b/nitrocli/src/tests/status.rs
index e8a4f51..838ebc9 100644
--- a/nitrocli/src/tests/status.rs
+++ b/nitrocli/src/tests/status.rs
@@ -33,17 +33,8 @@ fn not_found_raw() {
#[test_device]
fn not_found() {
- match nitrocli::handle(NO_DEV, &["status"]) {
- Ok(_) => assert!(false),
- Err(err) => {
- // Unfortunately we can't directly compare against the error
- // because not all of the variants implement PartialEq.
- match err {
- crate::Error::Error(x) => assert_eq!(x, "Nitrokey device not found".to_string()),
- _ => assert!(false, err),
- }
- }
- }
+ let res = nitrocli::handle(NO_DEV, &["status"]);
+ assert_eq!(res.unwrap_str_err(), "Nitrokey device not found");
}
#[test_device]