Files
rust/crates/test_utils/src/marks.rs

91 lines
2.3 KiB
Rust
Raw Normal View History

//! This module implements manually tracked test coverage, which is useful for
2019-01-23 15:36:29 +03:00
//! quickly finding a test responsible for testing a particular bit of code.
//!
2019-02-11 17:18:27 +01:00
//! See <https://matklad.github.io/2018/06/18/a-trick-for-test-maintenance.html>
2019-01-23 15:36:29 +03:00
//! for details, but the TL;DR is that you write your test as
//!
2019-11-17 18:35:05 +03:00
//! ```
2019-01-23 15:36:29 +03:00
//! #[test]
//! fn test_foo() {
//! covers!(test_foo);
//! }
//! ```
//!
//! and in the code under test you write
//!
2019-11-17 18:35:05 +03:00
//! ```
2019-02-11 17:18:27 +01:00
//! # use test_utils::tested_by;
//! # fn some_condition() -> bool { true }
2019-01-23 15:36:29 +03:00
//! fn foo() {
//! if some_condition() {
//! tested_by!(test_foo);
//! }
//! }
//! ```
//!
//! This module then checks that executing the test indeed covers the specified
//! function. This is useful if you come back to the `foo` function ten years
//! later and wonder where the test are: now you can grep for `test_foo`.
use std::sync::atomic::{AtomicUsize, Ordering};
#[macro_export]
macro_rules! tested_by {
2020-03-04 11:38:55 +01:00
($ident:ident; force) => {{
{
// sic! use call-site crate
crate::marks::$ident.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
}};
2019-03-16 18:06:45 +03:00
($ident:ident) => {{
2019-01-23 15:36:29 +03:00
#[cfg(test)]
{
// sic! use call-site crate
crate::marks::$ident.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
2019-03-16 18:06:45 +03:00
}};
2019-01-23 15:36:29 +03:00
}
#[macro_export]
macro_rules! covers {
2020-03-04 11:38:55 +01:00
// sic! use call-site crate
2019-01-23 15:36:29 +03:00
($ident:ident) => {
2020-03-04 11:38:55 +01:00
$crate::covers!(crate::$ident)
};
($krate:ident :: $ident:ident) => {
let _checker = $crate::marks::MarkChecker::new(&$krate::marks::$ident);
2019-01-23 15:36:29 +03:00
};
}
#[macro_export]
macro_rules! marks {
($($ident:ident)*) => {
$(
2019-01-23 15:36:29 +03:00
#[allow(bad_style)]
2020-03-04 11:38:55 +01:00
pub static $ident: std::sync::atomic::AtomicUsize =
2019-01-23 15:36:29 +03:00
std::sync::atomic::AtomicUsize::new(0);
)*
2019-01-23 15:36:29 +03:00
};
}
pub struct MarkChecker {
mark: &'static AtomicUsize,
value_on_entry: usize,
}
impl MarkChecker {
pub fn new(mark: &'static AtomicUsize) -> MarkChecker {
let value_on_entry = mark.load(Ordering::SeqCst);
2019-02-08 14:49:43 +03:00
MarkChecker { mark, value_on_entry }
2019-01-23 15:36:29 +03:00
}
}
impl Drop for MarkChecker {
fn drop(&mut self) {
if std::thread::panicking() {
return;
}
let value_on_exit = self.mark.load(Ordering::SeqCst);
assert!(value_on_exit > self.value_on_entry, "mark was not hit")
}
}