Skip to content

Commit

Permalink
fix: Do not warn tests outside a module for integration tests
Browse files Browse the repository at this point in the history
  • Loading branch information
berkus committed Jul 4, 2024
1 parent 918ae1b commit d7ef35e
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 16 deletions.
15 changes: 14 additions & 1 deletion clippy_lints/src/tests_outside_test_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ use rustc_hir::{Body, FnDecl};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::declare_lint_pass;
use rustc_span::def_id::LocalDefId;
use rustc_span::Span;
use rustc_span::source_map::SourceMap;
use rustc_span::{FileName, RealFileName, Span};
use std::path::Component;

declare_clippy_lint! {
/// ### What it does
Expand All @@ -15,6 +17,7 @@ declare_clippy_lint! {
/// ### Why restrict this?
/// The idiomatic (and more performant) way of writing tests is inside a testing module (flagged with `#[cfg(test)]`),
/// having test functions outside of this module is confusing and may lead to them being "hidden".
/// This does not apply to integration tests though, and this lint will ignore those.
///
/// ### Example
/// ```no_run
Expand Down Expand Up @@ -59,6 +62,7 @@ impl LateLintPass<'_> for TestsOutsideTestModule {
) {
if !matches!(kind, FnKind::Closure)
&& is_in_test_function(cx.tcx, body.id().hir_id)
&& !is_integration_test(cx.tcx.sess.source_map(), sp)
&& !is_in_cfg_test(cx.tcx, body.id().hir_id)
{
span_lint_and_note(
Expand All @@ -72,3 +76,12 @@ impl LateLintPass<'_> for TestsOutsideTestModule {
}
}
}

fn is_integration_test(sm: &SourceMap, sp: Span) -> bool {
match sm.span_to_filename(sp) {
FileName::Real(RealFileName::LocalPath(name)) => {
name.components().next() == Some(Component::Normal("tests".as_ref()))
},
_ => false,
}
}
5 changes: 2 additions & 3 deletions tests/ui/tests_outside_test_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@ fn main() {
// test code goes here
}

// Should lint
// Should not lint
// Because we're inside an integration test
#[test]
fn my_test() {}
//~^ ERROR: this function marked with #[test] is outside a #[cfg(test)] module
//~| NOTE: move it to a testing module marked with #[cfg(test)]

#[cfg(test)]
mod tests {
Expand Down
12 changes: 0 additions & 12 deletions tests/ui/tests_outside_test_module.stderr

This file was deleted.

0 comments on commit d7ef35e

Please sign in to comment.