内容简介:I started writing integration tests forFor example, let’s say that we have some function which returnsWe always can test if
I started writing integration tests for heim
recently (better late than never) and the testing code started to bloat up really quick; it’s not very easy to check the logic correctness elegantly with what assertion macros
we have in the Rust standard library, especially when we are working with the commonly used
Result
and
Option
types.
For example, let’s say that we have some function which returns io::Result<i32>
and we want to test if it returns Ok(42)
as expected:
fn foo() -> io::Result<i32> { Err(io::Error::new(io::ErrorKind::Other, "example purposes")) } #[test] fn test_foo() { let result = foo(); }
We always can test if Result
is Ok
with the
is_ok
method:
assert!(result.is_ok()); // This assert will panic with the following message: // // thread 'main' panicked at 'assertion failed: r.is_ok()', examples/foo.rs:10:5
The panic message is not really helpful, because we have no idea what error caused the assertion failure, and in addition we still need to get value from the Ok
variant somehow if this one assertion is correct. Maybe we should use
.unwrap
instead?
let value = result.unwrap(); assert_eq!(value, 42); // `.unwrap()` will panic too: // // thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: // Custom { kind: Other, error: "example purposes" }', examples/foo.rs:11:17
That’s better! Should we shorten this quick test now?
#[test] fn test_foo() { assert_eq!(do_foo().unwrap(), 42); }
Okay, that kinda does the trick both for Result
and Option
types.
Can we shorten it a little bit more? Of course, let’s write our own assertion macro!
macro_rules! assert_ok_eq { ($cond:expr, $expected:expr) => { match $cond { Ok(t) => { assert_eq!(t, $expected); }, e @ Err(..) => { panic!("assertion failed, expected Ok(..), got {:?}", e); } } }; }
It is a pretty simple macro, all it does is a match on the first macro argument and if is Ok(t)
, it compares that t
with the second macro argument:
#[test] fn test_foo() { assert_ok_eq!(foo(), 42); } // # If `foo()` returned an `Err`: // // thread 'main' panicked at 'assertion failed, expected Ok(..), // got Err(Custom { kind: Other, error: "example purposes" })', examples/foo.rs:8:5 // // # And if it returned an `Ok(1)`: // // thread 'main' panicked at 'assertion failed: `(left == right)` // left: `1`, // right: `42`', examples/foo.rs:8:5
Amazing, not only we had reduced the visual noise in this line now, but also declared our expectations in the macro name — it should be an Ok
variant and its value should be equal to the second argument.
More macros!
Once you have started making more abstractions, it is hard to stop, so I ended up with a separate crate called “ claim
", which provides a lot of assertion macros to supplement what we already have in libstd
:
-
for comparison:
assert_ge
,assert_gt
,assert_le
, andassert_lt
-
matching
:
assert_matches
-
Result
:assert_ok
,assert_err
, andassert_ok_eq
-
Option
:assert_some
,assert_none
, andassert_some_eq
-
and
Poll
:assert_pending
,assert_ready
,assert_ready_ok
,assert_ready_err
, andassert_ready_eq
Of course, other crates with the similar purpose already exists, there are assert2 , spectral , more-asserts , totems ,galvanic-assert, a lot of them !
Why I should use this one?
-
First of all, claim macros are quite conservative: only the most popular cases handled and for each one case there is a separate macro; for example, there is a
assert_some_eq!(Some(42), 42)
and not theassert_some!(Some(42), value == 42)
(because where thatvalue
came from?!) -
There is no “fluent” approach also, because I personally prefer not to use these half-assed DSLs, where each one is a unique and impossible to remember. I mean, why:
it.expected_to_be_okay().and.equal_to(5)
? -
Great thing is that current macros system had not changed that much for a last few years, so almost all those macros can be used with any modern enough Rust version; CI checks compatibility back to Rust 1.10 version, but I expect that it should also work with 1.0 version too.
-
Yet, some types are just not available in older versions, for example,
Poll
was introduced in Rust 1.36 and macros syntax needed to implementmatches!
macro for all Rust editions was added in Rust 1.32. With the help of autocfg crate,claim
automatically exposes corresponding macros if used Rust compiler can support them, so you don’t even need to enable any features manually! -
It does not need
std
at all, meaning that it can be used in the#![no-std]
environments too -
And it also has no dependencies (except for a small build one)!
So, it’s a very tiny crate, which makes panic messages a bit better. It is not much, but can be useful in some cases.
Links
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
单元测试之道Java版
David Thomas、Andrew Hunt / 陈伟柱、陶文 / 电子工业 / 2005-1 / 25.00元
程序员修炼三部曲丛书包含了四本书,介绍了每个注重实效的程序员和成功团队所必备的一些工具。 注重实效的程序员都会利用反馈来指导开发,并驱动个人的开发流程。编码的时候,最有用的反馈来自于“单元测试”。 为了测试一座桥梁,不会只在晴朗的天气,开一辆汽车从桥中间穿过,就认为已经完成了对桥梁的测试。然而许多程序员却正在使用这种测试方法——把这种一次顺利通过称为“测试”。事实上,注重实效的程序员应......一起来看看 《单元测试之道Java版》 这本书的介绍吧!
HTML 压缩/解压工具
在线压缩/解压 HTML 代码
MD5 加密
MD5 加密工具