@@ -2,7 +2,7 @@ use clippy_config::Conf;
22use clippy_utils:: consts:: { ConstEvalCtxt , Constant } ;
33use clippy_utils:: diagnostics:: { span_lint, span_lint_and_then} ;
44use clippy_utils:: ty:: { deref_chain, get_adt_inherent_method} ;
5- use clippy_utils:: { higher, is_from_proc_macro} ;
5+ use clippy_utils:: { higher, is_from_proc_macro, is_in_test } ;
66use rustc_ast:: ast:: RangeLimits ;
77use rustc_hir:: { Expr , ExprKind } ;
88use rustc_lint:: { LateContext , LateLintPass } ;
@@ -96,12 +96,14 @@ declare_clippy_lint! {
9696impl_lint_pass ! ( IndexingSlicing => [ INDEXING_SLICING , OUT_OF_BOUNDS_INDEXING ] ) ;
9797
9898pub struct IndexingSlicing {
99+ allow_indexing_slicing_in_tests : bool ,
99100 suppress_restriction_lint_in_const : bool ,
100101}
101102
102103impl IndexingSlicing {
103104 pub fn new ( conf : & ' static Conf ) -> Self {
104105 Self {
106+ allow_indexing_slicing_in_tests : conf. allow_indexing_slicing_in_tests ,
105107 suppress_restriction_lint_in_const : conf. suppress_restriction_lint_in_const ,
106108 }
107109 }
@@ -122,6 +124,7 @@ impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
122124 {
123125 let note = "the suggestion might not be applicable in constant blocks" ;
124126 let ty = cx. typeck_results ( ) . expr_ty ( array) . peel_refs ( ) ;
127+ let allowed_in_tests = self . allow_indexing_slicing_in_tests && is_in_test ( cx. tcx , expr. hir_id ) ;
125128 if let Some ( range) = higher:: Range :: hir ( index) {
126129 // Ranged indexes, i.e., &x[n..m], &x[n..], &x[..n] and &x[..]
127130 if let ty:: Array ( _, s) = ty. kind ( ) {
@@ -171,6 +174,10 @@ impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
171174 ( None , None ) => return , // [..] is ok.
172175 } ;
173176
177+ if allowed_in_tests {
178+ return ;
179+ }
180+
174181 span_lint_and_then ( cx, INDEXING_SLICING , expr. span , "slicing may panic" , |diag| {
175182 diag. help ( help_msg) ;
176183
@@ -209,6 +216,10 @@ impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
209216 }
210217 }
211218
219+ if allowed_in_tests {
220+ return ;
221+ }
222+
212223 span_lint_and_then ( cx, INDEXING_SLICING , expr. span , "indexing may panic" , |diag| {
213224 diag. help ( "consider using `.get(n)` or `.get_mut(n)` instead" ) ;
214225
0 commit comments