coverage_helper/
lib.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3/*!
4<!-- tidy:crate-doc:start -->
5
6**Note: This crate is now deprecated in favor of the pattern that is [recommended in the cargo-llvm-cov documentation](https://github.com/taiki-e/cargo-llvm-cov?tab=readme-ov-file#exclude-code-from-coverage).**
7
8> If you want to ignore all `#[test]`-related code, you can use module-level `#[coverage(off)]` attribute:
9>
10> ```rust
11> #![cfg_attr(coverage_nightly, feature(coverage_attribute))]
12>
13> #[cfg(test)]
14> #[cfg_attr(coverage_nightly, coverage(off))]
15> mod tests {
16>     // ...
17> }
18> ```
19>
20> cargo-llvm-cov excludes code contained in the directory named `tests` from the report by default, so you can also use it instead of `#[coverage(off)]` attribute.
21
22---
23
24Helper for <https://github.com/taiki-e/cargo-llvm-cov/issues/123>.
25
26**Note:** coverage-helper 0.2 supports `#[coverage(off)]`.
27See coverage-helper 0.1 for versions that support `#[no_coverage]`.
28
29## Usage
30
31Add this to your `Cargo.toml`:
32
33```toml
34[dev-dependencies]
35coverage-helper = "0.2"
36```
37
38## Examples
39
40```rust
41use coverage_helper::test;
42
43#[test]
44fn my_test() {
45    // ...
46}
47```
48
49Expanded to:
50
51```rust
52#[cfg_attr(all(coverage_nightly, test), coverage(off))]
53#[::core::prelude::v1::test]
54fn my_test() {
55    // ...
56}
57```
58
59<!-- tidy:crate-doc:end -->
60*/
61
62#![doc(test(
63    no_crate_inject,
64    attr(
65        deny(warnings, rust_2018_idioms, single_use_lifetimes),
66        allow(dead_code, unused_variables, deprecated)
67    )
68))]
69#![forbid(unsafe_code)]
70#![allow(deprecated, clippy::test_attr_in_doctest)]
71
72// older compilers require explicit `extern crate`.
73#[allow(unused_extern_crates)]
74extern crate proc_macro;
75
76#[macro_use]
77mod error;
78
79#[macro_use]
80mod quote;
81
82use proc_macro::{Span, TokenStream};
83
84#[deprecated(
85    since = "0.2.3",
86    note = "this crate is deprecated in favor of module-level #[coverage(off)] attribute; \
87            see <https://github.com/taiki-e/cargo-llvm-cov?tab=readme-ov-file#exclude-code-from-coverage> \
88            for more"
89)]
90#[proc_macro_attribute]
91pub fn test(args: TokenStream, input: TokenStream) -> TokenStream {
92    if !args.is_empty() {
93        return format_err!(Span::call_site(), "attribute must be of the form `#[test]`")
94            .into_compile_error();
95    }
96    let mut out = TokenStream::new();
97    if cfg!(coverage_helper_has_coverage_attribute) {
98        out.extend(quote! { #[cfg_attr(all(coverage_nightly, test), coverage(off))] });
99    }
100    out.extend(quote! { #[::core::prelude::v1::test] });
101    out.extend(input);
102    out
103}