4 个版本 (稳定版)

2.0.0 2024年6月20日
2.0.0-pre.12021年6月12日
1.1.0 2020年8月28日
1.0.0 2020年5月29日

#38 in 测试

Download history 24248/week @ 2024-04-15 23530/week @ 2024-04-22 23300/week @ 2024-04-29 21340/week @ 2024-05-06 22108/week @ 2024-05-13 20732/week @ 2024-05-20 21258/week @ 2024-05-27 24061/week @ 2024-06-03 23036/week @ 2024-06-10 23883/week @ 2024-06-17 21832/week @ 2024-06-24 22468/week @ 2024-07-01 21355/week @ 2024-07-08 21389/week @ 2024-07-15 22483/week @ 2024-07-22 21949/week @ 2024-07-29

89,463 每月下载量
62 个crate中使用 (直接使用16个)

MIT/Apache

9KB
105

cov-mark

验证你的测试是否执行了你认为它们应该执行的代码路径

fn safe_divide(dividend: u32, divisor: u32) -> u32 {
    if divisor == 0 {
        cov_mark::hit!(save_divide_zero);
        return 0;
    }
    dividend / divisor
}

#[test]
fn test_safe_divide_by_zero() {
    cov_mark::check!(save_divide_zero);
    assert_eq!(safe_divide(92, 0), 0);
}

详情请见 文档


lib.rs:

cov-mark

该库核心提供两个宏,hit!check!,用于验证某个测试是否执行了特定的代码路径。

这里是一个简短的示例

fn parse_date(s: &str) -> Option<(u32, u32, u32)> {
    if 10 != s.len() {
        // By using `cov_mark::hit!`
        // we signal which test exercises this code.
        cov_mark::hit!(short_date);
        return None;
    }

    if "-" != &s[4..5] || "-" != &s[7..8] {
        cov_mark::hit!(bad_dashes);
        return None;
    }
    // ...
}

#[test]
fn test_parse_date() {
    {
        // `cov_mark::check!` creates a guard object
        // that verifies that by the end of the scope we've
        // executed the corresponding `cov_mark::hit`.
        cov_mark::check!(short_date);
        assert!(parse_date("92").is_none());
    }

//  This will fail. Although the test looks like
//  it exercises the second condition, it does not.
//  The call to `check!` call catches this bug in the test.
//  {
//      cov_mark::check!(bad_dashes);
//      assert!(parse_date("27.2.2013").is_none());
//  }

    {
        cov_mark::check!(bad_dashes);
        assert!(parse_date("27.02.2013").is_none());
    }
}

这里说明了覆盖率标记为什么有用

  • 验证某些事情没有发生的正确原因。
  • 找到执行代码的测试(使用 check!(mark_name) 进行grep搜索)。
  • 找到测试应该检查的代码(使用 hit!(mark_name) 进行grep搜索)。
  • 确保代码和测试在重构过程中不会发生偏差。
  • (如果广泛使用) 验证每个分支都有一个相应的测试。

局限性

  • 标记名称必须是全局唯一的。

实现细节

每个覆盖率标记都是一个 AtomicUsize 计数器。 hit! 增加这个计数器,check! 返回一个检查标记是否增加的守卫对象。每个计数器存储为线程局部,允许对每个线程进行准确计数。

无运行时依赖

功能