内容简介: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 thatvaluecame 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,
Pollwas 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,claimautomatically 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
stdat 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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
HTML5秘籍(第2版)
[美] Matthew MacDonald / 李松峰、朱巍、刘帅 / 人民邮电出版社 / 2015-4 / 89.00元
不依赖插件添加音频和视频,构建适用于所有浏览器的播放页面。 用Canvas创建吸引人的视觉效果,绘制图形、图像、文本,播放动画,运行交互游戏。 用CSS3将页面变活泼,比如添加新奇的字体,利用变换和动画添加吸引人的效果。 设计更出色的Web表单,利用HTML5新增的表单元素更加高效地收集访客信息。 一次开发,多平台运行,实现响应式设计,创建适配桌面计算机、平板电脑和智能手机......一起来看看 《HTML5秘籍(第2版)》 这本书的介绍吧!