|
| 1 | +use clippy_utils::diagnostics::span_lint_and_then; |
| 2 | +use rustc_ast::NestedMetaItem; |
| 3 | +use rustc_lint::{EarlyContext, EarlyLintPass}; |
| 4 | +use rustc_session::declare_lint_pass; |
| 5 | + |
| 6 | +declare_clippy_lint! { |
| 7 | + /// ### What it does |
| 8 | + /// Checks for usage of `cfg` that excludes code from `test` builds. (i.e., `#{cfg(not(test))]`) |
| 9 | + /// |
| 10 | + /// ### Why is this bad? |
| 11 | + /// This may give the false impression that a codebase has 100% coverage, yet actually has untested code. |
| 12 | + /// Enabling this also guards against excessive mockery as well, which is an anti-pattern. |
| 13 | + /// |
| 14 | + /// ### Example |
| 15 | + /// ```rust |
| 16 | + /// # fn important_check() {} |
| 17 | + /// #[cfg(not(test))] |
| 18 | + /// important_check(); // I'm not actually tested, but not including me will falsely increase coverage! |
| 19 | + /// ``` |
| 20 | + /// Use instead: |
| 21 | + /// ```rust |
| 22 | + /// # fn important_check() {} |
| 23 | + /// important_check(); |
| 24 | + /// ``` |
| 25 | + #[clippy::version = "1.73.0"] |
| 26 | + pub CFG_NOT_TEST, |
| 27 | + restriction, |
| 28 | + "enforce against excluding code from test builds" |
| 29 | +} |
| 30 | + |
| 31 | +declare_lint_pass!(CfgNotTest => [CFG_NOT_TEST]); |
| 32 | + |
| 33 | +impl EarlyLintPass for CfgNotTest { |
| 34 | + fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &rustc_ast::Attribute) { |
| 35 | + if attr.has_name(rustc_span::sym::cfg) && contains_not_test(attr.meta_item_list().as_deref(), false) { |
| 36 | + span_lint_and_then( |
| 37 | + cx, |
| 38 | + CFG_NOT_TEST, |
| 39 | + attr.span, |
| 40 | + "code is excluded from test builds", |
| 41 | + |diag| { |
| 42 | + diag.help("consider not excluding any code from test builds"); |
| 43 | + diag.note_once("this could increase code coverage despite not actually being tested"); |
| 44 | + }, |
| 45 | + ); |
| 46 | + } |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +fn contains_not_test(list: Option<&[NestedMetaItem]>, not: bool) -> bool { |
| 51 | + list.is_some_and(|list| { |
| 52 | + list.iter().any(|item| { |
| 53 | + item.ident().is_some_and(|ident| match ident.name { |
| 54 | + rustc_span::sym::not => contains_not_test(item.meta_item_list(), !not), |
| 55 | + rustc_span::sym::test => not, |
| 56 | + _ => contains_not_test(item.meta_item_list(), not), |
| 57 | + }) |
| 58 | + }) |
| 59 | + }) |
| 60 | +} |
0 commit comments