-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
parametrize.rs
837 lines (798 loc) · 30.7 KB
/
parametrize.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
use std::hash::BuildHasherDefault;
use rustc_hash::FxHashMap;
use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::parenthesize::parenthesized_range;
use ruff_python_ast::AstNode;
use ruff_python_ast::{self as ast, Arguments, Decorator, Expr, ExprContext};
use ruff_python_codegen::Generator;
use ruff_python_trivia::CommentRanges;
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer};
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::checkers::ast::Checker;
use crate::registry::Rule;
use super::super::types;
use super::helpers::{is_pytest_parametrize, split_names};
/// ## What it does
/// Checks for the type of parameter names passed to `pytest.mark.parametrize`.
///
/// ## Why is this bad?
/// The `argnames` argument of `pytest.mark.parametrize` takes a string or
/// a sequence of strings. For a single parameter, it's preferable to use a
/// string. For multiple parameters, it's preferable to use the style
/// configured via the [`lint.flake8-pytest-style.parametrize-names-type`] setting.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// # single parameter, always expecting string
/// @pytest.mark.parametrize(("param",), [1, 2, 3])
/// def test_foo(param):
/// ...
///
///
/// # multiple parameters, expecting tuple
/// @pytest.mark.parametrize(["param1", "param2"], [(1, 2), (3, 4)])
/// def test_bar(param1, param2):
/// ...
///
///
/// # multiple parameters, expecting tuple
/// @pytest.mark.parametrize("param1,param2", [(1, 2), (3, 4)])
/// def test_baz(param1, param2):
/// ...
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.mark.parametrize("param", [1, 2, 3])
/// def test_foo(param):
/// ...
///
///
/// @pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)])
/// def test_bar(param1, param2):
/// ...
/// ```
///
/// ## Options
/// - `lint.flake8-pytest-style.parametrize-names-type`
///
/// ## References
/// - [`pytest` documentation: How to parametrize fixtures and test functions](https://docs.pytest.org/en/latest/how-to/parametrize.html#pytest-mark-parametrize)
#[violation]
pub struct PytestParametrizeNamesWrongType {
single_argument: bool,
expected: types::ParametrizeNameType,
}
impl Violation for PytestParametrizeNamesWrongType {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let PytestParametrizeNamesWrongType {
single_argument,
expected,
} = self;
let expected_string = {
if *single_argument {
"`str`".to_string()
} else {
match expected {
types::ParametrizeNameType::Csv => format!("a {expected}"),
types::ParametrizeNameType::Tuple | types::ParametrizeNameType::List => {
format!("`{expected}`")
}
}
}
};
format!("Wrong type passed to first argument of `@pytest.mark.parametrize`; expected {expected_string}")
}
fn fix_title(&self) -> Option<String> {
let PytestParametrizeNamesWrongType {
single_argument,
expected,
} = self;
let expected_string = {
if *single_argument {
"string".to_string()
} else {
match expected {
types::ParametrizeNameType::Csv => format!("{expected}"),
types::ParametrizeNameType::Tuple | types::ParametrizeNameType::List => {
format!("`{expected}`")
}
}
}
};
Some(format!("Use a {expected_string} for the first argument"))
}
}
/// ## What it does
/// Checks for the type of parameter values passed to `pytest.mark.parametrize`.
///
/// ## Why is this bad?
/// The `argvalues` argument of `pytest.mark.parametrize` takes an iterator of
/// parameter values, which can be provided as lists or tuples.
///
/// To aid in readability, it's recommended to use a consistent style for the
/// list of values rows, and, in the case of multiple parameters, for each row
/// of values.
///
/// The style for the list of values rows can be configured via the
/// [`lint.flake8-pytest-style.parametrize-values-type`] setting, while the
/// style for each row of values can be configured via the
/// [`lint.flake8-pytest-style.parametrize-values-row-type`] setting.
///
/// For example, [`lint.flake8-pytest-style.parametrize-values-type`] will lead to
/// the following expectations:
///
/// - `tuple`: `@pytest.mark.parametrize("value", ("a", "b", "c"))`
/// - `list`: `@pytest.mark.parametrize("value", ["a", "b", "c"])`
///
/// Similarly, [`lint.flake8-pytest-style.parametrize-values-row-type`] will lead to
/// the following expectations:
///
/// - `tuple`: `@pytest.mark.parametrize(("key", "value"), [("a", "b"), ("c", "d")])`
/// - `list`: `@pytest.mark.parametrize(("key", "value"), [["a", "b"], ["c", "d"]])`
///
/// ## Example
/// ```python
/// import pytest
///
///
/// # expected list, got tuple
/// @pytest.mark.parametrize("param", (1, 2))
/// def test_foo(param):
/// ...
///
///
/// # expected top-level list, got tuple
/// @pytest.mark.parametrize(
/// ("param1", "param2"),
/// (
/// (1, 2),
/// (3, 4),
/// ),
/// )
/// def test_bar(param1, param2):
/// ...
///
///
/// # expected individual rows to be tuples, got lists
/// @pytest.mark.parametrize(
/// ("param1", "param2"),
/// [
/// [1, 2],
/// [3, 4],
/// ],
/// )
/// def test_baz(param1, param2):
/// ...
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.mark.parametrize("param", [1, 2, 3])
/// def test_foo(param):
/// ...
///
///
/// @pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)])
/// def test_bar(param1, param2):
/// ...
/// ```
///
/// ## Options
/// - `lint.flake8-pytest-style.parametrize-values-type`
/// - `lint.flake8-pytest-style.parametrize-values-row-type`
///
/// ## References
/// - [`pytest` documentation: How to parametrize fixtures and test functions](https://docs.pytest.org/en/latest/how-to/parametrize.html#pytest-mark-parametrize)
#[violation]
pub struct PytestParametrizeValuesWrongType {
values: types::ParametrizeValuesType,
row: types::ParametrizeValuesRowType,
}
impl Violation for PytestParametrizeValuesWrongType {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let PytestParametrizeValuesWrongType { values, row } = self;
format!("Wrong values type in `@pytest.mark.parametrize` expected `{values}` of `{row}`")
}
fn fix_title(&self) -> Option<String> {
let PytestParametrizeValuesWrongType { values, row } = self;
Some(format!("Use `{values}` of `{row}` for parameter values"))
}
}
/// ## What it does
/// Checks for duplicate test cases in `pytest.mark.parametrize`.
///
/// ## Why is this bad?
/// Duplicate test cases are redundant and should be removed.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.mark.parametrize(
/// ("param1", "param2"),
/// [
/// (1, 2),
/// (1, 2),
/// ],
/// )
/// def test_foo(param1, param2):
/// ...
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.mark.parametrize(
/// ("param1", "param2"),
/// [
/// (1, 2),
/// ],
/// )
/// def test_foo(param1, param2):
/// ...
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as tests that rely on mutable global
/// state may be affected by removing duplicate test cases.
///
/// ## References
/// - [`pytest` documentation: How to parametrize fixtures and test functions](https://docs.pytest.org/en/latest/how-to/parametrize.html#pytest-mark-parametrize)
#[violation]
pub struct PytestDuplicateParametrizeTestCases {
index: usize,
}
impl Violation for PytestDuplicateParametrizeTestCases {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let PytestDuplicateParametrizeTestCases { index } = self;
format!("Duplicate of test case at index {index} in `@pytest_mark.parametrize`")
}
fn fix_title(&self) -> Option<String> {
Some("Remove duplicate test case".to_string())
}
}
fn elts_to_csv(elts: &[Expr], generator: Generator) -> Option<String> {
if !elts.iter().all(Expr::is_string_literal_expr) {
return None;
}
let node = Expr::from(ast::StringLiteral {
value: elts
.iter()
.fold(String::new(), |mut acc, elt| {
if let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = elt {
if !acc.is_empty() {
acc.push(',');
}
acc.push_str(value.to_str());
}
acc
})
.into_boxed_str(),
..ast::StringLiteral::default()
});
Some(generator.expr(&node))
}
/// Returns the range of the `name` argument of `@pytest.mark.parametrize`.
///
/// This accounts for parenthesized expressions. For example, the following code
/// will return the range marked with `^`:
/// ```python
/// @pytest.mark.parametrize(("x"), [(1, 2)])
/// # ^^^^^
/// def test(a, b):
/// ...
/// ```
///
/// This method assumes that the first argument is a string.
fn get_parametrize_name_range(
decorator: &Decorator,
expr: &Expr,
comment_ranges: &CommentRanges,
source: &str,
) -> Option<TextRange> {
decorator.expression.as_call_expr().and_then(|call| {
parenthesized_range(
expr.into(),
call.arguments.as_any_node_ref(),
comment_ranges,
source,
)
})
}
/// PT006
fn check_names(checker: &mut Checker, decorator: &Decorator, expr: &Expr) {
let names_type = checker.settings.flake8_pytest_style.parametrize_names_type;
match expr {
Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) => {
let names = split_names(value.to_str());
if names.len() > 1 {
match names_type {
types::ParametrizeNameType::Tuple => {
let name_range = get_parametrize_name_range(
decorator,
expr,
checker.indexer().comment_ranges(),
checker.locator().contents(),
)
.unwrap_or(expr.range());
let mut diagnostic = Diagnostic::new(
PytestParametrizeNamesWrongType {
single_argument: false,
expected: names_type,
},
name_range,
);
let node = Expr::Tuple(ast::ExprTuple {
elts: names
.iter()
.map(|name| {
Expr::from(ast::StringLiteral {
value: (*name).to_string().into_boxed_str(),
..ast::StringLiteral::default()
})
})
.collect(),
ctx: ExprContext::Load,
range: TextRange::default(),
parenthesized: true,
});
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
format!("({})", checker.generator().expr(&node)),
name_range,
)));
checker.diagnostics.push(diagnostic);
}
types::ParametrizeNameType::List => {
let name_range = get_parametrize_name_range(
decorator,
expr,
checker.indexer().comment_ranges(),
checker.locator().contents(),
)
.unwrap_or(expr.range());
let mut diagnostic = Diagnostic::new(
PytestParametrizeNamesWrongType {
single_argument: false,
expected: names_type,
},
name_range,
);
let node = Expr::List(ast::ExprList {
elts: names
.iter()
.map(|name| {
Expr::from(ast::StringLiteral {
value: (*name).to_string().into_boxed_str(),
..ast::StringLiteral::default()
})
})
.collect(),
ctx: ExprContext::Load,
range: TextRange::default(),
});
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
checker.generator().expr(&node),
name_range,
)));
checker.diagnostics.push(diagnostic);
}
types::ParametrizeNameType::Csv => {}
}
}
}
Expr::Tuple(ast::ExprTuple { elts, .. }) => {
if elts.len() == 1 {
if let Some(first) = elts.first() {
handle_single_name(checker, expr, first);
}
} else {
match names_type {
types::ParametrizeNameType::Tuple => {}
types::ParametrizeNameType::List => {
let mut diagnostic = Diagnostic::new(
PytestParametrizeNamesWrongType {
single_argument: false,
expected: names_type,
},
expr.range(),
);
let node = Expr::List(ast::ExprList {
elts: elts.clone(),
ctx: ExprContext::Load,
range: TextRange::default(),
});
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
checker.generator().expr(&node),
expr.range(),
)));
checker.diagnostics.push(diagnostic);
}
types::ParametrizeNameType::Csv => {
let mut diagnostic = Diagnostic::new(
PytestParametrizeNamesWrongType {
single_argument: false,
expected: names_type,
},
expr.range(),
);
if let Some(content) = elts_to_csv(elts, checker.generator()) {
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
content,
expr.range(),
)));
}
checker.diagnostics.push(diagnostic);
}
}
};
}
Expr::List(ast::ExprList { elts, .. }) => {
if elts.len() == 1 {
if let Some(first) = elts.first() {
handle_single_name(checker, expr, first);
}
} else {
match names_type {
types::ParametrizeNameType::List => {}
types::ParametrizeNameType::Tuple => {
let mut diagnostic = Diagnostic::new(
PytestParametrizeNamesWrongType {
single_argument: false,
expected: names_type,
},
expr.range(),
);
let node = Expr::Tuple(ast::ExprTuple {
elts: elts.clone(),
ctx: ExprContext::Load,
range: TextRange::default(),
parenthesized: true,
});
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
format!("({})", checker.generator().expr(&node)),
expr.range(),
)));
checker.diagnostics.push(diagnostic);
}
types::ParametrizeNameType::Csv => {
let mut diagnostic = Diagnostic::new(
PytestParametrizeNamesWrongType {
single_argument: false,
expected: names_type,
},
expr.range(),
);
if let Some(content) = elts_to_csv(elts, checker.generator()) {
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
content,
expr.range(),
)));
}
checker.diagnostics.push(diagnostic);
}
}
};
}
_ => {}
}
}
/// PT007
fn check_values(checker: &mut Checker, names: &Expr, values: &Expr) {
let values_type = checker.settings.flake8_pytest_style.parametrize_values_type;
let values_row_type = checker
.settings
.flake8_pytest_style
.parametrize_values_row_type;
let is_multi_named = if let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = &names {
split_names(value.to_str()).len() > 1
} else {
true
};
match values {
Expr::List(ast::ExprList { elts, .. }) => {
if values_type != types::ParametrizeValuesType::List {
let mut diagnostic = Diagnostic::new(
PytestParametrizeValuesWrongType {
values: values_type,
row: values_row_type,
},
values.range(),
);
diagnostic.set_fix({
// Determine whether the last element has a trailing comma. Single-element
// tuples _require_ a trailing comma, so this is a single-element list
// _without_ a trailing comma, we need to insert one.
let needs_trailing_comma = if let [item] = elts.as_slice() {
SimpleTokenizer::new(
checker.locator().contents(),
TextRange::new(item.end(), values.end()),
)
.all(|token| token.kind != SimpleTokenKind::Comma)
} else {
false
};
// Replace `[` with `(`.
let values_start = Edit::replacement(
"(".into(),
values.start(),
values.start() + TextSize::from(1),
);
// Replace `]` with `)` or `,)`.
let values_end = Edit::replacement(
if needs_trailing_comma {
"),".into()
} else {
")".into()
},
values.end() - TextSize::from(1),
values.end(),
);
Fix::unsafe_edits(values_start, [values_end])
});
checker.diagnostics.push(diagnostic);
}
if is_multi_named {
handle_value_rows(checker, elts, values_type, values_row_type);
}
}
Expr::Tuple(ast::ExprTuple { elts, .. }) => {
if values_type != types::ParametrizeValuesType::Tuple {
let mut diagnostic = Diagnostic::new(
PytestParametrizeValuesWrongType {
values: values_type,
row: values_row_type,
},
values.range(),
);
diagnostic.set_fix({
// Determine whether a trailing comma is present due to the _requirement_
// that a single-element tuple must have a trailing comma, e.g., `(1,)`.
//
// If the trailing comma is on its own line, we intentionally ignore it,
// since the expression is already split over multiple lines, as in:
// ```python
// @pytest.mark.parametrize(
// (
// "x",
// ),
// )
// ```
let has_trailing_comma = elts.len() == 1
&& checker.locator().up_to(values.end()).chars().rev().nth(1) == Some(',');
// Replace `(` with `[`.
let values_start = Edit::replacement(
"[".into(),
values.start(),
values.start() + TextSize::from(1),
);
// Replace `)` or `,)` with `]`.
let start = if has_trailing_comma {
values.end() - TextSize::from(2)
} else {
values.end() - TextSize::from(1)
};
let values_end = Edit::replacement("]".into(), start, values.end());
Fix::unsafe_edits(values_start, [values_end])
});
checker.diagnostics.push(diagnostic);
}
if is_multi_named {
handle_value_rows(checker, elts, values_type, values_row_type);
}
}
_ => {}
}
}
/// Given an element in a list, return the comma that follows it:
/// ```python
/// @pytest.mark.parametrize(
/// "x",
/// [.., (elt), ..],
/// ^^^^^
/// Tokenize this range to locate the comma.
/// )
/// ```
fn trailing_comma(element: &Expr, source: &str) -> Option<TextSize> {
SimpleTokenizer::starts_at(element.end(), source)
.find(|token| token.kind == SimpleTokenKind::Comma)
.map(|token| token.start())
}
/// PT014
fn check_duplicates(checker: &mut Checker, values: &Expr) {
let (Expr::List(ast::ExprList { elts, .. }) | Expr::Tuple(ast::ExprTuple { elts, .. })) =
values
else {
return;
};
let mut seen: FxHashMap<ComparableExpr, usize> =
FxHashMap::with_capacity_and_hasher(elts.len(), BuildHasherDefault::default());
let mut prev = None;
for (index, element) in elts.iter().enumerate() {
let expr = ComparableExpr::from(element);
seen.entry(expr)
.and_modify(|index| {
let mut diagnostic = Diagnostic::new(
PytestDuplicateParametrizeTestCases { index: *index },
element.range(),
);
if let Some(prev) = prev {
let values_end = values.end() - TextSize::new(1);
let previous_end =
trailing_comma(prev, checker.locator().contents()).unwrap_or(values_end);
let element_end =
trailing_comma(element, checker.locator().contents()).unwrap_or(values_end);
let deletion_range = TextRange::new(previous_end, element_end);
if !checker
.indexer()
.comment_ranges()
.intersects(deletion_range)
{
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_deletion(deletion_range)));
}
}
checker.diagnostics.push(diagnostic);
})
.or_insert(index);
prev = Some(element);
}
}
fn handle_single_name(checker: &mut Checker, expr: &Expr, value: &Expr) {
let mut diagnostic = Diagnostic::new(
PytestParametrizeNamesWrongType {
single_argument: true,
expected: types::ParametrizeNameType::Csv,
},
expr.range(),
);
let node = value.clone();
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
checker.generator().expr(&node),
expr.range(),
)));
checker.diagnostics.push(diagnostic);
}
fn handle_value_rows(
checker: &mut Checker,
elts: &[Expr],
values_type: types::ParametrizeValuesType,
values_row_type: types::ParametrizeValuesRowType,
) {
for elt in elts {
match elt {
Expr::Tuple(ast::ExprTuple { elts, .. }) => {
if values_row_type != types::ParametrizeValuesRowType::Tuple {
let mut diagnostic = Diagnostic::new(
PytestParametrizeValuesWrongType {
values: values_type,
row: values_row_type,
},
elt.range(),
);
diagnostic.set_fix({
// Determine whether a trailing comma is present due to the _requirement_
// that a single-element tuple must have a trailing comma, e.g., `(1,)`.
//
// If the trailing comma is on its own line, we intentionally ignore it,
// since the expression is already split over multiple lines, as in:
// ```python
// @pytest.mark.parametrize(
// (
// "x",
// ),
// )
// ```
let has_trailing_comma = elts.len() == 1
&& checker.locator().up_to(elt.end()).chars().rev().nth(1) == Some(',');
// Replace `(` with `[`.
let elt_start = Edit::replacement(
"[".into(),
elt.start(),
elt.start() + TextSize::from(1),
);
// Replace `)` or `,)` with `]`.
let start = if has_trailing_comma {
elt.end() - TextSize::from(2)
} else {
elt.end() - TextSize::from(1)
};
let elt_end = Edit::replacement("]".into(), start, elt.end());
Fix::unsafe_edits(elt_start, [elt_end])
});
checker.diagnostics.push(diagnostic);
}
}
Expr::List(ast::ExprList { elts, .. }) => {
if values_row_type != types::ParametrizeValuesRowType::List {
let mut diagnostic = Diagnostic::new(
PytestParametrizeValuesWrongType {
values: values_type,
row: values_row_type,
},
elt.range(),
);
diagnostic.set_fix({
// Determine whether the last element has a trailing comma. Single-element
// tuples _require_ a trailing comma, so this is a single-element list
// _without_ a trailing comma, we need to insert one.
let needs_trailing_comma = if let [item] = elts.as_slice() {
SimpleTokenizer::new(
checker.locator().contents(),
TextRange::new(item.end(), elt.end()),
)
.all(|token| token.kind != SimpleTokenKind::Comma)
} else {
false
};
// Replace `[` with `(`.
let elt_start = Edit::replacement(
"(".into(),
elt.start(),
elt.start() + TextSize::from(1),
);
// Replace `]` with `)` or `,)`.
let elt_end = Edit::replacement(
if needs_trailing_comma {
",)".into()
} else {
")".into()
},
elt.end() - TextSize::from(1),
elt.end(),
);
Fix::unsafe_edits(elt_start, [elt_end])
});
checker.diagnostics.push(diagnostic);
}
}
_ => {}
}
}
}
pub(crate) fn parametrize(checker: &mut Checker, decorators: &[Decorator]) {
for decorator in decorators {
if is_pytest_parametrize(decorator, checker.semantic()) {
if let Expr::Call(ast::ExprCall {
arguments: Arguments { args, .. },
..
}) = &decorator.expression
{
if checker.enabled(Rule::PytestParametrizeNamesWrongType) {
if let [names, ..] = &**args {
check_names(checker, decorator, names);
}
}
if checker.enabled(Rule::PytestParametrizeValuesWrongType) {
if let [names, values, ..] = &**args {
check_values(checker, names, values);
}
}
if checker.enabled(Rule::PytestDuplicateParametrizeTestCases) {
if let [_, values, ..] = &**args {
check_duplicates(checker, values);
}
}
}
}
}
}